鉴权并入 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
+109 -177
View File
@@ -9,10 +9,10 @@ import (
"log/slog"
"net"
"net/http"
"net/url"
"strings"
"time"
"commilitia.net/cdrop/internal/brokerclient"
"commilitia.net/cdrop/internal/db"
"commilitia.net/cdrop/internal/jwtauth"
)
@@ -49,12 +49,23 @@ type qrStartResp struct {
ExpiresAt int64 `json:"expires_at"`
}
// userResp is the display identity handed to a client. After the broker migration
// cdrop no longer holds an accounts table; the approver's name is best-effort (the new
// device refreshes it from X-Auth-Name via /api/me once its token is live).
type userResp struct {
ID string `json:"id"`
Name string `json:"name"`
Avatar string `json:"avatar,omitempty"`
}
type qrStatusResp struct {
Status string `json:"status"` // pending | approved | denied | expired
AccessToken string `json:"access_token,omitempty"`
ExpiresIn int `json:"expires_in,omitempty"`
User *userResp `json:"user,omitempty"`
DeviceName string `json:"device_name,omitempty"`
Status string `json:"status"` // pending | approved | denied | expired
AccessToken string `json:"access_token,omitempty"`
RefreshToken string `json:"refresh_token,omitempty"`
ExpiresIn int `json:"expires_in,omitempty"`
User *userResp `json:"user,omitempty"`
DeviceName string `json:"device_name,omitempty"`
DeviceID string `json:"device_id,omitempty"`
}
type qrRequestResp struct {
@@ -63,19 +74,13 @@ type qrRequestResp struct {
RequestIP string `json:"request_ip"`
ExpiresAt int64 `json:"expires_at"`
Status string `json:"status"`
// StepUp tells the approver UI a fresh re-auth is required before approving.
StepUp bool `json:"step_up"`
}
type qrApproveReq struct {
RequestID string `json:"request_id"`
ApprovalCode string `json:"approval_code"`
Scope string `json:"scope"` // full | guest (this milestone always guest)
Scope string `json:"scope"` // full | guest
Persist string `json:"persist"` // once | persist
// Step-up (when CDROP_STEP_UP_ENABLED): a fresh prompt=login PKCE code+verifier
// the backend exchanges and checks for a recent auth_time (AUTH.md §6).
StepUpCode string `json:"step_up_code"`
StepUpVerifier string `json:"step_up_verifier"`
}
type qrDenyReq struct {
@@ -191,10 +196,13 @@ func (s *Server) handleQRStatus(w http.ResponseWriter, r *http.Request) {
}
}
// collectQRSession turns an approved request into a live session for the new
// device. ConsumeLoginRequest is the single-use guard: only the poll that flips
// approved→consumed proceeds, so a duplicated/raced poll can't mint a second
// session.
// collectQRSession turns an approved request into a live session for the new device.
// ConsumeLoginRequest is the single-use guard: only the poll that flips
// approved→consumed proceeds, so a duplicated/raced poll can't mint a second session.
// The session itself is minted by the Auth Broker (path A): cdrop generates a stable
// device_id, has the broker mint a scoped access+refresh bound to it, and records the
// device row (with the broker's sid for later revocation). The new device holds the
// broker tokens directly — no cdrop cookie or self-signed token.
func (s *Server) collectQRSession(w http.ResponseWriter, r *http.Request, req db.LoginRequest) {
n, err := s.queries.ConsumeLoginRequest(r.Context(), req.ID)
if err != nil {
@@ -208,63 +216,74 @@ func (s *Server) collectQRSession(w http.ResponseWriter, r *http.Request, req db
return
}
raw, id, err := newSessionToken()
tier := "guest"
if req.GrantScope == "full" {
tier = "full"
}
accessTTL, refreshTTL := s.tierTTLs(tier)
deviceID, err := newDeviceID()
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "id gen"})
return
}
scope := req.GrantScope
if scope != "full" {
scope = "guest"
}
// Persistent borrows slide their window (kind self); one-time borrows are kind
// guest with a fixed short expiry that refresh never extends (AUTH.md §3.1).
now := time.Now()
kind := "guest"
exp := now.Add(time.Duration(s.cfg.QRGuestTTLSeconds) * time.Second)
if req.GrantPersist == "persist" {
kind = "self"
exp = now.Add(time.Duration(s.cfg.QRPersistTTLHours) * time.Hour)
}
if err := s.queries.CreateSelfSession(r.Context(), db.CreateSelfSessionParams{
ID: id,
sess, err := s.broker.MintSession(r.Context(), brokerclient.MintParams{
UserID: req.ApproverUserID,
DeviceName: req.NewDeviceName,
UserAgent: req.UserAgent,
Kind: kind,
Scope: scope,
GrantedBy: "qr",
CreatedAt: now.Unix(),
LastUsedAt: now.Unix(),
ExpiresAt: exp.Unix(),
}); err != nil {
slog.Error("create self session failed", "err", err)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "db"})
return
}
token, expiresIn, err := s.mintSessionToken(req.ApproverUserID, id, scope)
if err != nil {
slog.Error("mint session token failed", "err", err)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "mint failed"})
return
}
setSessionCookie(w, raw)
user := userResp{ID: req.ApproverUserID, Name: req.ApproverUserID}
if acct, err := s.queries.GetAccount(r.Context(), req.ApproverUserID); err == nil {
if acct.DisplayName != "" {
user.Name = acct.DisplayName
}
user.Avatar = acct.AvatarUrl
}
writeJSON(w, http.StatusOK, qrStatusResp{
Status: "approved",
AccessToken: token,
ExpiresIn: expiresIn,
User: &user,
DeviceName: req.NewDeviceName,
Tier: tier,
AccessTTL: accessTTL,
RefreshTTL: refreshTTL,
Sliding: true,
Label: req.NewDeviceName,
Meta: deviceID,
})
if err != nil {
slog.Error("broker mint failed", "err", err, "user", req.ApproverUserID)
writeJSON(w, http.StatusBadGateway, map[string]string{"error": "mint failed"})
return
}
now := time.Now().Unix()
if err := s.queries.CreateDevice(r.Context(), db.CreateDeviceParams{
DeviceID: deviceID,
UserID: req.ApproverUserID,
Name: req.NewDeviceName,
Type: req.NewDeviceType,
Tier: tier,
BrokerSid: sess.SID,
CreatedAt: now,
LastSeen: now,
}); err != nil {
// The session is already minted and usable; a failed device-row write only
// costs local management state (revoke / list), so proceed rather than strand
// the new device without its tokens.
slog.Error("create device failed", "err", err, "user", req.ApproverUserID, "device", deviceID)
}
expiresIn := int(sess.AccessExpires - now)
if expiresIn < 0 {
expiresIn = 0
}
// Best-effort display identity; the new device refreshes its real name from
// X-Auth-Name via /api/me once its token is live at the edge.
user := userResp{ID: req.ApproverUserID, Name: req.ApproverUserID}
writeJSON(w, http.StatusOK, qrStatusResp{
Status: "approved",
AccessToken: sess.Access,
RefreshToken: sess.Refresh,
ExpiresIn: expiresIn,
User: &user,
DeviceName: req.NewDeviceName,
DeviceID: deviceID,
})
}
// tierTTLs returns the configured access + refresh TTLs (seconds) for a tier.
func (s *Server) tierTTLs(tier string) (accessTTL, refreshTTL int) {
if tier == "guest" {
return s.cfg.GuestAccessTTLSeconds, s.cfg.GuestRefreshTTLSeconds
}
return s.cfg.FullAccessTTLSeconds, s.cfg.FullRefreshTTLSeconds
}
// handleQRRequest (full session) lets the approver see what they are about to
@@ -285,9 +304,6 @@ func (s *Server) handleQRRequest(w http.ResponseWriter, r *http.Request) {
RequestIP: req.RequestIp,
ExpiresAt: req.ExpiresAt,
Status: req.Status,
// Tell the approver UI to re-auth only if step-up is on AND this session
// hasn't recently stepped up (within the window) — no repeated prompts (#3).
StepUp: s.cfg.StepUpEnabled && !s.sessionRecentlySteppedUp(r),
})
}
@@ -309,19 +325,10 @@ func (s *Server) handleQRApprove(w http.ResponseWriter, r *http.Request) {
}
claims, _ := jwtauth.ClaimsFromContext(r.Context())
// Step-up: approving a new device into your account is sensitive. When enabled,
// require a fresh prompt=login re-auth (the provider's 2FA, if configured, is
// enforced during that exchange) — UNLESS this session already stepped up within
// the freshness window, so the same session isn't re-prompted repeatedly (#3).
if s.cfg.StepUpEnabled && !s.sessionRecentlySteppedUp(r) {
if !s.verifyStepUp(r, claims.UserID, body.StepUpCode, body.StepUpVerifier) {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "step_up_required"})
return
}
s.recordStepUp(r)
}
scope := "guest" // this milestone grants restricted guest sessions only
// Step-up (a fresh re-auth before approving a device) is deferred to the broker
// post-migration (/login?switch=1); a full-tier session is trusted to approve.
// The route is already gated by requireFullSession, so a guest can't reach here.
scope := "guest"
if body.Scope == "full" {
scope = "full"
}
@@ -329,6 +336,13 @@ func (s *Server) handleQRApprove(w http.ResponseWriter, r *http.Request) {
if body.Persist == "persist" {
persist = "persist"
}
// 原生客户端(非浏览器:iOS / macOS / Windows / Linux)只接受完整权限会话——用户原则:
// 原生 App 不允许受限访客(受限访客仅是 Web / PWA 的权宜)。批准端只给「信任并继续 / 拒绝」,
// 后端在此再兜底强制 full + persist,无论批准请求送来什么 scope。
if req.NewDeviceType != "" && req.NewDeviceType != "browser" {
scope = "full"
persist = "persist"
}
now := time.Now()
n, err := s.queries.ApproveLoginRequest(r.Context(), db.ApproveLoginRequestParams{
ApproverUserID: claims.UserID,
@@ -373,99 +387,6 @@ func (s *Server) handleQRDeny(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}
// sessionFromCookie resolves the caller's web_session row from the cdrop_session
// cookie. The scan-approval endpoints live under /api/auth/*, which the cookie's
// Path covers, so both OIDC and self sessions can be located here.
func (s *Server) sessionFromCookie(r *http.Request) (db.WebSession, bool) {
c, err := r.Cookie(sessionCookieName)
if err != nil || c.Value == "" {
return db.WebSession{}, false
}
sess, err := s.queries.GetWebSession(r.Context(), sessionID(c.Value))
if err != nil {
return db.WebSession{}, false
}
return sess, true
}
// sessionRecentlySteppedUp reports whether the caller's session passed step-up
// within StepUpMaxAgeSeconds — so a sensitive action skips re-auth and the same
// session isn't re-prompted repeatedly (#3, AUTH.md §6).
func (s *Server) sessionRecentlySteppedUp(r *http.Request) bool {
sess, ok := s.sessionFromCookie(r)
if !ok || sess.SteppedUpAt == 0 {
return false
}
window := int64(s.cfg.StepUpMaxAgeSeconds)
if window <= 0 {
window = 300
}
return time.Now().Unix()-sess.SteppedUpAt <= window
}
// recordStepUp stamps the caller's session as freshly stepped-up.
func (s *Server) recordStepUp(r *http.Request) {
sess, ok := s.sessionFromCookie(r)
if !ok {
return
}
if err := s.queries.SetSessionSteppedUp(r.Context(), db.SetSessionSteppedUpParams{
SteppedUpAt: time.Now().Unix(),
ID: sess.ID,
}); err != nil {
slog.Warn("record step-up failed", "err", err)
}
}
// verifyStepUp exchanges a fresh prompt=login authorization code and confirms it
// proves a recent interactive re-authentication by the same user: the id_token's
// signature validates (JWKS), its sub matches the caller, and its auth_time is
// within StepUpMaxAgeSeconds. Any failure → false (the caller answers 403). The
// code is single-use at the IdP, so it can't be replayed (AUTH.md §6).
func (s *Server) verifyStepUp(r *http.Request, userID, code, verifier string) bool {
if code == "" || verifier == "" || s.cfg.OIDCTokenURL == "" {
return false
}
form := url.Values{}
form.Set("grant_type", "authorization_code")
form.Set("code", code)
form.Set("code_verifier", verifier)
form.Set("client_id", s.cfg.OIDCClientID)
form.Set("redirect_uri", s.cfg.OIDCRedirectURI)
if s.cfg.OIDCClientSecret != "" {
form.Set("client_secret", s.cfg.OIDCClientSecret)
}
tr, err := postOIDCToken(r.Context(), s.cfg.OIDCTokenURL, form)
if err != nil {
slog.Warn("step-up exchange failed", "err", err)
return false
}
if tr.IDToken == "" {
return false
}
sub, authTime, err := s.auth.VerifyIDToken(r.Context(), tr.IDToken)
if err != nil {
slog.Warn("step-up id_token invalid", "err", err)
return false
}
if sub != userID {
return false
}
// Enforce the freshness window only when the IdP supplied auth_time (Casdoor
// omits it). When absent, the fresh single-use prompt=login code — exchanged
// once, just now — is itself the bound on how recent the re-auth was.
if authTime > 0 {
maxAge := int64(s.cfg.StepUpMaxAgeSeconds)
if maxAge <= 0 {
maxAge = 300
}
if time.Now().Unix()-authTime > maxAge {
return false
}
}
return true
}
// lookupQRRequest fetches a request and verifies the approval_code in constant
// time. It writes the error response itself and returns ok=false on any failure
// (missing args, unknown request, bad code, expired), so callers just early-return.
@@ -530,3 +451,14 @@ func randB64(n int) (string, error) {
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
// newDeviceID mints a stable opaque device identifier ("dev_" + base64url(16 random
// bytes)). It is cdrop's session<->device join key: passed to the broker as meta and
// echoed back as X-Auth-Meta. Pure [A-Za-z0-9_-], no control bytes (validMeta-safe).
func newDeviceID() (string, error) {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return "", err
}
return "dev_" + base64.RawURLEncoding.EncodeToString(b), nil
}