Skip to content

Commit 0c3db0f

Browse files
refactor(service-settings): the settings door calls the one request-to-ExecutionContext composition, resolveRequestExecutionContext (#24297)
Part of #23217 Clause-②: no Ruling-ref: 6227928430 Slice 3 of #23217 under ruling record 6227928430 (letter A): the settings door, `SettingsServicePlugin`'s `verifiedContextFromRequest` in `packages/services/service-settings/src/settings-service-plugin.ts`, calls the one `resolveRequestExecutionContext` that slice 1 landed in `@objectstack/core`. The card stays open for its two remaining doors, `service-storage` (slice 4) and `plugin-hono-server` (slice 5). `@objectstack/core`'s function is not touched: every settings difference is one of its existing named parameters, so the letter-B fallback (item 5) does not arise. Basis for the `Clause-②: no` line: the ruling's "later slices `Clause-②: no`". The settings door's outward answers are unchanged (the ten-row pin below and a 29-wiring fault probe read the same on both trees), and no export moves in `@objectstack/service-settings`. The one new method, `tenancyServiceResolver`, is private. ## What changed ### The door `verifiedContextFromRequest` keeps its door facts in their old order and calls the function once. Each parameter was measured on the hand-written door at `1e001c7df` before converting: | parameter | settings passes | what the hand-written door did | |:--|:--|:--| | `anonymous` | `'fail-closed'` | An unresolved request became a context with no `userId`, which the family's anonymous floor refuses with `401`. The function now yields no context and the door answers its existing fail-closed `{ enforced: true }`: the same floor, the same `401`. | | `authGate` | `'resolved'` | It carried `authz.authGate` from the read that admitted the caller. There was no re-read, and `isAuthGateActive()` was never asked. | | `credentials` | `'api-key-and-session'` | The request's headers went to `resolveAuthzContext`, so the API-key door was open. | | `sessionApi` | `'optional'` | The session read was lazy and swallowed every failure, so a key admitted without any session read. | | `session` | `'request'` | `api.getSession(inProcessSessionReadInput(headers))` (`.api`, else `getApi()`). | | `tenancy` | the door's async-registry thunk, or `undefined` on a host with none | `resolveAdmissionTenancyPosture`: `getKernel().getServiceAsync('tenancy')`, classified by `classifyAdmissionTenancyPosture`. | | `localization` | `'withhold'` | It read none. | | `requestLocale` | `undefined` | It read none. | | `accessToken` | `'withhold'` | Slice 1's table did not cover it, so it was measured: `SettingsContext` declares no bearer field, and the door's projection never read `authz.accessToken`. The bearer never left the door, so `'withhold'` also keeps it off the intermediate envelope. | | `oauth`, `onAdmission` | `undefined` | none | What stays at the door, in its old order: - the engine lookup, first, inside the fail-closed `try`; - the header normalisation; - the auth-service lookup, where a lookup that throws counts as no auth service; - the tenancy wiring, now a resolver thunk (`tenancyServiceResolver`). `resolveAdmissionTenancyPosture`, the settings service's own posture read, classifies that same thunk as before; - the projection to `SettingsContext`: `userId`, `tenantId`, system capabilities and grants as one list, `enforced: true`, and `authGate` when one holds; - the `catch` that re-raises the store-outage and API-key-lifecycle brands and otherwise fails closed. One ordering moved: the auth-service lookup now runs before the tenancy read (it used to run after). Both are registry lookups whose throw the door swallows, so no answer can tell the two orders apart. The probe below reads the same 29 answers on both trees. ### Readers moved in the same PR - `scripts/check-single-authz-resolver.mjs`: `DELEGATORS` gains the settings row (`resolveRequestExecutionContext`), the seat's decision recorded in the claim. The gate answers "all 4 entry points delegate"; `--self-test` exit 0. - `packages/core/src/security/authz-store-unavailable.test.ts`: the settings row of `TRANSPORT_LEDGER` is out. The door no longer calls the resolver itself, and the comment on the composition's row now names settings as its third caller. - `packages/runtime/src/security/request-execution-context.conformance.test.ts`: a settings row and a settings CONTROL (details below), with `@objectstack/service-settings` added to runtime's `devDependencies` and `pnpm-lock.yaml` regenerated by `pnpm install` (+3 lines). - **Outside the claim's declared surface:** `packages/runtime/vitest.config.ts` gains an anchored alias for `@objectstack/service-settings` to its `src/index.ts`. Without it, the new row would import the settings door from its built `dist/`, and `check:test-source-alias` requires a test to read a workspace dependency's source, not its build (the comment in the config says so). With it, the gate exits 0. - **Outside the claim's declared surface:** `scripts/slot-lookup-baseline.json` changes the settings door's count from 2 to 1. The deleted `getSession` closure held one of the file's two service lookups erased to `any` (`const authService: any = ctx.getService('auth')`). `check:slot-lookup` fails on a decrease too ("ratchet DOWN: run `--update`"), and `pnpm check:slot-lookup --update` wrote this one-line change. ### The ruling's one ADR-0096 / ADR-0069 pin `packages/services/service-settings/src/settings-routes.request-context-door.pin.test.ts` has ten rows on the real listing route, `GET /api/settings`. The plugin is booted for real with no seam captured, and each row reads the context that reached the settings service: | row | answer | |:--|:--| | ADR-0096: no credential | `401 UNAUTHENTICATED`, service never asked | | ADR-0096: a cookie the auth service does not recognise | `401` | | ADR-0096: a session read that fails (it resolved no caller: the floor, not an outage) | `401` | | ADR-0096: an ex-member's organization-stamped key under the walled posture, a healthy cookie beside it | `401`; the cookie never answers for the refused key | | ADR-0069: a held session | `403 PASSWORD_EXPIRED` with its message | | ADR-0069: the same held session while the gate probe says no gate is active | `403`; the posture is the admitting read's | | ADR-0069: a key whose owner holds an `account`-scope posture | `403 MFA_REQUIRED` with its message | | ADR-0069: a key beside the held cookie | `200` as the key's owner, no `authGate` | | CONTROL: an ungated session | `200` as that principal, with tenant, `enforced`, no `authGate` | | CONTROL: an API key on a host with no auth service | `200` as its owner | It was committed first, on the hand-written door (`78e9382c6`, door blob `7c72080fa`): `Tests 10 passed (10)`. It is green after the conversion too. ### The conformance row The settings door hands on a projection, `SettingsContext`, not the context. So the row declares that projection (`project`), and the door's answer must equal the projection of the function's context under the row's parameters. Its identity facts are `userId`, `tenantId` and `permissions`. The other two rows are unchanged: their entries are now named constants, typed by what each door hands on (`DoorRow` is generic over it), which re-indents them. The drive goes through the door's public entry: the real plugin booted on a plugin context over the world's services, and one `GET /api/settings`. The door returns its context to no caller. The family door's first read of it is the ADR-0069 check, `evaluateAuthGate(context, '')`, which runs on every route and every request ahead of the anonymous floor, so the drive reads the context there. It does so through a pass-through mock of that one `@objectstack/core` export, which records its argument and answers exactly as the real export does. The settings CONTROL shows that the requests tell apart: - `anonymous`: the guest entry would have handed on a different context; - `authGate`: `'reread-when-active'` drops the posture when no gate is active; - `credentials`: `'session-only'` admits nobody here; - `tenancy`: no posture admits the ex-member's key; - `sessionApi`: `'required'` admits nobody with no auth service; - and the projection's union: the key owner's system capability `export_reports` reaches `permissions`. **What no request can tell apart at this door:** the projection carries no locale, time zone or bearer, so `localization`, `requestLocale` and `accessToken` cannot be told apart here. The row declares the values the door passes, and the file's header says so. ## Measurements (the dispatch's mechanism assumptions) - **A1 (parameters):** held, row by row, as tabled above. `accessToken` was measured as `'withhold'`. - **A2 (source-text pins):** falsified. No test in `@objectstack/service-settings` reads the door's source text. Its one `readFileSync` pin (`value-domains.shared-predicate.pin.test.ts`) reads `value-domains.ts`. Nothing was re-aimed. - **A3 (bare-term censuses):** I took an identifier-token census of the door file at `1e001c7df` and at the conversion. 182 distinct tokens changed count. Code identifiers among them: `resolveAuthzContext` 4 to 2 (both left in comments), `resolveRequestExecutionContext` 0 to 3, `getSession` 3 to 0, `inProcessSessionReadInput` 2 to 0, `userAuthGateSourceOf` 2 to 0, `apiKeyLifecyclePolicySourceOf` 2 to 0, `getApi` 2 to 0, `getService` 9 to 8, `any` 13 to 10, `tenancyServiceResolver` 0 to 5. Three readers count these over this file: `TRANSPORT_LEDGER` (`resolveAuthzContext({`), `DELEGATORS` (`resolveRequestExecutionContext`) and the slot-lookup ratchet (the `any`-erased lookup). All three moved in this PR. The dogfood `authz-probe-blind-spot` census reads no settings file. - **A4 (ordering):** the auth-service lookup moved ahead of the tenancy read, and this door has no early session-API check (`sessionApi: 'optional'`). A one-off probe, never committed, drove 29 wirings through `GET /api/settings`: the hand-written door at door blob `7c72080fa`, then the converted door at `1d3595a69`. **All 29 answers are identical.** The double-fault rows: | wiring | before | after | |:--|:--|:--| | tenancy outage + auth lookup throws + session | 503 | 503 | | tenancy outage + session read throws | 503 | 503 | | tenancy outage + no session API + key | 503 | 503 | | tenancy outage + `getApi()` rejects + session | 503 | 503 | | tenancy outage + a revoked key | 503 | 503 | | tenancy outage + engine lookup throws | 401 | 401 | | tenancy outage + kernel accessor throws | 401 | 401 | | engine read rejects + auth lookup throws + key | 401 | 401 | | revoked key + engine lookup throws | 401 | 401 | The single-fault and healthy rows are identical too: healthy session or key 200; no credential 401; a revoked key 403 `API_KEY_REVOKED`; no session API, `getApi()` rejecting or no auth service with a key 200 and with a cookie 401; an engine read that rejects on a session 503. - **A5 (readers):** held. Adding the runtime `devDependency` creates no cycle: the transitive closure of `@objectstack/service-settings` (17 workspace packages over dependencies, devDependencies, peer and optional) never reaches `@objectstack/runtime`. - **A6:** held (`@objectstack/core: workspace:*`). ## Evidence - **Head:** `6328d1141` (`origin/main` `9822b053e` merged in). - **`@objectstack/service-settings`:** `Test Files 49 passed (49)`, `Tests 871 passed (871)`. `typecheck` exit 0, and its program includes the new pin (`tsc --listFiles`). - **`@objectstack/core`:** local project `Test Files 104 passed (104)`, `Tests 2551 passed (2551)`. The repo-project ledger `authz-store-unavailable.test.ts`: `Tests 38 passed (38)`, slice 2's 39 minus the settings row. `typecheck` exit 0, test layer 4 / 4 held. - **`@objectstack/runtime`:** local project `Test Files 416 passed (416)`, `Tests 6558 passed | 19 skipped (6577)`. `typecheck` exit 0, test layer 27 files / 190 errors / 68 signatures held. The conformance test, verbose: `Tests 10 passed (10)`: three rows, six requests, three CONTROLs. - **Ablation, declared direction RED:** the door's `authGate: 'resolved',` was mutated to `'withhold'` (marker `ABLATION-23217-s3-gate`) by `scripts/ablation-replace.mjs`: "anchor 1 to 0, blob 1d3595a to 3b27a1db91ba" (the tool prints arrows), with the marker counted on disk as 1. Both suites read the door from `src` (in-package relative imports, and runtime's new alias), so no dist preflight applies. - Observed in the settings door pins (the new pin, the ADR-0069 producer pin, the key account-posture pin): `Tests 8 failed | 27 passed (35)`, 3 of 3 files red. - Observed in the conformance test: `Tests 3 failed | 7 passed (10)`: the two gated-session requests and the settings CONTROL. - Restore: "blob == HEAD (1d3595a) and git diff HEAD is empty", marker 0. - The observed direction equals the declared one. - **Lint:** `pnpm exec eslint --no-inline-config` over the six changed `.ts` / `.mjs` files: exit 0, no output. The repo-wide `pnpm lint` is CI's. - **Gates:** `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` (no paths) derived 100 commands at `6328d1141`. Each was run with its exit code captured before any pipe. - 99 exited 0. - `pnpm check:dual-build-cjs-loads` exited 3 (PREREQUISITE NOT MET: no `dist/` for 41 entry points). So I built the whole tree under the verify lock (`turbo run build`, docs excluded: 76 tasks, 75 cache hits) and re-ran it on the same head: exit 0, "111 published require entry point(s) across 69 package(s) load". - `--ran` reconciliation: "100 derived, 100 run, 0 NOT-MEASURED, 0 UNRUN". - Among them, all exit 0: `check:authz-resolver`, `check:cross-package-test-inputs`, `check:test-source-alias`, `check:slot-lookup`, `check:engine-double-contract`, `check:objectql-double-limit`, `check:where-matcher`, `check:type-check-coverage`, `check:type-check-debt`, `check:published-files`, `check:nul-bytes`, `check-adr-0087-registration --base origin/main` and `check-changeset-no-major --base origin/main`. - Not run locally, and left to CI's Test Core: the core and runtime `test:repo` projects, beyond the one core ledger file this diff edits. ## Acceptance notes - The settings door's own `catch` is unchanged. The two brands are re-raised, and any other throw is the fail-closed `{ enforced: true }`. - A key's read failure answers `401`, before and after. The probe row "engine read rejects + key" answers `401 UNAUTHENTICATED`, where the same fault on a session request answers `503`. The cause is in `@objectstack/core`, not this door: `resolveApiKeyAdmission` catches a failing `sys_api_key` read and returns `{ outcome: 'none' }`. It is identical before and after this PR, and it is reported to the seat rather than changed here. - No changeset on `@objectstack/runtime`. Its diff is a `devDependency`, a vitest alias and a test, and none of those ships to a consumer. `@objectstack/service-settings` carries the `patch`. --- _Generated by [Claude Code](https://claude.ai/code/session_01SYEJqDL3NXxrJRBVqaMu9T)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 2ee5861 commit 0c3db0f

10 files changed

Lines changed: 608 additions & 140 deletions
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
---
2+
'@objectstack/service-settings': patch
3+
---
4+
5+
The settings routes' identity door resolves through `@objectstack/core`'s `resolveRequestExecutionContext`, the one request-to-`ExecutionContext` composition
6+
7+
Clause-②: no
8+
9+
- `SettingsServicePlugin` resolves the caller of every `/api/settings` route by calling `resolveRequestExecutionContext` with this door's differences as named parameters: `anonymous: 'fail-closed'`, `authGate: 'resolved'`, `credentials: 'api-key-and-session'`, `sessionApi: 'optional'`, `session: 'request'`, its own way to reach the `tenancy` service, `localization: 'withhold'`, no request locale, `accessToken: 'withhold'`, and no OAuth provenance or admission channel. The engine and auth-service lookups, the header normalisation, the tenancy wiring, the projection to `SettingsContext` and the fail-closed `catch` stay at the door.
10+
- The answers are the ones the door gave before: an anonymous caller, an unrecognised cookie, a failed session read and a refused API key get `401 UNAUTHENTICATED`; a session or an API key owner the authentication policy holds gets `403` with its code and message; an unreadable permission store or tenancy service gets `503 SERVICE_UNAVAILABLE`; and an API key its own lifecycle refuses gets its `403` and code. A one-off probe of 29 fault wirings through the listing route read the same answer on both sides of the change.
11+
- Nothing to do for a consumer: no export, route, configuration key or response shape changed.

‎packages/core/src/security/authz-store-unavailable.test.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -182,12 +182,13 @@ const TRANSPORT_LEDGER: Record<string, 'guarded' | 'propagates'> = {
182182
// The one request-to-ExecutionContext composition (ruling record 6227928430,
183183
// letter A). It catches nothing around the resolver: every door that calls
184184
// it — the runtime dispatcher's `resolve-execution-context.ts` first, REST's
185-
// `rest-server.ts` second, whose fail-closed `catch` re-raises the outage —
186-
// receives the outage and answers it at its own net.
185+
// `rest-server.ts` second and the settings door's
186+
// `settings-service-plugin.ts` third, each of the last two through a
187+
// fail-closed `catch` that re-raises the outage — receives the outage and
188+
// answers it at its own net.
187189
'packages/core/src/security/request-execution-context.ts': 'propagates',
188190
'packages/mcp/src/plugin.ts': 'propagates',
189191
'packages/services/service-datasource/src/admin-routes.ts': 'guarded',
190-
'packages/services/service-settings/src/settings-service-plugin.ts': 'guarded',
191192
'packages/services/service-storage/src/storage-service-plugin.ts': 'guarded',
192193
'packages/plugins/plugin-sharing/src/sharing-plugin.ts': 'guarded',
193194
'packages/plugins/plugin-hono-server/src/current-user-endpoints.ts': 'guarded',

‎packages/runtime/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@
6969
"@objectstack/service-job": "workspace:*",
7070
"@objectstack/service-messaging": "workspace:*",
7171
"@objectstack/service-package": "workspace:*",
72+
"@objectstack/service-settings": "workspace:*",
7273
"typescript": "^6.0.3",
7374
"vitest": "^4.1.11"
7475
},

‎packages/runtime/src/security/request-execution-context.conformance.test.ts‎

Lines changed: 239 additions & 58 deletions
Large diffs are not rendered by default.

‎packages/runtime/vitest.config.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,15 @@ export default defineConfig({
196196
// the #4567 regression (croner rejecting the expression envelope) is
197197
// reproduced by the actual scheduler rather than by a double.
198198
{ find: '@objectstack/service-job', replacement: path.resolve(__dirname, '../services/service-job/src/index.ts') },
199+
// Dev-only: src/security/request-execution-context.conformance.test.ts
200+
// drives the REAL settings door (`SettingsServicePlugin`'s context
201+
// resolver) as one row of ruling record 6227928430's conformance test, so
202+
// the row reads the door in the checkout, never a built copy of it.
203+
// Anchored: the package publishes only its root entry.
204+
{
205+
find: /^@objectstack\/service-settings$/,
206+
replacement: path.resolve(__dirname, '../services/service-settings/src/index.ts'),
207+
},
199208
// Dev-only: app-plugin.disabled-seed.test.ts drives the REAL
200209
// `sys_packages` → registry rehydration (#5047), so the empty-env seed
201210
// regression is proven against the actual hydration code rather than a
Lines changed: 241 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,241 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [ruling record 6227928430, letter A item 2] The settings door, proven on the
5+
* one request-to-`ExecutionContext` composition by this pin plus its existing
6+
* ones.
7+
*
8+
* `SettingsServicePlugin`'s `verifiedContextFromRequest` resolves the caller
9+
* for every `/api/settings` route. The two answers a door owes before any other
10+
* are pinned here on the real listing route (`GET /api/settings`), with the
11+
* plugin booted for real and no seam captured, and read at the settings
12+
* service, the route's own work:
13+
*
14+
* - ADR-0096: a request that resolves no principal never reaches the service.
15+
* The family answers it at its anonymous floor (`401 UNAUTHENTICATED`). A
16+
* session read that fails resolved no caller, so it is the same refusal and
17+
* not an outage, and a refused API key never falls through to the cookie
18+
* beside it.
19+
* - ADR-0069: a principal the authentication policy holds is refused `403`
20+
* with its posture. The door carries the posture decided off the read that
21+
* admitted the caller and reads no second time, so a held session is
22+
* refused whatever the auth service's gate probe says; a key answers for its
23+
* own owner's `account`-scope posture, whatever cookie rides beside it.
24+
*
25+
* The CONTROL rows prove the door admits somebody: an ungated session, and an
26+
* API key on a host with no auth service (the key door stays open without a
27+
* session API).
28+
*
29+
* Every row was green on the door's hand-written composition and is green on
30+
* the shared one.
31+
*/
32+
33+
import { describe, expect, it } from 'vitest';
34+
import {
35+
ANONYMOUS_DENY_CODE,
36+
ANONYMOUS_DENY_MESSAGE,
37+
ANONYMOUS_DENY_STATUS,
38+
hashApiKey,
39+
} from '@objectstack/core';
40+
import type { IHttpRequest, IHttpResponse, RouteHandler } from '@objectstack/spec/contracts';
41+
import { SettingsServicePlugin } from './settings-service-plugin.js';
42+
import type { SettingsContext } from './settings-service.types.js';
43+
import { bindCatalogFromTables } from './__tests__/security-catalog.testkit.js';
44+
45+
const ORG = 'org_alpha';
46+
const COOKIE = 'better-auth.session_token=tok_settings_door.c2ln';
47+
const HELD_COOKIE = 'better-auth.session_token=tok_settings_door_held.c2ln';
48+
const STRANGER_COOKIE = 'better-auth.session_token=tok_settings_door_unknown.c2ln';
49+
const KEY = 'osk_settings_door_key';
50+
const EX_MEMBER_KEY = 'osk_settings_door_ex_member';
51+
const HELD_OWNER_KEY = 'osk_settings_door_held_owner';
52+
const FUTURE = '2999-01-01T00:00:00Z';
53+
54+
const PASSWORD_EXPIRED = { code: 'PASSWORD_EXPIRED', message: 'Your password has expired.' };
55+
const MFA_REQUIRED = { code: 'MFA_REQUIRED', message: 'Multi-factor authentication is required.' };
56+
57+
interface Host {
58+
/** Whether an auth service is registered at all. */
59+
auth: boolean;
60+
/** What the auth service's gate probe answers (the door never asks it). */
61+
gateActive?: boolean;
62+
/** The auth service's session read throws for every request. */
63+
sessionReadFails?: boolean;
64+
}
65+
66+
/** One deployment: a walled (`isolated`) posture, an engine answering the permission tables, an auth service. */
67+
function services(host: Host): Record<string, unknown> {
68+
const tables: Record<string, Array<Record<string, unknown>>> = {
69+
sys_api_key: [
70+
{ id: 'k_live', key: hashApiKey(KEY), revoked: false, user_id: 'u_key', active_organization_id: ORG, expires_at: FUTURE },
71+
{ id: 'k_ex', key: hashApiKey(EX_MEMBER_KEY), revoked: false, user_id: 'u_ex', active_organization_id: ORG, expires_at: FUTURE },
72+
{ id: 'k_held', key: hashApiKey(HELD_OWNER_KEY), revoked: false, user_id: 'u_mfa', active_organization_id: ORG, expires_at: FUTURE },
73+
],
74+
sys_member: [
75+
{ user_id: 'u_key', organization_id: ORG, role: 'member' },
76+
{ user_id: 'u_mfa', organization_id: ORG, role: 'member' },
77+
{ user_id: 'u_ses', organization_id: ORG, role: 'member' },
78+
{ user_id: 'u_held', organization_id: ORG, role: 'member' },
79+
],
80+
};
81+
const objectql = bindCatalogFromTables({
82+
async find(object: string, q: { where?: Record<string, unknown>; limit?: number } | undefined) {
83+
const rows = (tables[object] ?? []).filter((row) => Object.entries(q?.where ?? {}).every(([k, v]) => {
84+
if (k.startsWith('$')) throw new Error(`fixture: unsupported combinator ${k}`);
85+
if (v !== null && typeof v === 'object') {
86+
return Array.isArray((v as { $in?: unknown[] }).$in) ? (v as { $in: unknown[] }).$in.includes(row[k]) : true;
87+
}
88+
return (v ?? null) === (row[k] ?? null);
89+
}));
90+
return typeof q?.limit === 'number' ? rows.slice(0, q.limit) : rows;
91+
},
92+
}, tables);
93+
94+
const registered: Record<string, unknown> = { objectql, tenancy: { posture: 'isolated' } };
95+
if (host.auth) {
96+
const sessions: Record<string, { user: Record<string, unknown>; session: Record<string, unknown> }> = {
97+
[COOKIE]: { user: { id: 'u_ses' }, session: { id: 'sess_ses', userId: 'u_ses', activeOrganizationId: ORG } },
98+
[HELD_COOKIE]: {
99+
user: { id: 'u_held', authGate: PASSWORD_EXPIRED },
100+
session: { id: 'sess_held', userId: 'u_held', activeOrganizationId: ORG },
101+
},
102+
};
103+
registered.auth = {
104+
api: {
105+
async getSession(input: { headers: Headers }) {
106+
if (host.sessionReadFails) throw new Error('session backend unavailable');
107+
return sessions[input.headers.get('cookie') ?? ''] ?? undefined;
108+
},
109+
},
110+
isAuthGateActive: () => host.gateActive ?? true,
111+
// `MFA_REQUIRED` is an `account`-scope posture: it holds every credential of its user.
112+
resolveUserAuthGates: async (userId: string) => (userId === 'u_mfa' ? [MFA_REQUIRED] : []),
113+
};
114+
}
115+
return registered;
116+
}
117+
118+
/** Boot the real plugin on `host` and answer one `GET /api/settings`. */
119+
async function listing(host: Host, headers: Record<string, string>) {
120+
const routes = new Map<string, RouteHandler>();
121+
const add = (verb: string) => (path: string, handler: RouteHandler) => { routes.set(`${verb} ${path}`, handler); };
122+
const http = {
123+
get: add('GET'), post: add('POST'), put: add('PUT'), delete: add('DELETE'), patch: add('PATCH'),
124+
use() {}, async listen() {}, async close() {},
125+
};
126+
const registered: Record<string, unknown> = { ...services(host), 'http-server': http };
127+
let readyHook: (() => Promise<void>) | undefined;
128+
let service: { listManifests(ctx: SettingsContext): unknown } | undefined;
129+
const ctx: any = {
130+
logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} },
131+
registerService: (name: string, value: unknown) => { if (name === 'settings') service = value as typeof service; },
132+
getService: (name: string) => registered[name],
133+
hook: (event: string, fn: () => Promise<void>) => { if (event === 'kernel:ready') readyHook = fn; },
134+
// The async registry the door reads the posture through; every name but
135+
// `tenancy` is registered or not exactly as `getService` answers it.
136+
getKernel: () => ({ getServiceAsync: async (name: string) => registered[name] }),
137+
};
138+
const plugin = new SettingsServicePlugin({ manifests: [], env: {}, actionHandlers: {} });
139+
await plugin.init(ctx);
140+
await plugin.start(ctx);
141+
await readyHook!();
142+
if (!service) throw new Error('fixture: the settings service was not registered');
143+
144+
// The route's own work, read where it happens: which context reached it.
145+
const seen: SettingsContext[] = [];
146+
const listManifests = service.listManifests.bind(service);
147+
service.listManifests = (context: SettingsContext) => { seen.push(context); return listManifests(context); };
148+
149+
const handler = routes.get('GET /api/settings');
150+
if (!handler) throw new Error('fixture: the listing route was not mounted');
151+
const answer: { status: number; body: any } = { status: 200, body: undefined };
152+
const res: any = {
153+
json(data: unknown) { answer.body = data; return res; },
154+
send() { return res; },
155+
status(code: number) { answer.status = code; return res; },
156+
header() { return res; },
157+
};
158+
await handler(
159+
{ params: {}, query: {}, headers, method: 'GET', path: '/api/settings' } as unknown as IHttpRequest,
160+
res as IHttpResponse,
161+
);
162+
return { answer, seen };
163+
}
164+
165+
const ANONYMOUS = { status: ANONYMOUS_DENY_STATUS, code: ANONYMOUS_DENY_CODE, message: ANONYMOUS_DENY_MESSAGE };
166+
167+
const ROWS: Array<{
168+
name: string;
169+
host: Host;
170+
headers: Record<string, string>;
171+
status: number;
172+
code?: string;
173+
message?: string;
174+
principal?: string;
175+
}> = [
176+
{
177+
name: 'ADR-0096: no credential is refused at the anonymous floor, and the service is never asked',
178+
host: { auth: true }, headers: {}, ...ANONYMOUS,
179+
},
180+
{
181+
name: 'ADR-0096: a cookie the auth service does not recognise is refused at the anonymous floor',
182+
host: { auth: true }, headers: { cookie: STRANGER_COOKIE }, ...ANONYMOUS,
183+
},
184+
{
185+
name: 'ADR-0096: a session read that fails resolved no caller, so it is the anonymous floor, not an outage',
186+
host: { auth: true, sessionReadFails: true }, headers: { cookie: COOKIE }, ...ANONYMOUS,
187+
},
188+
{
189+
name: "ADR-0096: an ex-member's organization-stamped key under the walled posture is refused, and the cookie beside it never answers for it",
190+
host: { auth: true }, headers: { 'x-api-key': EX_MEMBER_KEY, cookie: COOKIE }, ...ANONYMOUS,
191+
},
192+
{
193+
name: 'ADR-0069: a held session is refused 403 with its posture, and the service is never asked',
194+
host: { auth: true }, headers: { cookie: HELD_COOKIE },
195+
status: 403, code: PASSWORD_EXPIRED.code, message: PASSWORD_EXPIRED.message,
196+
},
197+
{
198+
name: 'ADR-0069: the same held session is refused while the gate probe says no gate is active (the posture is the admitting read\'s)',
199+
host: { auth: true, gateActive: false }, headers: { cookie: HELD_COOKIE },
200+
status: 403, code: PASSWORD_EXPIRED.code, message: PASSWORD_EXPIRED.message,
201+
},
202+
{
203+
name: "ADR-0069: a key whose owner holds an account-scope posture is refused 403 with the owner's posture",
204+
host: { auth: true }, headers: { 'x-api-key': HELD_OWNER_KEY },
205+
status: 403, code: MFA_REQUIRED.code, message: MFA_REQUIRED.message,
206+
},
207+
{
208+
name: 'ADR-0069: a key beside the held cookie answers for its own owner, never for the cookie',
209+
host: { auth: true }, headers: { 'x-api-key': KEY, cookie: HELD_COOKIE },
210+
status: 200, principal: 'u_key',
211+
},
212+
{
213+
name: 'CONTROL: an ungated session is admitted, and the service is asked as that principal',
214+
host: { auth: true }, headers: { cookie: COOKIE },
215+
status: 200, principal: 'u_ses',
216+
},
217+
{
218+
name: 'CONTROL: an API key on a host with no auth service is admitted as its owner',
219+
host: { auth: false }, headers: { 'x-api-key': KEY },
220+
status: 200, principal: 'u_key',
221+
},
222+
];
223+
224+
describe("[ruling 6227928430 item 2] the settings door: the ADR-0096 principal-less refusal and the ADR-0069 gate on the listing route", () => {
225+
it.each(ROWS)('$name', async (row) => {
226+
const { answer, seen } = await listing(row.host, row.headers);
227+
228+
expect(answer.status).toBe(row.status);
229+
if (row.code !== undefined) expect(answer.body?.error?.code).toBe(row.code);
230+
if (row.message !== undefined) expect(answer.body?.error?.message).toBe(row.message);
231+
if (row.principal === undefined) {
232+
expect(seen).toHaveLength(0);
233+
return;
234+
}
235+
expect(seen).toHaveLength(1);
236+
expect(seen[0]!.userId).toBe(row.principal);
237+
expect(seen[0]!.tenantId).toBe(ORG);
238+
expect(seen[0]!.enforced).toBe(true);
239+
expect('authGate' in seen[0]!).toBe(false);
240+
});
241+
});

0 commit comments

Comments
 (0)