鉴权并入 Auth Broker:委派设备会话统一模型 + 四端迁移

后端(委托 Auth Broker,路径 A):
- 删自建鉴权(OIDC exchange / 自签会话 / step-up / shortcut / web_sessions / accounts),cdrop 不再存任何凭证;鉴权中间件改读边缘注入的 X-Auth-Subject/Scope/Meta/Name/Roles 头(dev 旁路保留);Claims 加 Tier() / Guest()
- internal/brokerclient:mint / revoke(带 X-Broker-App)/ refresh / ListSessions(R1 列举),直连内网、吊销幂等

统一会话模型“委派设备会话”(Delegated Device Sessions):
- 每个客户端(浏览器 / 桌面 / 扫码设备)=一条带 meta(device_id) + label 的 broker 机器会话;Broker 作设备会话唯一注册表(R1 按用户+app 列举 + R2 按 (user,app,meta) 幂等铸造),cdrop 退化为薄覆盖层、不再自存权威会话表
- 新增代铸端点 POST /api/auth/device-session:凭边缘已验明的 X-Auth-Subject 委托 broker 铸 / 轮换设备会话(meta=device_id、按调用方 tier 防越权、sameOrigin CSRF、per-IP 限流);R2 幂等保证同一 device_id 重登原地轮换、不堆重复设备
- 会话列表=R1 权威 + 叠加 type(本地缓存)/ online(Hub presence,按设备名)/ current(meta 匹配本请求 X-Auth-Meta)+ 过滤 meta=""(device-authorize 引导会话残留);devices 表降级为 type/presence 薄缓存(非会话权威),device_id 主键、upsert 按 user 限定
- 吊销按 device_id → 缓存优先 / R1 兜底解析 sid → broker 吊销 + X-Broker-App;扫码登录保留三密钥编排,collect 改委托 broker 铸 + 落缓存行

Web 前端:
- 登录走 broker 全局 SSO 代跳(/api/auth/login 302);bootstrap 经 /api/me 注入身份后代铸设备会话(稳定 device_id 存 localStorage、Web Locks 跨 tab 串行防重复铸造);refresh 走 /api/auth/refresh
- 设备管理按 device_id;改名=同 device_id 重代铸(R2 原地轮换换 label、不产生重复行);登录页反应式守卫修登录回环
- 去 OIDC PKCE / step-up(删 oauth.callback / stepUp)

桌面客户端(Wails):
- loopback PKCE(RFC 8252)改指 broker 设备授权流(/device/authorize + /device/token)拿引导令牌,再代铸出带 meta 的托管设备会话——与浏览器同模型、同管理、同吊销;身份取自代铸响应(修“显示名显示为 UUID”);refresh 保留显示名;稳定 device_id 入桌面配置

iOS 客户端(arch A,原生 SwiftUI + 离屏无头 WebView 引擎 + 原生↔JS 桥):
- 引擎 / 文件管理 / 设备管理 / 应用图标 / 本地化(此前实现,随本次落入版本库)
- 鉴权=引擎自刷(boot 注入 refresh_token)+ broker 轮换经 sessionRotated 回报原生更新 Keychain;去 cookie 同步;Session 加 refreshToken / deviceId

实时 / 健壮性:
- presence 走 Hub union(设备表行 ∪ 表外实时连接,按名去重、live-only 标在线)
- Hub 通道 close 一律在写锁内、非阻塞 send 一律在读锁内,消除 close-vs-send 闭通道 send panic(revoke 每次 Kick 后该路径变热)

