扫码登录:cdrop 自签会话原语 + 薄账户层 + 受限访客 + 2FA step-up
身份仍源自 OAuth provider(user_id = OIDC sub),cdrop 在其上自维护一薄层: 自签会话令牌 + accounts 表,并新增扫码快速登录。实施蓝本见 AUTH.md。 后端 · 自签会话原语 - web_sessions 加 kind/scope/granted_by 列(bootstrap 幂等迁移);既有 oidc 会话行为不变,新增 self(滑动续期)/ guest(受限·不续)两类 - cdrop 自签 HS256 会话 access token,密钥派生自 SESSION_SECRET,与落盘 AES、 shortcut HS256 三密钥域隔离;jwtauth.verifySelfToken 无状态校验、靠 typ 区分 - requireFullSession 守卫:guest 会话不得改账号 / 再批准设备 / 签长效 token - /auth/refresh 按 kind 分流:self/guest 纯自签、不触 IdP 后端 · 扫码登录(internal/httpapi/qr.go) - qr/start・status・request・approve・deny 五端点 + login_requests 表 + reaper - 三密钥分离:QR 仅含批准信息,会话只投递给持私有 poll_secret 的原设备 (偷拍 QR 者无 poll_secret 领不到会话、未登录批不了准) - 会话在新设备侧领取(cookie 不经手机)、单次消费、短 TTL 后端 · 薄账户层与 2FA step-up - accounts 表(键 sub,不含任何凭证):exchange/refresh upsert match_key / 显示名 / 头像 / roles,供显示与未来管理员开启迁移标记时跨源关联 - step-up(默认关):开启后 qr/approve 要求新鲜 prompt=login 授权码,后端就地 换 id_token、JWKS 验签 + auth_time 窗口 + sub 匹配,provider 2FA 于此往返强制 前端(web/) - 显码页 /link/new + 批准页 /link + net/qr.ts,对齐 Theme B、复用 AuthShell 与聚珍排版管线、零新全局样式 - step-up 再认证流:批准前跑 prompt=login PKCE,回调分叉(不消费一次性 code、 独立 state key)后带 step_up_code/verifier 调 approve - 三语 i18n qr.*;新增 qrcode 依赖 修复 · clipboard sweeper(早已提交的损坏) - ClearExpiredClipboards 因 clipboard.sql 全角注释触发 sqlc 1.31 多字节偏移 bug,生成 SQL 被截断为「UPDATE clipboard_state SET content =」,sweeper 运行 期报「incomplete input」、过期剪贴板内容从未清除(短 TTL 暴露保护失效) - 注释改纯 ASCII 并加 bug 警告,重生成得完整 SQL;prod 已验证 sweeper 由 ERROR 转为正常清理(cleared count=1) 构建 - .dockerignore:排除本地 node_modules 等,避免宿主原生二进制污染镜像内 vite 构建 - Dockerfile.base:GOPROXY 改为可经 --build-arg 覆盖(默认仍官方代理,受限网络 构建时传区域镜像即可,仓库不固化区域值) 文档 - 新增 AUTH.md(账户与登录实施蓝本);README 特性;.env.example / compose.snippet 增配置项(QR / 自签会话 TTL / step-up / match_claim) 测试 - 自签 token 密钥域隔离、扫码端到端(领取 / 单次 / poll_secret 校验 / deny / step-up 门)、extractIdentity、web_sessions 升级迁移
This commit is contained in:
+117
-17
@@ -1,6 +1,7 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -109,12 +110,15 @@ func (s *Server) handleAuthExchange(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
user, err := extractUser(tr.IDToken, tr.AccessToken)
|
||||
identity, err := extractIdentity(tr.IDToken, tr.AccessToken, s.cfg.AccountMatchClaim)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusBadGateway,
|
||||
map[string]string{"error": "extract user: " + err.Error()})
|
||||
return
|
||||
}
|
||||
user := identity.User
|
||||
// Refresh the thin accounts row (display name / avatar / roles / match_key).
|
||||
s.upsertAccount(r.Context(), identity)
|
||||
|
||||
// Stash the refresh_token server-side and hand the browser an opaque,
|
||||
// HttpOnly cookie instead. Guarded so a deploy without the encryption key (or
|
||||
@@ -211,6 +215,15 @@ func (s *Server) handleAuthRefresh(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "session expired"})
|
||||
return
|
||||
}
|
||||
|
||||
// Self-signed sessions (scan-login: kind self/guest) carry no IdP refresh_token.
|
||||
// Mint a fresh cdrop access token straight from the row, slide the window for
|
||||
// persistent sessions, re-arm the cookie — never touching the IdP (AUTH.md §3.1).
|
||||
if sess.Kind != "oidc" {
|
||||
s.refreshSelfSession(w, r, sess, c.Value, now)
|
||||
return
|
||||
}
|
||||
|
||||
refreshToken, err := s.decryptRefresh(sess.RefreshToken)
|
||||
if err != nil {
|
||||
// Corrupt ciphertext or rotated key — the session is unusable, drop it.
|
||||
@@ -239,12 +252,15 @@ func (s *Server) handleAuthRefresh(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
user, err := extractUser(tr.IDToken, tr.AccessToken)
|
||||
identity, err := extractIdentity(tr.IDToken, tr.AccessToken, s.cfg.AccountMatchClaim)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusBadGateway,
|
||||
map[string]string{"error": "extract user: " + err.Error()})
|
||||
return
|
||||
}
|
||||
user := identity.User
|
||||
// Keep the thin accounts row fresh on every successful refresh too.
|
||||
s.upsertAccount(r.Context(), identity)
|
||||
|
||||
// Rotate: Casdoor issues a new refresh_token on each grant; fall back to the
|
||||
// existing one if it didn't. Slide the window forward and re-arm the cookie.
|
||||
@@ -274,6 +290,44 @@ func (s *Server) handleAuthRefresh(w http.ResponseWriter, r *http.Request) {
|
||||
})
|
||||
}
|
||||
|
||||
// refreshSelfSession renews a cdrop self-signed session without contacting the
|
||||
// IdP: it mints a fresh access token from the row. Persistent "self" sessions
|
||||
// slide their inactivity window; one-time "guest" borrows do not (their fixed
|
||||
// expires_at caps the borrow at QR_GUEST_TTL). Identity is enriched from the
|
||||
// accounts row when present, else falls back to the bare user_id.
|
||||
func (s *Server) refreshSelfSession(w http.ResponseWriter, r *http.Request, sess db.WebSession, rawCookie string, now time.Time) {
|
||||
token, expiresIn, err := s.mintSessionToken(sess.UserID, sess.ID, sess.Scope)
|
||||
if err != nil {
|
||||
slog.Error("mint session token failed", "err", err)
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "mint failed"})
|
||||
return
|
||||
}
|
||||
if sess.Kind == "self" {
|
||||
newExp := now.Add(time.Duration(s.cfg.QRPersistTTLHours) * time.Hour)
|
||||
if err := s.queries.SlideWebSession(r.Context(), db.SlideWebSessionParams{
|
||||
LastUsedAt: now.Unix(),
|
||||
ExpiresAt: newExp.Unix(),
|
||||
ID: sess.ID,
|
||||
}); err != nil {
|
||||
slog.Error("slide web session failed", "err", err)
|
||||
}
|
||||
setSessionCookie(w, rawCookie)
|
||||
}
|
||||
user := userResp{ID: sess.UserID, Name: sess.UserID}
|
||||
if acct, err := s.queries.GetAccount(r.Context(), sess.UserID); err == nil {
|
||||
if acct.DisplayName != "" {
|
||||
user.Name = acct.DisplayName
|
||||
}
|
||||
user.Avatar = acct.AvatarUrl
|
||||
}
|
||||
writeJSON(w, http.StatusOK, refreshResp{
|
||||
AccessToken: token,
|
||||
ExpiresIn: expiresIn,
|
||||
User: user,
|
||||
DeviceName: sess.DeviceName,
|
||||
})
|
||||
}
|
||||
|
||||
var oidcHTTPClient = &http.Client{Timeout: 10 * time.Second}
|
||||
|
||||
func postOIDCToken(ctx interface{ Done() <-chan struct{} }, tokenURL string, form url.Values) (*tokenResp, error) {
|
||||
@@ -304,11 +358,22 @@ func postOIDCToken(ctx interface{ Done() <-chan struct{} }, tokenURL string, for
|
||||
return &tr, nil
|
||||
}
|
||||
|
||||
// extractUser parses {sub, preferred_username | name} from the id_token if
|
||||
// available, else falls back to access_token. We DON'T verify the signature
|
||||
// here — the backend's auth middleware verifies access_token on every API
|
||||
// call via the JWKS cache, so any tamper would surface there.
|
||||
func extractUser(idToken, accessToken string) (userResp, error) {
|
||||
// tokenIdentity is what cdrop reads out of an OIDC id_token at login: the display
|
||||
// identity plus the thin-account fields — match_key (for the admin-gated migration
|
||||
// relink) and roles (the groups claim cache). AUTH.md §2.1.
|
||||
type tokenIdentity struct {
|
||||
User userResp
|
||||
MatchKey string
|
||||
Roles []string
|
||||
}
|
||||
|
||||
// extractIdentity parses {sub, preferred_username | name | email, avatar | picture,
|
||||
// matchClaim, groups} from the id_token if available, else the access_token. The
|
||||
// signature is NOT verified here — for OIDC sessions the auth middleware verifies
|
||||
// the access_token on every API call via JWKS, so any tamper surfaces there. (Once
|
||||
// OIDC sessions migrate to cdrop self-signed access tokens, this becomes the only
|
||||
// trust point and MUST then verify the id_token signature — AUTH.md §5.)
|
||||
func extractIdentity(idToken, accessToken, matchClaim string) (tokenIdentity, error) {
|
||||
pick := idToken
|
||||
if pick == "" {
|
||||
pick = accessToken
|
||||
@@ -319,31 +384,66 @@ func extractUser(idToken, accessToken string) (userResp, error) {
|
||||
jose.HS256,
|
||||
})
|
||||
if err != nil {
|
||||
return userResp{}, err
|
||||
return tokenIdentity{}, err
|
||||
}
|
||||
var std jwt.Claims
|
||||
custom := map[string]any{}
|
||||
if err := parsed.UnsafeClaimsWithoutVerification(&std, &custom); err != nil {
|
||||
return userResp{}, err
|
||||
return tokenIdentity{}, err
|
||||
}
|
||||
u := userResp{ID: std.Subject}
|
||||
id := tokenIdentity{User: userResp{ID: std.Subject}}
|
||||
if v, ok := custom["preferred_username"].(string); ok && v != "" {
|
||||
u.Name = v
|
||||
id.User.Name = v
|
||||
} else if v, ok := custom["name"].(string); ok && v != "" {
|
||||
u.Name = v
|
||||
id.User.Name = v
|
||||
} else if v, ok := custom["email"].(string); ok && v != "" {
|
||||
u.Name = v
|
||||
id.User.Name = v
|
||||
} else {
|
||||
u.Name = u.ID
|
||||
id.User.Name = id.User.ID
|
||||
}
|
||||
// Casdoor 的 OIDC id_token 暴露 avatar(自定义) 与 picture(标准 claim) 两种字段;
|
||||
// 不同 IdP 实现各异,所以都查一遍。值为空字符串视为未提供,前端落到字母方块回退。
|
||||
if v, ok := custom["avatar"].(string); ok && v != "" {
|
||||
u.Avatar = v
|
||||
id.User.Avatar = v
|
||||
} else if v, ok := custom["picture"].(string); ok && v != "" {
|
||||
u.Avatar = v
|
||||
id.User.Avatar = v
|
||||
}
|
||||
// match_key feeds the admin-gated cross-provider relink; pick the configured
|
||||
// claim (default email). Absent / non-string → empty, which simply never matches.
|
||||
if matchClaim != "" {
|
||||
if v, ok := custom[matchClaim].(string); ok {
|
||||
id.MatchKey = v
|
||||
}
|
||||
}
|
||||
if g, ok := custom["groups"].([]any); ok {
|
||||
for _, item := range g {
|
||||
if r, ok := item.(string); ok && r != "" {
|
||||
id.Roles = append(id.Roles, r)
|
||||
}
|
||||
}
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// upsertAccount refreshes the caller's thin accounts row from their OIDC identity
|
||||
// (AUTH.md §2.1). Best-effort — a write failure must never fail the login itself.
|
||||
func (s *Server) upsertAccount(ctx context.Context, id tokenIdentity) {
|
||||
if id.User.ID == "" {
|
||||
return
|
||||
}
|
||||
now := time.Now().Unix()
|
||||
if err := s.queries.UpsertAccount(ctx, db.UpsertAccountParams{
|
||||
UserID: id.User.ID,
|
||||
MatchKey: id.MatchKey,
|
||||
DisplayName: id.User.Name,
|
||||
AvatarUrl: id.User.Avatar,
|
||||
Roles: strings.Join(id.Roles, ","),
|
||||
Provider: "oidc",
|
||||
CreatedAt: now,
|
||||
LastLoginAt: now,
|
||||
}); err != nil {
|
||||
slog.Error("upsert account failed", "err", err, "user", id.User.ID)
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func truncate(s string, n int) string {
|
||||
|
||||
Reference in New Issue
Block a user