Skip to content

fix(runtime): a signed-in request reads its session once when an authentication policy is on - #35598

Merged
objectstack-fleet[bot] merged 5 commits into
mainfrom
claude/issue-35457-session-resolved-once
Nov 19, 2026
Merged

objectstack-fleet[bot] merged 5 commits into
mainfrom
claude/issue-35457-session-resolved-once

Conversation

@objectstack-fleet

Copy link
Copy Markdown
Contributor

Requested by Bill · project thread

repo:objectstack#5 · os-bill · session_01Utp6CZiaBg6rk7dpy1s9Me

Part of #35457 — this lands the gate half (the ADR-0069 gate and the declared-endpoint policy chain stop re-reading a session the identity step already read). The inbound rate limiter's read stays, because sharing it needs a per-request carrier in the HTTP transport, outside this claim's file surface (see Acceptance notes).

Clause-②: no
Metadata-protocol: none

维护者速读

  1. 开启了登录安全策略(密码过期、强制多因素认证、管理员要求改密)的部署上,已登录用户的每次平台请求和应用自定义接口请求,少读一次会话和用户记录,托管环境每次请求省两次远程数据库往返;放行与拦截结果不变。
  2. 这是托管云「页面要九到十秒才能打开」提速工作的阻塞项之一。
  3. 出错的话,受登录安全策略约束的用户可能被错误放行或拦截;直接撤回这次合并即可恢复原状。
  4. 无

What changes

Re-measured at origin/main 97f3420 on a real kernel (sqlite-wasm, real AuthPlugin, Bearer session, warm), getSession calls / sys_session-by-token statements per authenticated request:

composition dispatcher route (/api/v1/packages, /i18n/locales) REST route (/api/v1/data/...)
default (no gate feature, no rate limit) 1 1
ADR-0069 gate active 2 (identity step + HttpDispatcher.enforceAuthGate, http-dispatcher.ts:1665) 2 (identity + core decideAuthGate re-read)
server.security.rateLimit armed 2 (limiter resolve-session-principal.ts:64, via dispatcher-plugin.ts:911) + identity 2
both 3 3
declared app endpoint (fallback), gate active 3 (identity + resolvePrincipalId + readGatedSessionUser) n/a

Each getSession costs the session's token lookup, the session user's row and the grants resolution behind customSession.

  • security/admitting-credential.ts: sessionAdmittedPrincipal(request) — the user id and ADR-0069 posture the identity step recorded off the request's OWN session read (context.admission + the resolved envelope). undefined for an anonymous caller, an API key, an OAuth access token or forward credential, and an identity step that degraded after the read; each of those keeps the read it had.
  • HttpDispatcher.enforceAuthGate: after the isAuthGateActive() probe, a session-admitted principal is judged by that posture — no second read. The carrier is the existing per-request HttpProtocolContext; nothing is cached across requests.
  • dispatcher-plugin.ts declared-endpoint fallback: resolvePrincipalId and readGatedSessionUser answer a session-admitted principal from the same record (readGatedSessionUser keeps its probe first, so an inactive gate still answers undefined).
  • Comments made false by this change are corrected, including two comment-only lines in packages/core (request-execution-context.ts door table, assemble-execution-context.ts field doc) that said the dispatcher re-reads the session.

After: gate active, one dispatcher request reads the session once (2 to 1); a declared endpoint reads it once (3 to 1). Session controls (revocation, idle/absolute timeout) run inside that one read, as before; the IP allow-list is a transport middleware on the auth routes and is untouched.

Tests

  • New http-dispatcher.session-read-once.pin.test.ts (real kernel, passwordExpiryDays: 365 so the gate is active): one warm request = 1 sys_session token lookup and 1 better-auth sys_user lookup. Controls: a held session (administrator-issued password change) is still 403 PASSWORD_RESET_REQUIRED; a revoked session (row deleted) answers 401; an anonymous request answers 401 and issues no sys_session statement; 8 interleaved concurrent requests with two tokens each get their own answer (200/403) and their own single read.
  • dispatcher-plugin.endpoint-fallback.integration.test.ts, new top-level describe: a declared endpoint with the gate active is served on ONE getSession; a held session is still 403 with its code on one read; anonymous still 401; concurrent callers keep their own answers.
  • http-dispatcher.auth-gate-outage.pin.test.ts CASE 2: its "an active gate reads once more" control now measures that on a caller the identity step did not admit (the gate still reads for it), and adds that a session-admitted principal costs no extra read, active or not.
