Compare commits
116 Commits
8cbd83f0e5
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 0c34703ec7 | |||
| 59f2ef1bf2 | |||
| fa79b1e6ce | |||
| 6fcfbf1def | |||
| 3bc3051383 | |||
| 53bc8d73eb | |||
| 00fd89af1a | |||
| 27412f58af | |||
| 1090591503 | |||
| 30829eeb86 | |||
| 506f778ac3 | |||
| 36d69133b8 | |||
| 5db2bf3c98 | |||
| 3268c57bc6 | |||
| d00388504c | |||
| cc3068ace3 | |||
| 1605b5a9d6 | |||
| ca01ea3ea1 | |||
| 8395baa24f | |||
| daec39ead4 | |||
| 121ce7496c | |||
| c8f3940d26 | |||
| da6a5f8207 | |||
| 6131fb5d7b | |||
| 28ca98a506 | |||
| 95812c3a96 | |||
| efa916060a | |||
| cc2ca05cd4 | |||
| be2014cc31 | |||
| 6b07c19728 | |||
| 6a0a2e1912 | |||
| 7d7408a0ec | |||
| ee04a6372b | |||
| d6e877712a | |||
| 6d1a5b5c83 | |||
| 9cf6e4cedf | |||
| ad6ab30b5f | |||
| 789edcc61b | |||
| e38254821a | |||
| ff88865e91 | |||
| fb1bf4ab85 | |||
| ca90b3fea3 | |||
| 31258b995f | |||
| 24b27dcac4 | |||
| d6690c3764 | |||
| c9bb38454d | |||
| 2d4aefbdc0 | |||
| 56b6181598 | |||
| cdf48f1691 | |||
| f12c4ad8bd | |||
| 00ff738705 | |||
| fa76773efc | |||
| 0d7fc4dbe5 | |||
| bf8763e0de | |||
| 4a89137e38 | |||
| b7499e3815 | |||
| 12458e10dc | |||
| b85e8bd2ca | |||
| 19884b2a90 | |||
| 9f01aa3db8 | |||
| 026ee22c1e | |||
| 142c7b2d86 | |||
| 9dd166d5de | |||
| 1363792bb0 | |||
| 913bf4292b | |||
| 028e453d92 | |||
| 81cf7d9448 | |||
| 2207c85ca6 | |||
| 09c78d3ab8 | |||
| b2ae48e250 | |||
| 8abc79dc5b | |||
| 67765c17f4 | |||
| 630ed42d53 | |||
| 07fd678cf3 | |||
| 7e1bd538c1 | |||
| 56cd0c5715 | |||
| b4e537b4ad | |||
| d6ee8942f1 | |||
| 7847167043 | |||
| 867f0303d8 | |||
| 460b05f187 | |||
| 34c461a61c | |||
| 022086beb8 | |||
| 6f504ebe15 | |||
| 57aab71d45 | |||
| 6f36ef27bb | |||
| e8ed5e4f9f | |||
| b1e0d783e6 | |||
| 4043c89520 | |||
| 155ce28c37 | |||
| 6c69fcbaaa | |||
| 5b9af931c7 | |||
| 9d5ab9e215 | |||
| f69575d48f | |||
| fbe0910638 | |||
| 5c0ad30a7a | |||
| 206cd45098 | |||
| 4a06944fec | |||
| e0ba9c08e8 | |||
| bfcea1b3af | |||
| 0d0521f13d | |||
| 1b756d36ce | |||
| 53c4dbee8e | |||
| e626a2359e | |||
| 0fd84f0f6e | |||
| c30a3cd197 | |||
| 08aa0d69b6 | |||
| 81c2d2e6df | |||
| d80854deae | |||
| 9e5d805f5a | |||
| 4d5e6e2512 | |||
| cc8ddba7aa | |||
| c7ec5f7eb2 | |||
| 33719a549b | |||
| 17cec9ff06 | |||
| 4e5832c14b |
@@ -1,7 +0,0 @@
|
||||
PUBLIC_ORIGIN=https://api.example.com
|
||||
DATABASE_URL=postgresql://foundry:replace-me@postgres.internal:5432/foundry_auth
|
||||
GOOGLE_CLIENT_ID=replace-me.apps.googleusercontent.com
|
||||
GOOGLE_CLIENT_SECRET=replace-me
|
||||
FOUNDRY_PROJECTS='{"notes":"http://localhost:3000/auth/callback","board":"http://localhost:3001/auth/callback"}'
|
||||
HOST=127.0.0.1
|
||||
PORT=8080
|
||||
@@ -1,35 +0,0 @@
|
||||
name: Foundry Go checks
|
||||
on: [push, pull_request]
|
||||
|
||||
jobs:
|
||||
check:
|
||||
runs-on: ces-control
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache: false
|
||||
- name: Check formatting, test and build
|
||||
run: |
|
||||
set -eu
|
||||
test -z "$(gofmt -l cmd internal)"
|
||||
go test -mod=readonly ./...
|
||||
go build -mod=readonly -o bin/foundry ./cmd/foundry
|
||||
- name: Smoke test HTTP routes
|
||||
env:
|
||||
PUBLIC_ORIGIN: https://api.example.com
|
||||
DATABASE_URL: postgres://foundry:fixture@127.0.0.1:5432/foundry
|
||||
GOOGLE_CLIENT_ID: fixture
|
||||
GOOGLE_CLIENT_SECRET: fixture
|
||||
FOUNDRY_PROJECTS: '{"notes":"http://localhost:3000/auth/callback"}'
|
||||
PORT: '18080'
|
||||
run: |
|
||||
set -eu
|
||||
./bin/foundry &
|
||||
server_pid=$!
|
||||
trap 'kill "$server_pid" 2>/dev/null || true' EXIT
|
||||
curl --silent --show-error --fail --retry 5 --retry-connrefused http://127.0.0.1:18080/healthz
|
||||
status=$(curl --silent --show-error -o /dev/null -w '%{http_code}' http://127.0.0.1:18080/projects/notes/auth/me)
|
||||
test "$status" = 401
|
||||
+1
-2
@@ -1,2 +1 @@
|
||||
.env
|
||||
/bin/
|
||||
/target
|
||||
|
||||
Generated
+7
@@ -0,0 +1,7 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "bedrock"
|
||||
version = "0.1.0"
|
||||
@@ -0,0 +1,6 @@
|
||||
[package]
|
||||
name = "bedrock"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
@@ -1,24 +0,0 @@
|
||||
# 造物工坊 · Foundry Core
|
||||
|
||||
共享后端的第一版提供 Google 登录。各项目通过同一个 HTTPS API 登录,在私有 PostgreSQL 的认证库中维护独立账号和会话。项目业务库可分别配置独立的数据库和角色。
|
||||
|
||||
## 服务端配置
|
||||
|
||||
1. 在 Google Cloud 创建一个 Web application OAuth 客户端。授权重定向 URI 填写 `https://<API 域名>/auth/google/callback`。所有项目信任同一个客户端,因此共享 Google 同意页面的应用名称。
|
||||
2. 在服务器私网准备 PostgreSQL 13 或以上版本。在认证库执行一次 `db/001-auth.sql`(使用 `psql -v ON_ERROR_STOP=1`),给运行账号授予这四张表所需的查询及增删改权限。
|
||||
3. 按 `.env.example` 注入运行环境变量。每个项目配置一个固定的前端回调地址,本地开发可用 localhost。将 Google 客户端密钥和数据库连接串存入服务器的密钥管理设施。
|
||||
4. 由 Gitea Actions 在 `ces-control` 上使用 Go 1.25 构建并检查。部署时运行 `foundry` 二进制,通过 HTTPS 反向代理转发至服务监听地址。通过 `GET /healthz` 检查进程,通过 `GET /readyz` 检查认证库。
|
||||
5. 代理避免记录 Google 回调的查询参数及认证请求头。设置入口限流,并定时删除三张临时表(`oauth_attempts`、`login_grants`、`project_sessions`)中 `expires_at <= now()` 的记录。
|
||||
|
||||
## 前端接入
|
||||
|
||||
1. 在浏览器用 Web Crypto 生成 32 字节随机值,编码为无填充 Base64URL,作为 verifier 暂存在当前 tab 的 sessionStorage。对 verifier 字符串做 SHA-256 并用相同编码得到 challenge。
|
||||
2. 顶层导航到 `GET /projects/<project>/auth/google?challenge=<challenge>`。Google 回到共享 API 后,API 将浏览器重定向至已配置的项目回调。
|
||||
3. 回调页从 URL fragment 读取 `code` 或 `error`,用 history.replaceState 清掉 fragment。收到 code 时,向 `POST /projects/<project>/auth/exchange` 发送 `X-Foundry-Code` 和 `X-Foundry-Verifier` 请求头,随后清理暂存的 verifier。code 有效期一分钟,仅可使用一次。
|
||||
4. 将返回的八小时会话凭证保存在内存中,使用 `Authorization: Bearer <access_token>` 调用 `GET /projects/<project>/auth/me`。通过 `POST /projects/<project>/auth/logout` 撤销会话并清理本地凭证。刷新页面后,内存凭证需要通过重新登录获取。
|
||||
|
||||
同一个 Google 账号首次进入不同项目时,会分别创建用户 ID。会话绑定其签发项目。Google 账号的标识 `sub` 用于认领同一项目的既有账号,邮箱只作为资料字段。当前注册模式为开放注册。
|
||||
|
||||
## 验收
|
||||
|
||||
用同一个 Google 测试账号分别登录两个项目,确认用户 ID 不同。用 A 的会话请求 B 的 `me` 应返回 401。验证兑换码重放被拒绝,并确认退出 A 后 B 的会话仍有效。
|
||||
@@ -1,54 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"gitea.entroia.com/Zayden-Jung/foundry-core/internal/auth"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/stdlib"
|
||||
)
|
||||
|
||||
func env(key, fallback string) string {
|
||||
if value := os.Getenv(key); value != "" {
|
||||
return value
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func main() {
|
||||
origin, err := url.Parse(os.Getenv("PUBLIC_ORIGIN"))
|
||||
if err != nil || origin.Scheme != "https" || origin.Hostname() == "" || origin.User != nil ||
|
||||
(origin.Path != "" && origin.Path != "/") || origin.RawQuery != "" || origin.Fragment != "" {
|
||||
log.Fatal("PUBLIC_ORIGIN must be an HTTPS origin")
|
||||
}
|
||||
var callbacks map[string]string
|
||||
if err := json.Unmarshal([]byte(os.Getenv("FOUNDRY_PROJECTS")), &callbacks); err != nil || len(callbacks) == 0 {
|
||||
log.Fatal("FOUNDRY_PROJECTS must configure at least one project")
|
||||
}
|
||||
id, secret, dsn := os.Getenv("GOOGLE_CLIENT_ID"), os.Getenv("GOOGLE_CLIENT_SECRET"), os.Getenv("DATABASE_URL")
|
||||
if id == "" || secret == "" || dsn == "" {
|
||||
log.Fatal("Google credentials and DATABASE_URL are required")
|
||||
}
|
||||
config, err := pgx.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
log.Fatal("Invalid DATABASE_URL")
|
||||
}
|
||||
db := stdlib.OpenDB(*config)
|
||||
defer db.Close()
|
||||
handler, err := auth.New(db, callbacks, origin.ResolveReference(&url.URL{Path: "/auth/google/callback"}).String(), id, secret)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
server := &http.Server{
|
||||
Addr: net.JoinHostPort(env("HOST", "127.0.0.1"), env("PORT", "8080")),
|
||||
Handler: handler, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second,
|
||||
WriteTimeout: 30 * time.Second, IdleTimeout: 60 * time.Second,
|
||||
}
|
||||
log.Fatal(server.ListenAndServe())
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
BEGIN;
|
||||
|
||||
CREATE TABLE project_accounts (
|
||||
project text NOT NULL,
|
||||
id uuid NOT NULL,
|
||||
google_subject text NOT NULL,
|
||||
email text,
|
||||
PRIMARY KEY (project, id),
|
||||
UNIQUE (project, google_subject)
|
||||
);
|
||||
|
||||
CREATE TABLE oauth_attempts (
|
||||
state_hash text PRIMARY KEY,
|
||||
browser_hash text NOT NULL,
|
||||
project text NOT NULL,
|
||||
frontend_challenge text NOT NULL,
|
||||
google_verifier text NOT NULL,
|
||||
expires_at timestamptz NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE login_grants (
|
||||
token_hash text PRIMARY KEY,
|
||||
project text NOT NULL,
|
||||
account_id uuid NOT NULL,
|
||||
frontend_challenge text NOT NULL,
|
||||
expires_at timestamptz NOT NULL,
|
||||
FOREIGN KEY (project, account_id) REFERENCES project_accounts (project, id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE project_sessions (
|
||||
token_hash text PRIMARY KEY,
|
||||
project text NOT NULL,
|
||||
account_id uuid NOT NULL,
|
||||
expires_at timestamptz NOT NULL,
|
||||
FOREIGN KEY (project, account_id) REFERENCES project_accounts (project, id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX oauth_attempts_expiry ON oauth_attempts (expires_at);
|
||||
CREATE INDEX login_grants_expiry ON login_grants (expires_at);
|
||||
CREATE INDEX project_sessions_expiry ON project_sessions (expires_at);
|
||||
|
||||
COMMIT;
|
||||
@@ -1,14 +0,0 @@
|
||||
module gitea.entroia.com/Zayden-Jung/foundry-core
|
||||
|
||||
go 1.25.0
|
||||
|
||||
require github.com/jackc/pgx/v5 v5.7.6
|
||||
|
||||
require (
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
golang.org/x/crypto v0.37.0 // indirect
|
||||
golang.org/x/sync v0.13.0 // indirect
|
||||
golang.org/x/text v0.24.0 // indirect
|
||||
)
|
||||
@@ -1,28 +0,0 @@
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.7.6 h1:rWQc5FwZSPX58r1OQmkuaNicxdmExaEz5A2DO2hUuTk=
|
||||
github.com/jackc/pgx/v5 v5.7.6/go.mod h1:aruU7o91Tc2q2cFp5h4uP3f6ztExVpyVv88Xl/8Vl8M=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE=
|
||||
golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc=
|
||||
golang.org/x/sync v0.13.0 h1:AauUjRAJ9OSnvULf/ARrrVywoJDy0YS2AwQ98I37610=
|
||||
golang.org/x/sync v0.13.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||
golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=
|
||||
golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -1,329 +0,0 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var projectName = regexp.MustCompile(`^[a-z][a-z0-9-]*$`)
|
||||
var tokenPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{43}$`)
|
||||
|
||||
type service struct {
|
||||
db *sql.DB
|
||||
projects map[string]*url.URL
|
||||
redirectURI, clientID, secret string
|
||||
google *http.Client
|
||||
}
|
||||
|
||||
func New(db *sql.DB, callbacks map[string]string, redirectURI, id, secret string) (http.Handler, error) {
|
||||
s := &service{db: db, projects: make(map[string]*url.URL), redirectURI: redirectURI, clientID: id, secret: secret,
|
||||
google: &http.Client{Timeout: 10 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}
|
||||
for name, raw := range callbacks {
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid project callback for %q", name)
|
||||
}
|
||||
host := u.Hostname()
|
||||
local := u.Scheme == "http" && (host == "localhost" || host == "127.0.0.1" || host == "::1")
|
||||
if !projectName.MatchString(name) || host == "" || (u.Scheme != "https" && !local) || u.User != nil || u.Fragment != "" {
|
||||
return nil, fmt.Errorf("invalid project callback for %q", name)
|
||||
}
|
||||
s.projects[name] = u
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { reply(w, 200, payload{"status": "ok"}) })
|
||||
mux.HandleFunc("GET /readyz", s.wrap(func(w http.ResponseWriter, r *http.Request) error {
|
||||
if _, err := s.db.ExecContext(r.Context(), "SELECT 1 FROM project_accounts LIMIT 1"); err != nil {
|
||||
return err
|
||||
}
|
||||
reply(w, 200, payload{"status": "ready"})
|
||||
return nil
|
||||
}))
|
||||
mux.HandleFunc("GET /auth/google/callback", s.wrap(s.callback))
|
||||
mux.HandleFunc("/projects/{project}/auth/{action}", s.wrap(s.project))
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Header().Set("Referrer-Policy", "no-referrer")
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 25*time.Second)
|
||||
defer cancel()
|
||||
mux.ServeHTTP(w, r.WithContext(ctx))
|
||||
}), nil
|
||||
}
|
||||
|
||||
type payload map[string]any
|
||||
|
||||
func reply(w http.ResponseWriter, status int, body payload) {
|
||||
if body != nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
}
|
||||
w.WriteHeader(status)
|
||||
if body != nil {
|
||||
_ = json.NewEncoder(w).Encode(body)
|
||||
}
|
||||
}
|
||||
|
||||
func reject(w http.ResponseWriter, status int, code string) error {
|
||||
reply(w, status, payload{"error": code})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *service) wrap(handle func(http.ResponseWriter, *http.Request) error) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := handle(w, r); err != nil {
|
||||
log.Printf("request failed (%T)", err)
|
||||
_ = reject(w, 503, "service_unavailable")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func token() string {
|
||||
var value [32]byte
|
||||
rand.Read(value[:])
|
||||
return base64.RawURLEncoding.EncodeToString(value[:])
|
||||
}
|
||||
|
||||
func digest(value string) string {
|
||||
sum := sha256.Sum256([]byte(value))
|
||||
return base64.RawURLEncoding.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func (s *service) project(w http.ResponseWriter, r *http.Request) error {
|
||||
project, action := r.PathValue("project"), r.PathValue("action")
|
||||
frontend := s.projects[project]
|
||||
if frontend == nil {
|
||||
return reject(w, 404, "not_found")
|
||||
}
|
||||
if r.Method == http.MethodGet && action == "google" {
|
||||
return s.start(w, r, project)
|
||||
}
|
||||
|
||||
w.Header().Set("Vary", "Origin")
|
||||
if origin := r.Header.Get("Origin"); origin != "" {
|
||||
if origin != frontend.Scheme+"://"+frontend.Host {
|
||||
return reject(w, 403, "origin_denied")
|
||||
}
|
||||
w.Header().Set("Access-Control-Allow-Origin", origin)
|
||||
}
|
||||
switch {
|
||||
case r.Method == http.MethodOptions:
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Authorization, X-Foundry-Code, X-Foundry-Verifier")
|
||||
reply(w, 204, nil)
|
||||
case r.Method == http.MethodPost && action == "exchange":
|
||||
return s.exchange(w, r, project)
|
||||
case r.Method == http.MethodGet && action == "me":
|
||||
return s.account(w, r, project, false)
|
||||
case r.Method == http.MethodPost && action == "logout":
|
||||
return s.account(w, r, project, true)
|
||||
default:
|
||||
return reject(w, 405, "method_not_allowed")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func oauthCookie(state, value string, maxAge int) *http.Cookie {
|
||||
return &http.Cookie{Name: "__Host-foundry-oauth-" + state, Value: value, Path: "/", MaxAge: maxAge,
|
||||
Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode}
|
||||
}
|
||||
|
||||
func (s *service) start(w http.ResponseWriter, r *http.Request, project string) error {
|
||||
challenge := r.URL.Query().Get("challenge")
|
||||
if !tokenPattern.MatchString(challenge) {
|
||||
return reject(w, 400, "invalid_challenge")
|
||||
}
|
||||
state, browser, verifier := token(), token(), token()
|
||||
_, err := s.db.ExecContext(r.Context(), `
|
||||
INSERT INTO oauth_attempts VALUES ($1, $2, $3, $4, $5, now() + interval '10 minutes')
|
||||
`, digest(state), digest(browser), project, challenge, verifier)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
query := url.Values{
|
||||
"client_id": {s.clientID}, "redirect_uri": {s.redirectURI}, "response_type": {"code"},
|
||||
"scope": {"openid email"}, "state": {state}, "code_challenge": {digest(verifier)},
|
||||
"code_challenge_method": {"S256"}, "prompt": {"select_account"},
|
||||
}
|
||||
http.SetCookie(w, oauthCookie(state, browser, 600))
|
||||
http.Redirect(w, r, "https://accounts.google.com/o/oauth2/v2/auth?"+query.Encode(), 302)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *service) googleJSON(ctx context.Context, method, endpoint string, form url.Values, bearer string, result any) error {
|
||||
var body io.Reader
|
||||
if form != nil {
|
||||
body = strings.NewReader(form.Encode())
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, endpoint, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if form != nil {
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
}
|
||||
if bearer != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+bearer)
|
||||
}
|
||||
res, err := s.google.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
if res.StatusCode != 200 {
|
||||
return fmt.Errorf("Google returned HTTP %d", res.StatusCode)
|
||||
}
|
||||
return json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(result)
|
||||
}
|
||||
|
||||
func (s *service) callback(w http.ResponseWriter, r *http.Request) error {
|
||||
ctx := r.Context()
|
||||
query := r.URL.Query()
|
||||
state := query.Get("state")
|
||||
if !tokenPattern.MatchString(state) {
|
||||
return reject(w, 400, "invalid_state")
|
||||
}
|
||||
browser, err := r.Cookie(oauthCookie(state, "", 0).Name)
|
||||
if err != nil || !tokenPattern.MatchString(browser.Value) {
|
||||
return reject(w, 400, "invalid_state")
|
||||
}
|
||||
var project, challenge, verifier string
|
||||
err = s.db.QueryRowContext(ctx, `
|
||||
DELETE FROM oauth_attempts
|
||||
WHERE state_hash = $1 AND browser_hash = $2 AND expires_at > now()
|
||||
RETURNING project, frontend_challenge, google_verifier
|
||||
`, digest(state), digest(browser.Value)).Scan(&project, &challenge, &verifier)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return reject(w, 400, "invalid_state")
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
frontend := s.projects[project]
|
||||
if frontend == nil {
|
||||
return reject(w, 400, "invalid_state")
|
||||
}
|
||||
|
||||
http.SetCookie(w, oauthCookie(state, "", -1))
|
||||
destination := *frontend
|
||||
code := query.Get("code")
|
||||
if code == "" || query.Has("error") {
|
||||
destination.Fragment = "error=google_login_cancelled"
|
||||
http.Redirect(w, r, destination.String(), 302)
|
||||
return nil
|
||||
}
|
||||
var tokens struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
}
|
||||
err = s.googleJSON(ctx, "POST", "https://oauth2.googleapis.com/token", url.Values{
|
||||
"code": {code}, "client_id": {s.clientID}, "client_secret": {s.secret}, "redirect_uri": {s.redirectURI},
|
||||
"grant_type": {"authorization_code"}, "code_verifier": {verifier},
|
||||
}, "", &tokens)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tokens.AccessToken == "" {
|
||||
return errors.New("missing Google access token")
|
||||
}
|
||||
var user struct {
|
||||
Subject string `json:"sub"`
|
||||
Email *string `json:"email"`
|
||||
Verified bool `json:"email_verified"`
|
||||
}
|
||||
if err := s.googleJSON(ctx, "GET", "https://openidconnect.googleapis.com/v1/userinfo", nil, tokens.AccessToken, &user); err != nil {
|
||||
return err
|
||||
}
|
||||
if user.Subject == "" {
|
||||
return errors.New("missing Google subject")
|
||||
}
|
||||
if !user.Verified {
|
||||
user.Email = nil
|
||||
}
|
||||
|
||||
grant := token()
|
||||
_, err = s.db.ExecContext(ctx, `
|
||||
WITH account AS (
|
||||
INSERT INTO project_accounts (project, id, google_subject, email) VALUES ($1, gen_random_uuid(), $2, $3)
|
||||
ON CONFLICT (project, google_subject) DO UPDATE SET email = EXCLUDED.email
|
||||
RETURNING id
|
||||
)
|
||||
INSERT INTO login_grants
|
||||
SELECT $4, $1, id, $5, now() + interval '1 minute' FROM account
|
||||
`, project, user.Subject, user.Email, digest(grant), challenge)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
destination.Fragment = "code=" + grant
|
||||
http.Redirect(w, r, destination.String(), 302)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *service) exchange(w http.ResponseWriter, r *http.Request, project string) error {
|
||||
code, verifier := r.Header.Get("X-Foundry-Code"), r.Header.Get("X-Foundry-Verifier")
|
||||
if !tokenPattern.MatchString(code) || !tokenPattern.MatchString(verifier) {
|
||||
return reject(w, 400, "invalid_exchange")
|
||||
}
|
||||
session := token()
|
||||
result, err := s.db.ExecContext(r.Context(), `
|
||||
WITH grant AS (
|
||||
DELETE FROM login_grants
|
||||
WHERE token_hash = $1 AND project = $2 AND frontend_challenge = $3 AND expires_at > now()
|
||||
RETURNING account_id
|
||||
)
|
||||
INSERT INTO project_sessions
|
||||
SELECT $4, $2, account_id, now() + interval '8 hours' FROM grant
|
||||
`, digest(code), project, digest(verifier), digest(session))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
count, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if count == 0 {
|
||||
return reject(w, 401, "invalid_grant")
|
||||
}
|
||||
reply(w, 200, payload{"access_token": session, "token_type": "Bearer", "expires_in": 28800})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *service) account(w http.ResponseWriter, r *http.Request, project string, logout bool) error {
|
||||
token, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
|
||||
if !ok || !tokenPattern.MatchString(token) {
|
||||
return reject(w, 401, "invalid_session")
|
||||
}
|
||||
if logout {
|
||||
_, err := s.db.ExecContext(r.Context(), "DELETE FROM project_sessions WHERE token_hash = $1 AND project = $2", digest(token), project)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
reply(w, 204, nil)
|
||||
return nil
|
||||
}
|
||||
var id string
|
||||
var email *string
|
||||
err := s.db.QueryRowContext(r.Context(), `
|
||||
SELECT a.id::text, a.email FROM project_sessions s
|
||||
JOIN project_accounts a ON a.project = s.project AND a.id = s.account_id
|
||||
WHERE s.token_hash = $1 AND s.project = $2 AND s.expires_at > now()
|
||||
`, digest(token), project).Scan(&id, &email)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return reject(w, 401, "invalid_session")
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
reply(w, 200, payload{"project": project, "id": id, "email": email})
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() {
|
||||
println!("Hello, world!");
|
||||
}
|
||||
Reference in New Issue
Block a user