配置 / 删旧栈:
- config 改 broker 接入(CDROP_BROKER_* / CDROP_PUBLIC_URL / 按档 TTL),prod 强校验 broker 配置 + PUBLIC_URL(CSRF Origin 守卫不失效)
- 删 auth.go / selftoken.go / shortcut.go / jwks.go + 三表(web_sessions / accounts / shortcut_tokens)及验证链;.env.example / compose.snippet.yaml / Caddyfile.snippet 更新为 broker 模型(人机分流 + 公开端点放行 + X-Auth-Meta 透传)
- 测试全重写:QR / 会话含 mock broker(R1 列举 + R2 幂等);hub 加 close-vs-send 并发回归;config 加 prod 必填校验
This commit is contained in:
2026-06-26 02:07:11 +08:00
parent c79b176b87
commit 10cf36ecee
104 changed files with 7533 additions and 5318 deletions
+25 -215
View File
@@ -2,183 +2,46 @@ package httpapi
import (
"context"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"net/url"
"time"
"commilitia.net/cdrop/internal/db"
"commilitia.net/cdrop/internal/jwtauth"
)
// Browser "passwordless re-login" (web only — desktop persists its own
// refresh_token in the OS keyring and never touches these endpoints).
//
// The durable credential (Casdoor's ~15 KB refresh_token) stays server-side in
// web_sessions, encrypted at rest. The browser only ever holds an opaque cookie
// token whose SHA-256 is the row's primary key — so a leaked DB yields neither a
// usable cookie nor a decryptable token. The cookie is HttpOnly (XSS can't read
// it), Secure (HTTPS only), SameSite=Lax + Origin-checked (CSRF), and Path-scoped
// to /api/auth so it rides only these four endpoints, not every API call.
// Shared HTTP helpers for the auth surface. After the Auth Broker migration (path A)
// cdrop no longer keeps server-side sessions, cookies, or refresh tokens — identity
// and session lifecycle live in the broker. What remains here is the CSRF origin
// check, the scan-login poll-secret hash, and the login-request reaper.
const (
sessionCookieName = "cdrop_session"
sessionCookiePath = "/api/auth"
// webSessionTTL is the sliding inactivity window: each refresh pushes
// expires_at this far forward. The effective cap is min(this, the IdP's own
// refresh_token validity) — once Casdoor retires the refresh_token, refresh
// 401s and the user re-logs in regardless.
webSessionTTL = 7 * 24 * time.Hour
// refreshLockStripes bounds the per-session refresh lock set (see Server).
refreshLockStripes = 256
)
// lockRefresh serialises refreshes of one session id, returning the unlock fn.
// Callers must re-read the session row after acquiring it: a concurrent refresh
// may have already rotated the refresh_token.
func (s *Server) lockRefresh(id string) func() {
idx := stripeIndex(id)
s.refreshLocks[idx].Lock()
return func() { s.refreshLocks[idx].Unlock() }
}
// stripeIndex folds a session id into a stripe with FNV-1a — bounded, no cleanup.
func stripeIndex(id string) int {
var h uint32 = 2166136261
for i := 0; i < len(id); i++ {
h = (h ^ uint32(id[i])) * 16777619
}
return int(h % refreshLockStripes)
}
// deriveSessionKey turns a config secret of any length into a 32-byte AES key
// (mirrors jwtauth.DeriveHS256Key). Empty secret → nil (feature disabled).
func deriveSessionKey(secret string) []byte {
if secret == "" {
return nil
}
sum := sha256.Sum256([]byte(secret))
return sum[:]
}
// deriveSiteOrigin extracts scheme://host from the configured redirect_uri to
// give the CSRF Origin check a fixed expected value. Empty (dev) disables it.
func deriveSiteOrigin(redirectURI string) string {
if redirectURI == "" {
// deriveSiteOrigin extracts scheme://host from the configured public URL to give the
// CSRF Origin check a fixed expected value (and the scan-login QR its link origin).
// Empty / unparseable (dev) disables the origin check.
func deriveSiteOrigin(publicURL string) string {
if publicURL == "" {
return ""
}
u, err := url.Parse(redirectURI)
u, err := url.Parse(publicURL)
if err != nil || u.Scheme == "" || u.Host == "" {
return ""
}
return u.Scheme + "://" + u.Host
}
// newSessionToken mints a fresh opaque cookie token plus its storage id. raw
// goes in Set-Cookie; id (hex SHA-256 of raw) is the DB key, so the stored row
// never contains a usable cookie value.
func newSessionToken() (raw, id string, err error) {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return "", "", err
}
raw = base64.RawURLEncoding.EncodeToString(b)
return raw, sessionID(raw), nil
}
// sessionID hashes an opaque token to its storage form (hex SHA-256). The scan-login
// poll_secret is stored as this hash — the new device holds the plaintext, so a leaked
// DB never yields a usable secret.
func sessionID(raw string) string {
sum := sha256.Sum256([]byte(raw))
return hex.EncodeToString(sum[:])
}
// encryptRefresh seals a refresh_token with AES-256-GCM. Output is
// base64(nonce || ciphertext+tag); the key is s.sessionKey (env-derived).
func (s *Server) encryptRefresh(plain string) (string, error) {
if len(s.sessionKey) == 0 {
return "", errors.New("session key not configured")
}
gcm, err := newGCM(s.sessionKey)
if err != nil {
return "", err
}
nonce := make([]byte, gcm.NonceSize())
if _, err := rand.Read(nonce); err != nil {
return "", err
}
ct := gcm.Seal(nonce, nonce, []byte(plain), nil)
return base64.StdEncoding.EncodeToString(ct), nil
}
func (s *Server) decryptRefresh(enc string) (string, error) {
if len(s.sessionKey) == 0 {
return "", errors.New("session key not configured")
}
raw, err := base64.StdEncoding.DecodeString(enc)
if err != nil {
return "", err
}
gcm, err := newGCM(s.sessionKey)
if err != nil {
return "", err
}
if len(raw) < gcm.NonceSize() {
return "", errors.New("ciphertext too short")
}
nonce, ct := raw[:gcm.NonceSize()], raw[gcm.NonceSize():]
plain, err := gcm.Open(nil, nonce, ct, nil)
if err != nil {
return "", err
}
return string(plain), nil
}
func newGCM(key []byte) (cipher.AEAD, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
return cipher.NewGCM(block)
}
func setSessionCookie(w http.ResponseWriter, raw string) {
http.SetCookie(w, &http.Cookie{
Name: sessionCookieName,
Value: raw,
Path: sessionCookiePath,
MaxAge: int(webSessionTTL / time.Second),
HttpOnly: true,
Secure: true,
SameSite: http.SameSiteLaxMode,
})
}
func clearSessionCookie(w http.ResponseWriter) {
http.SetCookie(w, &http.Cookie{
Name: sessionCookieName,
Value: "",
Path: sessionCookiePath,
MaxAge: -1,
HttpOnly: true,
Secure: true,
SameSite: http.SameSiteLaxMode,
})
}
// sameOrigin is belt-and-suspenders CSRF defence atop SameSite=Lax: when the
// browser sends an Origin header (always, on fetch POST) it must match the
// deployment's own origin. Absent Origin (non-browser clients) is allowed, as is
// an unconfigured site origin (dev).
// sameOrigin is belt-and-suspenders CSRF defence: when the browser sends an Origin
// header (always, on fetch POST) it must match the deployment's own origin. Absent
// Origin (non-browser clients) is allowed, as is an unconfigured site origin (dev).
func (s *Server) sameOrigin(r *http.Request) bool {
origin := r.Header.Get("Origin")
if origin == "" || s.siteOrigin == "" {
@@ -187,61 +50,17 @@ func (s *Server) sameOrigin(r *http.Request) bool {
return origin == s.siteOrigin
}
// handleAuthLogout destroys the server-side session and clears the cookie.
// Cookie-authenticated (no bearer): the cookie is the only thing that proves
// which session to drop.
func (s *Server) handleAuthLogout(w http.ResponseWriter, r *http.Request) {
if c, err := r.Cookie(sessionCookieName); err == nil && c.Value != "" {
if err := s.queries.DeleteWebSession(r.Context(), sessionID(c.Value)); err != nil {
slog.Warn("web session delete failed", "err", err)
}
func truncate(s string, n int) string {
if len(s) <= n {
return s
}
clearSessionCookie(w)
w.WriteHeader(http.StatusNoContent)
return s[:n] + "…"
}
type sessionDeviceReq struct {
DeviceName string `json:"device_name"`
}
// handleAuthDevice persists this browser's device name into its session row so
// it survives PWA storage eviction: on the next boot, /auth/refresh hands the
// name back and the client re-hydrates selfDeviceName without a trip to /setup.
func (s *Server) handleAuthDevice(w http.ResponseWriter, r *http.Request) {
if !s.sameOrigin(r) {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "bad origin"})
return
}
c, err := r.Cookie(sessionCookieName)
if err != nil || c.Value == "" {
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "no session"})
return
}
var req sessionDeviceReq
if err := json.NewDecoder(io.LimitReader(r.Body, 4096)).Decode(&req); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid json"})
return
}
name := jwtauth.SanitizeDeviceName(req.DeviceName)
if name == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "empty device name"})
return
}
if err := s.queries.SetWebSessionDevice(r.Context(), db.SetWebSessionDeviceParams{
DeviceName: name,
ID: sessionID(c.Value),
}); err != nil {
slog.Error("set web session device failed", "err", err)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "persist failed"})
return
}
w.WriteHeader(http.StatusNoContent)
}
// RunWebSessionReaper periodically reclaims expired web_sessions rows. Lazy
// deletion on access covers the hot path; this sweeps sessions that simply go
// idle and are never touched again.
func RunWebSessionReaper(ctx context.Context, q *db.Queries) {
// RunLoginRequestReaper periodically reclaims expired scan-login request rows. They
// are short-lived (default 120s) and already rejected at use time; this sweeps the
// stragglers that are opened and never collected.
func RunLoginRequestReaper(ctx context.Context, q *db.Queries) {
ticker := time.NewTicker(1 * time.Hour)
defer ticker.Stop()
for {
@@ -249,16 +68,7 @@ func RunWebSessionReaper(ctx context.Context, q *db.Queries) {
case <-ctx.Done():
return
case <-ticker.C:
now := time.Now().Unix()
n, err := q.DeleteExpiredWebSessions(ctx, now)
if err != nil {
slog.Warn("web session reaper failed", "err", err)
} else if n > 0 {
slog.Info("web sessions reaped", "count", n)
}
// Scan-login requests are short-lived (default 120s); sweep the
// stragglers here too. Expired rows are already rejected at use time.
if n, err := q.DeleteExpiredLoginRequests(ctx, now); err != nil {
if n, err := q.DeleteExpiredLoginRequests(ctx, time.Now().Unix()); err != nil {
slog.Warn("login request reaper failed", "err", err)
} else if n > 0 {
slog.Info("login requests reaped", "count", n)