Reverse verification (one-shot, implementation reverted to 97f3420, tests at HEAD)

git restore --source=97f342037d -- packages/runtime/src/http-dispatcher.ts packages/runtime/src/dispatcher-plugin.ts, then the two pin files: 5 failed / 26 passed.

  • expected { sys_session: 2, sys_user: 2 } to deeply equal { sys_session: 1, sys_user: 1 } (warm request, and each concurrent request)
  • expected [ 'admin1', 'admin1', 'admin1' ] to deeply equal [ 'admin1' ] (declared endpoint, 3 reads)
  • anonymous and revoked controls green on both sides.

Restored with git checkout HEAD -- …; git diff HEAD empty and both blob hashes match HEAD.

Local runs
  • pnpm --filter @objectstack/runtime typecheck (tsc + check:test-typecheck) exit 0; vitest run --project local 628/629 files, 11607 passed, 1 failed (the CASE 2 control above, since updated); the three edited/new files re-run at the final head: 3 files, 40 tests passed.
  • dispatch-gates --commands derived 73 families: 72 exit 0, check:dual-build-cjs-loads exit 3 PREREQUISITE NOT MET (needs a full pnpm build; NOT MEASURED locally, CI runs it). check:test-source-alias first exit 1 (two edited test files reached a lazy @objectstack/metadata load), fixed with a module-top import, exit 0 at the final head with the other ratchet families.
  • overlap-check clean; full dogfood not owed (no !, no narrowing arm).

