Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .changeset/session-read-once-per-request.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion packages/core/src/security/assemble-execution-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/security/request-execution-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 (`<prefix>/apps/<ns>/…`). */
const DECLARED: ApiEndpoint[] = [
Expand Down Expand Up @@ -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]);
});
});
34 changes: 27 additions & 7 deletions packages/runtime/src/dispatcher-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -179,8 +180,12 @@ function safeGetService<T>(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.
Expand All @@ -194,6 +199,7 @@ function safeGetService<T>(ctx: PluginContext, name: string): T | undefined {
async function readGatedSessionUser(
authService: IAuthService | undefined,
headers: Record<string, unknown>,
admitted?: { authGate: unknown },
): Promise<unknown> {
let active = false;
try {
Expand All @@ -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.
Expand Down Expand Up @@ -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<IAuthService>(ctx, 'auth'),
headers as Record<string, unknown>,
),
//
// 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<IAuthService>(ctx, 'auth'),
headers as Record<string, unknown>,
);
},
// 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.
Expand All @@ -2545,6 +2561,10 @@ export function createDispatcherPlugin(config: DispatcherPluginConfig = {}): Plu
: readGatedSessionUser(
safeGetService<IAuthService>(ctx, 'auth'),
headers as Record<string, unknown>,
// 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
Expand Down
22 changes: 17 additions & 5 deletions packages/runtime/src/http-dispatcher.auth-gate-outage.pin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -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 () => {
Expand Down
Loading
Loading