鉴权并入 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
-496
View File
@@ -1,496 +0,0 @@
package httpapi
import (
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"strings"
"time"
"github.com/go-jose/go-jose/v4"
"github.com/go-jose/go-jose/v4/jwt"
"commilitia.net/cdrop/internal/db"
)
// PROJECT_BRIEF.md §2 keeps the browser path on standard OIDC PKCE. Backend
// proxies the token endpoint so the browser doesn't need a CORS-friendly OIDC
// provider. The browser is then handed a cdrop self-signed access token (sid-bound
// to its web_sessions row), not the IdP's RS256 token, so OIDC web sessions verify
// statefully and revoke immediately — unified with scan-login (AUTH.md §5).
type authConfigResp struct {
AuthMode string `json:"auth_mode"`
AuthorizeURL string `json:"authorize_url"`
// TokenURL is published so native clients (the desktop app) can run their
// own loopback PKCE flow directly against the provider, reusing this same
// client_id. The browser doesn't need it — it proxies through /api/auth/exchange.
TokenURL string `json:"token_url"`
ClientID string `json:"client_id"`
RedirectURI string `json:"redirect_uri"`
Scopes string `json:"scopes"`
}
// handleAuthConfig publishes everything the frontend needs to start the PKCE
// authorize redirect. No auth required (it's all public OIDC metadata).
func (s *Server) handleAuthConfig(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, authConfigResp{
AuthMode: s.cfg.AuthMode,
AuthorizeURL: s.cfg.OIDCAuthorizeURL,
TokenURL: s.cfg.OIDCTokenURL,
ClientID: s.cfg.OIDCClientID,
RedirectURI: s.cfg.OIDCRedirectURI,
Scopes: s.cfg.OIDCScopes,
})
}
type exchangeReq struct {
Code string `json:"code"`
CodeVerifier string `json:"code_verifier"`
}
type tokenResp struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
IDToken string `json:"id_token"`
ExpiresIn int `json:"expires_in"`
TokenType string `json:"token_type"`
}
type userResp struct {
ID string `json:"id"`
Name string `json:"name"`
Avatar string `json:"avatar,omitempty"`
}
// exchangeResp deliberately omits refresh_token: the durable credential never
// reaches the browser. It's encrypted into the server-side web_sessions row and
// represented to the client only by the HttpOnly session cookie set alongside.
type exchangeResp struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
User userResp `json:"user"`
}
func (s *Server) handleAuthExchange(w http.ResponseWriter, r *http.Request) {
var req exchangeReq
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid json"})
return
}
if req.Code == "" || req.CodeVerifier == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "missing code or code_verifier"})
return
}
if s.cfg.OIDCTokenURL == "" {
writeJSON(w, http.StatusInternalServerError,
map[string]string{"error": "OIDC token URL not configured"})
return
}
form := url.Values{}
form.Set("grant_type", "authorization_code")
form.Set("code", req.Code)
form.Set("code_verifier", req.CodeVerifier)
form.Set("client_id", s.cfg.OIDCClientID)
form.Set("redirect_uri", s.cfg.OIDCRedirectURI)
// Casdoor's "cdrop" application is a confidential client; PKCE is layered
// on top of the standard secret. Skip the secret if not configured to keep
// public-client OIDC providers happy.
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("oidc exchange failed", "err", err)
writeJSON(w, http.StatusBadGateway, map[string]string{"error": err.Error()})
return
}
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)
// By default the browser holds a cdrop self-signed access token (sid-bound),
// not the IdP's RS256 token — so the OIDC web session is verified statefully on
// every request (verifySelfToken → web_sessions lookup) and revoking the row
// logs this device out on its very next call, exactly like scan-login. We mint
// it only after stashing the refresh_token server-side (encrypted, behind an
// HttpOnly cookie) so the session is durable. The IdP RS256 token stays the
// fallback for degraded configs (no encryption key / no refresh_token / an
// id_token that fails verification) — it is still independently verified per
// request via JWKS (verifyRS256), and the next refresh upgrades the device to
// the unified self-token model. (AUTH.md §5; desktop keeps its RS256 token.)
accessToken, expiresIn := tr.AccessToken, tr.ExpiresIn
if len(s.sessionKey) > 0 && tr.RefreshToken != "" {
id, cerr := s.createWebSession(r, w, user.ID, tr.RefreshToken)
if cerr != nil {
slog.Error("create web session failed", "err", cerr)
} else {
// The id_token is the SOLE trust anchor for the minted self token (the
// IdP RS256 token no longer reaches the browser to be re-verified), so
// its signature MUST validate here and its subject must match. On
// failure we keep the durable session but hand back the per-request-
// verified RS256 token; the next refresh upgrades this device to the
// self-token model. (Should not happen with a healthy IdP — warn ops.)
sub, _, verr := s.auth.VerifyIDToken(r.Context(), tr.IDToken)
if verr != nil || sub != user.ID {
slog.Warn("oidc id_token verification failed; using RS256 fallback",
"err", verr, "sub_match", sub == user.ID)
} else if tok, ein, merr := s.mintSessionToken(user.ID, id, "full"); merr != nil {
slog.Error("mint session token failed", "err", merr)
} else {
accessToken, expiresIn = tok, ein
}
}
}
writeJSON(w, http.StatusOK, exchangeResp{
AccessToken: accessToken,
ExpiresIn: expiresIn,
User: user,
})
}
// createWebSession encrypts the refresh_token, persists a new session row, and
// sets the session cookie on the response. Returns the session row id so the
// caller can bind a cdrop self-signed access token to it (sid).
func (s *Server) createWebSession(r *http.Request, w http.ResponseWriter, userID, refreshToken string) (string, error) {
raw, id, err := newSessionToken()
if err != nil {
return "", err
}
enc, err := s.encryptRefresh(refreshToken)
if err != nil {
return "", err
}
now := time.Now()
if err := s.queries.CreateWebSession(r.Context(), db.CreateWebSessionParams{
ID: id,
UserID: userID,
RefreshToken: enc,
DeviceName: "",
UserAgent: truncate(r.UserAgent(), 256),
CreatedAt: now.Unix(),
LastUsedAt: now.Unix(),
ExpiresAt: now.Add(webSessionTTL).Unix(),
}); err != nil {
return "", err
}
setSessionCookie(w, raw)
return id, nil
}
// refreshResp is what the browser sees: a fresh access_token plus the identity
// and device name recovered from the session. No refresh_token — it stays
// server-side. This same endpoint, called with the cookie and no body on app
// boot, IS the passwordless re-login path.
type refreshResp struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
User userResp `json:"user"`
DeviceName string `json:"device_name"`
}
func (s *Server) handleAuthRefresh(w http.ResponseWriter, r *http.Request) {
if s.cfg.OIDCTokenURL == "" {
writeJSON(w, http.StatusInternalServerError,
map[string]string{"error": "OIDC token URL not configured"})
return
}
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 == "" {
clearSessionCookie(w)
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "no session"})
return
}
id := sessionID(c.Value)
// Serialise concurrent refreshes of this session, then read the row INSIDE the
// lock: a racing tab may already have rotated the refresh_token, and we must
// spend the current one, not a stale copy the IdP would reject.
unlock := s.lockRefresh(id)
defer unlock()
sess, err := s.queries.GetWebSession(r.Context(), id)
if err != nil {
// Unknown / deleted session → not authenticated. Clear the stale cookie.
clearSessionCookie(w)
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "invalid session"})
return
}
now := time.Now()
if sess.ExpiresAt < now.Unix() {
_ = s.queries.DeleteWebSession(r.Context(), id)
clearSessionCookie(w)
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.
_ = s.queries.DeleteWebSession(r.Context(), id)
clearSessionCookie(w)
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "invalid session"})
return
}
form := url.Values{}
form.Set("grant_type", "refresh_token")
form.Set("refresh_token", refreshToken)
form.Set("client_id", s.cfg.OIDCClientID)
if s.cfg.OIDCClientSecret != "" {
form.Set("client_secret", s.cfg.OIDCClientSecret)
}
tr, err := postOIDCToken(r.Context(), s.cfg.OIDCTokenURL, form)
if err != nil {
// The IdP rejected the refresh_token (expired / revoked) — the session is
// dead end to end, so destroy it rather than leave a row that always 401s.
slog.Warn("oidc refresh failed", "err", err)
_ = s.queries.DeleteWebSession(r.Context(), id)
clearSessionCookie(w)
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "refresh rejected"})
return
}
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.
newRefresh := tr.RefreshToken
if newRefresh == "" {
newRefresh = refreshToken
}
if enc, encErr := s.encryptRefresh(newRefresh); encErr == nil {
if err := s.queries.RotateWebSession(r.Context(), db.RotateWebSessionParams{
RefreshToken: enc,
LastUsedAt: now.Unix(),
ExpiresAt: now.Add(webSessionTTL).Unix(),
ID: id,
}); err != nil {
slog.Error("rotate web session failed", "err", err)
}
} else {
slog.Error("encrypt rotated refresh token failed", "err", encErr)
}
setSessionCookie(w, c.Value)
// Hand back a cdrop self-signed access token (sid-bound), not the IdP RS256
// token: the browser holds one uniform token type and revoking the session row
// logs this device out on its next request. The IdP round-trip above still ran
// — it rotated the refresh_token and surfaced IdP-side revocation (a rejected
// refresh deletes the session above) — its access_token simply no longer ships.
// Mint from the row's canonical user_id; degrade to the IdP token only if the
// HS256 key is unconfigured. (AUTH.md §5.)
accessToken, expiresIn := tr.AccessToken, tr.ExpiresIn
if tok, ein, mErr := s.mintSessionToken(sess.UserID, id, "full"); mErr != nil {
slog.Error("mint session token failed", "err", mErr)
} else {
accessToken, expiresIn = tok, ein
}
writeJSON(w, http.StatusOK, refreshResp{
AccessToken: accessToken,
ExpiresIn: expiresIn,
User: user,
DeviceName: sess.DeviceName,
})
}
// 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) {
req, err := http.NewRequest(http.MethodPost, tokenURL, strings.NewReader(form.Encode()))
if err != nil {
return nil, fmt.Errorf("build request: %w", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json")
resp, err := oidcHTTPClient.Do(req)
if err != nil {
return nil, fmt.Errorf("oidc unreachable: %w", err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("oidc status %d: %s", resp.StatusCode, truncate(string(body), 200))
}
var tr tokenResp
if err := json.Unmarshal(body, &tr); err != nil {
return nil, fmt.Errorf("oidc malformed: %w", err)
}
if tr.AccessToken == "" {
return nil, fmt.Errorf("oidc returned no access_token")
}
return &tr, nil
}
// 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 — callers verify separately around it: at login
// (handleAuthExchange) the id_token signature is checked via VerifyIDToken before
// the extracted subject is trusted to mint a self token; at refresh the IdP just
// authenticated the refresh_token over a TLS back-channel, so the token it returns
// is trusted by transport. Either way the extracted fields are sound. (AUTH.md §5.)
func extractIdentity(idToken, accessToken, matchClaim string) (tokenIdentity, error) {
pick := idToken
if pick == "" {
pick = accessToken
}
parsed, err := jwt.ParseSigned(pick, []jose.SignatureAlgorithm{
jose.RS256, jose.RS384, jose.RS512,
jose.ES256, jose.ES384, jose.ES512,
jose.HS256,
})
if err != nil {
return tokenIdentity{}, err
}
var std jwt.Claims
custom := map[string]any{}
if err := parsed.UnsafeClaimsWithoutVerification(&std, &custom); err != nil {
return tokenIdentity{}, err
}
id := tokenIdentity{User: userResp{ID: std.Subject}}
if v, ok := custom["preferred_username"].(string); ok && v != "" {
id.User.Name = v
} else if v, ok := custom["name"].(string); ok && v != "" {
id.User.Name = v
} else if v, ok := custom["email"].(string); ok && v != "" {
id.User.Name = v
} else {
id.User.Name = id.User.ID
}
// Casdoor 的 OIDC id_token 暴露 avatar(自定义) 与 picture(标准 claim) 两种字段;
// 不同 IdP 实现各异,所以都查一遍。值为空字符串视为未提供,前端落到字母方块回退。
if v, ok := custom["avatar"].(string); ok && v != "" {
id.User.Avatar = v
} else if v, ok := custom["picture"].(string); ok && 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)
}
}
func truncate(s string, n int) string {
if len(s) <= n {
return s
}
return s[:n] + "…"
}
-57
View File
@@ -1,57 +0,0 @@
package httpapi
import (
"testing"
"time"
"github.com/go-jose/go-jose/v4"
"github.com/go-jose/go-jose/v4/jwt"
)
// extractIdentity pulls the display identity plus the thin-account fields
// (match_key from the configured claim, roles from groups) out of an id_token.
// It does not verify the signature, so a throwaway HS256 key suffices here.
func TestExtractIdentity(t *testing.T) {
key := []byte("any-throwaway-signing-key-32-bytes!!")
sig, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.HS256, Key: key}, (&jose.SignerOptions{}).WithType("JWT"))
if err != nil {
t.Fatalf("signer: %v", err)
}
tok, err := jwt.Signed(sig).
Claims(jwt.Claims{Subject: "sub-123", Expiry: jwt.NewNumericDate(time.Now().Add(time.Hour))}).
Claims(map[string]any{
"preferred_username": "alice",
"email": "alice@example.net",
"avatar": "https://a/av.png",
"groups": []any{"admins", "staff"},
}).Serialize()
if err != nil {
t.Fatalf("sign: %v", err)
}
id, err := extractIdentity(tok, "", "email")
if err != nil {
t.Fatalf("extract: %v", err)
}
if id.User.ID != "sub-123" || id.User.Name != "alice" || id.User.Avatar != "https://a/av.png" {
t.Errorf("user wrong: %+v", id.User)
}
if id.MatchKey != "alice@example.net" {
t.Errorf("match_key: got %q, want alice@example.net", id.MatchKey)
}
if len(id.Roles) != 2 || id.Roles[0] != "admins" || id.Roles[1] != "staff" {
t.Errorf("roles: got %v, want [admins staff]", id.Roles)
}
// No name claim → falls back to sub; absent match claim → empty (never matches).
tok2, _ := jwt.Signed(sig).
Claims(jwt.Claims{Subject: "sub-x", Expiry: jwt.NewNumericDate(time.Now().Add(time.Hour))}).
Serialize()
id2, err := extractIdentity(tok2, "", "email")
if err != nil {
t.Fatalf("extract2: %v", err)
}
if id2.User.Name != "sub-x" || id2.MatchKey != "" || len(id2.Roles) != 0 {
t.Errorf("fallback wrong: %+v", id2)
}
}
+158
View File
@@ -0,0 +1,158 @@
package httpapi
import (
"encoding/json"
"log/slog"
"net/http"
"strings"
"time"
"commilitia.net/cdrop/internal/brokerclient"
"commilitia.net/cdrop/internal/db"
"commilitia.net/cdrop/internal/jwtauth"
)
// 代铸 (proxy-mint). The unified-session-model endpoint that makes every login — browser
// global-SSO and native device-authorize alike — a cdrop-managed device session, so all
// clients share one device list and one management surface.
//
// The caller has already been verified at the edge (X-Auth-Subject) by either a global-SSO
// cookie (browser) or a device-authorize bootstrap token (desktop/native). cdrop vouches for
// that subject and asks the broker (R2: idempotent by user+app+meta) to mint or rotate a
// device session bound to the client's stable device_id. Re-logins with the same device_id
// rotate the same session instead of piling up — the same trust model as scan-login collect.
type deviceSessionReq struct {
// DeviceID is the client's stable opaque id (persisted client-side). Empty on first
// contact — the server then mints one and returns it for the client to persist.
DeviceID string `json:"device_id"`
DeviceName string `json:"device_name"`
DeviceType string `json:"device_type"` // browser | macos | windows | linux | ios
}
type deviceSessionResp struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
ExpiresIn int `json:"expires_in"`
DeviceID string `json:"device_id"`
DeviceName string `json:"device_name"`
// UserID + Name + Avatar are the verified identity (X-Auth-Subject / X-Auth-Name /
// X-Auth-Avatar). They let a native client — which only ever sees nameless machine
// tokens — populate its identity with the real display name and picture instead of the
// subject UUID, without a /api/me round-trip.
UserID string `json:"user_id"`
Name string `json:"name"`
Avatar string `json:"avatar,omitempty"`
}
// handleDeviceSession mints (or idempotently rotates) the caller's cdrop device session.
func (s *Server) handleDeviceSession(w http.ResponseWriter, r *http.Request) {
// CSRF: a cookie-authenticated browser fetch carries a matching Origin; a cross-site
// forgery would not (blocking forged mints that would reintroduce phantom devices). The
// desktop's Go-initiated call sends no Origin and is allowed.
if !s.sameOrigin(r) {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "bad origin"})
return
}
claims, _ := jwtauth.ClaimsFromContext(r.Context())
var req deviceSessionReq
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&req); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid json"})
return
}
deviceID := strings.TrimSpace(req.DeviceID)
if deviceID == "" {
var err error
if deviceID, err = newDeviceID(); err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "id gen"})
return
}
} else if !validDeviceID(deviceID) {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid device_id"})
return
}
deviceName := jwtauth.SanitizeDeviceName(req.DeviceName)
if deviceName == "" {
deviceName = "New device"
}
deviceType := qrDeviceType(req.DeviceType)
// Mint at the caller's current trust tier: an SSO / device-authorize login is full, a
// restricted guest stays guest. This stops a borrowed (guest) browser from minting
// itself a full device session.
tier := "full"
if claims.Guest() {
tier = "guest"
}
accessTTL, refreshTTL := s.tierTTLs(tier)
sess, err := s.broker.MintSession(r.Context(), brokerclient.MintParams{
UserID: claims.UserID,
Tier: tier,
AccessTTL: accessTTL,
RefreshTTL: refreshTTL,
Sliding: true,
Label: deviceName,
Meta: deviceID,
})
if err != nil {
slog.Error("device-session mint failed", "err", err, "user", claims.UserID)
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: claims.UserID,
Name: deviceName,
Type: deviceType,
Tier: tier,
BrokerSid: sess.SID,
CreatedAt: now,
LastSeen: now,
}); err != nil {
// The session is minted and usable; a failed cache-row write only costs the local
// type/presence overlay, so proceed rather than strand the device without tokens.
slog.Error("device-session cache write failed", "err", err, "user", claims.UserID, "device", deviceID)
}
name := claims.Name
if name == "" {
name = claims.UserID
}
expiresIn := int(sess.AccessExpires - now)
if expiresIn < 0 {
expiresIn = 0
}
writeJSON(w, http.StatusOK, deviceSessionResp{
AccessToken: sess.Access,
RefreshToken: sess.Refresh,
ExpiresIn: expiresIn,
DeviceID: deviceID,
DeviceName: deviceName,
UserID: claims.UserID,
Name: name,
Avatar: claims.Avatar,
})
}
// validDeviceID accepts a cdrop device_id: the "dev_" prefix plus pure [A-Za-z0-9_-], capped
// in length. This both recognises cdrop's own ids (newDeviceID) and guarantees the value is
// control-byte-free, so it is safe to pass to the broker as meta (echoed into X-Auth-Meta).
func validDeviceID(id string) bool {
if !strings.HasPrefix(id, "dev_") || len(id) > 128 {
return false
}
for _, c := range id {
switch {
case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c >= '0' && c <= '9', c == '_', c == '-':
default:
return false
}
}
return true
}
+48 -19
View File
@@ -1,6 +1,7 @@
package httpapi
import (
"encoding/json"
"log/slog"
"net/http"
@@ -11,8 +12,10 @@ import (
)
type deviceItem struct {
DeviceID string `json:"device_id"`
Name string `json:"name"`
Type string `json:"type"`
Tier string `json:"tier"`
Online bool `json:"online"`
LastSeen int64 `json:"last_seen"`
}
@@ -32,8 +35,10 @@ func (s *Server) handleDevices(w http.ResponseWriter, r *http.Request) {
out := make([]deviceItem, 0, len(devs))
for _, d := range devs {
out = append(out, deviceItem{
DeviceID: d.DeviceID,
Name: d.Name,
Type: d.Type,
Tier: d.Tier,
Online: s.hub.Online(claims.UserID, d.Name),
LastSeen: d.LastSeen,
})
@@ -41,40 +46,64 @@ func (s *Server) handleDevices(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"devices": out})
}
// handleDeleteDevice 注销设备:删除 (user, name) 行 + Kick 在线 SSE + 立刻广播
// 新的 presence。请求方若注销的是自己当前设备,前端需同步调用 logout,否则
// 任何后续带 X-Device-Name 的认证请求都会被中间件再次 UPSERT 回来。
//
// 这是登录会话列表里「原生客户端(桌面 / iOS)」一栏的登出路径——它们用 IdP 令牌、
// 不入 web_sessions,故按设备名吊销(AUTH.md §4)。注销设备属敏感动作,与吊销网页
// 会话同口径要求最近一次 step-up403 step_up_required,前端据此发起再认证)。
// handleDeleteDevice removes a device: it revokes the device's broker session (so it
// can no longer refresh and dies within its short access TTL), then drops the local
// row, kicks its live SSE, and re-broadcasts presence. Identified by the stable
// device_id; the caller must own it. A full session is required (route-gated) — the
// old step-up requirement is gone, since a full-tier session is itself trusted.
func (s *Server) handleDeleteDevice(w http.ResponseWriter, r *http.Request) {
if s.cfg.StepUpEnabled && !s.sessionRecentlySteppedUp(r) {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "step_up_required"})
claims, _ := jwtauth.ClaimsFromContext(r.Context())
deviceID := chi.URLParam(r, "device_id")
if deviceID == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "missing device id"})
return
}
status, ok := s.revokeDevice(r, claims.UserID, deviceID)
if !ok {
writeJSON(w, status, map[string]string{"error": revokeErrorMsg(status)})
return
}
w.WriteHeader(http.StatusNoContent)
}
type renameDeviceReq struct {
Name string `json:"name"`
}
// handleRenameDevice changes a device's human-readable name. The device's identity is
// device_id, so a rename never changes which session / row it is — fixing the old
// model where the name was the key and renaming meant losing the device. Full session.
func (s *Server) handleRenameDevice(w http.ResponseWriter, r *http.Request) {
claims, _ := jwtauth.ClaimsFromContext(r.Context())
name := chi.URLParam(r, "name")
deviceID := chi.URLParam(r, "device_id")
if deviceID == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "missing device id"})
return
}
var body renameDeviceReq
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&body); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid json"})
return
}
name := jwtauth.SanitizeDeviceName(body.Name)
if name == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "missing device name"})
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "empty device name"})
return
}
rows, err := s.queries.DeleteDevice(r.Context(), db.DeleteDeviceParams{
UserID: claims.UserID,
Name: name,
n, err := s.queries.RenameDevice(r.Context(), db.RenameDeviceParams{
Name: name,
DeviceID: deviceID,
UserID: claims.UserID,
})
if err != nil {
slog.Error("delete device failed", "err", err, "user", claims.UserID, "name", name)
slog.Error("rename device failed", "err", err, "user", claims.UserID, "device", deviceID)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "db"})
return
}
if rows == 0 {
if n == 0 {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "device not found"})
return
}
s.hub.Kick(claims.UserID, name)
s.hub.PublishPresence(r.Context(), claims.UserID)
w.WriteHeader(http.StatusNoContent)
}
+59
View File
@@ -0,0 +1,59 @@
package httpapi
import (
"net/http"
"net/url"
"strings"
)
type authConfigResp struct {
AuthMode string `json:"auth_mode"`
BrokerURL string `json:"broker_url"`
BrokerApp string `json:"broker_app"`
}
// handleAuthConfig publishes the Auth Broker coordinates native clients (the desktop)
// need to run the broker device-authorization flow: the broker's public URL + this
// app's key in the broker apps registry. Public (it bootstraps native login).
func (s *Server) handleAuthConfig(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, authConfigResp{
AuthMode: s.cfg.AuthMode,
BrokerURL: s.cfg.BrokerPublicURL,
BrokerApp: s.cfg.BrokerAppOrDefault(),
})
}
// handleAuthLogin 302-redirects the browser to the Auth Broker's public login page
// for global SSO (the broker handles Casdoor and sets its domain cookie; on return the
// edge injects X-Auth from that cookie). cdrop owns this redirect so the broker's
// public URL lives in one server-side config. Public (it bootstraps login). The rd
// (return target) is constrained to this deployment's own origin — an open-redirect
// guard — defaulting to the site root.
func (s *Server) handleAuthLogin(w http.ResponseWriter, r *http.Request) {
if s.cfg.BrokerPublicURL == "" {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "login redirect not configured"})
return
}
rd := s.safeReturnTarget(r.URL.Query().Get("rd"))
dest := strings.TrimRight(s.cfg.BrokerPublicURL, "/") + "/login?rd=" + url.QueryEscape(rd)
http.Redirect(w, r, dest, http.StatusFound)
}
// safeReturnTarget validates a post-login return URL against this deployment's origin,
// falling back to the site root. It blocks open redirects: only a same-origin absolute
// URL (or, when no site origin is configured in dev, a site-relative path) is accepted.
func (s *Server) safeReturnTarget(rd string) string {
if s.siteOrigin == "" {
// dev: accept only a site-relative path, never an absolute URL.
if strings.HasPrefix(rd, "/") && !strings.HasPrefix(rd, "//") {
return rd
}
return "/"
}
if u, err := url.Parse(rd); err == nil && u.Scheme != "" && u.Host != "" {
if u.Scheme+"://"+u.Host == s.siteOrigin {
return rd
}
}
return s.siteOrigin + "/"
}
+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
}
+330 -354
View File
@@ -13,21 +13,115 @@ import (
"time"
"github.com/go-chi/chi/v5"
"github.com/go-jose/go-jose/v4"
"github.com/go-jose/go-jose/v4/jwt"
"commilitia.net/cdrop/internal/brokerclient"
"commilitia.net/cdrop/internal/config"
"commilitia.net/cdrop/internal/db"
"commilitia.net/cdrop/internal/hub"
"commilitia.net/cdrop/internal/jwtauth"
)
const qrTestSecret = "qr-test-session-secret-at-least-32-bytes"
// mockBrokerState records what the fake Auth Broker was asked to do, so tests can
// assert cdrop delegated correctly (mint params, revoke + its X-Broker-App scope).
type mockBrokerState struct {
mintCount int
lastMint map[string]any
revoked map[string]bool
lastRevokeApp string
// sessions holds the live (non-revoked) delegated sessions keyed by sid, so the mock
// can answer R1 (GET /internal/sessions) and enforce R2 idempotency (same user+app+meta
// → same sid).
sessions map[string]*mockSession
}
// newQRTestServer builds a Server with only the fields the scan-login handlers
// touch, backed by a fresh file-based sqlite (an in-memory DB would give each
// pooled connection its own empty schema).
func newQRTestServer(t *testing.T) *Server {
type mockSession struct {
sid, userID, app, meta, label, scope string
createdAt, lastUsedAt int64
}
// newMockBroker stands in for the Auth Broker's internal API: POST /internal/sessions
// mints (R2-idempotent by user+app+meta) a session, GET /internal/sessions lists the
// user's live machine sessions (R1), and DELETE /internal/sessions/{sid} revokes one.
func newMockBroker(t *testing.T) (*brokerclient.Client, *mockBrokerState) {
t.Helper()
st := &mockBrokerState{revoked: map[string]bool{}, sessions: map[string]*mockSession{}}
str := func(m map[string]any, k string) string {
if v, ok := m[k].(string); ok {
return v
}
return ""
}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == http.MethodPost && r.URL.Path == "/internal/sessions":
st.mintCount += 1
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
st.lastMint = body
userID, app, meta, label, tier := str(body, "user_id"), str(body, "app"), str(body, "meta"), str(body, "label"), str(body, "tier")
scope := "app:" + app
if tier != "" {
scope += ":" + tier
}
// R2 idempotency: same (user, app, meta) with non-empty meta rotates in place.
sid := ""
if meta != "" {
for _, sess := range st.sessions {
if !st.revoked[sess.sid] && sess.userID == userID && sess.app == app && sess.meta == meta {
sid = sess.sid
break
}
}
}
if sid == "" {
sid = fmt.Sprintf("sid-%d", st.mintCount)
}
now := time.Now().Unix()
created := now
if existing, ok := st.sessions[sid]; ok {
created = existing.createdAt // rotation preserves CreatedAt
}
st.sessions[sid] = &mockSession{sid: sid, userID: userID, app: app, meta: meta, label: label, scope: scope, createdAt: created, lastUsedAt: now}
_ = json.NewEncoder(w).Encode(map[string]any{
"id": sid, "app": "cdrop",
"access": "acc-" + sid, "refresh": "rtk-" + sid,
"access_expires": time.Now().Add(15 * time.Minute).Unix(),
"refresh_expires": time.Now().Add(24 * time.Hour).Unix(),
})
case r.Method == http.MethodGet && r.URL.Path == "/internal/sessions":
q := r.URL.Query()
userID, app := q.Get("user_id"), q.Get("app")
if userID == "" || app == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
out := []map[string]any{}
for _, sess := range st.sessions {
if st.revoked[sess.sid] || sess.userID != userID || sess.app != app {
continue
}
out = append(out, map[string]any{
"id": sess.sid, "scope": sess.scope, "label": sess.label, "meta": sess.meta,
"created_at": sess.createdAt, "last_used_at": sess.lastUsedAt,
"expires_at": time.Now().Add(24 * time.Hour).Unix(),
})
}
_ = json.NewEncoder(w).Encode(map[string]any{"sessions": out})
case r.Method == http.MethodDelete && strings.HasPrefix(r.URL.Path, "/internal/sessions/"):
st.revoked[strings.TrimPrefix(r.URL.Path, "/internal/sessions/")] = true
st.lastRevokeApp = r.Header.Get("X-Broker-App")
w.WriteHeader(http.StatusNoContent)
default:
http.NotFound(w, r)
}
}))
t.Cleanup(srv.Close)
return brokerclient.New(srv.URL, "test-key", "cdrop"), st
}
// newQRTestServer builds a Server with only the fields the scan-login + device
// handlers touch, backed by a fresh file-based sqlite and a mock broker.
func newQRTestServer(t *testing.T) (*Server, *mockBrokerState) {
t.Helper()
conn, err := db.Open(filepath.Join(t.TempDir(), "qr.db"))
if err != nil {
@@ -38,19 +132,24 @@ func newQRTestServer(t *testing.T) *Server {
t.Fatalf("bootstrap: %v", err)
}
q := db.New(conn)
return &Server{
broker, st := newMockBroker(t)
s := &Server{
cfg: &config.Config{
AuthMode: "prod", SessionSecret: qrTestSecret,
QRLoginEnabled: true, QRRequestTTLSeconds: 120,
QRGuestTTLSeconds: 3600, QRPersistTTLHours: 168,
SessionTokenTTLSeconds: 900,
AuthMode: "prod",
QRLoginEnabled: true,
QRRequestTTLSeconds: 120,
FullAccessTTLSeconds: 900,
FullRefreshTTLSeconds: 604800,
GuestAccessTTLSeconds: 900,
GuestRefreshTTLSeconds: 86400,
BrokerBaseURL: "http://broker", // non-empty so QRLoginOn() is true
},
queries: q,
hub: hub.New(q),
sessionKey: deriveSessionKey(qrTestSecret),
sessionTokenKey: jwtauth.DeriveSessionTokenKey(qrTestSecret),
siteOrigin: "https://drop.example.net",
queries: q,
hub: hub.New(q),
broker: broker,
siteOrigin: "https://drop.example.net",
}
return s, st
}
func qrStart(t *testing.T, s *Server, deviceName string) (qrStartResp, string) {
@@ -73,11 +172,11 @@ func qrStart(t *testing.T, s *Server, deviceName string) (qrStartResp, string) {
return resp, u.Query().Get("c")
}
func qrApprove(t *testing.T, s *Server, requestID, code, persist, approver string) int {
func qrApprove(t *testing.T, s *Server, requestID, code, scope, persist, approver string) int {
t.Helper()
body := fmt.Sprintf(`{"request_id":%q,"approval_code":%q,"scope":"guest","persist":%q}`, requestID, code, persist)
body := fmt.Sprintf(`{"request_id":%q,"approval_code":%q,"scope":%q,"persist":%q}`, requestID, code, scope, persist)
r := httptest.NewRequest(http.MethodPost, "/api/auth/qr/approve", strings.NewReader(body))
r = r.WithContext(jwtauth.ContextWithClaims(r.Context(), &jwtauth.Claims{UserID: approver, SessionScope: "full"}))
r = r.WithContext(jwtauth.ContextWithClaims(r.Context(), &jwtauth.Claims{UserID: approver, Scope: "full"}))
w := httptest.NewRecorder()
s.handleQRApprove(w, r)
return w.Code
@@ -100,14 +199,15 @@ func decodeStatus(t *testing.T, w *httptest.ResponseRecorder) qrStatusResp {
return resp
}
// The happy path: a new device starts a request, the approver authorises it as a
// one-time guest, and the new device collects a live guest session — cookie set,
// access token minted, request single-use thereafter.
// Happy path: a new device starts a request, the approver authorises it as a guest,
// and the new device collects a live guest session minted by the broker — broker
// access + refresh handed back, a device row recorded with the broker sid, the mint
// scoped to the device_id, and the request single-use thereafter.
func TestQRFlow_ApproveCollectGuestSingleUse(t *testing.T) {
s := newQRTestServer(t)
s, st := newQRTestServer(t)
start, code := qrStart(t, s, "Borrowed Laptop")
if c := qrApprove(t, s, start.RequestID, code, "once", "approver-1"); c != http.StatusNoContent {
if c := qrApprove(t, s, start.RequestID, code, "guest", "once", "approver-1"); c != http.StatusNoContent {
t.Fatalf("approve: got %d, want 204", c)
}
@@ -116,34 +216,31 @@ func TestQRFlow_ApproveCollectGuestSingleUse(t *testing.T) {
t.Fatalf("status: %d %s", w.Code, w.Body.String())
}
got := decodeStatus(t, w)
if got.Status != "approved" || got.AccessToken == "" || got.DeviceName != "Borrowed Laptop" {
if got.Status != "approved" || got.AccessToken == "" || got.RefreshToken == "" {
t.Fatalf("collected status wrong: %+v", got)
}
if got.ExpiresIn != 900 {
t.Errorf("expires_in: got %d, want 900", got.ExpiresIn)
if got.DeviceName != "Borrowed Laptop" || got.DeviceID == "" {
t.Fatalf("collected device wrong: %+v", got)
}
var hasCookie bool
for _, ck := range w.Result().Cookies() {
if ck.Name == sessionCookieName && ck.Value != "" {
hasCookie = true
}
}
if !hasCookie {
t.Error("collection must set the session cookie on the new device's response")
if !strings.HasPrefix(got.DeviceID, "dev_") {
t.Errorf("device_id not opaque dev_ token: %q", got.DeviceID)
}
// The minted token is a properly signed guest session token.
if scope := selfTokenScope(t, got.AccessToken); scope != "guest" {
t.Fatalf("minted token scope: got %q, want guest", scope)
// The broker was asked to mint at tier guest with our device_id as meta.
if st.mintCount != 1 {
t.Fatalf("mint count: got %d, want 1", st.mintCount)
}
if st.lastMint["tier"] != "guest" || st.lastMint["meta"] != got.DeviceID {
t.Errorf("mint params wrong: %+v", st.lastMint)
}
// A guest (one-time) session row exists for the approver and is non-sliding.
rows, err := s.queries.ListWebSessionsByUser(context.Background(), "approver-1")
if err != nil || len(rows) != 1 {
t.Fatalf("expected one session row, got %d (err=%v)", len(rows), err)
// A device row exists for the approver, tier guest, bound to the broker sid.
dev, err := s.queries.GetDevice(context.Background(), got.DeviceID)
if err != nil {
t.Fatalf("device row missing: %v", err)
}
if rows[0].Kind != "guest" || rows[0].Scope != "guest" {
t.Errorf("session kind/scope: got %s/%s, want guest/guest", rows[0].Kind, rows[0].Scope)
if dev.UserID != "approver-1" || dev.Tier != "guest" || dev.BrokerSid != "sid-1" {
t.Errorf("device row wrong: %+v", dev)
}
// Single use: a second collection finds the request consumed.
@@ -152,288 +249,131 @@ func TestQRFlow_ApproveCollectGuestSingleUse(t *testing.T) {
}
}
// A persistent ("trust this device") approval yields a sliding self session.
func TestQRFlow_PersistYieldsSelfSession(t *testing.T) {
s := newQRTestServer(t)
// A full approval mints a full-tier session.
func TestQRFlow_ApproveCollectFull(t *testing.T) {
s, st := newQRTestServer(t)
start, code := qrStart(t, s, "Home PC")
if c := qrApprove(t, s, start.RequestID, code, "persist", "approver-2"); c != http.StatusNoContent {
if c := qrApprove(t, s, start.RequestID, code, "full", "persist", "approver-2"); c != http.StatusNoContent {
t.Fatalf("approve: got %d, want 204", c)
}
if got := decodeStatus(t, qrStatus(s, start.RequestID, start.PollSecret)); got.Status != "approved" {
t.Fatalf("collect: %+v", got)
got := decodeStatus(t, qrStatus(s, start.RequestID, start.PollSecret))
if got.Status != "approved" {
t.Fatalf("status: %+v", got)
}
rows, _ := s.queries.ListWebSessionsByUser(context.Background(), "approver-2")
if len(rows) != 1 || rows[0].Kind != "self" {
t.Fatalf("persistent approval must create a kind=self session, got %+v", rows)
if st.lastMint["tier"] != "full" {
t.Errorf("mint tier: got %v, want full", st.lastMint["tier"])
}
dev, err := s.queries.GetDevice(context.Background(), got.DeviceID)
if err != nil || dev.Tier != "full" {
t.Errorf("device row: %+v (err=%v)", dev, err)
}
}
// The poll_secret is the new device's only credential: a wrong one is rejected
// even for a real, approved request, so a QR photographer can't collect it.
func TestQRFlow_WrongPollSecretRejected(t *testing.T) {
s := newQRTestServer(t)
s, _ := newQRTestServer(t)
start, code := qrStart(t, s, "Laptop")
_ = qrApprove(t, s, start.RequestID, code, "once", "approver-3")
if w := qrStatus(s, start.RequestID, "not-the-secret"); w.Code != http.StatusForbidden {
t.Errorf("wrong poll secret: got %d, want 403", w.Code)
}
// The real secret still works afterwards (the bad attempt didn't consume it).
if got := decodeStatus(t, qrStatus(s, start.RequestID, start.PollSecret)); got.Status != "approved" {
t.Errorf("real secret after a bad attempt: got %q, want approved", got.Status)
_ = qrApprove(t, s, start.RequestID, code, "guest", "once", "approver-1")
w := qrStatus(s, start.RequestID, "not-the-secret")
if w.Code != http.StatusForbidden {
t.Fatalf("wrong poll secret: got %d, want 403", w.Code)
}
}
// Denial propagates to the polling device.
func TestQRFlow_Deny(t *testing.T) {
s := newQRTestServer(t)
s, _ := newQRTestServer(t)
start, code := qrStart(t, s, "Laptop")
body := fmt.Sprintf(`{"request_id":%q,"approval_code":%q}`, start.RequestID, code)
r := httptest.NewRequest(http.MethodPost, "/api/auth/qr/deny", strings.NewReader(body))
r = r.WithContext(jwtauth.ContextWithClaims(r.Context(), &jwtauth.Claims{UserID: "approver-4", SessionScope: "full"}))
r = r.WithContext(jwtauth.ContextWithClaims(r.Context(), &jwtauth.Claims{UserID: "approver-1", Scope: "full"}))
w := httptest.NewRecorder()
s.handleQRDeny(w, r)
if w.Code != http.StatusNoContent {
t.Fatalf("deny: got %d, want 204", w.Code)
}
if got := decodeStatus(t, qrStatus(s, start.RequestID, start.PollSecret)); got.Status != "denied" {
t.Errorf("status after deny: got %q, want denied", got.Status)
t.Errorf("after deny: got %q, want denied", got.Status)
}
}
// With step-up enabled, approving without a fresh re-auth is refused (the gate
// rejects an empty step-up proof before any IdP call). AUTH.md §6.
func TestQRFlow_StepUpRequiredRejectsWithoutReauth(t *testing.T) {
s := newQRTestServer(t)
s.cfg.StepUpEnabled = true
start, code := qrStart(t, s, "Laptop")
if c := qrApprove(t, s, start.RequestID, code, "once", "approver-su"); c != http.StatusForbidden {
t.Errorf("approve without step-up proof: got %d, want 403", c)
}
}
// A pending request long-polls then reports pending for the client to re-poll.
func TestQRFlow_PendingLongPoll(t *testing.T) {
saved := qrStatusPollWindow
old := qrStatusPollWindow
qrStatusPollWindow = 50 * time.Millisecond
defer func() { qrStatusPollWindow = saved }()
defer func() { qrStatusPollWindow = old }()
s := newQRTestServer(t)
s, _ := newQRTestServer(t)
start, _ := qrStart(t, s, "Laptop")
w := qrStatus(s, start.RequestID, start.PollSecret)
if got := decodeStatus(t, w); got.Status != "pending" {
t.Errorf("pending long-poll: got %q, want pending", got.Status)
got := decodeStatus(t, qrStatus(s, start.RequestID, start.PollSecret))
if got.Status != "pending" {
t.Errorf("unapproved long-poll: got %q, want pending", got.Status)
}
}
// noopAuthStore satisfies jwtauth.Store for middleware wiring in tests (no device
// upsert happens without an X-Device-Name header).
type noopAuthStore struct{}
func (noopAuthStore) UpsertDevice(context.Context, db.UpsertDeviceParams) error { return nil }
func (noopAuthStore) GetShortcutToken(context.Context, string) (db.ShortcutToken, error) {
return db.ShortcutToken{}, fmt.Errorf("none")
}
func (noopAuthStore) TouchShortcutTokenUsed(context.Context, db.TouchShortcutTokenUsedParams) error {
return nil
}
func (noopAuthStore) GetWebSession(_ context.Context, id string) (db.WebSession, error) {
return db.WebSession{ID: id}, nil // session always live in these tests
}
// End-to-end through the REAL chain (auth.Middleware → requireFullSession): a
// guest session token is rejected 403 on an account-management route, a full one
// passes. This is the backend enforcement behind AUTH.md §3.2 (guest can't approve
// devices / remove devices / mint tokens).
// requireFullSession lets a full session through and blocks a restricted guest.
func TestRequireFullSession_GuestBlockedFullPasses(t *testing.T) {
secret := "test-session-secret-at-least-32-bytes-ok"
srv := &Server{
cfg: &config.Config{SessionTokenTTLSeconds: 900},
sessionTokenKey: jwtauth.DeriveSessionTokenKey(secret),
}
guest, _, err := srv.mintSessionToken("u", "sid", "guest")
if err != nil {
t.Fatalf("mint guest: %v", err)
}
full, _, err := srv.mintSessionToken("u", "sid", "full")
if err != nil {
t.Fatalf("mint full: %v", err)
}
a := jwtauth.New(&config.Config{AuthMode: "prod", SessionSecret: secret}, noopAuthStore{})
handler := a.Middleware(requireFullSession(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
handler := requireFullSession(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
})))
probe := func(tok string) int {
r := httptest.NewRequest(http.MethodPost, "/api/auth/qr/approve", nil)
r.Header.Set("Authorization", "Bearer "+tok)
}))
check := func(scope string) int {
r := httptest.NewRequest(http.MethodGet, "/x", nil)
r = r.WithContext(jwtauth.ContextWithClaims(r.Context(), &jwtauth.Claims{UserID: "u", Scope: scope}))
w := httptest.NewRecorder()
handler.ServeHTTP(w, r)
return w.Code
}
if c := probe(guest); c != http.StatusForbidden {
t.Errorf("guest token on requireFullSession route: got %d, want 403", c)
if c := check("app:cdrop:guest"); c != http.StatusForbidden {
t.Errorf("guest on full-only route: got %d, want 403", c)
}
if c := probe(full); c != http.StatusOK {
t.Errorf("full token on requireFullSession route: got %d, want 200", c)
if c := check("app:cdrop:full"); c != http.StatusOK {
t.Errorf("full on full-only route: got %d, want 200", c)
}
}
// Revoking a session is sensitive: with step-up enabled it is refused (403
// step_up_required) until the caller's session has recently stepped up, then it
// proceeds (here to 400 missing-id, i.e. past the gate). Step-up state is keyed on
// the cookie session, so it is per-device (AUTH.md §1/§6).
func TestSessionRevoke_RequiresStepUp(t *testing.T) {
s := newQRTestServer(t)
s.cfg.StepUpEnabled = true
s.cfg.StepUpMaxAgeSeconds = 300
raw, id, err := newSessionToken()
if err != nil {
t.Fatalf("token: %v", err)
}
now := time.Now().Unix()
if err := s.queries.CreateSelfSession(context.Background(), db.CreateSelfSessionParams{
ID: id, UserID: "u", DeviceName: "", UserAgent: "", Kind: "oidc", Scope: "full",
GrantedBy: "", CreatedAt: now, LastUsedAt: now, ExpiresAt: now + 3600,
}); err != nil {
t.Fatalf("create session: %v", err)
// Deleting a device revokes its broker session (scoped by X-Broker-App) and drops the
// local row.
func TestDeleteDevice_RevokesBrokerSession(t *testing.T) {
s, st := newQRTestServer(t)
start, code := qrStart(t, s, "Old Phone")
_ = qrApprove(t, s, start.RequestID, code, "full", "persist", "owner")
got := decodeStatus(t, qrStatus(s, start.RequestID, start.PollSecret))
if got.DeviceID == "" {
t.Fatal("no device_id from collect")
}
revoke := func() int {
r := httptest.NewRequest(http.MethodDelete, "/api/auth/sessions/x", nil)
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: raw})
r = r.WithContext(jwtauth.ContextWithClaims(r.Context(),
&jwtauth.Claims{UserID: "u", SessionScope: "full"}))
w := httptest.NewRecorder()
s.handleSessionRevoke(w, r)
return w.Code
}
// Not stepped up → blocked before any deletion.
if c := revoke(); c != http.StatusForbidden {
t.Fatalf("revoke without step-up: got %d, want 403", c)
}
// Record step-up on this (cookie) session → gate now passes (400 = missing id,
// reached past the step-up check).
if err := s.queries.SetSessionSteppedUp(context.Background(), db.SetSessionSteppedUpParams{
SteppedUpAt: now, ID: id,
}); err != nil {
t.Fatalf("set stepped up: %v", err)
}
if c := revoke(); c == http.StatusForbidden {
t.Errorf("revoke after step-up still 403; gate did not honour stepped_up_at")
}
}
// selfTokenScope verifies a self-signed session token under the test's session
// key (proving the signature) and returns its scope claim.
func selfTokenScope(t *testing.T, token string) string {
t.Helper()
parsed, err := jwt.ParseSigned(token, []jose.SignatureAlgorithm{jose.HS256})
if err != nil {
t.Fatalf("parse token: %v", err)
}
var std jwt.Claims
custom := map[string]any{}
if err := parsed.Claims(jwtauth.DeriveSessionTokenKey(qrTestSecret), &std, &custom); err != nil {
t.Fatalf("verify token signature: %v", err)
}
if typ, _ := custom["typ"].(string); typ != "session" {
t.Fatalf("token typ: got %q, want session", typ)
}
scope, _ := custom["scope"].(string)
return scope
}
// revokeByID drives handleSessionRevoke with the chi {id} param and full claims,
// step-up off (the gate is exercised separately).
func revokeByID(s *Server, id, userID string) *httptest.ResponseRecorder {
r := httptest.NewRequest(http.MethodDelete, "/api/auth/sessions/"+id, nil)
r := httptest.NewRequest(http.MethodDelete, "/api/devices/"+got.DeviceID, nil)
r = r.WithContext(jwtauth.ContextWithClaims(r.Context(), &jwtauth.Claims{UserID: "owner", Scope: "full"}))
rctx := chi.NewRouteContext()
rctx.URLParams.Add("id", id)
ctx := context.WithValue(r.Context(), chi.RouteCtxKey, rctx)
ctx = jwtauth.ContextWithClaims(ctx, &jwtauth.Claims{UserID: userID, SessionScope: "full"})
rctx.URLParams.Add("device_id", got.DeviceID)
r = r.WithContext(context.WithValue(r.Context(), chi.RouteCtxKey, rctx))
w := httptest.NewRecorder()
s.handleSessionRevoke(w, r.WithContext(ctx))
return w
}
// Revoking a web session removes its device registration too, so a revoked device
// disappears from the device list at once (the user can no longer remove devices
// by hand). AUTH.md §4.
func TestSessionRevoke_DeletesDevice(t *testing.T) {
s := newQRTestServer(t) // step-up off by default
ctx := context.Background()
now := time.Now().Unix()
_, id, err := newSessionToken()
if err != nil {
t.Fatalf("token: %v", err)
}
if err := s.queries.CreateSelfSession(ctx, db.CreateSelfSessionParams{
ID: id, UserID: "u", DeviceName: "Laptop", UserAgent: "", Kind: "oidc", Scope: "full",
GrantedBy: "", CreatedAt: now, LastUsedAt: now, ExpiresAt: now + 3600,
}); err != nil {
t.Fatalf("create session: %v", err)
}
if err := s.queries.UpsertDevice(ctx, db.UpsertDeviceParams{
UserID: "u", Name: "Laptop", Type: "browser", LastSeen: now,
}); err != nil {
t.Fatalf("upsert device: %v", err)
s.handleDeleteDevice(w, r)
if w.Code != http.StatusNoContent {
t.Fatalf("delete device: got %d, want 204 (%s)", w.Code, w.Body.String())
}
if w := revokeByID(s, id, "u"); w.Code != http.StatusNoContent {
t.Fatalf("revoke: got %d %s, want 204", w.Code, w.Body.String())
if !st.revoked["sid-1"] {
t.Error("broker session sid-1 was not revoked")
}
if _, err := s.queries.GetWebSession(ctx, id); err == nil {
t.Errorf("session still present after revoke")
if st.lastRevokeApp != "cdrop" {
t.Errorf("revoke X-Broker-App: got %q, want cdrop", st.lastRevokeApp)
}
devs, _ := s.queries.ListDevicesByUser(ctx, "u")
for _, d := range devs {
if d.Name == "Laptop" {
t.Errorf("device 'Laptop' not deleted on session revoke")
}
if _, err := s.queries.GetDevice(context.Background(), got.DeviceID); err == nil {
t.Error("device row should be gone after delete")
}
}
// The session list unifies web_sessions with native client devices (desktop / iOS)
// that have no web_session, while never double-listing a device that already has a
// session and excluding shortcut-token devices. AUTH.md §4.
func TestSessionsList_IncludesNativeDevices(t *testing.T) {
s := newQRTestServer(t)
ctx := context.Background()
now := time.Now().Unix()
_, id, err := newSessionToken()
if err != nil {
t.Fatalf("token: %v", err)
}
if err := s.queries.CreateSelfSession(ctx, db.CreateSelfSessionParams{
ID: id, UserID: "u", DeviceName: "Web", UserAgent: "", Kind: "oidc", Scope: "full",
GrantedBy: "", CreatedAt: now, LastUsedAt: now, ExpiresAt: now + 3600,
}); err != nil {
t.Fatalf("create session: %v", err)
}
for _, d := range []struct{ name, typ string }{
{"Web", "browser"}, // has a web_session — must not be double-listed
{"Desk", "macos"}, // native, no session — must appear as native
{"iShortcut", "shortcut"}, // scoped token — excluded from session list
} {
if err := s.queries.UpsertDevice(ctx, db.UpsertDeviceParams{
UserID: "u", Name: d.name, Type: d.typ, LastSeen: now,
}); err != nil {
t.Fatalf("upsert device %s: %v", d.name, err)
}
}
// The session list surfaces the user's devices with their tier as scope.
func TestSessionsList_ShowsDevices(t *testing.T) {
s, _ := newQRTestServer(t)
start, code := qrStart(t, s, "Tablet")
_ = qrApprove(t, s, start.RequestID, code, "guest", "once", "owner")
got := decodeStatus(t, qrStatus(s, start.RequestID, start.PollSecret))
r := httptest.NewRequest(http.MethodGet, "/api/auth/sessions", nil)
r = r.WithContext(jwtauth.ContextWithClaims(r.Context(),
&jwtauth.Claims{UserID: "u", SessionScope: "full"}))
r = r.WithContext(jwtauth.ContextWithClaims(r.Context(), &jwtauth.Claims{UserID: "owner", Scope: "app:cdrop:guest", DeviceID: got.DeviceID}))
w := httptest.NewRecorder()
s.handleSessionsList(w, r)
if w.Code != http.StatusOK {
t.Fatalf("sessions list: got %d %s", w.Code, w.Body.String())
t.Fatalf("sessions list: %d %s", w.Code, w.Body.String())
}
var resp struct {
Sessions []sessionView `json:"sessions"`
@@ -441,96 +381,132 @@ func TestSessionsList_IncludesNativeDevices(t *testing.T) {
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatalf("decode: %v", err)
}
var web, webNativeDup, desk, shortcut bool
for _, v := range resp.Sessions {
switch {
case v.DeviceName == "Web" && !v.Native && v.Kind == "oidc":
web = true
case v.DeviceName == "Web" && v.Native:
webNativeDup = true
case v.DeviceName == "Desk" && v.Native && v.Kind == "macos":
desk = true
case v.DeviceName == "iShortcut":
shortcut = true
}
if len(resp.Sessions) != 1 {
t.Fatalf("session count: got %d, want 1", len(resp.Sessions))
}
if !web {
t.Errorf("web session for 'Web' missing")
}
if webNativeDup {
t.Errorf("'Web' double-listed as a native device")
}
if !desk {
t.Errorf("native device 'Desk' missing from session list")
}
if shortcut {
t.Errorf("shortcut device leaked into session list")
sv := resp.Sessions[0]
if sv.DeviceID != got.DeviceID || sv.Scope != "guest" || !sv.Current {
t.Errorf("session view wrong: %+v", sv)
}
}
// The sweeper drops browser devices whose web_session is gone (orphans) while
// keeping browser devices that still have a live session and all native devices.
func TestDeleteOrphanBrowserDevices(t *testing.T) {
s := newQRTestServer(t)
ctx := context.Background()
now := time.Now().Unix()
// Browser "Kept" has a live session; browser "Orphan" has none; native "Desk"
// (macos) legitimately has no session and must survive.
_, id, err := newSessionToken()
if err != nil {
t.Fatalf("token: %v", err)
// deviceSession drives the 代铸 endpoint with the given identity and returns the response.
func deviceSession(t *testing.T, s *Server, userID, scope, deviceID, name, dtype, origin string) deviceSessionResp {
t.Helper()
body := fmt.Sprintf(`{"device_id":%q,"device_name":%q,"device_type":%q}`, deviceID, name, dtype)
r := httptest.NewRequest(http.MethodPost, "/api/auth/device-session", strings.NewReader(body))
if origin != "" {
r.Header.Set("Origin", origin)
}
if err := s.queries.CreateSelfSession(ctx, db.CreateSelfSessionParams{
ID: id, UserID: "u", DeviceName: "Kept", Kind: "oidc", Scope: "full",
CreatedAt: now, LastUsedAt: now, ExpiresAt: now + 3600,
}); err != nil {
t.Fatalf("create session: %v", err)
}
for _, d := range []struct{ name, typ string }{
{"Kept", "browser"}, {"Orphan", "browser"}, {"Desk", "macos"},
} {
if err := s.queries.UpsertDevice(ctx, db.UpsertDeviceParams{
UserID: "u", Name: d.name, Type: d.typ, LastSeen: now,
}); err != nil {
t.Fatalf("upsert %s: %v", d.name, err)
}
}
if _, err := s.queries.DeleteOrphanBrowserDevices(ctx, now); err != nil {
t.Fatalf("sweep: %v", err)
}
devs, _ := s.queries.ListDevicesByUser(ctx, "u")
got := map[string]bool{}
for _, d := range devs {
got[d.Name] = true
}
if !got["Kept"] {
t.Errorf("browser 'Kept' with a live session was wrongly swept")
}
if got["Orphan"] {
t.Errorf("orphan browser 'Orphan' was not swept")
}
if !got["Desk"] {
t.Errorf("native 'Desk' was wrongly swept (it keeps no web_session)")
}
}
// Removing a native device (the session list's logout path for desktop / iOS) is
// sensitive and requires a recent step-up, mirroring web-session revocation.
func TestDeleteDevice_RequiresStepUp(t *testing.T) {
s := newQRTestServer(t)
s.cfg.StepUpEnabled = true
s.cfg.StepUpMaxAgeSeconds = 300
r := httptest.NewRequest(http.MethodDelete, "/api/devices/Desk", nil)
rctx := chi.NewRouteContext()
rctx.URLParams.Add("name", "Desk")
ctx := context.WithValue(r.Context(), chi.RouteCtxKey, rctx)
ctx = jwtauth.ContextWithClaims(ctx, &jwtauth.Claims{UserID: "u", SessionScope: "full"})
r = r.WithContext(jwtauth.ContextWithClaims(r.Context(), &jwtauth.Claims{UserID: userID, Name: "Commilitia", Avatar: "https://example.net/a.png", Scope: scope}))
w := httptest.NewRecorder()
s.handleDeleteDevice(w, r.WithContext(ctx))
if w.Code != http.StatusForbidden {
t.Fatalf("delete device without step-up: got %d, want 403", w.Code)
s.handleDeviceSession(w, r)
if w.Code != http.StatusOK {
t.Fatalf("device-session: %d %s", w.Code, w.Body.String())
}
var resp deviceSessionResp
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatalf("decode device-session: %v", err)
}
return resp
}
// listSessions calls the session-management list for a caller riding device deviceID.
func listSessions(t *testing.T, s *Server, userID, scope, deviceID string) []sessionView {
t.Helper()
r := httptest.NewRequest(http.MethodGet, "/api/auth/sessions", nil)
r = r.WithContext(jwtauth.ContextWithClaims(r.Context(), &jwtauth.Claims{UserID: userID, Scope: scope, DeviceID: deviceID}))
w := httptest.NewRecorder()
s.handleSessionsList(w, r)
if w.Code != http.StatusOK {
t.Fatalf("sessions list: %d %s", w.Code, w.Body.String())
}
var resp struct {
Sessions []sessionView `json:"sessions"`
}
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatalf("decode list: %v", err)
}
return resp.Sessions
}
// 代铸 turns an edge-verified login into a managed device session that joins the unified
// list as the current device, with its type overlaid and the verified display name returned.
func TestDeviceSession_MintsManagedDevice(t *testing.T) {
s, st := newQRTestServer(t)
resp := deviceSession(t, s, "owner", "full", "dev_browser01", "Laptop", "browser", "")
if resp.AccessToken == "" || resp.RefreshToken == "" {
t.Fatal("device-session returned no tokens")
}
if resp.DeviceID != "dev_browser01" {
t.Errorf("device_id: got %q", resp.DeviceID)
}
if resp.Name != "Commilitia" {
t.Errorf("name: got %q, want the verified X-Auth-Name not the subject UUID", resp.Name)
}
if resp.Avatar != "https://example.net/a.png" {
t.Errorf("avatar: got %q, want the verified X-Auth-Avatar", resp.Avatar)
}
if st.lastMint["tier"] != "full" || st.lastMint["meta"] != "dev_browser01" || st.lastMint["label"] != "Laptop" {
t.Errorf("mint params: %+v", st.lastMint)
}
list := listSessions(t, s, "owner", "app:cdrop:full", "dev_browser01")
if len(list) != 1 || list[0].DeviceID != "dev_browser01" || list[0].Kind != "browser" || !list[0].Current {
t.Errorf("unified list wrong: %+v", list)
}
}
// Re-login with the same device_id rotates the one session (R2), not piling up duplicates,
// and adopts the latest label — the fix for the "duplicate phantom devices" regression.
func TestDeviceSession_Idempotent(t *testing.T) {
s, _ := newQRTestServer(t)
_ = deviceSession(t, s, "owner", "full", "dev_same01", "Laptop", "browser", "")
_ = deviceSession(t, s, "owner", "full", "dev_same01", "Laptop Renamed", "browser", "")
list := listSessions(t, s, "owner", "app:cdrop:full", "dev_same01")
if len(list) != 1 {
t.Fatalf("idempotent re-mint: got %d sessions, want 1", len(list))
}
if list[0].DeviceName != "Laptop Renamed" {
t.Errorf("rotation should adopt the latest label: got %q", list[0].DeviceName)
}
}
// A meta-less machine session (a desktop device-authorize bootstrap) must not surface as a
// phantom device — the unified list filters it out, leaving only真正的托管设备.
func TestSessionsList_FiltersMetalessBootstrap(t *testing.T) {
s, _ := newQRTestServer(t)
if _, err := s.broker.MintSession(context.Background(), brokerclient.MintParams{
UserID: "owner", Tier: "full", Label: "bootstrap",
}); err != nil {
t.Fatalf("bootstrap mint: %v", err)
}
_ = deviceSession(t, s, "owner", "full", "dev_real01", "Laptop", "browser", "")
list := listSessions(t, s, "owner", "app:cdrop:full", "dev_real01")
if len(list) != 1 || list[0].DeviceID != "dev_real01" {
t.Fatalf("metaless bootstrap not filtered: %+v", list)
}
}
// A cookie-authenticated mint must carry a same-origin Origin; a cross-site forgery (which
// would reintroduce phantom devices) is rejected.
func TestDeviceSession_RejectsCrossOrigin(t *testing.T) {
s, _ := newQRTestServer(t)
body := `{"device_id":"dev_x01","device_name":"X","device_type":"browser"}`
r := httptest.NewRequest(http.MethodPost, "/api/auth/device-session", strings.NewReader(body))
r.Header.Set("Origin", "https://evil.example.net")
r = r.WithContext(jwtauth.ContextWithClaims(r.Context(), &jwtauth.Claims{UserID: "owner", Scope: "full"}))
w := httptest.NewRecorder()
s.handleDeviceSession(w, r)
if w.Code != http.StatusForbidden {
t.Fatalf("cross-origin device-session: got %d, want 403", w.Code)
}
}
// A restricted guest minting its device session stays guest — no escalation to full.
func TestDeviceSession_GuestTierNotEscalated(t *testing.T) {
s, st := newQRTestServer(t)
_ = deviceSession(t, s, "owner", "app:cdrop:guest", "dev_guest01", "Borrowed", "browser", "")
if st.lastMint["tier"] != "guest" {
t.Errorf("guest caller minted tier %v, want guest", st.lastMint["tier"])
}
}
+61
View File
@@ -0,0 +1,61 @@
package httpapi
import (
"encoding/json"
"io"
"log/slog"
"net/http"
"time"
)
type refreshReq struct {
RefreshToken string `json:"refresh_token"`
}
type refreshResp struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
ExpiresIn int `json:"expires_in"`
}
// handleAuthRefresh proxies a token refresh to the Auth Broker. The SPA holds a
// broker-minted access + refresh; when the access expires it POSTs the refresh token
// here and cdrop relays it to the broker's /refresh, returning the rotated pair. The
// proxy keeps the browser same-origin (no broker CORS) and means cdrop stores no
// credential — it only forwards. Public (the access token is expired, which is the
// point); Origin-checked for CSRF.
func (s *Server) handleAuthRefresh(w http.ResponseWriter, r *http.Request) {
if !s.sameOrigin(r) {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "bad origin"})
return
}
var req refreshReq
if err := json.NewDecoder(io.LimitReader(r.Body, 8192)).Decode(&req); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid json"})
return
}
if req.RefreshToken == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "missing refresh token"})
return
}
res, err := s.broker.RefreshSession(r.Context(), req.RefreshToken)
if err != nil {
// A rejected refresh (expired / rotated / revoked) is the client's cue to
// re-authenticate; relay it as 401. (A broker outage also lands here — rare,
// and re-login is the safe fallback.)
slog.Warn("broker refresh failed", "err", err)
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "refresh rejected"})
return
}
expiresIn := int(res.AccessExpires - time.Now().Unix())
if expiresIn < 0 {
expiresIn = 0
}
writeJSON(w, http.StatusOK, refreshResp{
AccessToken: res.Access,
RefreshToken: res.Refresh,
ExpiresIn: expiresIn,
})
}
-39
View File
@@ -1,39 +0,0 @@
package httpapi
import (
"time"
"github.com/go-jose/go-jose/v4"
"github.com/go-jose/go-jose/v4/jwt"
)
// mintSessionToken signs a short-lived cdrop self-signed session access token
// (AUTH.md §3.1): HS256 over the SessionSecret-derived key, sub=userID, sid=the
// web_sessions row id, typ=session, scope=full|guest. The matching verifier is
// jwtauth.verifySelfToken. Returns the token and its lifetime in seconds (for the
// client's expires_in). Used by scan-login and self/guest session refresh — never
// touches the IdP.
func (s *Server) mintSessionToken(userID, sid, scope string) (string, int, error) {
ttl := time.Duration(s.cfg.SessionTokenTTLSeconds) * time.Second
now := time.Now()
sig, err := jose.NewSigner(
jose.SigningKey{Algorithm: jose.HS256, Key: s.sessionTokenKey},
(&jose.SignerOptions{}).WithType("JWT"),
)
if err != nil {
return "", 0, err
}
std := jwt.Claims{
Subject: userID,
IssuedAt: jwt.NewNumericDate(now),
Expiry: jwt.NewNumericDate(now.Add(ttl)),
}
tok, err := jwt.Signed(sig).
Claims(std).
Claims(map[string]any{"typ": "session", "scope": scope, "sid": sid}).
Serialize()
if err != nil {
return "", 0, err
}
return tok, int(ttl / time.Second), nil
}
+92 -100
View File
@@ -6,13 +6,13 @@ import (
"encoding/json"
"log/slog"
"net/http"
"sync"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/httprate"
"commilitia.net/cdrop/internal/brokerclient"
"commilitia.net/cdrop/internal/calls"
"commilitia.net/cdrop/internal/clipboard"
"commilitia.net/cdrop/internal/config"
@@ -38,23 +38,11 @@ type Server struct {
push *push.Sender // inert when VAPID keys unset → push endpoints 503
mux *chi.Mux
// sessionKey encrypts browser refresh_tokens at rest (web_sessions); nil when
// CDROP_SESSION_SECRET is unset (dev), which disables passwordless re-login.
// siteOrigin is the deployment's scheme://host, used for the CSRF Origin check.
sessionKey []byte
// broker delegates session lifecycle to the Auth Broker (mint / revoke / refresh).
broker *brokerclient.Client
// siteOrigin is the deployment's scheme://host, used for the CSRF Origin check
// and the scan-login QR link.
siteOrigin string
// sessionTokenKey signs cdrop's self-signed session access tokens (scan-login;
// AUTH.md §3.1), derived from SessionSecret in a separate domain from sessionKey.
// nil when SessionSecret is unset → minting is unavailable (QR stays off).
sessionTokenKey []byte
// refreshLocks serialise concurrent refreshes of the same web session (all of
// a user's browser tabs share one cookie → one refresh_token). Striped so the
// lock set stays bounded; collisions just serialise unrelated sessions, which
// is harmless. Prevents a multi-tab race from spending a one-time-use
// refresh_token twice and logging the user out everywhere.
refreshLocks [refreshLockStripes]sync.Mutex
}
func New(
@@ -82,9 +70,8 @@ func New(
push: pushSender,
mux: chi.NewRouter(),
sessionKey: deriveSessionKey(cfg.SessionSecret),
siteOrigin: deriveSiteOrigin(cfg.OIDCRedirectURI),
sessionTokenKey: jwtauth.DeriveSessionTokenKey(cfg.SessionSecret),
broker: brokerclient.New(cfg.BrokerBaseURL, cfg.BrokerInternalKey, cfg.BrokerAppOrDefault()),
siteOrigin: deriveSiteOrigin(cfg.PublicURL),
}
s.routes()
return s
@@ -105,99 +92,94 @@ func (s *Server) routes() {
s.mux.NotFound(webui.Handler().ServeHTTP)
s.mux.Route("/api", func(r chi.Router) {
// Public OIDC PKCE plumbing — no auth required (it bootstraps it).
// Public navigation: 302 to the broker's global-SSO login (bootstraps login).
r.Get("/auth/login", s.handleAuthLogin)
// Public: broker coordinates for native clients' device-authorization flow.
r.Get("/auth/config", s.handleAuthConfig)
// Rate-limit the credential-bearing OAuth endpoints (G4): they proxy to
// the IdP, so without a cap cdrop is a brute-force / token-pivot relay.
// Per-IP (RealIP is mounted above); 60/min is ample for real logins and
// hourly refresh even behind a shared NAT, while choking a scripted flood.
// Public, rate-limited (per-IP; RealIP is mounted above). No bearer: the new
// device isn't logged in yet (its poll_secret is the only credential), and
// refresh runs precisely when the access token is expired. 60/min is ample
// for real use behind a shared NAT while choking a scripted flood.
r.Group(func(r chi.Router) {
r.Use(httprate.LimitByIP(60, time.Minute))
r.Post("/auth/exchange", s.handleAuthExchange)
// Token refresh — proxied to the Auth Broker, so the SPA stays same-origin
// and cdrop stores no credential (it just relays the rotated pair).
r.Post("/auth/refresh", s.handleAuthRefresh)
// Cookie-authenticated (no bearer): the HttpOnly session cookie is the
// only credential. logout drops the server session; device persists
// this browser's name into the session for PWA-eviction recovery.
r.Post("/auth/logout", s.handleAuthLogout)
r.Post("/auth/device", s.handleAuthDevice)
// Scan-login: the new device opens a request and long-polls status.
// Public (no bearer — the device isn't logged in yet); the private
// poll_secret in the X-Poll-Secret header is the only credential.
// Scan-login: the new device opens a request and long-polls status. The
// private poll_secret in the X-Poll-Secret header is the only credential.
r.Post("/auth/qr/start", s.handleQRStart)
r.Get("/auth/qr/status", s.handleQRStatus)
})
// Protected routes. gzip / compress is intentionally NOT mounted —
// Authenticated routes. Every request past here carries the broker's
// edge-injected X-Auth-* identity (prod) or a dev token. Guests and full
// sessions both reach this tier. gzip / compress is intentionally NOT mounted —
// it would buffer the SSE stream.
r.Group(func(r chi.Router) {
r.Use(s.auth.Middleware)
// Clipboard is the one capability a scoped shortcut token may reach
// (iOS Shortcut sync) — it must carry the "clipboard" scope. Full
// login sessions pass requireScope unconditionally.
// Clipboard, transfer, messaging, presence, push — guests included.
r.Get("/clipboard", s.handleClipboardGet)
r.Put("/clipboard", s.handleClipboardPut)
// Lightweight version probe — no content; lets pollers detect change
// cheaply before fetching the full body.
r.Get("/clipboard/version", s.handleClipboardVersion)
r.Get("/me", s.handleMe)
r.Post("/me/disconnect", s.handleDisconnect)
// 代铸: turn an edge-verified login (SSO cookie or device-authorize bootstrap)
// into a cdrop-managed device session bound to a stable device_id, so browser
// and native clients share one device list. Authenticated but not full-only —
// it mints at the caller's own tier. Rate-limited per IP: with R2 idempotency a
// normal client mints about once per login, so a generous cap simply bounds an
// authenticated identity that loops fresh device_ids to mint unbounded sessions.
r.Group(func(r chi.Router) {
r.Use(requireScope(shortcutScope))
r.Get("/clipboard", s.handleClipboardGet)
r.Put("/clipboard", s.handleClipboardPut)
// Lightweight version probe — no content; lets pollers (iOS
// Shortcut) detect change cheaply before fetching the full body.
r.Get("/clipboard/version", s.handleClipboardVersion)
r.Use(httprate.LimitByIP(20, time.Minute))
r.Post("/auth/device-session", s.handleDeviceSession)
})
// Logout revokes the calling device's own broker session (self-service).
r.Post("/auth/logout", s.handleLogout)
r.Get("/hub/events", s.handleEvents)
r.Post("/hub/signal", s.handleSignal)
r.Post("/message", s.handleMessage)
r.Get("/devices", s.handleDevices)
r.Get("/push/vapid-key", s.handlePushVAPIDKey)
r.Post("/push/subscribe", s.handlePushSubscribe)
r.Delete("/push/subscribe", s.handlePushUnsubscribe)
r.Get("/calls/credentials", s.handleCallsCredentials)
// Full sessions only — restricted guests (scan-login borrows) are
// rejected: they transfer files but can't manage devices, approve other
// devices, or revoke sessions.
r.Group(func(r chi.Router) {
r.Use(requireFullSession)
r.Delete("/devices/{device_id}", s.handleDeleteDevice)
r.Patch("/devices/{device_id}", s.handleRenameDevice)
// Scan-login approval side: the logged-in approver views and authorises
// the new device. Guests can't reach here, so a borrowed device can't
// approve further devices.
r.Get("/auth/qr/request", s.handleQRRequest)
r.Post("/auth/qr/approve", s.handleQRApprove)
r.Post("/auth/qr/deny", s.handleQRDeny)
// Session management: list logged-in devices with their permission
// level and revoke one (logout that device).
r.Get("/auth/sessions", s.handleSessionsList)
r.Delete("/auth/sessions/{id}", s.handleSessionRevoke)
})
// Everything else requires a full login session; scoped shortcut
// tokens are rejected, so a leaked token's blast radius stays the
// clipboard and nothing more (including token self-management).
r.Group(func(r chi.Router) {
r.Use(rejectScoped)
r.Get("/me", s.handleMe)
r.Post("/me/disconnect", s.handleDisconnect)
r.Get("/hub/events", s.handleEvents)
r.Post("/hub/signal", s.handleSignal)
r.Post("/message", s.handleMessage)
r.Get("/devices", s.handleDevices)
r.Get("/push/vapid-key", s.handlePushVAPIDKey)
r.Post("/push/subscribe", s.handlePushSubscribe)
r.Delete("/push/subscribe", s.handlePushUnsubscribe)
r.Get("/calls/credentials", s.handleCallsCredentials)
// Account-management surface: restricted guest (scan-login borrow)
// sessions are rejected here too — they can transfer files but not
// remove devices, nor mint / list / revoke long-lived shortcut
// tokens. Full / OIDC / dev sessions pass (AUTH.md §3.2).
r.Group(func(r chi.Router) {
r.Use(requireFullSession)
r.Delete("/devices/{name}", s.handleDeleteDevice)
r.Post("/shortcut/issue", s.handleShortcutIssue)
r.Get("/shortcut", s.handleShortcutList)
r.Delete("/shortcut/{jti}", s.handleShortcutRevoke)
// Scan-login approval side: the logged-in approver views and
// authorises the new device. Guest sessions can't reach here, so a
// borrowed device can't approve further devices.
r.Get("/auth/qr/request", s.handleQRRequest)
r.Post("/auth/qr/approve", s.handleQRApprove)
r.Post("/auth/qr/deny", s.handleQRDeny)
// Session management: list logins with their permission level,
// really revoke one (logout), and the standalone step-up the
// revoke flow re-uses. All under /api/auth so the session cookie
// (Path=/api/auth) is available for step-up state.
r.Post("/auth/stepup", s.handleStepUp)
r.Get("/auth/sessions", s.handleSessionsList)
r.Delete("/auth/sessions/{id}", s.handleSessionRevoke)
})
r.Route("/transfer", func(r chi.Router) {
r.Post("/initiate", s.handleTransferInit)
r.Post("/{id}/accept", s.transitionHandler(transfer.StateAccepted, ""))
r.Post("/{id}/cancel", s.transitionHandler(transfer.StateCancelled, ""))
r.Post("/{id}/p2p", s.transitionHandler(transfer.StateP2PActive, transfer.ModeP2P))
r.Post("/{id}/fallback", s.transitionHandler(transfer.StateRelayActive, transfer.ModeRelay))
r.Post("/{id}/done", s.transitionHandler(transfer.StateDone, ""))
r.Post("/{id}/fail", s.transitionHandler(transfer.StateFailed, ""))
})
r.Route("/relay/{id}", func(r chi.Router) {
r.Post("/chunk", s.handleRelayChunk)
r.Get("/stream", s.handleRelayStream)
})
r.Route("/transfer", func(r chi.Router) {
r.Post("/initiate", s.handleTransferInit)
r.Post("/{id}/accept", s.transitionHandler(transfer.StateAccepted, ""))
r.Post("/{id}/cancel", s.transitionHandler(transfer.StateCancelled, ""))
r.Post("/{id}/p2p", s.transitionHandler(transfer.StateP2PActive, transfer.ModeP2P))
r.Post("/{id}/fallback", s.transitionHandler(transfer.StateRelayActive, transfer.ModeRelay))
r.Post("/{id}/done", s.transitionHandler(transfer.StateDone, ""))
r.Post("/{id}/fail", s.transitionHandler(transfer.StateFailed, ""))
})
r.Route("/relay/{id}", func(r chi.Router) {
r.Post("/chunk", s.handleRelayChunk)
r.Get("/stream", s.handleRelayStream)
})
})
})
@@ -223,12 +205,16 @@ func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
}
type meResp struct {
UserID string `json:"user_id"`
UserID string `json:"user_id"`
// Name is the display name from the broker (X-Auth-Name); falls back to user_id.
Name string `json:"name"`
// Avatar is the broker account's picture URL (X-Auth-Avatar); empty when none.
Avatar string `json:"avatar,omitempty"`
Groups []string `json:"groups"`
DeviceName string `json:"device_name"`
// Scope is the session's capability level: "guest" (scan-login borrow,
// capability-limited) or "full" (normal login). The UI hides account-management
// affordances on guest sessions (AUTH.md §3.2).
// affordances on guest sessions.
Scope string `json:"scope"`
}
@@ -243,8 +229,14 @@ func (s *Server) handleMe(w http.ResponseWriter, r *http.Request) {
if claims.Guest() {
scope = "guest"
}
name := claims.Name
if name == "" {
name = claims.UserID
}
writeJSON(w, http.StatusOK, meResp{
UserID: claims.UserID,
Name: name,
Avatar: claims.Avatar,
Groups: claims.Groups,
DeviceName: device,
Scope: scope,
+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)
-123
View File
@@ -1,123 +0,0 @@
package httpapi
import (
"encoding/base64"
"strings"
"testing"
)
func TestEncryptRefreshRoundTrip(t *testing.T) {
s := &Server{sessionKey: deriveSessionKey("a-strong-session-secret")}
plain := strings.Repeat("refresh.token.", 2000) // ~28 KB, mimics Casdoor's large JWT
enc, err := s.encryptRefresh(plain)
if err != nil {
t.Fatalf("encrypt: %v", err)
}
if strings.Contains(enc, plain) {
t.Fatal("ciphertext leaks plaintext")
}
got, err := s.decryptRefresh(enc)
if err != nil {
t.Fatalf("decrypt: %v", err)
}
if got != plain {
t.Fatalf("roundtrip mismatch: len(got)=%d, len(want)=%d", len(got), len(plain))
}
}
func TestEncryptRefreshNonceIsRandom(t *testing.T) {
s := &Server{sessionKey: deriveSessionKey("secret")}
a, _ := s.encryptRefresh("same plaintext")
b, _ := s.encryptRefresh("same plaintext")
if a == b {
t.Fatal("two encryptions of the same plaintext are identical — nonce not random")
}
}
func TestDecryptRefreshRejectsTamper(t *testing.T) {
s := &Server{sessionKey: deriveSessionKey("secret")}
enc, err := s.encryptRefresh("token")
if err != nil {
t.Fatalf("encrypt: %v", err)
}
raw, err := base64.StdEncoding.DecodeString(enc)
if err != nil {
t.Fatalf("decode: %v", err)
}
raw[len(raw)-1] ^= 0xFF // flip a bit in the GCM tag
if _, err := s.decryptRefresh(base64.StdEncoding.EncodeToString(raw)); err == nil {
t.Fatal("tampered ciphertext must fail authentication")
}
}
func TestDecryptRefreshRejectsWrongKey(t *testing.T) {
enc, err := (&Server{sessionKey: deriveSessionKey("key-one")}).encryptRefresh("token")
if err != nil {
t.Fatalf("encrypt: %v", err)
}
if _, err := (&Server{sessionKey: deriveSessionKey("key-two")}).decryptRefresh(enc); err == nil {
t.Fatal("decryption under a different key must fail")
}
}
func TestEncryptRefreshNoKey(t *testing.T) {
s := &Server{sessionKey: nil}
if _, err := s.encryptRefresh("token"); err == nil {
t.Fatal("encrypt without a key must error")
}
}
func TestSessionIDDeterministicAndHashed(t *testing.T) {
raw, id, err := newSessionToken()
if err != nil {
t.Fatalf("newSessionToken: %v", err)
}
if id != sessionID(raw) {
t.Fatal("newSessionToken id must equal sessionID(raw)")
}
if id == raw || strings.Contains(id, raw) {
t.Fatal("stored id must be a hash of the cookie value, not the value itself")
}
// SHA-256 hex is always 64 chars.
if len(id) != 64 {
t.Fatalf("session id length: got %d, want 64", len(id))
}
}
func TestNewSessionTokenUnique(t *testing.T) {
seen := make(map[string]bool)
for i := 0; i < 1000; i++ {
raw, _, err := newSessionToken()
if err != nil {
t.Fatalf("newSessionToken: %v", err)
}
if seen[raw] {
t.Fatal("duplicate session token generated")
}
seen[raw] = true
}
}
func TestDeriveSessionKey(t *testing.T) {
if deriveSessionKey("") != nil {
t.Fatal("empty secret must yield a nil key (feature disabled)")
}
if got := len(deriveSessionKey("x")); got != 32 {
t.Fatalf("derived key length: got %d, want 32 (AES-256)", got)
}
}
func TestDeriveSiteOrigin(t *testing.T) {
cases := []struct{ in, want string }{
{"https://drop.example.net/oauth/callback", "https://drop.example.net"},
{"http://localhost:5173/oauth/callback", "http://localhost:5173"},
{"", ""},
{"not a url", ""},
}
for _, c := range cases {
if got := deriveSiteOrigin(c.in); got != c.want {
t.Errorf("deriveSiteOrigin(%q) = %q, want %q", c.in, got, c.want)
}
}
}
+157 -169
View File
@@ -1,11 +1,8 @@
package httpapi
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"time"
"github.com/go-chi/chi/v5"
@@ -13,206 +10,197 @@ import (
"commilitia.net/cdrop/internal/jwtauth"
)
// Session management (AUTH.md §1, §6): list the caller's logins with their
// capability level, and really revoke one (delete the row → its access token can
// no longer refresh and dies within its short TTL). Revocation is a sensitive
// action, so it requires a recent step-up. A standalone step-up endpoint lets the
// UI establish that re-auth once (per session/device) and reuse it across actions
// within the window — the same session isn't re-prompted repeatedly (#3).
// Session management. After the unified-session-model rework, every logged-in client —
// browser, desktop, QR-paired device — is one delegated device session in the broker. The
// broker (R1: GET /internal/sessions) is the single authoritative device list; cdrop no
// longer keeps a parallel authoritative session table. The local `devices` rows survive only
// as a type/presence cache: they supply each device's type for the list overlay and back the
// real-time presence view (which is cdrop's domain, keyed by device name). Listing reads R1
// and overlays type/online/current; revoking calls the broker (the session's source of truth)
// then drops the local cache row.
type stepUpReq struct {
Code string `json:"code"`
Verifier string `json:"verifier"`
}
// handleStepUp exchanges a fresh prompt=login code and, on success, stamps the
// caller's session as stepped-up (per-session, cookie-keyed). Sensitive actions
// within StepUpMaxAgeSeconds then skip re-auth. 403 on failure; 204 when step-up
// is disabled (nothing to establish).
func (s *Server) handleStepUp(w http.ResponseWriter, r *http.Request) {
if !s.cfg.StepUpEnabled {
w.WriteHeader(http.StatusNoContent)
return
}
claims, _ := jwtauth.ClaimsFromContext(r.Context())
var body stepUpReq
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 8192)).Decode(&body); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid json"})
return
}
if !s.verifyStepUp(r, claims.UserID, body.Code, body.Verifier) {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "step_up_required"})
return
}
s.recordStepUp(r)
w.WriteHeader(http.StatusNoContent)
// requireFullSession rejects restricted guest sessions (scan-login borrow): they can
// transfer files but not manage devices, approve other devices, or revoke sessions.
// A full / dev session passes (AUTH Broker scope tier — Claims.Guest reads X-Auth-Scope).
func requireFullSession(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
claims, ok := jwtauth.ClaimsFromContext(r.Context())
if !ok {
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "no session"})
return
}
if claims.Guest() {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "full session required"})
return
}
next.ServeHTTP(w, r)
})
}
type sessionView struct {
ID string `json:"id"`
ID string `json:"id"` // device_id (the revoke handle exposed to the client)
DeviceID string `json:"device_id"`
DeviceName string `json:"device_name"`
Kind string `json:"kind"` // oidc | self | guest | macos | windows | linux | ios
Kind string `json:"kind"` // device type: browser | macos | windows | linux | ios
Scope string `json:"scope"` // full | guest
Current bool `json:"current"`
Online bool `json:"online"` // device currently connected (SSE) — UI sorts online first
// Native marks a device that authenticates with an IdP token and keeps no
// web_session row (desktop / iOS). It is surfaced from the devices registry so
// the session list covers every device; its "logout" routes to the device
// endpoint rather than the web-session one.
Native bool `json:"native"`
CreatedAt int64 `json:"created_at"`
LastUsedAt int64 `json:"last_used_at"`
ExpiresAt int64 `json:"expires_at"`
Online bool `json:"online"`
CreatedAt int64 `json:"created_at"`
LastUsedAt int64 `json:"last_used_at"`
}
// isNativeDeviceType reports whether a device type is a real native client (one
// that authenticates via the IdP and keeps no web_session). browser devices are
// expected to carry a web_session; "shortcut" tokens have their own panel.
func isNativeDeviceType(t string) bool {
switch t {
case "macos", "windows", "linux", "ios":
return true
default:
return false
}
}
// handleSessionsList returns the caller's login sessions with their scope, so the
// UI can show the permission level (完整 / 受限访客) and offer real logout. The list
// is unified: web_sessions (browser / scan-login) PLUS native client devices
// (desktop / iOS) that have no web_session of their own — so every logged-in
// device appears in one place and orphaned device rows fall away (AUTH.md §4).
// handleSessionsList returns the caller's logged-in devices with their permission level
// (完整 / 受限访客) and live online flag, so the UI can show each and offer logout. The
// authoritative list is the broker's delegated device sessions (R1); cdrop overlays the
// device type (local cache), the online dot (hub presence, keyed by device name), and the
// "current" flag (the session whose meta is this request's X-Auth-Meta).
func (s *Server) handleSessionsList(w http.ResponseWriter, r *http.Request) {
claims, _ := jwtauth.ClaimsFromContext(r.Context())
now := time.Now().Unix()
rows, err := s.queries.ListWebSessionsByUser(r.Context(), claims.UserID)
sessions, err := s.broker.ListSessions(r.Context(), claims.UserID)
if err != nil {
slog.Error("list sessions failed", "err", err, "user", claims.UserID)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "db"})
writeJSON(w, http.StatusBadGateway, map[string]string{"error": "broker"})
return
}
current := ""
if c, err := r.Cookie(sessionCookieName); err == nil && c.Value != "" {
current = sessionID(c.Value)
}
// Cookieless callers (native apps) can't match by cookie; fall back to their
// own device name to mark the "current" row.
callerDevice, _ := jwtauth.DeviceNameFromContext(r.Context())
out := make([]sessionView, 0, len(rows))
named := make(map[string]struct{}, len(rows))
for _, row := range rows {
if row.ExpiresAt < now {
continue // hide expired sessions (reaped separately)
// device_id -> cached type, for the type overlay (a missing cache falls back to
// "browser"). The cache is bounded by the background device sweeper (last_seen TTL); a
// logged-out device's row is reaped there, not on this read path — this GET stays
// side-effect-free, and the session list itself is always R1-authoritative regardless of
// any stale cache row (the row only ever supplies a type for a device that is in R1).
typeByID := map[string]string{}
if devs, err := s.queries.ListDevicesByUser(r.Context(), claims.UserID); err == nil {
for _, d := range devs {
typeByID[d.DeviceID] = d.Type
}
if row.DeviceName != "" {
named[row.DeviceName] = struct{}{}
}
out := make([]sessionView, 0, len(sessions))
for _, sess := range sessions {
// A meta-less session is a non-cdrop-managed machine session — a desktop
// device-authorize bootstrap that the desktop replaces via 代铸 right away. It has
// no device_id, so it isn't a managed device and must not show as a phantom row.
if sess.Meta == "" {
continue
}
typ := typeByID[sess.Meta]
if typ == "" {
typ = "browser"
}
scope := "full"
if jwtauth.ScopeTier(sess.Scope) == "guest" {
scope = "guest"
}
out = append(out, sessionView{
ID: row.ID,
DeviceName: row.DeviceName,
Kind: row.Kind,
Scope: row.Scope,
Current: row.ID == current || (current == "" && row.DeviceName != "" && row.DeviceName == callerDevice),
Online: row.DeviceName != "" && s.hub.Online(claims.UserID, row.DeviceName),
CreatedAt: row.CreatedAt,
LastUsedAt: row.LastUsedAt,
ExpiresAt: row.ExpiresAt,
ID: sess.Meta,
DeviceID: sess.Meta,
DeviceName: sess.Label,
Kind: typ,
Scope: scope,
Current: sess.Meta == claims.DeviceID,
Online: s.hub.Online(claims.UserID, sess.Label),
CreatedAt: sess.CreatedAt,
LastUsedAt: sess.LastUsedAt,
})
}
// Native clients keep no web_session — surface them from the devices registry,
// skipping any whose name already has a web_session (no double-listing).
if devs, derr := s.queries.ListDevicesByUser(r.Context(), claims.UserID); derr == nil {
for _, d := range devs {
if !isNativeDeviceType(d.Type) {
continue
}
if _, ok := named[d.Name]; ok {
continue
}
out = append(out, sessionView{
ID: "device:" + d.Name,
DeviceName: d.Name,
Kind: d.Type,
Scope: "full",
Native: true,
Current: current == "" && d.Name != "" && d.Name == callerDevice,
Online: s.hub.Online(claims.UserID, d.Name),
CreatedAt: d.LastSeen,
LastUsedAt: d.LastSeen,
ExpiresAt: 0,
})
}
}
writeJSON(w, http.StatusOK, map[string]any{"sessions": out})
}
// deviceNameHasLiveSession reports whether the user still has a non-expired
// web_session bound to deviceName — used to avoid deleting a device that another
// live session (e.g. a re-login that left the old row) still depends on.
func (s *Server) deviceNameHasLiveSession(ctx context.Context, userID, deviceName string) bool {
rows, err := s.queries.ListWebSessionsByUser(ctx, userID)
if err != nil {
return false
}
now := time.Now().Unix()
for _, ws := range rows {
if ws.DeviceName == deviceName && ws.ExpiresAt >= now {
return true
}
}
return false
}
// handleSessionRevoke deletes a session row (scoped to its owner), really
// invalidating that login. Requires a recent step-up (403 step_up_required
// otherwise). Kicks the device's live SSE so it drops immediately.
// handleSessionRevoke logs out a device by id (= device_id): it resolves the device's broker
// session, revokes it, and drops the local cache row. Full session required (route-gated).
func (s *Server) handleSessionRevoke(w http.ResponseWriter, r *http.Request) {
if s.cfg.StepUpEnabled && !s.sessionRecentlySteppedUp(r) {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "step_up_required"})
return
}
claims, _ := jwtauth.ClaimsFromContext(r.Context())
id := chi.URLParam(r, "id")
if id == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "missing id"})
return
}
// Read the device name before deletion so we can kick its SSE.
deviceName := ""
if sess, err := s.queries.GetWebSession(r.Context(), id); err == nil && sess.UserID == claims.UserID {
deviceName = sess.DeviceName
}
n, err := s.queries.DeleteWebSessionForUser(r.Context(), db.DeleteWebSessionForUserParams{
ID: id,
UserID: claims.UserID,
})
if err != nil {
slog.Error("revoke session failed", "err", err)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "db"})
status, ok := s.revokeDevice(r, claims.UserID, id)
if !ok {
writeJSON(w, status, map[string]string{"error": revokeErrorMsg(status)})
return
}
if n == 0 {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "not found"})
return
}
if deviceName != "" {
// Drop the device registration too, so a revoked device disappears from the
// device list at once (we no longer remove devices by hand) — unless another
// live session still uses this name.
if !s.deviceNameHasLiveSession(r.Context(), claims.UserID, deviceName) {
if _, derr := s.queries.DeleteDevice(r.Context(), db.DeleteDeviceParams{
UserID: claims.UserID,
Name: deviceName,
}); derr != nil {
slog.Warn("delete device on session revoke failed", "err", derr)
}
}
s.hub.Kick(claims.UserID, deviceName)
s.hub.PublishPresence(r.Context(), claims.UserID)
}
w.WriteHeader(http.StatusNoContent)
}
// revokeDevice tears down a device's broker session and local cache row, then kicks its live
// SSE and re-broadcasts presence. Returns the HTTP status to report and whether it succeeded;
// the caller writes the response. Shared by device deletion, session revocation, and logout
// (they are the same operation). The broker session id is resolved cache-first (the local row
// holds the stable broker_sid) and falls back to R1 — the authoritative list — so a missing or
// pruned cache row still revokes correctly and stays authorized to this user.
func (s *Server) revokeDevice(r *http.Request, userID, deviceID string) (int, bool) {
sid, name := "", ""
if dev, err := s.queries.GetDevice(r.Context(), deviceID); err == nil && dev.UserID == userID {
sid = dev.BrokerSid
name = dev.Name
}
if sid == "" {
sessions, err := s.broker.ListSessions(r.Context(), userID)
if err != nil {
slog.Error("revoke: list sessions failed", "err", err, "user", userID)
return http.StatusBadGateway, false
}
for _, sess := range sessions {
if sess.Meta == deviceID {
sid = sess.SID
name = sess.Label
break
}
}
}
if sid == "" {
// Not this user's device, or already gone from both the cache and the broker.
return http.StatusNotFound, false
}
// Revoke the broker session first so the device can't refresh; a 404 (already gone) is
// idempotent success inside RevokeSession.
if err := s.broker.RevokeSession(r.Context(), sid); err != nil {
slog.Error("broker revoke failed", "err", err, "user", userID, "sid", sid)
return http.StatusBadGateway, false
}
if _, err := s.queries.DeleteDevice(r.Context(), db.DeleteDeviceParams{
DeviceID: deviceID,
UserID: userID,
}); err != nil {
// The session is already revoked; a failed cache delete is non-fatal (the sweeper
// and the next list-prune clean it). Report success so the client sees the logout.
slog.Warn("delete device cache failed", "err", err, "user", userID, "device", deviceID)
}
if name != "" {
s.hub.Kick(userID, name)
}
s.hub.PublishPresence(r.Context(), userID)
return http.StatusNoContent, true
}
// handleLogout logs out the calling device by revoking its own broker session (so it can no
// longer refresh) and dropping its cache row. The client also discards its tokens. A caller
// with no managed device (no X-Auth-Meta) just succeeds — there is nothing server-side to
// revoke. Origin-checked for CSRF.
func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
if !s.sameOrigin(r) {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "bad origin"})
return
}
claims, _ := jwtauth.ClaimsFromContext(r.Context())
if claims.DeviceID != "" {
if status, ok := s.revokeDevice(r, claims.UserID, claims.DeviceID); !ok && status != http.StatusNotFound {
slog.Warn("logout revoke failed", "status", status, "user", claims.UserID)
}
}
w.WriteHeader(http.StatusNoContent)
}
func revokeErrorMsg(status int) string {
switch status {
case http.StatusNotFound:
return "device not found"
case http.StatusBadGateway:
return "revoke failed"
default:
return "db"
}
}
-260
View File
@@ -1,260 +0,0 @@
package httpapi
import (
"crypto/rand"
"encoding/base64"
"encoding/json"
"log/slog"
"net/http"
"strings"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-jose/go-jose/v4"
"github.com/go-jose/go-jose/v4/jwt"
"commilitia.net/cdrop/internal/db"
"commilitia.net/cdrop/internal/jwtauth"
)
// shortcutScope is the single scope a shortcut token is granted; the route layer
// only lets a token carrying it reach the clipboard endpoints (see server.go).
const shortcutScope = "clipboard"
// requireScope gates a route group that scoped shortcut tokens may also reach: a
// scoped token must carry the named scope, while a full login session always
// passes (it has no scope restriction).
func requireScope(scope string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
claims, ok := jwtauth.ClaimsFromContext(r.Context())
if !ok {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "claims missing"})
return
}
if claims.Scoped() && !claims.HasScope(scope) {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "insufficient scope"})
return
}
next.ServeHTTP(w, r)
})
}
}
// rejectScoped blocks scoped shortcut tokens outright — for every route only a
// full login session may touch. A leaked clipboard token thus reaches nothing
// here: not the device list, transfers, signalling, nor token self-management.
func rejectScoped(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
claims, ok := jwtauth.ClaimsFromContext(r.Context())
if !ok {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "claims missing"})
return
}
if claims.Scoped() {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "session token required"})
return
}
next.ServeHTTP(w, r)
})
}
// requireFullSession rejects restricted guest sessions (scan-login borrow): they
// may transfer files but not reach account-management surfaces — removing devices,
// approving more devices, or minting / listing / revoking long-lived tokens. A
// borrowed device thus can't escalate. Full / OIDC / dev sessions pass; scoped
// shortcut tokens are already blocked upstream by rejectScoped (AUTH.md §3.2).
func requireFullSession(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
claims, ok := jwtauth.ClaimsFromContext(r.Context())
if !ok {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "claims missing"})
return
}
if claims.Guest() {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "full session required"})
return
}
next.ServeHTTP(w, r)
})
}
// 这些端点只由登录会话调用(路由层 rejectScoped 守门)——用 token 不能自管 token
// 防止泄漏的快捷指令 token 自我续期或越权。
type shortcutIssueReq struct {
Label string `json:"label"`
}
type shortcutIssueResp struct {
// Token 仅在签发时返回这一次,服务端不留可还原副本(只存 jti 等元数据)。
Token string `json:"token"`
Jti string `json:"jti"`
Label string `json:"label"`
Scopes []string `json:"scopes"`
ExpiresAt int64 `json:"expires_at"`
}
type shortcutTokenView struct {
Jti string `json:"jti"`
Label string `json:"label"`
Scopes []string `json:"scopes"`
CreatedAt int64 `json:"created_at"`
ExpiresAt int64 `json:"expires_at"`
LastUsedAt *int64 `json:"last_used_at"`
Revoked bool `json:"revoked"`
}
// handleShortcutIssue mints a long-lived, clipboard-scoped HS256 token, stores
// its metadata, and returns the token string once. Disabled (503) when no HS256
// secret is configured.
func (s *Server) handleShortcutIssue(w http.ResponseWriter, r *http.Request) {
if len(s.cfg.HS256Secret) == 0 {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "shortcut tokens not enabled"})
return
}
claims, _ := jwtauth.ClaimsFromContext(r.Context())
var req shortcutIssueReq
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&req); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid json"})
return
}
label := strings.TrimSpace(req.Label)
if label == "" {
label = "iOS Shortcut"
}
if len(label) > 64 {
label = label[:64]
}
now := time.Now()
active, err := s.queries.CountActiveShortcutTokensByUser(r.Context(), db.CountActiveShortcutTokensByUserParams{
UserID: claims.UserID,
ExpiresAt: now.Unix(),
})
if err != nil {
slog.Error("count shortcut tokens failed", "err", err, "user", claims.UserID)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "db"})
return
}
if active >= int64(s.cfg.ShortcutMaxPerUser) {
writeJSON(w, http.StatusConflict, map[string]string{"error": "too many active tokens"})
return
}
jti, err := randomTokenID()
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "id gen"})
return
}
expires := now.Add(time.Duration(s.cfg.ShortcutTokenTTLDays) * 24 * time.Hour)
token, err := signShortcutToken(s.cfg.HS256Secret, claims.UserID, jti, shortcutScope, now, expires)
if err != nil {
slog.Error("sign shortcut token failed", "err", err)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "sign"})
return
}
if err := s.queries.InsertShortcutToken(r.Context(), db.InsertShortcutTokenParams{
Jti: jti,
UserID: claims.UserID,
Label: label,
Scopes: shortcutScope,
CreatedAt: now.Unix(),
ExpiresAt: expires.Unix(),
}); err != nil {
slog.Error("insert shortcut token failed", "err", err, "user", claims.UserID)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "db"})
return
}
writeJSON(w, http.StatusCreated, shortcutIssueResp{
Token: token,
Jti: jti,
Label: label,
Scopes: []string{shortcutScope},
ExpiresAt: expires.Unix(),
})
}
// handleShortcutList returns the caller's tokens (metadata only, never the token
// string).
func (s *Server) handleShortcutList(w http.ResponseWriter, r *http.Request) {
claims, _ := jwtauth.ClaimsFromContext(r.Context())
rows, err := s.queries.ListShortcutTokensByUser(r.Context(), claims.UserID)
if err != nil {
slog.Error("list shortcut tokens failed", "err", err, "user", claims.UserID)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "db"})
return
}
out := make([]shortcutTokenView, 0, len(rows))
for _, t := range rows {
out = append(out, shortcutTokenView{
Jti: t.Jti,
Label: t.Label,
Scopes: strings.Fields(t.Scopes),
CreatedAt: t.CreatedAt,
ExpiresAt: t.ExpiresAt,
LastUsedAt: t.LastUsedAt,
Revoked: t.Revoked != 0,
})
}
writeJSON(w, http.StatusOK, map[string]any{"tokens": out})
}
// handleShortcutRevoke flips the revoked flag (scoped to the caller's user_id so
// one user can't revoke another's). verifyHS256 reads the flag on every request,
// so revocation takes effect on the token's next use.
func (s *Server) handleShortcutRevoke(w http.ResponseWriter, r *http.Request) {
claims, _ := jwtauth.ClaimsFromContext(r.Context())
jti := chi.URLParam(r, "jti")
if jti == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "missing jti"})
return
}
n, err := s.queries.RevokeShortcutToken(r.Context(), db.RevokeShortcutTokenParams{
Jti: jti,
UserID: claims.UserID,
})
if err != nil {
slog.Error("revoke shortcut token failed", "err", err, "user", claims.UserID)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "db"})
return
}
if n == 0 {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "not found"})
return
}
w.WriteHeader(http.StatusNoContent)
}
// signShortcutToken mints a compact HS256 JWT: sub=userID, jti, scope (space-
// delimited OAuth-style, informational — the store row is authoritative), iat,
// exp. The shared HS256 secret is the same one verifyHS256 checks against.
func signShortcutToken(secret, userID, jti, scope string, iat, exp time.Time) (string, error) {
sig, err := jose.NewSigner(
jose.SigningKey{Algorithm: jose.HS256, Key: jwtauth.DeriveHS256Key(secret)},
(&jose.SignerOptions{}).WithType("JWT"),
)
if err != nil {
return "", err
}
std := jwt.Claims{
Subject: userID,
ID: jti,
IssuedAt: jwt.NewNumericDate(iat),
Expiry: jwt.NewNumericDate(exp),
}
return jwt.Signed(sig).Claims(std).Claims(map[string]any{"scope": scope}).Serialize()
}
// randomTokenID returns a 128-bit URL-safe random id for the jti.
func randomTokenID() (string, error) {
var b [16]byte
if _, err := rand.Read(b[:]); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b[:]), nil
}
+11 -9
View File
@@ -38,6 +38,7 @@ func (s *Server) handleEvents(w http.ResponseWriter, r *http.Request) {
http.Error(w, "missing device", http.StatusBadRequest)
return
}
deviceType := jwtauth.DeviceTypeFromContext(r.Context())
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
@@ -50,7 +51,7 @@ func (s *Server) handleEvents(w http.ResponseWriter, r *http.Request) {
}
flusher.Flush()
client := s.hub.Connect(r.Context(), claims.UserID, deviceName)
client := s.hub.Connect(r.Context(), claims.UserID, deviceName, deviceType)
defer s.hub.Disconnect(client)
slog.Debug("sse connected", "user", claims.UserID, "device", deviceName)
@@ -74,14 +75,15 @@ func (s *Server) handleEvents(w http.ResponseWriter, r *http.Request) {
}
flusher.Flush()
// Refresh last_seen so a connection-only client (no other API calls)
// keeps its device row alive past TTL — matches the sliding
// refresh_token semantics requested for device persistence.
_ = s.queries.UpsertDevice(r.Context(), db.UpsertDeviceParams{
UserID: claims.UserID,
Name: deviceName,
Type: jwtauth.DeviceTypeFromContext(r.Context()),
LastSeen: time.Now().Unix(),
})
// keeps its managed device row alive past the sweeper TTL while connected.
if claims.DeviceID != "" {
_ = s.queries.TouchDevice(r.Context(), db.TouchDeviceParams{
LastSeen: time.Now().Unix(),
Tier: claims.Tier(),
DeviceID: claims.DeviceID,
UserID: claims.UserID,
})
}
case <-r.Context().Done():
return
}