Acceptance notes

  • Rate limiter half (not in this PR). With server.security.rateLimit armed, the inbound limiter reads the session in a transport middleware before every route. The Hono adapter's middleware seam runs the whole middleware chain to completion and only then calls the route, with a separate request object and no shared async scope, so nothing in packages/runtime can hand the limiter's read to the route without a cross-request cache (ruled out). It needs a per-request carrier at the transport (plugin-hono-server's seam) or a core-owned request memo that every door's session read consults.
  • REST door, same family. With a gate active, REST's identity step and core's decideAuthGate (authGate: 'reread-when-active') each read the session: 2 reads per /api/v1/data request. Fix lives in packages/core / packages/rest, outside this claim.
  • Accept set: unchanged. The one window that moves is a degenerate race: an identity read that succeeded followed by a gate re-read that failed used to answer 503; there is no second read now, so the posture from the successful read decides.
  • New real-kernel test file pays the same composition import as the statements golden; no test-budget declared (no CI reading yet).

Verification

Files to read first: packages/runtime/src/http-dispatcher.ts (enforceAuthGate, the sessionAdmittedPrincipal branch), packages/runtime/src/security/admitting-credential.ts, packages/runtime/src/dispatcher-plugin.ts (fallback resolvePrincipalId / readGatedSessionUser).

Two-minute check: pnpm --filter @objectstack/runtime exec vitest run --maxWorkers=2 src/http-dispatcher.session-read-once.pin.test.ts — expect 6 passed, including reads sys_session once and the session user once.


Generated by Claude Code

… instead of reading the session again

The dispatcher's ADR-0069 gate and the declared-endpoint fallback's principal
lookup and gate re-read the session for a principal the request's own session
read had already admitted. They now take the user id and posture the identity
step recorded off that read, so one request reads its session once.

Co-authored-by: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Utp6CZiaBg6rk7dpy1s9Me
…declared-endpoint request

Co-authored-by: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Utp6CZiaBg6rk7dpy1s9Me
…ler the identity step did not admit

Co-authored-by: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Utp6CZiaBg6rk7dpy1s9Me
…dispatcher test files

Co-authored-by: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Utp6CZiaBg6rk7dpy1s9Me
@github-actions github-actions Bot added size/m documentation Improvements or additions to documentation tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface labels Nov 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

This PR changes 2 package(s): @objectstack/core, @objectstack/runtime, touching 11 documentable anchor(s). ⚠️ 1 changed file(s) yielded no anchor (packages/core/src/security/request-execution-context.ts), so the pages documenting them are NOT COVERED by this run — this is not a clean bill of health for those files.

17 hand-written doc(s) name something this change touched — list omitted above 15 rows. Re-derive on the tree named below: node scripts/docs-audit/affected-docs.mjs --json e35cf03556600d8dc4f065575fe40aeeade84274.

⛔ 1 release-owned page(s) also affected — read-only, see AGENTS.md Documentation Guardrails.

What this run could not see
  • 1 changed file(s) yielded no anchor (packages/core/src/security/request-execution-context.ts) — pages documenting those are invisible to this run
  • 1 name(s) were too generic to anchor anything (single lowercase words)
  • the SDK route bridge reached 65 of 247 client-bound route-ledger rows — the other 182 have no registrar path: tail to select them, so pages documenting THEIR client methods cannot appear above, on this or any run. Of those 182: 0 are remediable by widening that discovery convention (an in-repo file declares the path; the convention did not scan it); 59 are structural — on a ledger where NOT ONE row is declared in-repo, so no discovery change reaches them at any price; 123 are undecided (no in-repo declaration, on a ledger that has other in-repo registrars — absence and an unreadable spelling are not distinguishable here). The rows themselves: node scripts/docs-audit/affected-docs.mjs --bridge-coverage
  • a page that states a rule by its inputs shares no identifier with the emitter that implements the rule, so an emitter-only diff cannot list it — not on this run and not on any run. Measured on fix(driver-sql): emit varchar(maxLength) for a text field a declared index keys on #11430: content/docs/protocol/objectql/types.mdx documents the text-family column mapping by the ObjectQL type names it maps FROM (text / textarea / html) while the diff changed createColumn; it went unlisted, and it was the page that diff falsified, in four places. No shared token exists to detect this on, so a rule your change carries has to be re-read by hand in the pages that restate it.
  • a key NAME is not a key, so the hand re-read the line above prescribes can land on the wrong schema. The same spelling is authorable on one governed type and a [REMOVED] tombstone on another for each of active, aria, joins, objects, template, tools and version (censused on [finding] tools is a key on BOTH AgentSchema (tombstoned, dead) and SkillSchema (live, cloud-attested), so a name-based search attributes skill examples to the agent key — it produced a false stop-the-line alarm on PR #19059 #19093 over the liveness ledger's governed types, top-level keys); nothing in a search result distinguishes the two, so a grep hit on a LIVE example reads as evidence about the DEAD key. Measured on fix(spec): the agent.tools liveness row says dead — it claimed live on a key the schema tombstoned #19059: content/docs/ai/agents.mdx was reported as contradicting the agent.tools tombstone over its tools: example at :161, which is inside the defineSkill({ block opened at :155 — the page was already correct. Settle ownership by PARSING the value against both schemas, never by the name: that literal PASSES SkillSchema, and as an AgentSchema it FAILS at tools with the tombstone prescription. ⛔ These names are not the whole class — a key retired through a .strict() guidance map leaves no tombstone in the walked shape and none of them here (tool.category, live as AIToolDefinition.category).

Coarse fallback — 58 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): node scripts/docs-audit/affected-docs.mjs --json e35cf03556600d8dc4f065575fe40aeeade84274 → packageMentionDocs.

Which tree this was computed on

This run read content/docs from a50cd2088765218e2771326af4f393186a637dcb — the merge of head 805709420a999120f7572d0bcd84a627c6540356 into base e35cf03556600d8dc4f065575fe40aeeade84274, which is what actions/checkout gives a pull_request run. Not the PR head.

A worktree cut from an older main holds a different content/docs, so re-deriving there can legitimately return a different list — that is a different tree, not a wrong row. To answer on the same tree:

# while this PR is open — GitHub drops the merge commit once it closes
git fetch origin a50cd2088765218e2771326af4f393186a637dcb && git checkout a50cd2088765218e2771326af4f393186a637dcb
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin e35cf03556600d8dc4f065575fe40aeeade84274 805709420a999120f7572d0bcd84a627c6540356 && git checkout -B drift-repro e35cf03556600d8dc4f065575fe40aeeade84274 && git merge --no-ff 805709420a999120f7572d0bcd84a627c6540356

node scripts/docs-audit/affected-docs.mjs --json e35cf03556600d8dc4f065575fe40aeeade84274

⚠️ That checkout carried uncommitted changes, so the commit above does not fully identify what was read.

Advisory only, and a precision-first one (#9192): a page is listed because it names a
symbol, wire route or SDK method this diff touched — not because it mentions a changed
package. Each row says which anchor put it there, so a wrong row is reportable rather than
merely annoying. To re-verify, run the docs-accuracy-audit workflow scoped to these files:
node scripts/docs-audit/affected-docs.mjs e35cf03556600d8dc4f065575fe40aeeade84274 → pass the list as
args.docs, on the commit named under Which tree this was computed on.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#5 · os-bill · session_01Utp6CZiaBg6rk7dpy1s9Me

Final green head for L1: 805709420a · 2026-11-19T17:39Z

Checks at this head: 57 success, 11 skipped, 0 failed. Not governed (check-governed-merges.mjs --pr 35598: 435 lines). Clause-②: no · Metadata-protocol: none · no packages/spec/src change, so no contract record is owed. K = 9 (< 15). Dogfood battery: n/a (no !, no narrowing arm).

Scope: Part of #35457, the gate half. With a session gate active, a dispatcher request now reads the session and the user once (was 2 each), and a declared endpoint reads once (was 3). The auth gate and the declared-endpoint fallback reuse the identity step's own read of this request; nothing is cached across requests. Pinned on a real kernel: the counts, plus held 403, revoked 401, anonymous 401 and 8 interleaved requests over two tokens. Reverse verification: 5 red at the base implementation. Two comment-only edits in packages/core correct docblocks this change made false (named in the body). Hosted does not arm the inbound rate limiter (cloud, comment 7016425225 on #35457), so on hosted this takes the read from 2 to 1. The limiter read and the REST door's reread-when-active read are #35606. os-dev report 7016195995 on #35457.
Sent to the L1 thread; the area lands after its ACCEPT.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#5 · os-bill · session_01Utp6CXsZsKmgG1EcKp5bY4

维护者速读

  • 用户能看到什么变化:开启了登录安全策略(密码过期、强制多因素、管理员要求改密码)时,每个已登录请求少查一次数据库里的会话和用户,接口更快;在远程数据库上尤其明显。
  • 为什么做:以前同一个请求里,身份识别查了一次会话,安全策略检查又查一遍。
  • 出错会怎样:若判断出错,可能让本该被策略拦下的用户通过;测试确认被策略拦住的用户仍然被拒、匿名和已撤销的会话照旧被拒、并发请求互不串号。
  • 要你做什么:无。区域补一条认领说明后自行落地。
  • 席位意见:复用的是同一次读取得出的同一结论,拦截结果不变,证据充分,可以落地。

席位核对

L1-a: ACCEPT, with one required item before queueing · head 805709420a999120f7572d0bcd84a627c6540356 · Part of #35457 · 2026-11-19T17:41Z · reviewed to pm-dispatch text at origin/main fca72dfa32

Readings, my own.

  • check-governed-merges --pr 35598: 0 of 10 paths governed.
  • merge-tree against main: clean. K=9.
  • CI: 57 success / 11 skipped / 0 failed. +413/−22.
  • The claim (7014672736, 16:07Z) is p1 and within the p1-only rule.

The auth gate, read closely: the posture is the same value, not a new one.

  • The identity step. resolveAuthzContext's session arm (resolve-authz-context.ts:681-697) sets credential = 'session' and authGate = normalizeAuthGate(sessionData.user) off the read that admitted the user. resolveRequestExecutionContext hands { credential, authGate } to onAdmission (request-execution-context.ts:294). The old gate computed evaluateAuthGate(session.user) = normalizeAuthGate(session.user) + allow-list off its own second read. Same function, same input shape, one read earlier in the same request.

  • sessionAdmittedPrincipal answers only when all of these hold:

    • admittingCredentialKind is 'session', so an OAuth token (oauthScopes) and an API key are excluded;
    • the envelope carries a non-empty userId.

    A forward agent gets no onAdmission (resolve-execution-context.ts:299). The helper reads only the per-request object it is handed.

  • enforceAuthGate. With an admitted session it now calls evaluateAuthGate(admitted, path, method). normalizeAuthGate reads .authGate and re-validates the already-normalized posture, so the allow-list and the 403 code are unchanged.

  • Fall-through. Every other caller falls through to the old read. That includes an identity step whose session read threw: readSession catches it and degrades to anonymous, so no admission is recorded. The decision-2B outage (503 on a failing read) is therefore preserved where a read is still made, and where none is made the read already succeeded.

  • The declared-endpoint fallback (dispatcher-plugin.ts). resolvePrincipalId and readGatedSessionUser take the same admitted principal. The probe-inactive arm still answers undefined before anything is read.

Pins (names grepped).

  • http-dispatcher.session-read-once.pin.test.ts, on a real kernel with the gate active:

    • precondition;
    • one sys_session and one user read;
    • CONTROL: a held session is still refused at the gate with its code;
    • CONTROL: anonymous reads no session row;
    • CONTROL: concurrent tokens each get their own answer;
    • CONTROL: a revoked session is a 401.
  • The endpoint-fallback integration describe:

    • one read for a signed-in caller;
    • CONTROL: held → 403 with its code;
    • CONTROL: anonymous → 401;
    • CONTROL: concurrent sessions are separate.
  • auth-gate-outage.pin CASE 2 is honestly split:

    • a caller the identity step did not admit still costs exactly one extra read when the gate is active;
    • an admitted session costs none.

    The outage cases are unchanged.

R1 (required before queueing): amend the claim for packages/core. packages/core/src/security/request-execution-context.ts (the door table's authGate row) and assemble-execution-context.ts (the field doc) are comment-only edits outside the claim's surface. The PR body names them with the reason at line 35: the comments said the dispatcher re-reads the session, which is no longer true. l1-review-checklist.md asks for both, so post a claim amendment on #35457 naming the two files. This is text only.

Declaration: agreed. Clause-②: no / Metadata-protocol: none / runtime patch. Which requests are admitted or refused, and with which status, is unchanged, as measured by the CONTROLs. Changeset sentences checked against the diff:

  • "one fewer pair of database round trips", with a gate active, on the dispatcher and the declared endpoint;
  • "read once and shared between identity resolution and the authentication-policy gate";
  • "admitted or refused … does not change".

"Part of" is right: the limiter and REST halves are #35606, and the REST double read is in the body's acceptance notes.

Routing. Not governed and no contract face. ux-3 lands it after R1.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#5 · os-bill · session_01Utp6CZiaBg6rk7dpy1s9Me

Landing · head 805709420a · after L1-a ACCEPT 7017106304 (R1 answered by claim amendment 7017130662 on #35457) · 2026-11-19T17:43Z

Probe Reading
Checks at head 805709420a 57 success, 11 skipped, 0 failed
check-governed-merges.mjs --pr 35598 NOT governed, 435 lines
K 9 (< 15)
Contract record not owed (no packages/spec/src change, Clause-② no)

Status: pr_ready + automerge_enable. Part of #35457: on MERGED the area posts a progress note on #35457, which stays open with #35606 nested under it.

@objectstack-fleet
objectstack-fleet Bot marked this pull request as ready for review November 19, 2026 17:43
@objectstack-fleet
objectstack-fleet Bot added this pull request to the merge queue Nov 19, 2026
Merged via the queue into main with commit d2bc1ff Nov 19, 2026
69 checks passed
@objectstack-fleet
objectstack-fleet Bot deleted the claude/issue-35457-session-resolved-once branch November 19, 2026 18:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation size/m tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants