Skip to content

Desktop sign-in through an approved loopback exchange for v2-server - #432

Open
zhangxinhao wants to merge 8 commits into
ora-space:mainfrom
zhangxinhao:feat/1379-desktop-login-cloud
Open

zhangxinhao wants to merge 8 commits into
ora-space:mainfrom
zhangxinhao:feat/1379-desktop-login-cloud

Conversation

@zhangxinhao

@zhangxinhao zhangxinhao commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

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.

ora-space/specs#324, the desktop follow-up ADR that A6 D6 asks for, is merged as approved (df1f362e); both halves land against it.

ADR

What it does

  • Credential table (0008_desktop_tokens.sql, internal/store/desktop_tokens.go): sessions gains kind (web / desktop) and last_used_at. A desktop token is ora_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. SessionUser and web Logout now only see kind = 'web'; DesktopTokenUser / RevokeDesktopToken only kind = 'desktop'. Existing rows become web sessions.
  • Bearer identification (authed): a request with an Authorization header is judged by that header alone: a desktop token or 401, 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 the Origin check (a browser never attaches the token on its own). Every session / tenant / owner route therefore accepts desktop tokens with the same account and tenant authorization.
  • Routes (internal/server/desktop_login.go):
    • POST /auth/desktop/approve: web session + same Origin only; any Authorization header is 403 web_session_required (a desktop cannot mint tokens for itself). Accepts only http://127.0.0.1:<port>/<path> or http://[::1]:<port>/<path> without query or fragment (localhost refused: it resolves through DNS/hosts), S256 with a 43-character challenge, a non-empty state ≤ 512 bytes. Returns the loopback URL with code and state.
    • 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 same 400 invalid_grant. Cache-Control: no-store.
    • POST /auth/desktop/logout: revokes the bearer token of this request only; 204 also when already gone; 401 without a well-formed bearer header.
    • POST /auth/desktop/deny: what 「取消」 calls. Web session + same Origin only, any Authorization header refused like approve; the body is only redirectUri and state, checked by the same loopback and state rules as approve. Issues nothing; returns the loopback URL with error=access_denied and the original state, so the desktop ends that sign-in at once.
    • Codes live in memory (2 minutes, 10000 max, oldest evicted, like login attempts).
  • frontend-v2 /desktop/authorize: behind the session gate (a signed-out visitor logs in by whatever V2_LOGIN offers 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. 「取消」 calls POST /auth/desktop/deny and 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.
  • README: the new routes, the bearer rule, and the simplifications (no rotation, device list or remote revocation per A6 D7; expired rows are not purged).

Verification

  • v2-server: 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 plus plain method, short challenge and empty state; approval needs the web session (no session, foreign Origin, 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, Basic scheme, bearer write with a foreign Origin); 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 the kind = 'web' filter makes the corresponding tests fail.
  • frontend-v2: typecheck, lint, vitest for the new page (6 tests, including 「取消」 redirecting with only redirectUri / state and the refused-deny case) and src/app (34) pass.
  • Browser, locally, V2_LOGIN=email, real v2-server + Vite + Chromium, a script playing the desktop (loopback listener on 127.0.0.1:0, PKCE): open /desktop/authorize signed out → email login → back on the approval page → 「允许」 → browser lands on the loopback callback → exchange 200, token starts with ora_dt_, same user id as the web session → replay 400 → /api/v1/me and /api/v1/me/tenants with the bearer 200 → desktop logout 204 → bearer 401 → the browser session is still signed in (200).
  • 「取消」 came after that browser run (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).

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 ObsisMc left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

按安全 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/ 这类路径能通过,但主机仍是回环,没有影响。

  • 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 三项是绿的。

非阻塞

  1. http://127.0.0.1:1/cb#(只有一个空 #)能通过校验:u.Fragment 为空,但原串里有 #,拼出的 redirectUrl 会把 ?code=…&state=… 放进 fragment,回环监听收不到。只影响发起这次登录的那个 desktop,不会泄露授权码。建议直接 strings.Contains(raw, "#")。(行内评论)
  2. 过期区间写反了: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 != "" {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

非阻塞:只有一个空 # 时(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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

非阻塞:这里的区间反了。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
@zhangxinhao

Copy link
Copy Markdown
Contributor Author

谢谢细看。两点都在 6b9db8cf 改了:

  1. loopbackRedirect 解析前先拒绝任何 #,测试加了 http://127.0.0.1:53682/cb#。
  2. 行为保持不变(A6 允许按小时粗略刷新),改了注释和 README 的说法:最后一次使用后 30 天减 1 小时到 30 天之间过期。

两点提醒(Basic 认证的反向代理、frame-ancestors)我记下了,这次不改。

「取消」 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 wanglongan587 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

审的 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 的 base da523184 新),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 wanglongan587 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

审过 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)

  1. 「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” 只对这两条成立,请与「取消」分开写。
  2. Routes 列表少了 POST /auth/desktop/deny:只收网页会话、同样校验 redirectUri 和 state(body 只有这两项)、不签发任何东西,返回带 error=access_denied 和 state 的回环地址(server.go:160、desktop_login.go:159、OpenAPI 的 /auth/desktop/deny)。
  3. 「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 wanglongan587 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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、Bearer 403。
  • 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)。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants