diff --git a/.changeset/session-read-once-per-request.md b/.changeset/session-read-once-per-request.md new file mode 100644 index 00000000000..692892be15e --- /dev/null +++ b/.changeset/session-read-once-per-request.md @@ -0,0 +1,10 @@ +--- +'@objectstack/runtime': patch +--- + +fix(runtime): a signed-in request reads its session once when an authentication policy is on + +Clause-②: no +Metadata-protocol: none + +With an ADR-0069 authentication policy active (password expiry, required MFA, an administrator-issued password change), every signed-in request served by the runtime dispatcher, and every request to an app's declared endpoint, now makes one fewer pair of database round trips: the session and its user are read once and shared between identity resolution and the authentication-policy gate, where the gate used to read them again. Which requests are admitted or refused, and with which status, does not change. diff --git a/packages/core/src/security/assemble-execution-context.ts b/packages/core/src/security/assemble-execution-context.ts index 9cd91cbbb3b..7d79757889a 100644 --- a/packages/core/src/security/assemble-execution-context.ts +++ b/packages/core/src/security/assemble-execution-context.ts @@ -281,7 +281,7 @@ export interface ExecutionContextAssemblyInput { * consumer reads it (`RestServer.enforceAuth` → `403 { code, message }`); * - the **runtime / MCP dispatcher** passes `undefined`, because it enforces * the same ADR-0069 gate at its OWN seam (`HttpDispatcher.enforceAuthGate` - * re-reads the session and calls `evaluateAuthGate` there) and never reads + * calls `evaluateAuthGate` there on the admission's posture) and never reads * `context.authGate` — carrying it would be a second, unread copy. * * Until #7280 declared it, this posture reached the envelope through an diff --git a/packages/core/src/security/request-execution-context.ts b/packages/core/src/security/request-execution-context.ts index 688d4863e99..536045410e5 100644 --- a/packages/core/src/security/request-execution-context.ts +++ b/packages/core/src/security/request-execution-context.ts @@ -42,7 +42,7 @@ * | parameter | values, and the door that takes each | * |:--|:--| * | `anonymous` | `'guest'`: the runtime / MCP dispatcher. `'fail-closed'`: REST, settings, storage, the `/auth/me` endpoints | - * | `authGate` | `'withhold'`: the dispatcher (its `enforceAuthGate` re-reads the session; a key's answer leaves through `onAdmission`) and the `/auth/me` endpoints (allow-listed for a gated user). `'resolved'`: settings and the storage download door. `'reread-when-active'`: REST. The storage family's ADR-0069 gate reader, which runs before every storage route, stays hand-written beside this function (#24366) | + * | `authGate` | `'withhold'`: the dispatcher (its `enforceAuthGate` judges the posture that leaves through `onAdmission`, a key's or the session read's, and re-reads the session only for a principal no own-session read admitted) and the `/auth/me` endpoints (allow-listed for a gated user). `'resolved'`: settings and the storage download door. `'reread-when-active'`: REST. The storage family's ADR-0069 gate reader, which runs before every storage route, stays hand-written beside this function (#24366) | * | `credentials` | `'session-only'`: the `/auth/me` endpoints, which never opened an API-key door. `'api-key-and-session'`: every other door | * | `sessionApi` | `'required'`: REST and the `/auth/me` endpoints, which authenticate nobody without a session API. `'optional'`: the dispatcher, settings and storage, which still admit an API key | * | `session` | `'request'`: every door. `{ established }` / `'none'`: the dispatcher's `/mcp` face, for a verified / an unverifiable OAuth access token | diff --git a/packages/runtime/src/dispatcher-plugin.endpoint-fallback.integration.test.ts b/packages/runtime/src/dispatcher-plugin.endpoint-fallback.integration.test.ts index 1dc76587339..6a29ff02f93 100644 --- a/packages/runtime/src/dispatcher-plugin.endpoint-fallback.integration.test.ts +++ b/packages/runtime/src/dispatcher-plugin.endpoint-fallback.integration.test.ts @@ -40,6 +40,9 @@ import { ApiEndpointSchema, type ApiEndpoint } from '@objectstack/spec/api'; import type { ApiEndpointMatch, IHttpServer } from '@objectstack/spec/contracts'; import { createDispatcherPlugin } from './dispatcher-plugin.js'; +// Paid at collection, not inside a case's clock: the dispatcher's reach +// (`domains/packages.ts` → `standalone-stack.ts`) loads it lazily. +import '@objectstack/metadata'; /** Two declared endpoints in the ADR-0121 D1 shape (`/apps//…`). */ const DECLARED: ApiEndpoint[] = [ @@ -619,3 +622,98 @@ describe('the wired chain — policies, then the real pipeline (#5129)', () => { expect(engineFinds.filter((f) => f.object === 'showcase_task')).toEqual([]); }); }); + +// ============================================================================ +// One session read per declared-endpoint request +// ============================================================================ + +/** + * The fallback resolves the request's scope (`resolveRequestScope`, one session + * read) and then asks the policy chain two more session questions: the + * principal id (`resolvePrincipalId`) and, while an ADR-0069 gate feature is + * active, the session user (`resolveGatedSessionUser`). Each was a read of its + * own, so a signed-in caller's request read its session three times. A + * principal the request's own session admitted now answers both from the + * identity step's read. + * + * Counted: every `getSession` the `auth` service is asked, per request. The + * controls run through the same composition: a session the policy holds is + * still refused 403 with its posture's code, an anonymous caller is still + * refused 401, and concurrent callers with different sessions each get their + * own answer. + */ +describe('a declared-endpoint request reads its session once (gate active)', () => { + let kernel: LiteKernel; + let baseUrl: string; + const reads: string[] = []; + const POSTURE = { code: 'PASSWORD_EXPIRED', message: 'Your password has expired. Please change it to continue.' }; + + beforeAll(async () => { + ({ kernel, baseUrl } = await boot([ + fakeMetadataPlugin({ withMatcher: true, endpoints: EXECUTABLE }), + { + name: 'com.objectstack.test.counting-session-services', + version: '1.0.0', + init: async (ctx: PluginContext) => { + ctx.registerService('auth', { + isAuthGateActive: () => true, + api: { + async getSession({ headers }: { headers: Headers }) { + const uid = headers.get('x-test-user'); + reads.push(uid ?? ''); + if (!uid) return null; + return { user: { id: uid, ...(uid === 'held1' ? { authGate: POSTURE } : {}) }, session: { userId: uid } }; + }, + }, + }); + ctx.registerService('objectql', { + async find(object: string, options: any) { + if (object === 'sys_user_permission_set') { + return options?.where?.user_id === 'admin1' + ? [{ user_id: 'admin1', permission_set_id: 'ps-admin', permission_set: 'admin_full_access', organization_id: null }] + : []; + } + if (object === 'sys_permission_set') { + const ids: string[] = options?.where?.id?.$in ?? []; + return ids.includes('ps-admin') ? [ADMIN_SET] : []; + } + if (object === 'showcase_task') return TASK_ROWS; + return []; + }, + }); + }, + }, + ])); + }, 30_000); + afterAll(() => shutdown(kernel), 30_000); + + const get = (user?: string) => fetch(`${baseUrl}/api/v1/apps/showcase/my-tasks`, { + headers: user ? { 'x-test-user': user } : {}, + }); + + it('⭐ a signed-in caller is served on ONE session read', async () => { + reads.length = 0; + const res = await get('admin1'); + expect(res.status).toBe(200); + expect(reads).toEqual(['admin1']); + }); + + it('CONTROL — a session the policy holds is still refused 403 with its posture\'s code, on one read', async () => { + reads.length = 0; + const res = await get('held1'); + expect(res.status).toBe(403); + expect((await res.json() as { error: { code: string } }).error.code).toBe('PASSWORD_EXPIRED'); + expect(reads).toEqual(['held1']); + }); + + it('CONTROL — an anonymous caller is still refused 401', async () => { + const res = await get(); + expect(res.status).toBe(401); + expect((await res.json() as { error: { code: string } }).error.code).toBe('UNAUTHENTICATED'); + }); + + it('CONTROL — concurrent callers with different sessions each get their own answer', async () => { + const statuses = await Promise.all(Array.from({ length: 6 }, (_, i) => get(i % 2 === 0 ? 'admin1' : 'held1').then((r) => r.status))); + expect(statuses).toEqual([200, 403, 200, 403, 200, 403]); + }); +}); diff --git a/packages/runtime/src/dispatcher-plugin.ts b/packages/runtime/src/dispatcher-plugin.ts index 298ce680e55..80221144c1f 100644 --- a/packages/runtime/src/dispatcher-plugin.ts +++ b/packages/runtime/src/dispatcher-plugin.ts @@ -20,6 +20,7 @@ import { type SecurityHeadersOptions, } from './security/index.js'; import { resolveSessionData, resolveSessionPrincipalId } from './security/resolve-session-principal.js'; +import { sessionAdmittedPrincipal } from './security/admitting-credential.js'; import { buildActorUser } from './security/actor-user.js'; import { resolveKernelCache } from './security/kernel-cache.js'; import { @@ -179,8 +180,12 @@ function safeGetService(ctx: PluginContext, name: string): T | undefined { * - No gate feature is active, or the probe is absent or throws: the answer * is `undefined` and no session is read. The gate costs nothing while it * is off, and a host whose probe faults never declared a gate. - * - The gate is active: a dedicated session read. The answer is its user, or - * `undefined` when there is no session. The API-key caller and the + * - The gate is active and the request's own session admitted the principal + * (`admitted`, read off the identity step's record): the posture decided + * off that same read. ⛔ No second read: the request's session is read + * once, and every seam of the request shares that read. + * - The gate is active otherwise: a dedicated session read. The answer is its + * user, or `undefined` when there is no session. The API-key caller and the * anonymous caller have none, and no policy holds them. * - The gate is active and the read FAILS: the branded authorization-store * outage, answered `503 SERVICE_UNAVAILABLE` by the fallback's error exit. @@ -194,6 +199,7 @@ function safeGetService(ctx: PluginContext, name: string): T | undefined { async function readGatedSessionUser( authService: IAuthService | undefined, headers: Record, + admitted?: { authGate: unknown }, ): Promise { let active = false; try { @@ -202,6 +208,7 @@ async function readGatedSessionUser( active = false; } if (!authService || !active) return undefined; + if (admitted) return { authGate: admitted.authGate }; try { const api = authService.api ?? (await authService.getApi?.()); // A provider that mounts no session API has no session to hold. @@ -2524,11 +2531,20 @@ export function createDispatcherPlugin(config: DispatcherPluginConfig = {}): Plu // and the dispatcher's route mounts make (#4910). // Two answers to "who is calling" eventually // disagree about what counts as authenticated. - resolvePrincipalId: (headers) => - resolveSessionPrincipalId( - safeGetService(ctx, 'auth'), - headers as Record, - ), + // + // A principal this request's own session read + // already admitted (the identity step above, + // `resolveRequestScope`) is answered from that + // read: the session is read once per request. + resolvePrincipalId: (headers) => { + const admitted = sessionAdmittedPrincipal(protocolContext); + return admitted + ? Promise.resolve(admitted.userId) + : resolveSessionPrincipalId( + safeGetService(ctx, 'auth'), + headers as Record, + ); + }, // ADR-0069: the session the authentication-policy // gate is asked about, read only while a gate feature // is active. Same `auth` occupant as the lookup above. @@ -2545,6 +2561,10 @@ export function createDispatcherPlugin(config: DispatcherPluginConfig = {}): Plu : readGatedSessionUser( safeGetService(ctx, 'auth'), headers as Record, + // The posture off the identity step's + // read, for a principal the request's + // own session admitted: no second read. + sessionAdmittedPrincipal(protocolContext), ), limiters: endpointLimiters, // The authored `server.trustProxy`, read from the diff --git a/packages/runtime/src/http-dispatcher.auth-gate-outage.pin.test.ts b/packages/runtime/src/http-dispatcher.auth-gate-outage.pin.test.ts index 847edf2db83..0a92174e628 100644 --- a/packages/runtime/src/http-dispatcher.auth-gate-outage.pin.test.ts +++ b/packages/runtime/src/http-dispatcher.auth-gate-outage.pin.test.ts @@ -49,6 +49,9 @@ import { ApiErrorSchema, BaseResponseSchema } from '@objectstack/spec/api'; import { HttpDispatcher } from './http-dispatcher.js'; import type { HttpProtocolContext } from './http-dispatcher.js'; import { createDispatcherPlugin } from './dispatcher-plugin.js'; +// Paid at collection, not inside a case's clock: the dispatcher's reach +// (`domains/packages.ts` → `standalone-stack.ts`) loads it lazily. +import '@objectstack/metadata'; const ORIGIN = 'http://tenant.example'; /** Not allow-listed, and the domain hands the request to a recording member. */ @@ -159,15 +162,24 @@ describe('[#23245] HttpDispatcher.enforceAuthGate — an active gate that cannot expect(off.member.handleRedeliver).toHaveBeenCalledTimes(1); expect(off.auth.isAuthGateActive).toHaveBeenCalled(); - // "No read" measured, not assumed: an ACTIVE gate on the same request - // reads exactly once more than the inactive one does (the identity - // step's own reads are the shared baseline). - const on = harness({ gateActive: true, backend: 'healthy', user: CLEAR_USER }); - const offHealthy = harness({ gateActive: false, backend: 'healthy', user: CLEAR_USER }); + // "No read" measured, not assumed: for a caller the identity step did + // NOT admit (a cookie no session answers for), an ACTIVE gate on the + // same request reads exactly once more than the inactive one does (the + // identity step's own read is the shared baseline). A principal the + // request's own session admitted is judged off that read, so the gate + // adds no read for it, active or not. + const on = harness({ gateActive: true, backend: 'healthy' }); + const offHealthy = harness({ gateActive: false, backend: 'healthy' }); await on.dispatcher.dispatch('POST', ROUTE, {}, {}, ctx(request())); await offHealthy.dispatcher.dispatch('POST', ROUTE, {}, {}, ctx(request())); expect(on.auth.getSession.mock.calls.length).toBe(offHealthy.auth.getSession.mock.calls.length + 1); expect(off.auth.getSession.mock.calls.length).toBe(offHealthy.auth.getSession.mock.calls.length); + + const onAdmitted = harness({ gateActive: true, backend: 'healthy', user: CLEAR_USER }); + const offAdmitted = harness({ gateActive: false, backend: 'healthy', user: CLEAR_USER }); + await onAdmitted.dispatcher.dispatch('POST', ROUTE, {}, {}, ctx(request())); + await offAdmitted.dispatcher.dispatch('POST', ROUTE, {}, {}, ctx(request())); + expect(onAdmitted.auth.getSession.mock.calls.length).toBe(offAdmitted.auth.getSession.mock.calls.length); }); it('CASE 3 — ACTIVE, CLEAR: a successful read carrying no posture still admits', async () => { diff --git a/packages/runtime/src/http-dispatcher.session-read-once.pin.test.ts b/packages/runtime/src/http-dispatcher.session-read-once.pin.test.ts new file mode 100644 index 00000000000..8d9279e5053 --- /dev/null +++ b/packages/runtime/src/http-dispatcher.session-read-once.pin.test.ts @@ -0,0 +1,196 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * One authenticated dispatcher request reads its session ONCE, on a REAL + * kernel with an ADR-0069 gate feature active (password expiry), the + * composition `default-organization-statements.golden.test.ts` boots. + * + * ## What doubled + * + * The identity step (`HttpDispatcher.resolveRequestScope`) reads the session + * through the auth service and records the posture decided off that read + * (`context.admission`). With any gate feature active, the gate + * (`HttpDispatcher.enforceAuthGate`) then read the SAME session again for a + * principal that read had just admitted, so `sys_session` by token and the + * session's `sys_user` row were each read twice per request, one remote round + * trip each on a hosted database. The gate now judges that principal by the + * posture off the identity step's read. + * + * ## What this pins + * + * 1. ⭐ A warm authenticated request issues ONE `sys_session` lookup by token + * and ONE better-auth `sys_user` lookup by id (two each before). + * 2. CONTROLS, each through the same gate: + * - a session the policy holds is still refused at the gate, 403 with the + * posture's code, and the domain never answers; + * - a revoked session resolves no principal: 401, as an anonymous caller; + * - an anonymous request resolves no principal and reads no session row; + * - two concurrent requests with different tokens each get their own + * answer, interleaved several times. + * + * Counted: every statement the SQL driver issues inside the request's own + * async context (knex's `query` event), as the statements golden counts them. + * Warm: two requests first, so the localization cache and the served metadata + * are warm before any count is read. + */ + +import { AsyncLocalStorage } from 'node:async_hooks'; +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQLPlugin } from '@objectstack/objectql'; +import { HonoServerPlugin } from '@objectstack/plugin-hono-server'; +import { createRestApiPlugin } from '@objectstack/rest'; +import { AuthManager, AuthPlugin } from '@objectstack/plugin-auth'; +import { SecurityPlugin, appSecurityPluginOptions } from '@objectstack/plugin-security'; +import { SharingServicePlugin } from '@objectstack/plugin-sharing'; +import { PlatformObjectsPlugin } from '@objectstack/platform-objects/plugin'; +import { AppPlugin } from './app-plugin.js'; +import { DefaultDatasourcePlugin } from './default-datasource-plugin.js'; +import { createDispatcherPlugin } from './dispatcher-plugin.js'; +// Paid at collection, not inside the boot's clock: the app plugin's reach loads it lazily. +import '@objectstack/metadata'; + +const BOOT_TIMEOUT = 180_000; +const ORIGIN = 'http://localhost:3000'; +const API = '/api/v1'; +const SYS = { isSystem: true }; +/** `AuthPlugin`'s dev-admin defaults (`OS_SEED_ADMIN_*` unset). */ +const OWNER = { email: 'admin@objectos.ai', password: 'admin123' }; +const HELD = { email: 'held@pin.test', password: 'held-pin-password-session-once', name: 'Held member' }; +/** A dispatcher-served route outside the ADR-0069 allow-list, answering 401 to an anonymous caller. */ +const ROUTE = '/packages'; +/** The better-auth session read's token lookup — one per session read. */ +const SESSION_TOKEN_LOOKUP = /^select \* from `sys_session` where `token` = \? limit \?$/; +/** The better-auth session read's own user lookup — one per session read. */ +const SESSION_USER_LOOKUP = /^select \* from `sys_user` where `id` = \? limit \?$/; + +const PIN_APP: any = { + manifest: { id: 'com.pin.sessionreadonce', name: 'Session read once pins', version: '1.0.0' }, + objects: [{ name: 'pin_note', label: 'Pin note', fields: { title: { type: 'text', label: 'Title' } } }], +}; + +const statements = new AsyncLocalStorage(); +let kernel: any; +let engine: any; +let app: any; +let auth: any; +let ownerToken = ''; +let heldToken = ''; +let prevNodeEnv: string | undefined; + +async function signIn(who: { email: string; password: string }): Promise { + const res: Response = await app.request(`${ORIGIN}${API}/auth/sign-in/email`, { + method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(who), + }); + expect(res.status, await res.clone().text()).toBe(200); + return ((await res.json()) as { token: string }).token; +} + +/** One request to {@link ROUTE}, and the statements the driver issued for it. */ +async function request(token?: string): Promise<{ status: number; body: any; sql: string[] }> { + const sql: string[] = []; + const res: Response = await statements.run(sql, () => + app.request(`${ORIGIN}${API}${ROUTE}`, token ? { headers: { Authorization: `Bearer ${token}` } } : {}), + ); + const text = await res.text(); + return { status: res.status, body: text ? JSON.parse(text) : undefined, sql: [...sql] }; +} + +const sessionReads = (sql: string[]) => ({ + sys_session: sql.filter((s) => SESSION_TOKEN_LOOKUP.test(s)).length, + sys_user: sql.filter((s) => SESSION_USER_LOOKUP.test(s)).length, +}); + +beforeAll(async () => { + prevNodeEnv = process.env.NODE_ENV; + process.env.NODE_ENV = 'development'; // the dev-admin seed, as `objectstack dev` arms it + kernel = new ObjectKernel(); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(new DefaultDatasourcePlugin({ driver: 'sqlite-wasm', config: { filename: ':memory:' } })); + await kernel.use(new HonoServerPlugin({ port: 0 })); + await kernel.use(new AppPlugin(PIN_APP)); + await kernel.use(new PlatformObjectsPlugin()); + // ADR-0069 D3: password expiry on, so the gate is ACTIVE on every request. + await kernel.use(new AuthPlugin({ secret: 'session-read-once-pin-secret-0001', passwordExpiryDays: 365 })); + await kernel.use(new SecurityPlugin(appSecurityPluginOptions(PIN_APP))); + await kernel.use(new SharingServicePlugin()); + await kernel.use(createRestApiPlugin({})); + await kernel.use(createDispatcherPlugin({})); + await kernel.bootstrap(); + engine = await kernel.getServiceAsync('objectql'); + app = (await kernel.getServiceAsync('http-server')).getRawApp(); + auth = await kernel.getServiceAsync('auth'); + (engine as any).getDriver('sys_user').knex.on('query', (q: { sql?: unknown }) => { + statements.getStore()?.push(String(q?.sql ?? '')); + }); + ownerToken = await signIn(OWNER); + + // The held member, provisioned through the operator door as the stack's + // own auth manager stages it, then flagged for an administrator-issued + // password change: a posture the gate refuses. + const ticket = auth.stageOperatorProvisioning(HELD.email); + let signUp: Response; + try { + signUp = await app.request(`${ORIGIN}${API}/auth/sign-up/email`, { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ ...HELD, [AuthManager.OPERATOR_PROVISIONING_TICKET_FIELD]: ticket }), + }); + } finally { + auth.clearOperatorProvisioning(HELD.email); + } + expect(signUp.status, await signUp.clone().text()).toBe(200); + heldToken = await signIn(HELD); + const [held] = await engine.find('sys_user', { where: { email: HELD.email }, limit: 1, context: SYS }); + await engine.update('sys_user', { id: held.id, must_change_password: true }, { context: SYS }); +}, BOOT_TIMEOUT); + +afterAll(async () => { + try { await kernel?.shutdown?.(); } catch { /* best-effort */ } + if (prevNodeEnv === undefined) delete process.env.NODE_ENV; + else process.env.NODE_ENV = prevNodeEnv; +}, 60_000); + +describe('one authenticated dispatcher request reads its session once (real kernel, gate active)', () => { + it('precondition: an ADR-0069 gate feature is active, so the gate runs on every request', () => { + expect(auth.isAuthGateActive()).toBe(true); + }); + + it('⭐ a warm authenticated request reads sys_session once and the session user once', async () => { + await request(ownerToken); + await request(ownerToken); + const r = await request(ownerToken); + expect(r.status, JSON.stringify(r.body)).toBe(200); + expect(sessionReads(r.sql)).toEqual({ sys_session: 1, sys_user: 1 }); + }); + + it('CONTROL — a session the policy holds is still refused at the gate, with the posture\'s code', async () => { + const r = await request(heldToken); + expect(r.status).toBe(403); + expect(r.body?.error?.code).toBe('PASSWORD_RESET_REQUIRED'); + expect(sessionReads(r.sql), r.sql.join('\n')).toEqual({ sys_session: 1, sys_user: 1 }); + }); + + it('CONTROL — an anonymous request resolves no principal and reads no session row', async () => { + const r = await request(); + expect(r.status, JSON.stringify(r.body)).toBe(401); + expect(r.sql.filter((s) => /`sys_session`/.test(s))).toEqual([]); + }); + + it('CONTROL — two concurrent requests with different tokens each get their own answer', async () => { + const answers = await Promise.all( + Array.from({ length: 8 }, (_, i) => request(i % 2 === 0 ? ownerToken : heldToken)), + ); + expect(answers.map((a) => a.status)).toEqual([200, 403, 200, 403, 200, 403, 200, 403]); + for (const a of answers) expect(sessionReads(a.sql)).toEqual({ sys_session: 1, sys_user: 1 }); + }); + + it('CONTROL — a revoked session resolves no principal: 401, as an anonymous caller', async () => { + const token = await signIn(OWNER); + expect((await request(token)).status).toBe(200); + const [row] = await engine.find('sys_session', { where: { token }, limit: 1, context: SYS }); + expect(row, 'precondition: the session row exists').toBeDefined(); + await engine.delete('sys_session', { where: { id: row.id }, context: SYS }); + const r = await request(token); + expect(r.status, JSON.stringify(r.body)).toBe(401); + }); +}); diff --git a/packages/runtime/src/http-dispatcher.ts b/packages/runtime/src/http-dispatcher.ts index 9bf979a54df..823847b674e 100644 --- a/packages/runtime/src/http-dispatcher.ts +++ b/packages/runtime/src/http-dispatcher.ts @@ -40,7 +40,7 @@ import { DomainHandlerRegistry, type DomainRoute, type DomainHandlerDeps } from // only — `actionExecutionDeps` hands the endpoint step the same `deps` object // every domain already passes to `callData`, without this file calling it. import type { ActionExecutionDeps } from './action-execution.js'; -import { admittingCredentialKind } from './security/admitting-credential.js'; +import { admittingCredentialKind, sessionAdmittedPrincipal } from './security/admitting-credential.js'; import { createAnalyticsDomain, handleAnalyticsRequest } from './domains/analytics.js'; import { isServiceServeable } from './service-serveable.js'; import { createI18nDomain, handleI18nRequest } from './domains/i18n.js'; @@ -120,9 +120,10 @@ export interface HttpProtocolContext { * {@link executionContext}'s principal, and — for an API key — the * key-admission seam's ADR-0069 answer on the key's owner. Written by * {@link HttpDispatcher.resolveRequestScope}; read by the ADR-0069 gate, - * which judges a key-admitted request by the key's answer and re-reads the - * session only for a principal a session admitted. Undefined for an - * anonymous request. + * which judges a key-admitted request by the key's answer and a principal + * the request's own session admitted by the posture decided off that same + * read (`sessionAdmittedPrincipal`), so the session is read once per + * request. Undefined for an anonymous request. */ admission?: { credential: 'api_key' | 'session'; authGate: AuthGate | undefined }; /** @@ -1592,6 +1593,9 @@ export class HttpDispatcher { * - allow-listed path, no `auth` service, or no gate feature active — * including an `isAuthGateActive()` probe that THROWS (a host whose * probe faults never declared a gate) — answers null with no read; + * - the gate is active and the request's own session admitted the + * principal (`sessionAdmittedPrincipal`) ⇒ the posture decided off the + * identity step's read, with no second read: its 403, or null; * - the gate is active and the session API, the header bag or the read * itself fails ⇒ the branded outage, never null; * - the gate is active and the read RESOLVES with no posture (no session, @@ -1632,6 +1636,20 @@ export class HttpDispatcher { if (!authService || typeof authService.isAuthGateActive !== 'function' || !authService.isAuthGateActive()) { return null; } + // A principal THIS request's own session read admitted is judged by + // the posture decided off that same read, recorded by the identity + // step above (`resolveRequestScope` → `context.admission`). ⛔ No + // second read for it: one request reads its session once, and the + // gate and principal resolution share that read. The read already + // succeeded, so there is no unread session for decision 2 B to + // refuse. An anonymous request, an OAuth access token (whose session + // the door established) and an identity step that degraded after + // the read fall through to the read below, as before. + const admitted = sessionAdmittedPrincipal(context as HttpProtocolContext | undefined); + if (admitted) { + const gate = evaluateAuthGate(admitted, cleanPath, method); + return gate ? this.error(gate.message, 403, { code: gate.code }) : null; + } // The gate is ACTIVE from here: the session read either answers or // is the outage it is (#13906 decision 2 B). ⛔ Never a // `.catch(() => undefined)` on it — that converts a THROW into the diff --git a/packages/runtime/src/security/admitting-credential.ts b/packages/runtime/src/security/admitting-credential.ts index 353f2ae9833..6e104b272be 100644 --- a/packages/runtime/src/security/admitting-credential.ts +++ b/packages/runtime/src/security/admitting-credential.ts @@ -1,5 +1,6 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +import type { AuthGate } from '@objectstack/core'; import type { AIRouteCredentialKind } from '@objectstack/spec/contracts'; /** @@ -29,3 +30,38 @@ export function admittingCredentialKind(request: AdmittingCredentialFacts | unde if (Array.isArray(request?.executionContext?.oauthScopes)) return 'oauth'; return request?.admission?.credential; } + +/** The request facts {@link sessionAdmittedPrincipal} reads. */ +export interface SessionAdmissionFacts { + executionContext?: { userId?: unknown; oauthScopes?: unknown }; + admission?: { credential: 'api_key' | 'session'; authGate: AuthGate | undefined }; +} + +/** + * The principal THIS request's own session read admitted, as the identity step + * recorded it (`HttpDispatcher.resolveRequestScope`): the user id it resolved + * and the ADR-0069 posture decided off that same read (`resolveAuthzContext`'s + * session arm, `normalizeAuthGate(session.user)`). It is how a later seam of the + * SAME request asks "who is the session, and does a policy hold it" without + * reading the session again: one read per request, shared by every seam that + * needs it. + * + * `undefined` unless the identity step resolved a principal from the request's + * own session: an anonymous caller, an API key (judged by the key's own + * answer), an OAuth access token or a forward credential (whose session the + * door ESTABLISHED, so the request's own session was never read for it), and an + * identity step that degraded to anonymous after the read all answer + * `undefined`. Each of those keeps whatever read its seam made before. + * + * ⛔ Request-scoped by construction: it reads only the request object it is + * handed, which the dispatcher builds per request. Never cache its answer + * beyond the request. + */ +export function sessionAdmittedPrincipal( + request: SessionAdmissionFacts | undefined, +): { userId: string; authGate: AuthGate | undefined } | undefined { + if (admittingCredentialKind(request) !== 'session') return undefined; + const userId = request?.executionContext?.userId; + if (typeof userId !== 'string' || userId.length === 0) return undefined; + return { userId, authGate: request?.admission?.authGate }; +} diff --git a/packages/runtime/src/security/resolve-execution-context.ts b/packages/runtime/src/security/resolve-execution-context.ts index 074b7b86efa..d9f77dd25cc 100644 --- a/packages/runtime/src/security/resolve-execution-context.ts +++ b/packages/runtime/src/security/resolve-execution-context.ts @@ -234,10 +234,11 @@ export async function resolveExecutionContext(opts: ResolveOptions): Promise