Repository navigation
Desktop sign-in through an approved loopback exchange for v2-server - #432
zhangxinhao wants to merge 8 commits into
Conversation
A desktop token is a sessions row of kind desktop: it expires after 30 days without use (last use refreshed at most hourly), has no absolute limit and is never accepted as a cookie, while web logout and web session lookup ignore it.
POST /auth/desktop/approve turns a web session's approval into a two-minute, single-use code bound to a loopback redirect URI and a PKCE S256 challenge; POST /auth/desktop/token exchanges it for a desktop token; POST /auth/desktop/logout revokes that token only. A request with an Authorization header is judged by the bearer token alone and needs no Origin check.
/desktop/authorize asks the signed-in person to allow Ora desktop and only then approves, sending the browser back to the desktop's loopback address.
ObsisMc
left a comment
There was a problem hiding this comment.
按安全 review 看了 cloud 这一半(69cc5c73),对照 A6 D6、不变量 6–9 和 specs#324 里 desktop 依赖 Cloud 的部分(只收 127.0.0.1 / [::1]、不收 localhost、401 才算令牌失效)。Approve,下面两点不阻塞。
作者请重点看的三处
-
authed的 Bearer 优先:session/tenant/owner三级都经routes.go走h.authed,没有别的路由读会话 Cookie(public 里只有/auth/logout读 Cookie,它自己查Origin)。带Authorization头就只走bearerUser,头格式不对或令牌不认识都是401,不会退回 Cookie。我试过把这里改成"头格式不对就退回 Cookie",TestBearerHeaderAloneDecidesTheCaller会失败。Bearer 请求不查Origin没有问题:v2-server 不发 CORS 头,Authorization也不是 CORS 安全头,跨站页面带不上它。网页会话当 Bearer、desktop 令牌当 Cookie 都不认(靠kind区分),approve拒绝 Bearer,所以拿令牌换不出新令牌。 -
loopbackRedirect:用临时测试试了 40 多种写法,都被拒绝:- IP 的别种写法:
127.1、2130706433、0x7f.0.0.1、127.0.0.2、[::ffff:127.0.0.1]、[0:0:0:0:0:0:0:1]、[::1%25eth0]、%31%32%37.0.0.1; - 主机伪装和 userinfo:
localhost、127.0.0.1%2Eevil.com、u@、:80@evil.com、各种反斜杠; - 端口:缺省、
0、65536、+80、080; - 其他:tab、换行、开头空格、
http:127.0.0.1…、http:///…、https。
//evil.com/这类路径能通过,但主机仍是回环,没有影响。 - IP 的别种写法:
-
DesktopTokenUser按小时顺延:先查后改,UPDATE带last_used_at < now() - 1h条件,并发请求只会写一次;吊销和改写同时发生时,DELETE胜出。见下面第 2 点,注释里的过期区间写反了。
其余几项
- 授权码:
take先删再校验,所以不论成败,第一次兑换都会用掉授权码。我去掉delete后,重放测试拿到了200,说明测试守得住。 - PKCE 和回调:S256 用常量时间比较,只收 43 字符的 challenge,verifier 43–128 字符,回调必须原样一致。所有拒绝都是同一个
invalid_grant。 - 令牌:令牌 32 字节随机,库里只存 SHA-256。
- 吊销:desktop 登出只删
kind='desktop'的这一个令牌,网页登出只删web。 - 停用账号:签发和每次认人都检查
status='active' AND deleted_at IS NULL,批准之后才停用的账号也换不出令牌。 - 前端:只有点「允许」才会发请求;
SessionGate的returnTo带着location.search,登录回来参数不丢。
已跑的测试(GOMAXPROCS=2 go test -p 1 -count=1,本地 PostgreSQL):internal/store -run 'Desktop|Session' 和 internal/server -run 'Desktop|Bearer|CrossOrigin|Disabling|Login|Logout',全部通过。CI 三项是绿的。
非阻塞
http://127.0.0.1:1/cb#(只有一个空#)能通过校验:u.Fragment为空,但原串里有#,拼出的redirectUrl会把?code=…&state=…放进 fragment,回环监听收不到。只影响发起这次登录的那个 desktop,不会泄露授权码。建议直接strings.Contains(raw, "#")。(行内评论)- 过期区间写反了:
expires_at只在last_used_at超过 1 小时才刷新,刷新后 1 小时内的使用不会写库,所以实际是在最后一次使用后的 30 天减 1 小时到 30 天之间过期,不是"30 天到 30 天零 1 小时"。A6 允许"按小时粗略刷新",行为没问题,只需改desktop_tokens.go的注释和 README 那句;或者刷新时写now() + 30d + 1h,让文档说的成立。(行内评论)
另有两点只作提醒,不用改:
- 如果部署在要求 Basic 认证的反向代理后面,浏览器会自动给每个请求带上
Authorization: Basic …,网页会话就会全部401。这是安全的失败方式,也符合 A6"带头就只按头认人",只是部署时要知道。 /desktop/authorize没有frame-ancestors。被嵌入页面诱导点击的话,授权码也只会送到受害者本机的回环地址,远程拿不到,可以以后一起加。
| func loopbackRedirect(raw string) bool { | ||
| u, e := url.Parse(raw) | ||
| if e != nil || u.Scheme != "http" || u.User != nil || u.RawQuery != "" || u.ForceQuery || | ||
| u.Fragment != "" || !strings.HasPrefix(u.Path, "/") || u.Opaque != "" { |
There was a problem hiding this comment.
非阻塞:只有一个空 # 时(http://127.0.0.1:1/cb#),u.Fragment 是空串,校验能通过;拼出的 redirectUrl 会把 ?code=…&state=… 放进 fragment,回环监听收不到。不会泄露,但建议在 url.Parse 之前直接 strings.Contains(raw, "#") 拒绝。
| const DesktopTokenIdle = 30 * 24 * time.Hour | ||
|
|
||
| // desktopTokenTouch is how stale last_used_at may get before a request refreshes it, so a busy | ||
| // desktop writes once an hour rather than on every request. A token therefore expires between |
There was a problem hiding this comment.
非阻塞:这里的区间反了。expires_at 只在 last_used_at 超过 1 小时才刷新,刷新后 1 小时内的使用不会写库,所以实际是在最后一次使用后的 30 天减 1 小时到 30 天之间过期。README 里"30 天到 30 天零 1 小时之间"也要一起改;或者刷新时写 now() + DesktopTokenIdle + desktopTokenTouch,让现在的说法成立。
…rect An empty '#' parses to an empty fragment yet still moves the appended code and state out of the query. Also correct the stated desktop token expiry window: uses within an hour of a refresh are not recorded, so a token expires between 30 days minus one hour and 30 days after its last use. Refs ora-space/circus#1379
|
谢谢细看。两点都在
两点提醒(Basic 认证的反向代理、 |
「取消」 on /desktop/authorize now calls POST /auth/desktop/deny, which checks the redirect address and state like approval and answers the loopback address with error=access_denied, so the desktop ends its sign-in at once instead of waiting for its timeout. Nothing is issued. Refs ora-space/circus#1379
frontend-v2 uses npm (package-lock.json); the pnpm lock and workspace files were generated locally and added by accident in the previous commit. Refs ora-space/circus#1379
wanglongan587
left a comment
There was a problem hiding this comment.
审的 head:15161217(在 69cc5c73 之后又推了 6b9db8cf、6f49d4e6、15161217 三笔)。69cc5c73 那一版 @ObsisMc 已按安全角度 Approve,我在这三笔增量上复核,Approve。合并门槛不变:ora-space/specs#324 还是 proposed(并在 owner 那里挂着 Request changes),本 PR 描述已写明不合并。
这三笔改了什么、我核了什么
loopbackRedirect提前拒#(v2-server/internal/server/desktop_login.go:83-86):strings.Contains(raw, "#")直接拒,http://127.0.0.1:53682/cb#落进TestDesktopApprovalAcceptsOnlyLoopbackAndS256的拒绝表。原来的问题(u.Fragment为空但拼出的redirectUrl会把code/state塞进 fragment)确实堵住了;解析顺序在url.Parse之前,没有绕过写法能先过解析。POST /auth/desktop/deny(desktop_login.go:159-182、server.go:160、前端page.tsx的「取消」):只收网页会话(带Authorization头403 web_session_required)、Origin由authed的sameOrigin兜住(login.go:158-183,Origin 判定在:166,判定本身在:61)、redirectUri用同一个loopbackRedirect、state用新抽出来的desktopState,只回{redirectUrl}= 回调地址 +error=access_denied+state,不签发任何东西。TestDesktopDenialReturnsToTheLoopback把 200 的形状、三类非法回调、空 state、无会话 401、Bearer 403 都覆盖了;前端两条用例分别覆盖"跳回回环"和"服务器拒绝时仍显示已取消"。desktop#806 的loopback.rs::classify本来就带error就按Denied收尾(error_redirect_is_denied),两端语义对得上。0008_desktop_tokens.sql没有挪号:当前upstream/main的最新迁移还是0007_workspace_reclaims.sql(main 已到c3b62695,比本 PR 的 baseda523184新),0008仍然接得上。- 过期区间的注释和 README 改对了:
desktop_tokens.go:22-26与 README 现在都说"最后一次使用后 30 天减 1 小时到 30 天之间",与desktopTokenTouch的实际写法一致。
CI 在 15161217 上三项全绿;base 落后 main 是 owner 在 #1379 里要求"重新送审时按当时的 main 核对"的那一条,不阻塞本次 review。
两点提醒(不阻塞)
deny校验方式和approve一样,只看回环地址与state,不确认"是否真有进行中的授权"——无状态、无签发,被重复调用最多多送一次access_denied,可以接受。deny的主体只有redirectUri、state两项,靠decodeStrict拒未知字段;将来若给 approve 加参数,别把deny的 body 收成同一份结构,否则会出现"取消也需要 challenge"的误伤。
我没做的
没在本机跑 go test(internal/server、internal/store 的 fixture 需要本地 PostgreSQL,这台机器上没有可用的库);上面关于 deny 与 # 的结论来自代码与用例的逐条比对,以及 CI 在 15161217 上的全绿结果。
wanglongan587
left a comment
There was a problem hiding this comment.
审过 commit a85d1fbcf6144f4fa219364613f144762bc9e2e8(并入当前 main 后的 head)。代码没有问题,PR 描述有一处和实现对不上,请在合并前改掉,因此这一轮是 Request changes。
这次核了什么
- head 只并入 main:
a85d1fbc的父提交是e685f422(上次送审的 head)和fe0b378b(当前upstream/main)。并入的改动与 main 自己的增量逐字节相同(只有index行不同),没有冲突解决;特性增量与e685f422相同。base 就是当前 main。 - 迁移:
v2-server/internal/store/migrations/0008_desktop_tokens.sql仍接在 main 最新的0007_workspace_reclaims.sql之后。 - CI:
a85d1fbc上server、frontend、e2e三项都是 SUCCESS。 - ADR 一节:写明 A6 在本 PR 合并后仍是
approved、D6 的 Cloud 侧与不变量 7–9 已在此实现、desktop 侧和#1292的 IDaaS 验证仍缺、由 #1084 的落地运行一起改为implemented,与 specs#324 已合并为approved一致。
要改的(只改 PR 描述,不用推新提交、不用重跑 CI)
- 「What it does」的 frontend 段还写着 “「取消」 posts nothing”,与
6f49d4e6之后的实现相反:现在点「取消」调POST /auth/desktop/deny,浏览器带error=access_denied回到回环地址,desktop 立即结束这次登录;只有服务器拒绝跳回时,页面才停住显示「已取消…」(page.tsx的 deny mutation;page.test.tsx:51断言了跳回与deny只带redirectUri/state,:69覆盖拒绝时的情况)。同一句里的 “a server refusal or an incomplete link shows an error and never navigates” 只对这两条成立,请与「取消」分开写。 - Routes 列表少了
POST /auth/desktop/deny:只收网页会话、同样校验redirectUri和state(body 只有这两项)、不签发任何东西,返回带error=access_denied和state的回环地址(server.go:160、desktop_login.go:159、OpenAPI 的/auth/desktop/deny)。 - 「Verification」里 frontend 的 “the new page (5 tests)” 现在是 6 条(
page.test.tsx)。另外浏览器实测那一段是在 deny 之前跑的,可以补一句:「取消」由前端测试和 desktop#806 的 Windows 真机实测覆盖。
README、OpenAPI 和测试都已经按 deny 更新,只有描述还停在改动前,两者互相矛盾;描述是这次评审和 owner 合并时唯一的行为说明,所以按有问题处理。
改完(不需要新提交)在这里回一句,我在 a85d1fbc 上改成 Approve,运行 issue 的 review:lgtm 也按这个 SHA 打。
wanglongan587
left a comment
There was a problem hiding this comment.
Approved at a85d1fbc.
这一轮按 @zhangxinhao 的回复核对:只有描述改动,没有新提交。描述里改的四点我都对着 a85d1fbc 的代码看过:
- frontend:
frontend-v2/src/lib/auth-api.ts的denyDesktopLogin只发redirectUri和state;page.tsx里「取消」成功即navigation.assign(redirectUrl),服务器拒绝 deny 时才停在「已取消。没能通知 Ora desktop…」;「允许」失败仍然只报错、不跳转。与描述一致。 - Routes:
denyDesktop(internal/server/desktop_login.go:159-182)带Authorization就403 web_session_required,redirectUri复用loopbackRedirect,state复用desktopState,只回error=access_denied+ 原样state,不签发;路由挂在rt.session(server.go:160),desktop-login.openapi.json有/auth/desktop/deny。 - Verification:前端
page.test.tsx是 6 条,其中「取消」那条断言只发两个字段且不碰/auth/desktop/approve,另一条断言服务器拒绝 deny 时停在「已取消」、不跳转;TestDesktopDenialReturnsToTheLoopback覆盖 200 形状、三类非法回调、空 state、无会话401、Bearer403。 - A6 一节:改成「落地运行把 desktop ADR 改为
implemented,在 A6 上记 D6 两侧已实现,A6 等 #1292 验完 D1–D5」——与 #1397 的计划一致。
代码本身相对上次评审没有变化:本 head 的合并部分与 main fe0b378b 自己的增量逐字节相同(只有 index 行不同),特性增量与 e685f422 一致;迁移仍是 0008_desktop_tokens.sql 接 0007_workspace_reclaims.sql;server / frontend / e2e 都跑在 a85d1fbc 上并通过(run 45122692526)。
Refs ora-space/circus#1379
Cloud half of ora-space/circus#1084: Ora desktop signs in to v2-server through the system browser and a loopback redirect (A6 D6). The desktop half is a separate desktop PR under the same run.
ADR
decisions/cloud/login/0-idaas-or-email-login-with-shared-web-and-desktop-sessions.md,approved) staysapprovedafter this PR. Implemented here: D6's Cloud side (approval page, single-use code bound to the PKCE challenge and loopback redirect URI, desktop token stored as SHA-256 with 30 idle days and no rotation, bearer-only identification, desktop logout revokes only its token) and invariants 7–9 for desktop tokens. Still missing: the desktop side (desktop PR, same run) and the real-IDaaS verification of D1–D5 (phase3 基座 I2 内网验证:华为 IDaaS 网页登录真实登录与入队(随 #1059 现场验收) circus#1292). The landing run of #1084 moves the desktop ADR toimplementedand records on A6 that D6 is implemented on both sides; A6 itself becomesimplementedonce phase3 基座 I2 内网验证:华为 IDaaS 网页登录真实登录与入队(随 #1059 现场验收) circus#1292 has verified D1–D5 with real IDaaS.approved(df1f362e).v2-server/desktop-login.openapi.json, and the tests validate every response against it.What it does
0008_desktop_tokens.sql,internal/store/desktop_tokens.go):sessionsgainskind(web/desktop) andlast_used_at. A desktop token isora_dt_+ 43 base64url characters, SHA-256 in the table, expires 30 days after its last use (refreshed at most hourly, guarded so concurrent requests write once), no absolute limit. Issuing re-checks the account in the same statement, so an approval followed by a disable yields nothing.SessionUserand webLogoutnow only seekind = 'web';DesktopTokenUser/RevokeDesktopTokenonlykind = 'desktop'. Existing rows become web sessions.authed): a request with anAuthorizationheader is judged by that header alone: a desktop token or401, never a fallback to the cookie, so whoever is signed in to the browser cannot stand in for a missing or revoked token. Bearer requests skip theOrigincheck (a browser never attaches the token on its own). Everysession/tenant/ownerroute therefore accepts desktop tokens with the same account and tenant authorization.internal/server/desktop_login.go):POST /auth/desktop/approve: web session + sameOriginonly; anyAuthorizationheader is403 web_session_required(a desktop cannot mint tokens for itself). Accepts onlyhttp://127.0.0.1:<port>/<path>orhttp://[::1]:<port>/<path>without query or fragment (localhostrefused: it resolves through DNS/hosts),S256with a 43-character challenge, a non-empty state ≤ 512 bytes. Returns the loopback URL withcodeandstate.POST /auth/desktop/token: the first exchange spends the code whatever happens; it yields a token only with the right verifier (constant-time S256 compare) and the identical redirect URI. Every refusal is the same400 invalid_grant.Cache-Control: no-store.POST /auth/desktop/logout: revokes the bearer token of this request only;204also when already gone;401without a well-formed bearer header.POST /auth/desktop/deny: what 「取消」 calls. Web session + sameOriginonly, anyAuthorizationheader refused like approve; the body is onlyredirectUriandstate, checked by the same loopback and state rules as approve. Issues nothing; returns the loopback URL witherror=access_deniedand the originalstate, so the desktop ends that sign-in at once./desktop/authorize: behind the session gate (a signed-out visitor logs in by whateverV2_LOGINoffers and comes back to the same request), asks 「允许 Ora desktop 以「<名字>」的身份登录?」 and posts the approval only on 「允许」, then sends the browser to the returned loopback URL. 「取消」 callsPOST /auth/desktop/denyand sends the browser to the returned loopback URL (error=access_denied), so the desktop ends the sign-in at once; only if the server refuses the deny does the page stay and show 「已取消…」. On 「允许」, a server refusal or an incomplete link shows an error and never navigates.Verification
gofmt -l .clean,go vet ./...,go test -race -count=1 ./...against PostgreSQL: all 35 packages pass. New tests: full approve → exchange → bearer flow and IPv6 loopback; single use and binding (replay, wrong verifier, wrong redirect, short verifier — each also proves the failed attempt spent the code); 11 rejected redirect URIs plusplainmethod, short challenge and empty state; approval needs the web session (no session, foreignOrigin, bearer, bearer + cookie); the bearer header alone decides (another user's cookie beside a token, unknown token beside a cookie, web session as bearer, desktop token as cookie,Basicscheme, bearer write with a foreignOrigin); logout scope (two devices, web logout, desktop logout) and disabled accounts (token rejected, approved-then-disabled exchange refused); store tests for kind separation, 30-day idle expiry and refresh; code table expiry and bound. Removing the bearer branch or thekind = 'web'filter makes the corresponding tests fail.typecheck,lint,vitestfor the new page (6 tests, including 「取消」 redirecting with onlyredirectUri/stateand the refused-deny case) andsrc/app(34) pass.V2_LOGIN=email, real v2-server + Vite + Chromium, a script playing the desktop (loopback listener on127.0.0.1:0, PKCE): open/desktop/authorizesigned out → email login → back on the approval page → 「允许」 → browser lands on the loopback callback → exchange200, token starts withora_dt_, same user id as the web session → replay400→/api/v1/meand/api/v1/me/tenantswith the bearer200→ desktop logout204→ bearer401→ the browser session is still signed in (200).6f49d4e6): it is covered by the frontend tests,TestDesktopDenialReturnsToTheLoopback, and the Windows real-machine run on desktop#806 (confirm page 「取消」 → desktop shows Denied, nothing stored).