鉴权并入 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
+43 -29
View File
@@ -13,26 +13,12 @@ import (
"cdrop-desktop/platform"
)
// loginResultFromToken decodes the identity out of the exchanged tokens and
// assembles the payload the WebView store consumes. Shared by login + refresh.
func loginResultFromToken(tok *platform.TokenResult) (*platform.LoginResult, error) {
user, err := platform.UserFromToken(tok.IDToken, tok.AccessToken)
if err != nil {
return nil, err
}
return &platform.LoginResult{
AccessToken: tok.AccessToken,
RefreshToken: tok.RefreshToken,
ExpiresIn: tok.ExpiresIn,
User: user,
}, nil
}
// App is the Wails application context bound to the WebView.
type App struct {
ctx context.Context
apiBase string
token *platform.TokenResult // in-memory copy; refresh_token persists in the OS secret store (see session.go)
user platform.UserInfo // display identity from 代铸; preserved across refresh (machine tokens are nameless)
quitting bool // set by the menu bar "Quit" so beforeClose allows the real exit
startHidden bool // set by main when launched via autostart: come up to the menu bar, no window
@@ -58,6 +44,7 @@ func (a *App) startup(ctx context.Context) {
RefreshToken: s.RefreshToken,
ExpiresIn: s.ExpiresIn,
}
a.user = s.User
}
// Keep the autostart entry in sync with this binary: when it's enabled,
// re-apply so an entry written by an older build (no --hidden flag) or one
@@ -222,17 +209,40 @@ func (a *App) StartLogin() {
flow := platform.NewFlow(cfg, func(u string) {
runtime.BrowserOpenURL(a.ctx, u)
})
tok, err := flow.Login(a.ctx)
// Step 1: device-authorize → a bootstrap machine token (proves identity, no meta).
boot, err := flow.Login(a.ctx)
if err != nil {
runtime.EventsEmit(a.ctx, "oauth:error", map[string]string{"detail": err.Error()})
return
}
res, err := loginResultFromToken(tok)
// Step 2: 代铸 the bootstrap token into a cdrop-managed device session bound to this
// device's stable device_id, so the desktop is managed exactly like a browser. The
// device session's tokens supersede the bootstrap (which is discarded, left to expire).
deviceID, err := platform.ResolveDeviceID()
if err != nil {
runtime.EventsEmit(a.ctx, "oauth:error", map[string]string{"detail": err.Error()})
return
}
a.token = tok
ds, err := platform.MintDeviceSession(a.ctx, a.apiBase, boot.AccessToken, deviceID, platform.ResolveDeviceName(), platform.DeviceType())
if err != nil {
runtime.EventsEmit(a.ctx, "oauth:error", map[string]string{"detail": err.Error()})
return
}
// Identity from the verified 代铸 response (X-Auth-Subject / X-Auth-Name / X-Auth-Avatar),
// so the real display name and picture show rather than the subject UUID a nameless
// machine token yields.
user := platform.UserInfo{ID: ds.UserID, Name: ds.Name, Avatar: ds.Avatar}
if user.Name == "" {
user.Name = user.ID
}
res := &platform.LoginResult{
AccessToken: ds.AccessToken,
RefreshToken: ds.RefreshToken,
ExpiresIn: ds.ExpiresIn,
User: user,
}
a.token = &platform.TokenResult{AccessToken: ds.AccessToken, RefreshToken: ds.RefreshToken, ExpiresIn: ds.ExpiresIn}
a.user = user
if err := platform.SaveSession(*res); err != nil {
runtime.LogWarningf(a.ctx, "persist session failed: %v", err)
}
@@ -262,9 +272,15 @@ func (a *App) Refresh() (*platform.SessionView, error) {
if tok.RefreshToken == "" {
tok.RefreshToken = a.token.RefreshToken // providers that don't rotate: keep the old one
}
res, err := loginResultFromToken(tok)
if err != nil {
return nil, err
// Preserve the identity established at login: the refreshed access token is a nameless
// machine token (it carries meta, not the display name), so re-deriving identity from it
// would regress the name to the subject UUID. The device session keeps its meta across
// rotation, so the device stays the same managed device.
res := &platform.LoginResult{
AccessToken: tok.AccessToken,
RefreshToken: tok.RefreshToken,
ExpiresIn: tok.ExpiresIn,
User: a.user,
}
a.token = tok
if err := platform.SaveSession(*res); err != nil {
@@ -368,11 +384,11 @@ func (a *App) EffectiveDownloadDir() string {
return platform.ResolveDownloadDir()
}
// resolveOAuthConfig prefers explicit env overrides (dev / a pinned client);
// otherwise it fetches /api/auth/config from the backend and reuses the web
// app's client_id for the desktop's loopback PKCE flow (see desktop/PLAN.md §3).
// resolveOAuthConfig prefers explicit env overrides (dev / a pinned broker);
// otherwise it fetches /api/auth/config from the backend for the broker's public URL,
// then runs the broker device-authorization flow against it.
func (a *App) resolveOAuthConfig() (platform.OAuthConfig, error) {
if env := oauthConfigFromEnv(); env.ClientID != "" {
if env := oauthConfigFromEnv(); env.BrokerURL != "" {
return env, nil
}
return platform.FetchOAuthConfig(a.ctx, a.apiBase)
@@ -380,10 +396,8 @@ func (a *App) resolveOAuthConfig() (platform.OAuthConfig, error) {
func oauthConfigFromEnv() platform.OAuthConfig {
return platform.OAuthConfig{
AuthorizeURL: os.Getenv("CDROP_OAUTH_AUTHORIZE_URL"),
TokenURL: os.Getenv("CDROP_OAUTH_TOKEN_URL"),
ClientID: os.Getenv("CDROP_OAUTH_CLIENT_ID"),
Scopes: os.Getenv("CDROP_OAUTH_SCOPES"),
BrokerURL: os.Getenv("CDROP_BROKER_URL"),
App: envOr("CDROP_BROKER_APP", "cdrop"),
}
}
+7 -9
View File
@@ -44,20 +44,18 @@ func main() {
// Tell the backend this is a native desktop client, not a browser, so the
// device list shows the right kind. The page forwards it as X-Device-Type.
deviceType := ""
switch runtime.GOOS {
case "darwin":
deviceType = "macos"
case "windows":
deviceType = "windows"
case "linux":
deviceType = "linux"
}
deviceType := platform.DeviceType()
// Restore the persisted login + device name by injecting them into index.html
// at load — the wails:// scheme has no persistent WebView storage (see
// session.go).
session, _ := platform.LoadSession()
// Heal a stale display identity (older builds baked the subject UUID and no avatar into
// the on-disk session) from the authoritative /api/me, and re-persist, BEFORE injecting it
// — so the name + picture are correct on every launch instead of depending on a fragile
// per-launch WebView /api/me (the source of the intermittent UUID regression). Bounded +
// best-effort: offline keeps the persisted identity.
session = platform.HealIdentity(session, app.apiBase)
// When the OS starts us at login, the autostart entry appends a --hidden flag
// (see SetLaunchAtLogin). Come up straight to the menu bar / tray with no
+41
View File
@@ -1,10 +1,13 @@
package platform
import (
"crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"os"
"path/filepath"
"runtime"
)
// DesktopConfig is the desktop-only preference set, persisted as JSON under the
@@ -14,6 +17,44 @@ type DesktopConfig struct {
LaunchAtLogin bool `json:"launch_at_login"`
DeviceName string `json:"device_name"` // empty = use the hostname
DownloadDir string `json:"download_dir"` // empty = system Downloads dir
// DeviceID is this device's stable opaque cdrop id — the broker `meta` and the
// session<->device join key. Minted once on first login and persisted so re-logins
// rotate the one managed device session (broker R2) instead of spawning duplicates.
DeviceID string `json:"device_id,omitempty"`
}
// DeviceType maps the host OS to the cdrop device kind, shown in the unified device list
// and sent as device_type when 代铸ing this device's session.
func DeviceType() string {
switch runtime.GOOS {
case "darwin":
return "macos"
case "windows":
return "windows"
case "linux":
return "linux"
default:
return "browser"
}
}
// ResolveDeviceID returns the persisted stable device_id, minting and persisting a fresh
// one ("dev_" + base64url(16 random bytes)) on first use. The format matches the backend's
// newDeviceID, so it passes validDeviceID and the broker's meta validation.
func ResolveDeviceID() (string, error) {
cfg, _ := LoadConfig()
if cfg.DeviceID != "" {
return cfg.DeviceID, nil
}
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return "", err
}
cfg.DeviceID = "dev_" + base64.RawURLEncoding.EncodeToString(b)
if err := SaveConfig(cfg); err != nil {
return "", err
}
return cfg.DeviceID, nil
}
// ResolveDeviceName returns the persisted device name, or the hostname when the
+13 -16
View File
@@ -10,11 +10,11 @@ import (
"time"
)
// FetchOAuthConfig pulls the provider coordinates from the cdrop backend's
// /api/auth/config. The desktop reuses the same OAuth client as the web app
// (the client_id published there) and runs its own loopback PKCE flow against
// the provider, instead of the browser's in-page redirect + /api/auth/exchange
// proxy. apiBase is the backend origin, e.g. https://drop.commilitia.net.
// FetchOAuthConfig pulls the Auth Broker coordinates from the cdrop backend's
// /api/auth/config (broker_url = the broker's public origin). The desktop runs the
// broker device-authorization flow (RFC 8252 loopback PKCE) against that broker,
// minting a cdrop-scoped machine token. apiBase is the backend origin, e.g.
// https://drop.commilitia.net.
func FetchOAuthConfig(ctx context.Context, apiBase string) (OAuthConfig, error) {
endpoint := strings.TrimRight(apiBase, "/") + "/api/auth/config"
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
@@ -34,23 +34,20 @@ func FetchOAuthConfig(ctx context.Context, apiBase string) (OAuthConfig, error)
}
var c struct {
AuthorizeURL string `json:"authorize_url"`
TokenURL string `json:"token_url"`
ClientID string `json:"client_id"`
Scopes string `json:"scopes"`
BrokerURL string `json:"broker_url"`
App string `json:"broker_app"`
}
if err := json.NewDecoder(resp.Body).Decode(&c); err != nil {
return OAuthConfig{}, fmt.Errorf("oauth: decode config: %w", err)
}
cfg := OAuthConfig{
AuthorizeURL: c.AuthorizeURL,
TokenURL: c.TokenURL,
ClientID: c.ClientID,
Scopes: c.Scopes,
app := c.App
if app == "" {
app = "cdrop"
}
if cfg.AuthorizeURL == "" || cfg.TokenURL == "" || cfg.ClientID == "" {
return OAuthConfig{}, errors.New("oauth: backend config missing authorize_url / token_url / client_id")
cfg := OAuthConfig{BrokerURL: c.BrokerURL, App: app}
if cfg.BrokerURL == "" {
return OAuthConfig{}, errors.New("oauth: backend config missing broker_url")
}
return cfg, nil
}
+25 -20
View File
@@ -15,12 +15,9 @@ func TestFetchOAuthConfig_Success(t *testing.T) {
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"auth_mode": "prod",
"authorize_url": "https://casdoor.example/login/oauth/authorize",
"token_url": "https://casdoor.example/api/login/oauth/access_token",
"client_id": "web-client-id",
"redirect_uri": "https://drop.example/oauth/callback",
"scopes": "openid profile groups",
"auth_mode": "prod",
"broker_url": "https://sso.example.net",
"broker_app": "cdrop",
})
}))
defer srv.Close()
@@ -30,30 +27,39 @@ func TestFetchOAuthConfig_Success(t *testing.T) {
if err != nil {
t.Fatalf("FetchOAuthConfig: %v", err)
}
if cfg.ClientID != "web-client-id" {
t.Errorf("client_id = %q, want web-client-id (reused web client)", cfg.ClientID)
if cfg.BrokerURL != "https://sso.example.net" {
t.Errorf("broker_url = %q", cfg.BrokerURL)
}
if cfg.TokenURL != "https://casdoor.example/api/login/oauth/access_token" {
t.Errorf("token_url = %q", cfg.TokenURL)
if cfg.App != "cdrop" {
t.Errorf("app = %q, want cdrop", cfg.App)
}
if cfg.Scopes != "openid profile groups" {
t.Errorf("scopes = %q", cfg.Scopes)
}
func TestFetchOAuthConfig_DefaultsApp(t *testing.T) {
// broker_app omitted → defaults to "cdrop".
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{"broker_url": "https://sso.example.net"})
}))
defer srv.Close()
cfg, err := FetchOAuthConfig(context.Background(), srv.URL)
if err != nil {
t.Fatalf("FetchOAuthConfig: %v", err)
}
if cfg.App != "cdrop" {
t.Errorf("app = %q, want default cdrop", cfg.App)
}
}
func TestFetchOAuthConfig_Incomplete(t *testing.T) {
// backend missing token_url / client_id (e.g. dev mode) must be rejected.
// backend missing broker_url (native login not configured) must be rejected.
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"auth_mode": "dev",
"authorize_url": "https://casdoor.example/login/oauth/authorize",
})
_ = json.NewEncoder(w).Encode(map[string]any{"auth_mode": "prod"})
}))
defer srv.Close()
if _, err := FetchOAuthConfig(context.Background(), srv.URL); err == nil {
t.Fatal("want error for incomplete backend config, got nil")
t.Fatal("want error for missing broker_url, got nil")
}
}
@@ -62,7 +68,6 @@ func TestFetchOAuthConfig_BadStatus(t *testing.T) {
w.WriteHeader(http.StatusInternalServerError)
}))
defer srv.Close()
if _, err := FetchOAuthConfig(context.Background(), srv.URL); err == nil {
t.Fatal("want error for 500 status, got nil")
}
+89
View File
@@ -0,0 +1,89 @@
package platform
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"time"
)
// 代铸 (proxy-mint) on the desktop. The device-authorization flow yields a bootstrap
// machine token (scope app:cdrop, no meta) that proves the user's identity but is not a
// cdrop-managed device. This call exchanges it for a managed device session bound to this
// device's stable device_id, so the desktop joins cdrop's unified device list and is
// managed exactly like a browser — the same model, not a separate native-only track.
// DeviceSessionResult is the managed device session minted by 代铸: the device tokens that
// supersede the bootstrap token, plus the verified identity (so a native client, which only
// ever sees nameless machine tokens, shows the real display name instead of the sub UUID).
type DeviceSessionResult struct {
AccessToken string
RefreshToken string
ExpiresIn int
DeviceID string
UserID string
Name string
Avatar string
}
// MintDeviceSession POSTs to {apiBase}/api/auth/device-session with the bootstrap token as
// Bearer; cdrop vouches for the verified subject and has the broker mint (R2-idempotent by
// user+app+meta) a session bound to deviceID. Re-login with the same deviceID rotates the
// one session rather than piling up duplicates.
func MintDeviceSession(ctx context.Context, apiBase, bootstrapToken, deviceID, deviceName, deviceType string) (*DeviceSessionResult, error) {
body, err := json.Marshal(map[string]string{
"device_id": deviceID,
"device_name": deviceName,
"device_type": deviceType,
})
if err != nil {
return nil, fmt.Errorf("device-session: marshal: %w", err)
}
endpoint := strings.TrimRight(apiBase, "/") + "/api/auth/device-session"
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
if err != nil {
return nil, fmt.Errorf("device-session: build request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", "Bearer "+bootstrapToken)
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("device-session: request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("device-session: status %d", resp.StatusCode)
}
var dr struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
ExpiresIn int `json:"expires_in"`
DeviceID string `json:"device_id"`
UserID string `json:"user_id"`
Name string `json:"name"`
Avatar string `json:"avatar"`
}
if err := json.NewDecoder(resp.Body).Decode(&dr); err != nil {
return nil, fmt.Errorf("device-session: decode: %w", err)
}
if dr.AccessToken == "" {
return nil, errors.New("device-session: response missing access token")
}
return &DeviceSessionResult{
AccessToken: dr.AccessToken,
RefreshToken: dr.RefreshToken,
ExpiresIn: dr.ExpiresIn,
DeviceID: dr.DeviceID,
UserID: dr.UserID,
Name: dr.Name,
Avatar: dr.Avatar,
}, nil
}
+81
View File
@@ -0,0 +1,81 @@
package platform
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// MintDeviceSession sends the bootstrap token as Bearer + the device descriptor, and maps
// the response into the device-session result the desktop then rides.
func TestMintDeviceSession(t *testing.T) {
var gotAuth string
var gotBody map[string]string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost || r.URL.Path != "/api/auth/device-session" {
http.NotFound(w, r)
return
}
gotAuth = r.Header.Get("Authorization")
_ = json.NewDecoder(r.Body).Decode(&gotBody)
_ = json.NewEncoder(w).Encode(map[string]any{
"access_token": "acc-x", "refresh_token": "rtk-x", "expires_in": 900,
"device_id": "dev_abc", "user_id": "sub-1", "name": "Commilitia",
"avatar": "https://example.net/a.png",
})
}))
defer srv.Close()
res, err := MintDeviceSession(context.Background(), srv.URL, "boot-token", "dev_abc", "Mac", "macos")
if err != nil {
t.Fatalf("MintDeviceSession: %v", err)
}
if gotAuth != "Bearer boot-token" {
t.Errorf("Authorization: got %q, want Bearer boot-token", gotAuth)
}
if gotBody["device_id"] != "dev_abc" || gotBody["device_name"] != "Mac" || gotBody["device_type"] != "macos" {
t.Errorf("request body: %+v", gotBody)
}
if res.AccessToken != "acc-x" || res.RefreshToken != "rtk-x" || res.DeviceID != "dev_abc" ||
res.UserID != "sub-1" || res.Name != "Commilitia" || res.ExpiresIn != 900 ||
res.Avatar != "https://example.net/a.png" {
t.Errorf("result: %+v", res)
}
}
// A non-200 from the endpoint surfaces as an error rather than a half-built session.
func TestMintDeviceSession_ErrorStatus(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusBadGateway)
}))
defer srv.Close()
if _, err := MintDeviceSession(context.Background(), srv.URL, "boot", "dev_abc", "Mac", "macos"); err == nil {
t.Fatal("expected error on non-200, got nil")
}
}
// ResolveDeviceID mints a validMeta-safe "dev_"-prefixed id and persists it (stable across
// calls). Uses an isolated config dir so it doesn't touch the real one.
func TestResolveDeviceID(t *testing.T) {
// os.UserConfigDir honours XDG_CONFIG_HOME on Linux and HOME on macOS.
dir := t.TempDir()
t.Setenv("XDG_CONFIG_HOME", dir)
t.Setenv("HOME", dir)
id, err := ResolveDeviceID()
if err != nil {
t.Fatalf("ResolveDeviceID: %v", err)
}
if !strings.HasPrefix(id, "dev_") || len(id) < 8 {
t.Errorf("device id format: %q", id)
}
again, err := ResolveDeviceID()
if err != nil {
t.Fatalf("ResolveDeviceID (2): %v", err)
}
if again != id {
t.Errorf("device id not stable: %q != %q", again, id)
}
}
+104
View File
@@ -0,0 +1,104 @@
package platform
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"strings"
"time"
)
// HealIdentity refreshes a persisted session's display identity (name + avatar) from the
// authoritative /api/me and re-persists it, BEFORE the session is injected into the WebView.
//
// Why: a session minted by an older build derived identity from the broker's nameless machine
// token, baking the subject UUID (and no avatar) into the on-disk session. The newer login path
// records the real name/picture, but an already-logged-in user keeps the stale session. Correcting
// it only in the WebView (per launch, via /api/me) is fragile — when the boot access token has
// expired and the refresh is momentarily flaky, the correction silently fails and the UUID shows
// again (the reported intermittent regression). Healing the persisted session here fixes it at the
// source: once a single launch succeeds, the on-disk identity is correct and every later boot is
// correct without any /api/me dependency.
//
// Synchronous and bounded so it can run before wails.Run; best-effort — on any network failure it
// returns the session unchanged (offline simply keeps whatever was last persisted, which a prior
// successful heal already corrected). If the access token has expired it refreshes once (and the
// rotated refresh token is persisted so it is not lost).
func HealIdentity(s *LoginResult, apiBase string) *LoginResult {
if s == nil || s.AccessToken == "" {
return s
}
// Once healed, the persisted name is a real display name (not the subject UUID); skip the
// /api/me round-trip then so it costs nothing on every later launch. A stale session (name
// still equal to the UUID) falls through and heals — fetching the avatar in the same pass.
if s.User.Name != "" && s.User.Name != s.User.ID {
return s
}
ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second)
defer cancel()
info, status := fetchMe(ctx, apiBase, s.AccessToken)
tokenRotated := false
if status == http.StatusUnauthorized && s.RefreshToken != "" {
if cfg, err := FetchOAuthConfig(ctx, apiBase); err == nil {
if tok, rerr := NewFlow(cfg, func(string) {}).Refresh(ctx, s.RefreshToken); rerr == nil && tok.AccessToken != "" {
s.AccessToken = tok.AccessToken
if tok.RefreshToken != "" {
s.RefreshToken = tok.RefreshToken // broker rotates refresh; the old one is now dead
}
s.ExpiresIn = tok.ExpiresIn
tokenRotated = true
info, status = fetchMe(ctx, apiBase, s.AccessToken)
}
}
}
changed := tokenRotated // a rotated refresh token must be persisted, regardless of the heal outcome
if status == http.StatusOK && info.ID != "" {
// Replace a stale name only with a real display name (not the subject UUID).
if info.Name != "" && info.Name != info.ID && info.Name != s.User.Name {
s.User.Name = info.Name
changed = true
}
if info.Avatar != "" && info.Avatar != s.User.Avatar {
s.User.Avatar = info.Avatar
changed = true
}
}
if changed {
if err := SaveSession(*s); err != nil {
slog.Warn("cdrop: heal identity save failed", "err", err)
}
}
return s
}
// fetchMe GETs /api/me with the access token, returning the identity and HTTP status (0 on a
// transport error). It hits the public origin directly (no WebView proxy needed here).
func fetchMe(ctx context.Context, apiBase, accessToken string) (UserInfo, int) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(apiBase, "/")+"/api/me", nil)
if err != nil {
return UserInfo{}, 0
}
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("Accept", "application/json")
resp, err := (&http.Client{Timeout: 10 * time.Second}).Do(req)
if err != nil {
return UserInfo{}, 0
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return UserInfo{}, resp.StatusCode
}
var m struct {
UserID string `json:"user_id"`
Name string `json:"name"`
Avatar string `json:"avatar"`
}
if err := json.NewDecoder(resp.Body).Decode(&m); err != nil {
return UserInfo{}, 0
}
return UserInfo{ID: m.UserID, Name: m.Name, Avatar: m.Avatar}, http.StatusOK
}
+66
View File
@@ -0,0 +1,66 @@
package platform
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
keyring "github.com/zalando/go-keyring"
)
// A session whose name is still the subject UUID (minted by an older build) heals from
// /api/me — name + avatar corrected and re-persisted, so later launches are correct without
// any further /api/me.
func TestHealIdentity_StaleNameHealed(t *testing.T) {
keyring.MockInit()
dir := t.TempDir()
t.Setenv("XDG_CONFIG_HOME", dir)
t.Setenv("HOME", dir)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/api/me" {
_ = json.NewEncoder(w).Encode(map[string]any{
"user_id": "sub-1", "name": "Commilitia", "avatar": "https://a.net/x.png",
})
return
}
w.WriteHeader(http.StatusNotFound)
}))
defer srv.Close()
s := &LoginResult{
AccessToken: "acc", RefreshToken: "rtk", ExpiresIn: 900,
User: UserInfo{ID: "sub-1", Name: "sub-1"}, // stale: name == subject UUID
}
out := HealIdentity(s, srv.URL)
if out.User.Name != "Commilitia" {
t.Errorf("name: got %q, want Commilitia", out.User.Name)
}
if out.User.Avatar != "https://a.net/x.png" {
t.Errorf("avatar: got %q, want the /api/me avatar", out.User.Avatar)
}
loaded, err := LoadSession()
if err != nil || loaded == nil || loaded.User.Name != "Commilitia" || loaded.User.Avatar != "https://a.net/x.png" {
t.Errorf("heal not persisted: %+v (err %v)", loaded, err)
}
}
// A session that already has a real display name is left untouched and never hits /api/me.
func TestHealIdentity_HealthyNameSkips(t *testing.T) {
called := false
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
called = true
w.WriteHeader(http.StatusNotFound)
}))
defer srv.Close()
s := &LoginResult{AccessToken: "acc", User: UserInfo{ID: "sub-1", Name: "Commilitia"}}
out := HealIdentity(s, srv.URL)
if called {
t.Error("a healthy identity must skip the /api/me round-trip")
}
if out.User.Name != "Commilitia" {
t.Errorf("name changed unexpectedly: %q", out.User.Name)
}
}
+69 -68
View File
@@ -1,10 +1,12 @@
// Package platform implements cdrop desktop's native capabilities — the Go
// shell that the shared web UI drives over Wails bindings.
//
// This file owns the OAuth login flow: an RFC 8252 loopback redirect against
// Casdoor with PKCE as a public client (no secret). The authorization code
// exchange happens here in Go on purpose, so the PKCE verifier and the
// resulting tokens never enter the WebView / JS context.
// This file owns the login flow: the Auth Broker device-authorization flow (RFC
// 8252 loopback redirect with PKCE, as a public client no secret). The desktop
// opens the system browser at the broker's consent page; on approval the broker
// redirects to the loopback /callback with a one-time code, which Go exchanges
// (with the PKCE verifier) for a broker machine token. The verifier and the
// resulting tokens never enter the WebView / JS context — refresh is Go-driven.
package platform
import (
@@ -22,29 +24,25 @@ import (
"time"
)
// OAuthConfig carries the provider coordinates. For Casdoor the token endpoint
// is /api/login/oauth/access_token (non-standard) and authorize is
// /login/oauth/authorize; the desktop registers as its own public client.
// OAuthConfig carries the Auth Broker coordinates. BrokerURL is the broker's PUBLIC
// origin (e.g. https://sso.commilitia.net); App is this app's key in the broker apps
// registry ("cdrop"). The app's loopback redirect must be registered in the broker's
// apps.json (redirect_uris) for the device flow to accept it.
type OAuthConfig struct {
AuthorizeURL string
TokenURL string
ClientID string
Scopes string // space-separated; empty defaults to "openid profile groups"
BrokerURL string
App string
}
// TokenResult is the subset of the token response the shell keeps. IDToken is
// captured so the identity can be decoded from the richer id_token claims (it's
// present when the openid scope is granted — our default scopes include it).
// TokenResult is the subset of the broker token response the shell keeps. ExpiresIn
// is derived from the broker's access_expires (unix) at parse time.
type TokenResult 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"`
AccessToken string
RefreshToken string
ExpiresIn int
}
// Flow runs one interactive login. openURL is injected so production uses
// Wails' runtime.BrowserOpenURL while tests substitute a fake user-agent.
// Flow runs one interactive login. openURL is injected so production uses Wails'
// runtime.BrowserOpenURL while tests substitute a fake user-agent.
type Flow struct {
cfg OAuthConfig
openURL func(string)
@@ -63,15 +61,17 @@ func NewFlow(cfg OAuthConfig, openURL func(string)) *Flow {
}
}
// Login performs the loopback PKCE flow and returns the exchanged tokens.
// Login performs the broker device-authorization loopback PKCE flow and returns the
// minted machine token.
//
// Steps: generate verifier/challenge/state → bind an ephemeral 127.0.0.1
// listener → open the system browser at the authorize URL → wait for the
// browser to hit the loopback /callback with the code → validate state →
// exchange code+verifier at the token endpoint. The verifier never leaves Go.
// Steps: generate verifier/challenge/state → bind an ephemeral 127.0.0.1 listener →
// open the system browser at the broker's /device/authorize (which sends the user
// through broker SSO if needed, then shows a consent page) → wait for the browser to
// hit the loopback /callback with the code → validate state → exchange code+verifier
// at /device/token. The verifier never leaves Go.
func (f *Flow) Login(ctx context.Context) (*TokenResult, error) {
if f.cfg.AuthorizeURL == "" || f.cfg.TokenURL == "" || f.cfg.ClientID == "" {
return nil, errors.New("oauth: incomplete config (authorize_url / token_url / client_id)")
if f.cfg.BrokerURL == "" || f.cfg.App == "" {
return nil, errors.New("oauth: incomplete config (broker_url / app)")
}
verifier, challenge, err := newPKCE()
@@ -132,14 +132,13 @@ func (f *Flow) Login(ctx context.Context) (*TokenResult, error) {
go func() { _ = srv.Serve(ln) }()
defer srv.Close()
authURL := f.cfg.AuthorizeURL + "?" + url.Values{
"response_type": {"code"},
"client_id": {f.cfg.ClientID},
authURL := strings.TrimRight(f.cfg.BrokerURL, "/") + "/device/authorize?" + url.Values{
"app": {f.cfg.App},
"redirect_uri": {redirectURI},
"scope": {f.scopes()},
"state": {state},
"code_challenge": {challenge},
"code_challenge_method": {"S256"},
"description": {"cdrop 桌面客户端"},
}.Encode()
f.openURL(authURL)
@@ -156,52 +155,50 @@ func (f *Flow) Login(ctx context.Context) (*TokenResult, error) {
}
}
func (f *Flow) scopes() string {
if s := strings.TrimSpace(f.cfg.Scopes); s != "" {
return s
}
return "openid profile groups"
}
// exchange trades the authorization code + PKCE verifier for tokens. Casdoor
// accepts form-encoded public-client requests (no client_secret). authorize and
// token must carry the identical redirect_uri, so we pass the same value.
// exchange trades the authorization code + PKCE verifier (+ the same redirect_uri)
// for the broker machine token at /device/token.
func (f *Flow) exchange(ctx context.Context, code, verifier, redirectURI string) (*TokenResult, error) {
return f.postToken(ctx, url.Values{
"grant_type": {"authorization_code"},
"code": {code},
"code_verifier": {verifier},
"client_id": {f.cfg.ClientID},
"redirect_uri": {redirectURI},
return f.postJSON(ctx, strings.TrimRight(f.cfg.BrokerURL, "/")+"/device/token", map[string]string{
"code": code,
"code_verifier": verifier,
"redirect_uri": redirectURI,
})
}
// Refresh exchanges a refresh_token for a fresh token (public client, no
// secret). Call it when the access token nears expiry; the access token never
// leaves Go, so refresh is driven from the shell, not the WebView.
// Refresh exchanges a refresh credential for a fresh access token (+ rotated refresh)
// at the broker's /refresh. Call it when the access token nears expiry; the refresh
// credential never leaves Go, so refresh is driven from the shell, not the WebView.
func (f *Flow) Refresh(ctx context.Context, refreshToken string) (*TokenResult, error) {
if f.cfg.TokenURL == "" || f.cfg.ClientID == "" {
return nil, errors.New("oauth: incomplete config (token_url / client_id)")
if f.cfg.BrokerURL == "" {
return nil, errors.New("oauth: incomplete config (broker_url)")
}
if refreshToken == "" {
return nil, errors.New("oauth: empty refresh token")
}
return f.postToken(ctx, url.Values{
"grant_type": {"refresh_token"},
"refresh_token": {refreshToken},
"client_id": {f.cfg.ClientID},
"scope": {f.scopes()},
return f.postJSON(ctx, strings.TrimRight(f.cfg.BrokerURL, "/")+"/refresh", map[string]string{
"refresh": refreshToken,
})
}
// postToken POSTs a form-encoded request to the token endpoint and decodes the
// response. Shared by the authorization-code exchange and refresh.
func (f *Flow) postToken(ctx context.Context, form url.Values) (*TokenResult, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, f.cfg.TokenURL, strings.NewReader(form.Encode()))
// brokerTokenResp is the broker's response shape for /device/token and /refresh.
type brokerTokenResp struct {
Access string `json:"access"`
Refresh string `json:"refresh"`
AccessExpires int64 `json:"access_expires"`
}
// postJSON POSTs a JSON body to a broker token endpoint and decodes the response.
// Shared by the device-token exchange and refresh.
func (f *Flow) postJSON(ctx context.Context, endpoint string, body map[string]string) (*TokenResult, error) {
buf, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("oauth: marshal token request: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(string(buf)))
if err != nil {
return nil, fmt.Errorf("oauth: build token request: %w", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
resp, err := f.client.Do(req)
@@ -212,14 +209,18 @@ func (f *Flow) postToken(ctx context.Context, form url.Values) (*TokenResult, er
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("oauth: token endpoint status %d", resp.StatusCode)
}
var tok TokenResult
if err := json.NewDecoder(resp.Body).Decode(&tok); err != nil {
var tr brokerTokenResp
if err := json.NewDecoder(resp.Body).Decode(&tr); err != nil {
return nil, fmt.Errorf("oauth: decode token: %w", err)
}
if tok.AccessToken == "" {
return nil, errors.New("oauth: token response missing access_token")
if tr.Access == "" {
return nil, errors.New("oauth: token response missing access")
}
return &tok, nil
expiresIn := int(tr.AccessExpires - time.Now().Unix())
if expiresIn < 0 {
expiresIn = 0
}
return &TokenResult{AccessToken: tr.Access, RefreshToken: tr.Refresh, ExpiresIn: expiresIn}, nil
}
// --- PKCE (RFC 7636) ---
+63 -69
View File
@@ -10,6 +10,7 @@ import (
"net/url"
"strings"
"testing"
"time"
)
func TestNewPKCE(t *testing.T) {
@@ -32,45 +33,55 @@ func TestNewPKCE(t *testing.T) {
}
}
// TestLogin_Success drives the whole loopback flow with a fake Casdoor token
// endpoint and a fake browser, with no real network or prod dependency.
// decodeBody reads a JSON request body into a map.
func decodeBody(t *testing.T, r *http.Request) map[string]string {
t.Helper()
var m map[string]string
if err := json.NewDecoder(r.Body).Decode(&m); err != nil {
t.Fatalf("decode body: %v", err)
}
return m
}
// TestLogin_Success drives the whole broker device-authorization loopback flow with a
// fake /device/token endpoint and a fake browser — no real network or prod dependency.
func TestLogin_Success(t *testing.T) {
var gotForm url.Values
tokenSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
t.Errorf("token endpoint ParseForm: %v", err)
var gotBody map[string]string
brokerSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/device/token" {
t.Errorf("token path = %s, want /device/token", r.URL.Path)
}
gotForm = r.PostForm
gotBody = decodeBody(t, r)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"access_token": "at-123",
"refresh_token": "rt-456",
"expires_in": 3600,
"token_type": "Bearer",
"id": "sid-1",
"app": "cdrop",
"access": "at-123",
"refresh": "rtk-456",
"access_expires": time.Now().Add(15 * time.Minute).Unix(),
})
}))
defer tokenSrv.Close()
defer brokerSrv.Close()
cfg := OAuthConfig{
AuthorizeURL: "https://casdoor.example/login/oauth/authorize",
TokenURL: tokenSrv.URL,
ClientID: "cdrop-desktop",
}
cfg := OAuthConfig{BrokerURL: brokerSrv.URL, App: "cdrop"}
// Fake browser: parse the authorize URL, assert it carries PKCE, then GET
// the loopback redirect with a code + the same state (authorized).
// Fake browser: parse the /device/authorize URL, assert it carries app + PKCE,
// then GET the loopback redirect with a code + the same state (approved).
openURL := func(authURL string) {
u, err := url.Parse(authURL)
if err != nil {
t.Errorf("parse authURL: %v", err)
return
}
if !strings.HasSuffix(u.Path, "/device/authorize") {
t.Errorf("authorize path = %s, want /device/authorize", u.Path)
}
q := u.Query()
if q.Get("code_challenge") == "" || q.Get("code_challenge_method") != "S256" {
t.Errorf("authorize request missing PKCE challenge: %v", q)
}
if q.Get("client_id") != "cdrop-desktop" {
t.Errorf("authorize client_id = %q", q.Get("client_id"))
if q.Get("app") != "cdrop" {
t.Errorf("authorize app = %q", q.Get("app"))
}
cb := q.Get("redirect_uri") + "?code=auth-code-xyz&state=" + url.QueryEscape(q.Get("state"))
resp, err := http.Get(cb)
@@ -86,37 +97,29 @@ func TestLogin_Success(t *testing.T) {
t.Fatalf("Login: %v", err)
}
if tok.AccessToken != "at-123" {
t.Errorf("access_token = %q, want at-123", tok.AccessToken)
t.Errorf("access = %q, want at-123", tok.AccessToken)
}
if tok.RefreshToken != "rt-456" {
t.Errorf("refresh_token = %q, want rt-456", tok.RefreshToken)
if tok.RefreshToken != "rtk-456" {
t.Errorf("refresh = %q, want rtk-456", tok.RefreshToken)
}
if tok.ExpiresIn != 3600 {
t.Errorf("expires_in = %d, want 3600", tok.ExpiresIn)
if tok.ExpiresIn <= 0 || tok.ExpiresIn > 900 {
t.Errorf("expires_in = %d, want ~900 (derived from access_expires)", tok.ExpiresIn)
}
// The exchange must carry the code + PKCE verifier and, as a public client,
// no client_secret.
if gotForm.Get("grant_type") != "authorization_code" {
t.Errorf("grant_type = %q", gotForm.Get("grant_type"))
// The exchange must carry the code, the PKCE verifier, and the same redirect_uri.
if gotBody["code"] != "auth-code-xyz" {
t.Errorf("code = %q", gotBody["code"])
}
if gotForm.Get("code") != "auth-code-xyz" {
t.Errorf("code = %q", gotForm.Get("code"))
}
if gotForm.Get("code_verifier") == "" {
if gotBody["code_verifier"] == "" {
t.Error("token exchange missing code_verifier")
}
if gotForm.Get("client_secret") != "" {
t.Error("public client must not send client_secret")
if !strings.HasPrefix(gotBody["redirect_uri"], "http://127.0.0.1:") {
t.Errorf("redirect_uri = %q, want loopback", gotBody["redirect_uri"])
}
}
func TestLogin_StateMismatch(t *testing.T) {
cfg := OAuthConfig{
AuthorizeURL: "https://casdoor.example/login/oauth/authorize",
TokenURL: "https://casdoor.example/token",
ClientID: "cdrop-desktop",
}
cfg := OAuthConfig{BrokerURL: "https://sso.example.net", App: "cdrop"}
openURL := func(authURL string) {
u, _ := url.Parse(authURL)
redirect := u.Query().Get("redirect_uri")
@@ -132,55 +135,46 @@ func TestLogin_StateMismatch(t *testing.T) {
}
func TestLogin_IncompleteConfig(t *testing.T) {
_, err := NewFlow(OAuthConfig{ClientID: "only-id"}, func(string) {}).Login(context.Background())
_, err := NewFlow(OAuthConfig{App: "only-app"}, func(string) {}).Login(context.Background())
if err == nil {
t.Fatal("want error for incomplete config, got nil")
}
}
func TestRefresh_Success(t *testing.T) {
var gotForm url.Values
tokenSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = r.ParseForm()
gotForm = r.PostForm
var gotBody map[string]string
brokerSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/refresh" {
t.Errorf("refresh path = %s, want /refresh", r.URL.Path)
}
gotBody = decodeBody(t, r)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"access_token": "new-at",
"refresh_token": "new-rt",
"expires_in": 3600,
"access": "new-at",
"refresh": "new-rtk",
"access_expires": time.Now().Add(15 * time.Minute).Unix(),
})
}))
defer tokenSrv.Close()
defer brokerSrv.Close()
cfg := OAuthConfig{
AuthorizeURL: "https://casdoor.example/login/oauth/authorize",
TokenURL: tokenSrv.URL,
ClientID: "cdrop-desktop",
}
tok, err := NewFlow(cfg, func(string) {}).Refresh(context.Background(), "old-rt")
cfg := OAuthConfig{BrokerURL: brokerSrv.URL, App: "cdrop"}
tok, err := NewFlow(cfg, func(string) {}).Refresh(context.Background(), "old-rtk")
if err != nil {
t.Fatalf("Refresh: %v", err)
}
if tok.AccessToken != "new-at" {
t.Errorf("access_token = %q, want new-at", tok.AccessToken)
t.Errorf("access = %q, want new-at", tok.AccessToken)
}
if gotForm.Get("grant_type") != "refresh_token" {
t.Errorf("grant_type = %q", gotForm.Get("grant_type"))
if tok.RefreshToken != "new-rtk" {
t.Errorf("refresh = %q, want new-rtk (rotated)", tok.RefreshToken)
}
if gotForm.Get("refresh_token") != "old-rt" {
t.Errorf("refresh_token = %q", gotForm.Get("refresh_token"))
}
if gotForm.Get("client_secret") != "" {
t.Error("public client must not send client_secret on refresh")
if gotBody["refresh"] != "old-rtk" {
t.Errorf("sent refresh = %q, want old-rtk", gotBody["refresh"])
}
}
func TestRefresh_EmptyToken(t *testing.T) {
cfg := OAuthConfig{
AuthorizeURL: "https://x/authorize",
TokenURL: "https://x/token",
ClientID: "c",
}
cfg := OAuthConfig{BrokerURL: "https://sso.example.net", App: "cdrop"}
if _, err := NewFlow(cfg, func(string) {}).Refresh(context.Background(), ""); err == nil {
t.Fatal("want error for empty refresh token")
}