diff --git a/.changeset/door-reads-own-kernel.md b/.changeset/door-reads-own-kernel.md new file mode 100644 index 00000000000..d89f2b9a23e --- /dev/null +++ b/.changeset/door-reads-own-kernel.md @@ -0,0 +1,19 @@ +--- +'@objectstack/runtime': patch +--- + +fix(runtime): a dispatcher door reads its service only from the request's own kernel + +Clause-②: no (narrowing) +Metadata-protocol: none + + + +Who sees it: a host that wires a `kernel-resolver` and places requests on a kernel of their own (one per environment). A host with one kernel, including one serving per-environment scoped factories, reads exactly as before. + +- On such a host every service lookup a dispatcher door makes (`DomainHandlerDeps.resolveService`, `resolveServiceOrLoud`, `classifyServiceOrLoud`, `getObjectQL`, with or without an environment id) reads the request's own kernel alone. A slot that kernel does not register is absent, and the door gives the answer it gives for an absent service (`501`, `503` or an empty capability, as before for that door). +- A posture or policy a door reads (the tenancy posture, the API-key lifecycle policy) is the request kernel's. +- The HTTP transport slot (`http.server`) is no environment's service and is read as before. + +**BREAKING** for a host that places requests on their own kernels and registers a service a dispatcher door uses on the host kernel only: that door now answers as it does when the service is absent. +The fix for such a host: register the service on each environment kernel whose requests should be served by it. diff --git a/packages/runtime/src/dispatcher-plugin.endpoint-request-kernel-identity.integration.test.ts b/packages/runtime/src/dispatcher-plugin.endpoint-request-kernel-identity.integration.test.ts new file mode 100644 index 00000000000..691471e1443 --- /dev/null +++ b/packages/runtime/src/dispatcher-plugin.endpoint-request-kernel-identity.integration.test.ts @@ -0,0 +1,173 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A declared endpoint judges who is calling with the `auth` of the kernel the + * request was placed on. + * + * On a host whose `kernel-resolver` places a request on a kernel of its own, + * the declarative-endpoint step reads the caller's session and asks the + * authentication-policy gate off that kernel's `auth`, the same service the + * identity step judged the request with, so "who is calling" has one answer + * per request and a policy the environment declares holds on its endpoints. + * + * Real boot, real socket: a LiteKernel host with the real Hono transport and + * the real dispatcher plugin, a stub `kernel-resolver`, and an environment + * kernel carrying its own `metadata`, `automation`, `objectql` and `auth`. The + * host kernel carries an `auth` of its own, which a request placed on the + * environment kernel must never be judged by. + */ + +import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest'; +// Paid during collection, not inside a case's clock (`check:test-source-alias`). +import '@objectstack/metadata'; +import { LiteKernel, Plugin, PluginContext } from '@objectstack/core'; +import { HonoServerPlugin } from '@objectstack/plugin-hono-server'; +import { ApiEndpointSchema, type ApiEndpoint } from '@objectstack/spec/api'; +import type { ApiEndpointMatch, IHttpServer } from '@objectstack/spec/contracts'; + +import { createDispatcherPlugin } from './dispatcher-plugin.js'; + +const PATH = '/api/v1/apps/showcase/identity-probe'; +const FLOW = 'identity_probe_flow'; +const ENV_ID = 'env-1'; +const MFA_REQUIRED = { + code: 'MFA_REQUIRED', + message: 'Multi-factor authentication is required. Please set up an authenticator app to continue.', +}; + +const ENDPOINT: ApiEndpoint = ApiEndpointSchema.parse({ + name: 'identity_probe', + path: PATH, + method: 'GET', + type: 'flow', + target: FLOW, + authRequired: true, +}); + +const observed = { flowRuns: 0, hostSessionReads: 0 }; + +/** A session API that admits the user named in one header, with the posture `postures` gives it. */ +function sessionAuth(header: string, gateActive: boolean, postures: Record, onRead?: () => void) { + return { + isAuthGateActive: () => gateActive, + api: { + async getSession({ headers }: { headers: Headers }) { + onRead?.(); + const uid = headers.get(header); + if (!uid) return null; + const authGate = postures[uid]; + return { user: { id: uid, ...(authGate ? { authGate } : {}) }, session: { userId: uid } }; + }, + }, + }; +} + +/** The environment kernel: its own endpoint declaration, flow engine, data engine and `auth`. */ +function makeEnvironmentKernel() { + const services: Record = { + metadata: { + list: async () => [], + matchEndpoint: async (q: { path: string; method: string }): Promise => + q.path.replace(/\/$/, '') === ENDPOINT.path && q.method.toUpperCase() === ENDPOINT.method + ? { endpoint: ENDPOINT, params: {} } + : undefined, + }, + automation: { + execute: async (flow: string) => { + observed.flowRuns++; + return { servedBy: ENV_ID, flow }; + }, + }, + objectql: { + registry: { getObject: () => null, getRegisteredTypes: () => [] }, + find: async () => [], + }, + // The environment's own `auth`: its policy gate is active, and `u_held` is held by it. + auth: sessionAuth('x-env-user', true, { u_held: MFA_REQUIRED, u_env: undefined }), + }; + const get = (name: string) => services[name] ?? null; + return { getServiceAsync: async (name: string) => get(name), getService: get, context: { getService: get } }; +} + +const ENVIRONMENT = makeEnvironmentKernel(); + +/** The host kernel's `auth`: a session API of its own, with no policy gate. */ +function hostAuthPlugin(): Plugin { + return { + name: 'com.objectstack.test.host-auth', + version: '1.0.0', + init: async (ctx: PluginContext) => { + ctx.registerService('auth', sessionAuth('x-host-user', false, { u_host: undefined }, () => { observed.hostSessionReads++; })); + }, + }; +} + +function resolverPlugin(): Plugin { + return { + name: 'com.objectstack.test.kernel-resolver', + version: '1.0.0', + init: async (ctx: PluginContext) => { + ctx.registerService('kernel-resolver', { + resolveKernel: async (context: any) => { + const envId = (context?.request?.headers ?? {})['x-environment-id']; + if (envId !== ENV_ID) return undefined; + context.environmentId = ENV_ID; + return ENVIRONMENT; + }, + }); + }, + }; +} + +let kernel: LiteKernel | undefined; +let baseUrl = ''; + +beforeAll(async () => { + kernel = new LiteKernel(); + kernel.use(new HonoServerPlugin({ port: 0, cors: false })); + kernel.use(hostAuthPlugin()); + kernel.use(resolverPlugin()); + kernel.use(createDispatcherPlugin({ prefix: '/api/v1', securityHeaders: false, enforceProjectMembership: false })); + await kernel.bootstrap(); + baseUrl = `http://127.0.0.1:${kernel.getService('http.server').getPort!()}`; +}, 60_000); + +afterAll(async () => { + if (!kernel) return; + await Promise.race([kernel.shutdown(), new Promise((resolve) => setTimeout(resolve, 10_000))]); +}, 60_000); + +beforeEach(() => { + observed.flowRuns = 0; + observed.hostSessionReads = 0; +}); + +const call = (headers: Record) => fetch(`${baseUrl}${PATH}`, { headers: { 'x-environment-id': ENV_ID, ...headers } }); + +describe('a declared endpoint judges who is calling with the request kernel\'s auth', () => { + it('a session only another kernel\'s auth knows is no caller: authRequired answers 401 and nothing runs', async () => { + const res = await call({ 'x-host-user': 'u_host' }); + + expect(res.status, await res.clone().text()).toBe(401); + expect(observed.flowRuns).toBe(0); + expect(observed.hostSessionReads).toBe(0); + }, 60_000); + + it('a session the request kernel\'s policy holds is refused with that policy\'s answer, and nothing runs', async () => { + const res = await call({ 'x-env-user': 'u_held' }); + const body = await res.json() as { error?: { code?: string; message?: string } }; + + expect(res.status).toBe(403); + expect(body.error?.code).toBe(MFA_REQUIRED.code); + expect(body.error?.message).toBe(MFA_REQUIRED.message); + expect(observed.flowRuns).toBe(0); + }, 60_000); + + it('control: a session the request kernel\'s auth admits, not held, is served', async () => { + const res = await call({ 'x-env-user': 'u_env' }); + + expect(res.status, await res.clone().text()).toBe(200); + expect(observed.flowRuns).toBe(1); + expect(observed.hostSessionReads).toBe(0); + }, 60_000); +}); diff --git a/packages/runtime/src/dispatcher-plugin.ts b/packages/runtime/src/dispatcher-plugin.ts index caaaa55c0a4..6eda53f3657 100644 --- a/packages/runtime/src/dispatcher-plugin.ts +++ b/packages/runtime/src/dispatcher-plugin.ts @@ -954,6 +954,13 @@ export function createDispatcherPlugin(config: DispatcherPluginConfig = {}): Plu // the engine the auth service reads through: the route's own // identity step is answered by this read, so a request reads // its session once with the limiter armed. + // + // These are the HOST plugin context's `auth` and `objectql` on + // purpose: the limiter runs before any environment is resolved, + // and the principal it reads only keys a rate-limit bucket. It + // admits nobody and authorizes nothing; who is calling is + // judged per request off the request's kernel by the identity + // step and, for a declared endpoint, the step below. resolvePrincipalId: (headers) => resolveSessionPrincipalId( safeGetService(ctx, 'auth'), @@ -2623,14 +2630,22 @@ export function createDispatcherPlugin(config: DispatcherPluginConfig = {}): Plu // already admitted (the identity step above, // `resolveRequestScope`) is answered from that // read: the session is read once per request. - resolvePrincipalId: (headers) => { + // + // The `auth` asked is the one THIS request's + // identity is judged with, resolved per request + // off the request's kernel + // (`HttpDispatcher.resolveIdentityAuth`), ⛔ + // never the host plugin context's: the session + // and the policy gate answer for the kernel the + // request was placed on. One that cannot be read + // keys no principal here, and answers the + // outage in the gate read below. + resolvePrincipalId: async (headers) => { const admitted = sessionAdmittedPrincipal(protocolContext); - return admitted - ? Promise.resolve(admitted.userId) - : resolveSessionPrincipalId( - safeGetService(ctx, 'auth'), - headers as Record, - ); + if (admitted) return admitted.userId; + const authService = await dispatcher.resolveIdentityAuth(protocolContext) + .catch(() => undefined) as IAuthService | undefined; + return resolveSessionPrincipalId(authService, headers as Record); }, // ADR-0069: the session the authentication-policy // gate is asked about, read only while a gate feature @@ -2642,11 +2657,11 @@ export function createDispatcherPlugin(config: DispatcherPluginConfig = {}): Plu // seam, as the dispatcher's gate judges it: the // owner's account-scope posture, or none. ⛔ No cookie // re-read for it. - resolveGatedSessionUser: (headers) => + resolveGatedSessionUser: async (headers) => protocolContext.admission?.credential === 'api_key' - ? Promise.resolve({ authGate: protocolContext.admission.authGate }) + ? { authGate: protocolContext.admission.authGate } : readGatedSessionUser( - safeGetService(ctx, 'auth'), + await dispatcher.resolveIdentityAuth(protocolContext) as IAuthService | undefined, headers as Record, // The posture off the identity step's // read, for a principal the request's diff --git a/packages/runtime/src/domain-handler-registry.ts b/packages/runtime/src/domain-handler-registry.ts index c9f47815445..d9209bf86cc 100644 --- a/packages/runtime/src/domain-handler-registry.ts +++ b/packages/runtime/src/domain-handler-registry.ts @@ -179,6 +179,16 @@ export interface DomainHandlerDeps { * Environment-scoped service resolution (per-request kernel aware), typed * by the slot when the slot is a core one. * + * ⭐ A door is served only by the request's own kernel. On a host whose + * `kernel-resolver` placed the request on a kernel of its own, this member + * (and {@link resolveServiceOrLoud}, {@link classifyServiceOrLoud} and + * {@link getObjectQL}, given an environment id or not) reads that kernel + * alone: a slot it lacks answers `undefined`, ⛔ never another kernel's + * service. On a host with one kernel, its scoped lookup is the request's + * own and is read as before. The one exception is the HTTP transport slot + * (`http.server`), which is no environment's service; the `auth` identity + * is judged with has its own member, {@link resolveIdentityAuth}. + * * [#4127 batch 2] `getService` got this treatment first because every one of * its call sites already passed a `CoreServiceName`. This one is mixed, and * the overloads split it exactly where the evidence does: @@ -285,6 +295,21 @@ export interface DomainHandlerDeps { * and answers both misses as `never-registered`, the answer it gave before. */ classifyServiceOrLoud?(context: HttpProtocolContext, name: string, environmentId?: string): Promise; + /** + * The `auth` service the request's identity is judged with: the one the + * identity step read the session with and admission judged an API key's + * lifecycle by (`HttpDispatcher.resolveIdentityAuth`). The request's own + * kernel answers when it registers `auth`; one registered and failing is + * re-raised as the authorization-store outage, never answered by another + * kernel; a request kernel with none is answered by the host kernel's. + * + * For a door that decides something identity is later judged by (the + * `/keys` signing policy), so the two cannot disagree. Every other door + * reads `auth` through {@link resolveService}. Optional, so a deps written + * before it existed still compiles; a door reading a deps without it reads + * {@link resolveServiceOrLoud}. + */ + resolveIdentityAuth?(context: HttpProtocolContext): Promise; /** * Unscoped service lookup on the current kernel, typed by the slot. * diff --git a/packages/runtime/src/domains/automation.ts b/packages/runtime/src/domains/automation.ts index 8dc366baa49..1dbf837f1e9 100644 --- a/packages/runtime/src/domains/automation.ts +++ b/packages/runtime/src/domains/automation.ts @@ -3084,16 +3084,16 @@ async function unregisterAndDeleteFlow( * serve it. The smallest composition of the two resolvers that exist: * * 1. `resolveService`, the order every `/actions` read uses (`getObjectQL` - * included): the request's own kernel first on a host that routes a - * request to a kernel of its own, then the host kernel's scoped factory, - * then its singletons. An instance it answers is the door's instance, + * included): on a host that routes a request to a kernel of its own, + * that kernel alone; on a host with one kernel, its scoped factory, then + * its singletons. An instance it answers is the door's instance, * whichever leg answers it, a leg that did not resolve before it included. * 2. Only on a miss, `resolveServiceOrLoud` classifies it: a name nothing * registered (or a scoped registration with no instance in this scope) is * absent, `undefined`; any other rejection is re-raised. The quiet probe * absorbs every rejection, so a miss there is absence or a failure it - * swallowed, and this step is what tells the two apart. Its own order - * (the host's scoped leg first) never decides WHICH instance is read: it + * swallowed, and this step is what tells the two apart. It reads the + * same kernels as step 1 and never decides WHICH instance is read: it * is asked only when step 1 found none. * * Scoped by the request's environment, as the door's reads are: unscoped, a diff --git a/packages/runtime/src/domains/door-own-kernel.test.ts b/packages/runtime/src/domains/door-own-kernel.test.ts new file mode 100644 index 00000000000..a3a3c898e95 --- /dev/null +++ b/packages/runtime/src/domains/door-own-kernel.test.ts @@ -0,0 +1,279 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A dispatcher door reads its service only from the request's own kernel. + * + * On a host whose `kernel-resolver` places a request on a kernel of its own, + * every lookup a door makes through {@link DomainHandlerDeps} reads that kernel + * alone, with or without an environment id: a slot the request kernel lacks is + * the door's absent-service answer, never the host kernel's service. A posture + * a door reads is the request kernel's. On a host with one kernel nothing + * changes: its scoped lookup is the request's own. + * + * What this pins: + * 1. per door family, each slot the family reads, through every kernel-reading + * member (`resolveService`, `resolveServiceOrLoud`, `classifyServiceOrLoud`, + * `getObjectQL`) on a two-kernel fixture: host has it, request kernel + * lacks it ⇒ not served; request kernel has it ⇒ the request kernel's; + * 2. three doors driven through their real handlers: the host's member is + * never called and the door gives its absent-service answer; + * 3. a posture is read off the request kernel even when the host has one; + * 4. what stays: one-kernel and scoped-factory hosts, the HTTP transport slot, + * and the identity step's reach; + * 5. the net: every function member of the deps object, found rather than + * listed, is called on the fixture, and the host kernel is never asked for + * the probe slot — so a member added later that reads the host fails here. + */ + +import { describe, it, expect, vi } from 'vitest'; +// Paid during collection, not inside a case's clock: the dispatcher reaches +// `standalone-stack.ts`, whose dynamic `@objectstack/metadata` import would +// otherwise load inside the first case that gets that far (check:test-source-alias). +import '@objectstack/metadata'; + +import { ObjectKernel, ServiceLifecycle } from '@objectstack/core'; +import { KNOWLEDGE_SOURCE_ADMISSION_SERVICE } from '@objectstack/metadata-core'; +import { SHARE_LINK_SERVICE } from '@objectstack/spec/contracts'; + +import { HttpDispatcher } from '../http-dispatcher.js'; +import type { HttpProtocolContext } from '../http-dispatcher.js'; +import type { DomainHandlerDeps } from '../domain-handler-registry.js'; +import { handleSecurityRequest } from './security.js'; +import { handleNotificationRequest } from './notifications.js'; +import { handleShareLinksRequest } from './share-links.js'; + +const ENV_ID = 'env_request'; + +/** No graceful-shutdown handlers: one kernel per case would otherwise pile up process listeners. */ +const bareKernel = (): ObjectKernel => new ObjectKernel({ gracefulShutdown: false, skipSystemValidation: true }); + +const depsOf = (d: HttpDispatcher): DomainHandlerDeps => (d as any).domainDeps; + +/** The tag of a value {@link tagged} built, read off a slot's contract type without erasing it. */ +const tagOf = (value: unknown): string | undefined => (value as { __tag?: string } | null | undefined)?.__tag; + +/** A value tagged with the kernel that registered it; `registry` makes it pass `getObjectQL`'s shape check. */ +const tagged = (tag: string) => ({ __tag: tag, registry: {} }); + +/** A `kernel-resolver`-shaped placement: a host kernel, and the request's own kernel. */ +function twoKernels(hostServices: Record, ownServices: Record = {}) { + const host = bareKernel(); + for (const [name, value] of Object.entries(hostServices)) host.registerService(name, value); + const own = bareKernel(); + for (const [name, value] of Object.entries(ownServices)) own.registerService(name, value); + const dispatcher = new HttpDispatcher(host as never); + const context = { + kernel: own, + environmentId: ENV_ID, + executionContext: { userId: 'u_1', isSystem: false, positions: ['admin'], permissions: [] }, + } as unknown as HttpProtocolContext; + return { dispatcher, deps: depsOf(dispatcher), context, host, own }; +} + +/** Each door family, and the slots its lookups name. */ +const FAMILIES: Array<{ family: string; slots: string[] }> = [ + { family: 'actions', slots: ['metadata', 'objectql'] }, + { family: 'automation', slots: ['protocol', 'objectql', 'metadata'] }, + { family: 'keys', slots: ['objectql', 'tenancy', 'auth'] }, + { family: 'activation-gate', slots: ['tenancy'] }, + { family: 'mcp-authoring', slots: ['protocol', 'automation', 'objectql'] }, + { + family: 'mcp', + slots: ['mcp', 'auth', 'metadata', 'protocol', 'security', 'objectql', 'record-context', + 'analytics', 'knowledge', 'i18n', 'file-attachments', 'external-datasource'], + }, + { family: 'meta', slots: ['metadata'] }, + { family: 'notifications', slots: ['notification'] }, + { family: 'security', slots: ['security'] }, + { family: 'share-links', slots: [SHARE_LINK_SERVICE, 'objectql'] }, + { family: 'knowledge', slots: [KNOWLEDGE_SOURCE_ADMISSION_SERVICE] }, +]; + +describe('a dispatcher door reads its service only from the request\'s own kernel', () => { + for (const { family, slots } of FAMILIES) { + for (const slot of slots) { + it(`${family}: '${slot}' absent from the request kernel is not served by the host kernel's`, async () => { + const { deps, context } = twoKernels({ [slot]: tagged('host') }); + + expect(await deps.resolveService(context, slot, ENV_ID)).toBeUndefined(); + expect(await deps.resolveServiceOrLoud(context, slot, ENV_ID)).toBeUndefined(); + const classified = await deps.classifyServiceOrLoud!(context, slot, ENV_ID); + expect(classified.outcome).not.toBe('resolved'); + if (slot === 'objectql') expect(await deps.getObjectQL(context, ENV_ID)).toBeNull(); + }); + + it(`${family}: '${slot}' on the request kernel is the request kernel's`, async () => { + const { deps, context } = twoKernels({ [slot]: tagged('host') }, { [slot]: tagged('own') }); + + expect((await deps.resolveService(context, slot, ENV_ID))?.__tag).toBe('own'); + expect((await deps.resolveServiceOrLoud(context, slot, ENV_ID))?.__tag).toBe('own'); + const classified = await deps.classifyServiceOrLoud!(context, slot, ENV_ID); + expect(classified.outcome === 'resolved' ? tagOf(classified.value) : classified.outcome).toBe('own'); + if (slot === 'objectql') expect(tagOf(await deps.getObjectQL(context, ENV_ID))).toBe('own'); + }); + } + } + + it('a host-only scoped factory is not served to a request with a kernel of its own', async () => { + const host = bareKernel(); + const factory = vi.fn((_ctx: unknown, scopeId?: string) => tagged(`host-scoped:${scopeId}`)); + host.registerServiceFactory('security', factory, ServiceLifecycle.SCOPED); + const dispatcher = new HttpDispatcher(host as never); + const context = { kernel: bareKernel(), environmentId: ENV_ID } as unknown as HttpProtocolContext; + const deps = depsOf(dispatcher); + + expect(await deps.resolveService(context, 'security', ENV_ID)).toBeUndefined(); + expect(await deps.resolveServiceOrLoud(context, 'security', ENV_ID)).toBeUndefined(); + expect(factory).not.toHaveBeenCalled(); + }); +}); + +describe('a door driven through its handler is never served by the host kernel\'s member', () => { + it('security: answers 503 and the host kernel\'s member is never called', async () => { + const hostMember = vi.fn(async () => []); + const { deps, context } = twoKernels({ security: { listAudienceBindingSuggestions: hostMember } }); + + const result = await handleSecurityRequest(deps, '/suggested-bindings', 'GET', undefined, {}, context); + + expect(result.response?.status).toBe(503); + expect(hostMember).not.toHaveBeenCalled(); + }); + + it('notifications: the host kernel\'s inbox is never read', async () => { + const listInbox = vi.fn(async () => ({ items: [], total: 0 })); + const { deps, context } = twoKernels({ notification: { send: vi.fn(), sendBatch: vi.fn(), listInbox } }); + + const result = await handleNotificationRequest(deps, '/inbox', 'GET', undefined, {}, context); + + expect(result.response?.status).toBe(501); + expect(result.response?.body?.error?.code).toBe('NOT_IMPLEMENTED'); + expect(listInbox).not.toHaveBeenCalled(); + }); + + it('share-links: answers 501 NOT_IMPLEMENTED and the host kernel\'s service is never called', async () => { + const listLinks = vi.fn(async () => []); + const { deps, context } = twoKernels({ + [SHARE_LINK_SERVICE]: { createLink: vi.fn(), listLinks, revokeLink: vi.fn(), resolveToken: vi.fn() }, + }); + + const result = await handleShareLinksRequest(deps, '/', 'GET', undefined, { object: 'crm_lead', recordId: 'r_1' }, context); + + expect(result.response?.status).toBe(501); + expect(result.response?.body?.error?.code).toBe('NOT_IMPLEMENTED'); + expect(listLinks).not.toHaveBeenCalled(); + }); +}); + +describe('a posture a door reads is the request kernel\'s', () => { + it('keys / activation-gate: `tenancy` is the request kernel\'s when the host also has one', async () => { + const { deps, context } = twoKernels({ tenancy: tagged('host') }, { tenancy: tagged('own') }); + + expect((await deps.resolveServiceOrLoud(context, 'tenancy', ENV_ID))?.__tag).toBe('own'); + }); + + it('keys / activation-gate: a host `tenancy` scoped factory does not answer before the request kernel', async () => { + const host = bareKernel(); + host.registerServiceFactory('tenancy', () => tagged('host-scoped'), ServiceLifecycle.SCOPED); + const own = bareKernel(); + own.registerService('tenancy', tagged('own')); + const dispatcher = new HttpDispatcher(host as never); + const context = { kernel: own, environmentId: ENV_ID } as unknown as HttpProtocolContext; + + expect((await depsOf(dispatcher).resolveServiceOrLoud(context, 'tenancy', ENV_ID))?.__tag).toBe('own'); + }); +}); + +describe('what reads as before', () => { + it('a host with one kernel: its own services answer, with or without an environment id', async () => { + const host = bareKernel(); + host.registerService('security', tagged('host')); + const dispatcher = new HttpDispatcher(host as never); + const deps = depsOf(dispatcher); + + expect(tagOf(await deps.resolveService({} as HttpProtocolContext, 'security', ENV_ID))).toBe('host'); + expect((await deps.resolveServiceOrLoud({ kernel: host } as unknown as HttpProtocolContext, 'security', ENV_ID))?.__tag).toBe('host'); + }); + + it('a host with one kernel: its scoped factory answers for the scope, and a miss in scope stays told apart', async () => { + const host = bareKernel(); + host.registerServiceFactory('knowledge', (_ctx: unknown, scopeId?: string) => + scopeId === ENV_ID ? tagged(`scoped:${scopeId}`) : undefined, ServiceLifecycle.SCOPED); + const dispatcher = new HttpDispatcher(host as never); + const deps = depsOf(dispatcher); + const context = { environmentId: ENV_ID } as unknown as HttpProtocolContext; + + expect((await deps.resolveService(context, 'knowledge', ENV_ID))?.__tag).toBe(`scoped:${ENV_ID}`); + expect((await deps.classifyServiceOrLoud!(context, 'knowledge', 'env_other')).outcome).toBe('no-instance-in-scope'); + }); + + it('the HTTP transport slot is the host\'s: a tenant kernel owns no socket', async () => { + const { deps, context } = twoKernels({ 'http.server': tagged('host') }); + + expect(tagOf(await deps.resolveService(context, 'http.server', ENV_ID))).toBe('host'); + }); + + it('the identity step reads the request kernel first, then the host kernel', async () => { + const { dispatcher, own } = twoKernels({ auth: tagged('host'), tenancy: tagged('host') }, { tenancy: tagged('own') }); + const internals = dispatcher as any; + + expect((await internals.resolveService(own, 'auth', ENV_ID, 'host-fallback'))?.__tag).toBe('host'); + expect((await internals.resolveServiceOrLoud(own, 'tenancy', ENV_ID, 'host-fallback'))?.__tag).toBe('own'); + }); +}); + +/** + * The net, found rather than listed: every function member of the deps object + * a door is handed. Each is called on the two-kernel fixture with the probe + * slot (in the arguments a lookup takes), and the host kernel records every + * name it is asked for. A member that reads a slot off the host kernel for a + * request placed on its own kernel — today's or one added later — fails here. + * The transport slot is the declared exception and is the positive control: + * the recorder sees it, so the net is capable of failing. + */ +describe('the net: no member of the deps object reads a slot off the host kernel', () => { + function recordingHost(services: Record) { + const asked: string[] = []; + const read = (name: string) => { + asked.push(name); + if (name in services) return services[name]; + throw Object.assign(new Error(`Service '${name}' not found`), { code: 'SERVICE_NOT_FOUND' }); + }; + const kernel = { + getState: () => 'running', + getService: (name: string) => read(name), + getServiceAsync: async (name: string) => read(name), + context: { getService: (name: string) => read(name) }, + }; + return { kernel, asked }; + } + + it('every kernel-reading member reads the request kernel alone', async () => { + const PROBE = 'probe_slot'; + const { kernel: host, asked } = recordingHost({ [PROBE]: tagged('host'), objectql: tagged('host'), 'http.server': tagged('host') }); + const dispatcher = new HttpDispatcher(host as never); + const deps = depsOf(dispatcher) as unknown as Record; + const context = { kernel: bareKernel(), environmentId: ENV_ID } as unknown as HttpProtocolContext; + asked.length = 0; + + const members = Object.entries(deps).filter(([, value]) => typeof value === 'function'); + expect(members.map(([name]) => name)).toEqual(expect.arrayContaining([ + 'resolveService', 'resolveServiceOrLoud', 'classifyServiceOrLoud', 'getService', 'getObjectQL', 'getRequestKernelService', + ])); + for (const [name, member] of members) { + const answers: unknown[] = []; + for (const args of [[context, PROBE, ENV_ID], [context, PROBE], [context, ENV_ID]]) { + try { + answers.push(await (member as (...a: unknown[]) => unknown)(...args)); + } catch { + // A member that refuses these arguments reads nothing. + } + } + expect(asked.filter((n) => n === PROBE || n === 'objectql'), `deps.${name} asked the host kernel for a slot`).toEqual([]); + expect(answers.some((a) => tagOf(a) === 'host'), `deps.${name} answered the host kernel's service`).toBe(false); + } + + // Positive control: the declared exception is seen by the recorder. + await (deps.resolveService as DomainHandlerDeps['resolveService'])(context, 'http.server', ENV_ID); + expect(asked).toContain('http.server'); + }); +}); diff --git a/packages/runtime/src/domains/keys.ts b/packages/runtime/src/domains/keys.ts index ce6c6dafff5..879ebecc16d 100644 --- a/packages/runtime/src/domains/keys.ts +++ b/packages/runtime/src/domains/keys.ts @@ -288,9 +288,10 @@ export async function handleKeysRequest( // ── [#23367, ruling A] The lifecycle policy, from the auth service. ── // - // The same source the key-admission seam judges with, so the life a key - // is signed with and the life it is admitted under cannot disagree. A - // kernel with no `auth` service has no auth configuration: the signing + // The same source the key-admission seam judges with — the `auth` the + // request's identity is judged with (`deps.resolveIdentityAuth`), read the + // same way — so the life a key is signed with and the life it is admitted + // under cannot disagree. With no `auth` service there is no auth configuration: the signing // then keeps its pre-policy behaviour (no default, no ceiling). An `auth` // service that is registered and FAILED to build is the outage it is — // the #15900 reasoning above, for the same kind of input: the policy @@ -299,7 +300,9 @@ export async function handleKeysRequest( let policy: ApiKeyLifecyclePolicy | undefined; try { const source = apiKeyLifecyclePolicySourceOf( - await deps.resolveServiceOrLoud(context, 'auth', context.environmentId), + deps.resolveIdentityAuth + ? await deps.resolveIdentityAuth(context) + : await deps.resolveServiceOrLoud(context, 'auth', context.environmentId), ); policy = source ? await source() : undefined; } catch (err) { diff --git a/packages/runtime/src/flow-start-confirmation-gated-target.test.ts b/packages/runtime/src/flow-start-confirmation-gated-target.test.ts index c97e62222b2..bfe324c81a6 100644 --- a/packages/runtime/src/flow-start-confirmation-gated-target.test.ts +++ b/packages/runtime/src/flow-start-confirmation-gated-target.test.ts @@ -457,10 +457,11 @@ describe('the declarations are read from the services the request\'s own /action expectConfirmationRefusal(await start(new HttpDispatcher(host as never), { kernel: env, environmentId: ENV_ID }), automation.execute); }); - // Records today's limitation: this answer changes when per-leg loud resolution lands for every dispatcher door. - it('kernel-resolver host (records today\'s limitation, changes when per-leg loud resolution lands): where the request\'s own kernel fails to resolve the slot and the host kernel answers it, the start is judged on the host instance, as the /actions door would serve it', async () => { + it('kernel-resolver host: where the request\'s own kernel fails to resolve the slot, the start is refused 503 and the host kernel\'s instance is never read', async () => { const host = bareKernel(); - host.registerService('protocol', protocolServing(true)); + const hostProtocol = protocolServing(true); + const hostRead = vi.spyOn(hostProtocol, 'getMetaItems'); + host.registerService('protocol', hostProtocol); const env = bareKernel(); const automation = automationService(); env.registerService('automation', automation); @@ -468,7 +469,10 @@ describe('the declarations are read from the services the request\'s own /action // The request's own slot is wired and fails, not absent: the case is not vacuous. await expect(env.getServiceAsync('protocol')).rejects.toThrow('environment protocol factory failed'); - expectConfirmationRefusal(await start(new HttpDispatcher(host as never), { kernel: env, environmentId: ENV_ID }), automation.execute); + const answer = await start(new HttpDispatcher(host as never), { kernel: env, environmentId: ENV_ID }); + expect(answer.status).toBe(503); + expect(automation.execute).not.toHaveBeenCalled(); + expect(hostRead).not.toHaveBeenCalled(); }); it('kernel-resolver host: a shape that merely lacks every source gains no 503 — the account starts the flow', async () => { diff --git a/packages/runtime/src/http-dispatcher.request-kernel-first.test.ts b/packages/runtime/src/http-dispatcher.request-kernel-first.test.ts index 76ce842409d..bdb7b706b32 100644 --- a/packages/runtime/src/http-dispatcher.request-kernel-first.test.ts +++ b/packages/runtime/src/http-dispatcher.request-kernel-first.test.ts @@ -26,11 +26,16 @@ // SCOPED factory on the default kernel, no request kernel) — plus the action // door's subject-record load driven through the real `callData`. // -// Does NOT cover: `resolveServiceOrLoud` / `classifyService`, whose order this -// card deliberately leaves alone (it decides which kernel's `tenancy` answers -// the identity step — see `./domains/scoped-service-miss-attribution.test.ts`). +// Does NOT cover: `resolveServiceOrLoud` / `classifyService` (see +// `./domains/scoped-service-miss-attribution.test.ts`), nor the rule that a +// door reads the request's own kernel alone, through every deps member, which +// is `./domains/door-own-kernel.test.ts`. import { describe, it, expect } from 'vitest'; +// Paid during collection, not inside a case's clock: the dispatcher reaches +// `standalone-stack.ts`, whose dynamic `@objectstack/metadata` import would +// otherwise load inside the first case that gets that far (check:test-source-alias). +import '@objectstack/metadata'; import { ObjectKernel, ServiceLifecycle } from '@objectstack/core'; import { recordNotFoundError } from '@objectstack/metadata-protocol'; @@ -98,10 +103,10 @@ describe('[#22944] a request routed to its own kernel is answered by that kernel expect(protocol.__tag).toBe('env'); }); - it('still falls back to the host kernel for a service the environment kernel does not have', async () => { + it('a service the environment kernel does not have is absent: a door is served only by the request\'s own kernel', async () => { const { dispatcher, context } = kernelResolverHost(); const svc = await depsOf(dispatcher).resolveService(context, 'host-only', ENV_ID); - expect(svc?.__tag).toBe('host-only'); + expect(svc).toBeUndefined(); }); it('the action door\'s subject-record load delivers a row the caller can read (was 404 RECORD_NOT_FOUND)', async () => { diff --git a/packages/runtime/src/http-dispatcher.ts b/packages/runtime/src/http-dispatcher.ts index 32763f5e2b2..a135c642743 100644 --- a/packages/runtime/src/http-dispatcher.ts +++ b/packages/runtime/src/http-dispatcher.ts @@ -426,6 +426,40 @@ function withSeedReading( return { ...body, seed }; } +/** + * Which kernels may answer a service lookup made for a request. + * + * - `'own-kernel'` (the default everywhere): the request's own kernel alone. + * On a host with one kernel that kernel is the host kernel, so its scoped + * lookup is the request's own and is asked as it always was. On a + * `kernel-resolver` host a request placed on a kernel of its own is served + * by that kernel and no other: a slot that kernel lacks reads as absent, and + * the door gives the answer it gives for an absent service. + * - `'host-fallback'`: the request's own kernel first, then the host kernel's + * scoped lookup. Passed at exactly two call sites: + * ① {@link HttpDispatcher.resolveIdentityAuth}, the `auth` service a + * request's identity is judged with (its session read, the authentication + * gate, the API-key lifecycle policy). Only `auth`: every other read the + * identity step makes (`tenancy`, `settings`, its ObjectQL) is own-kernel. + * ② {@link HOST_TRANSPORT_SLOT}, the transport a same-origin forward is + * injected into. + * + * Every other member of {@link DomainHandlerDeps} reads `'own-kernel'`, so no + * dispatcher door has a host-fallback lookup to reach for. The domain tests in + * `./domains/door-own-kernel.test.ts` hold that, per member, and hold the set + * of call sites that pass `'host-fallback'`. + */ +type ServiceReach = 'own-kernel' | 'host-fallback'; + +/** + * The one slot a door's lookup reads with `'host-fallback'` reach: the HTTP + * transport. It is no environment's service — a tenant kernel owns no socket + * and registers none — and a same-origin `type: 'api'` forward is injected + * into the host's raw app, which places it in the request's environment + * ({@link resolverPlacedEnvironmentOf}) like any request it receives. + */ +const HOST_TRANSPORT_SLOT = 'http.server'; + /** * [#32887] The environment a host's {@link KernelResolver} placed each request * in, kept beside the request and readable only through @@ -568,8 +602,17 @@ export class HttpDispatcher { // parameter. This object is built once and shared by every request the // host serves, so it cannot hold "the kernel of the request in flight" // — there is no such thing here. The request carries its own. + // + // Every kernel-reading member below reads the request's OWN kernel + // alone (`ServiceReach` 'own-kernel'): a door is served only by the + // kernel the request was placed on. The transport slot is the one + // name read with host reach (`HOST_TRANSPORT_SLOT` says why). resolveService: (context: HttpProtocolContext, name: string, environmentId?: string) => - this.resolveService(this.requestKernel(context), name, environmentId), + this.resolveService(this.requestKernel(context), name, environmentId, + name === HOST_TRANSPORT_SLOT ? 'host-fallback' : 'own-kernel'), + // The `auth` a request's identity is judged with, for a door that + // signs a credential under the same policy admission judges it by. + resolveIdentityAuth: (context: HttpProtocolContext) => this.resolveIdentityAuth(context), // [#15900] The classified lookup, reachable from a DOMAIN gate. The // identity step has read `tenancy` this way since #15366/PR #15909; the // two gates that decide a mint and an install-wide activation write ask @@ -724,9 +767,14 @@ export class HttpDispatcher { // "registered and failed to build" (re-raised, so the door // answers 503 instead of admitting on a posture it could not // read). Every other name keeps the probe. - getService: (n: string) => n === 'tenancy' - ? this.resolveServiceOrLoud(this.requestKernel(context), n, context.environmentId) - : this.resolveService(this.requestKernel(context), n, context.environmentId), + // `auth` is read with the identity reach (`ServiceReach` ①, + // `resolveIdentityAuth`); every other name, `tenancy` and + // `settings` included, off the request's own kernel alone. + getService: (n: string) => n === 'auth' + ? this.resolveIdentityAuth(context) + : n === 'tenancy' + ? this.resolveServiceOrLoud(this.requestKernel(context), n, context.environmentId) + : this.resolveService(this.requestKernel(context), n, context.environmentId), // Resolve ObjectQL from the per-request kernel DIRECTLY. The scoped // `resolveService('objectql', envId)` factory can return a different // instance that doesn't see THIS env's rows (the gotcha @@ -1646,7 +1694,10 @@ export class HttpDispatcher { // — the whole auth gate turns on it — but IAuthService never declared // it. `packages/rest` probes it the same way, so two independent // callers agree on a member the contract does not mention. - const authService = await this.resolveService(this.requestKernel(context), 'auth', context.environmentId); + // The `auth` the identity step judged this request with + // (`resolveIdentityAuth`): the gate judges the principal that step + // resolved, off the same service. + const authService = await this.resolveIdentityAuth(context); if (!authService || typeof authService.isAuthGateActive !== 'function' || !authService.isAuthGateActive()) { return null; } @@ -2696,13 +2747,16 @@ export class HttpDispatcher { * Fallback chain: getServiceAsync(scopeId) → getServiceAsync → getService (sync) → context.getService → services map. * Only returns when a non-null service is found; otherwise falls through to the next step. * - * When `scopeId` is provided, tries the SCOPED factory on `defaultKernel` first (SharedProjectPlugin - * mode). Falls back to `kernel` — THE REQUEST'S OWN kernel, passed in by the - * caller (#5155) — for singleton / legacy services. + * The order, by host shape: + * - a request with no kernel of its own (single-environment hosts, + * SharedProjectPlugin): the SCOPED factory on `defaultKernel` first when + * `scopeId` is provided, then `kernel` (which IS `defaultKernel`) for + * singleton / legacy services; + * - a request a `kernel-resolver` placed on a kernel of its own + * (`kernel !== defaultKernel`): that kernel's chain alone, and the host + * kernel's scoped lookup after it only for `reach: 'host-fallback'`. * - * [#22944] Except when the request carries a kernel of its OWN — a - * `kernel-resolver` host routed it to its environment's kernel, so - * `kernel !== defaultKernel`. That kernel answers first. The host kernel's + * [#22944] Why the request's own kernel answers first there: the host kernel's * SINGLETONS (`protocol`, `metadata`, `objectql`) answer * `getServiceAsync(name, scopeId)` whatever the scope, so asking the host * first handed every dispatcher door that passes `context.environmentId` @@ -2713,18 +2767,27 @@ export class HttpDispatcher { * REST-owned routes never had this — `RestServer.resolveProtocol` takes the * environment kernel's own `protocol`. A request with no kernel of its own * (single-environment hosts, SharedProjectPlugin) resolves exactly as before. + * + * A request with a kernel of its own is served by that kernel alone: the + * host kernel's scoped lookup is a leg of this chain only where it IS the + * request kernel's own (no kernel of its own), or where the caller passes + * `reach: 'host-fallback'` — see {@link ServiceReach}, which names the + * callers that may and why. Default `'own-kernel'`, so a caller that says + * nothing never reads a service off another kernel. */ - private async resolveService(kernel: any, name: string, scopeId?: string) { - if (kernel && kernel !== this.defaultKernel && typeof kernel.getServiceAsync === 'function') { + private async resolveService(kernel: any, name: string, scopeId?: string, reach: ServiceReach = 'own-kernel') { + const ownsKernel = this.ownsKernel(kernel); + if (ownsKernel && typeof kernel.getServiceAsync === 'function') { try { const svc = await kernel.getServiceAsync(name, scopeId); if (svc != null) return svc; } catch { - // Not on the request's own kernel — fall through to the host's scoped lookup + // Not on the request's own kernel — fall through to the rest of its own chain } } - // Prefer scoped lookup on defaultKernel when scopeId is given (shared-kernel / multi-environment mode) - if (scopeId && typeof this.defaultKernel.getServiceAsync === 'function') { + // Prefer scoped lookup on defaultKernel when scopeId is given (shared-kernel / multi-environment mode). + // For a request with a kernel of its own this leg reads ANOTHER kernel, so it runs only on an explicit reach. + if (scopeId && (!ownsKernel || reach === 'host-fallback') && typeof this.defaultKernel.getServiceAsync === 'function') { try { const svc = await this.defaultKernel.getServiceAsync(name, scopeId); if (svc != null) return svc; @@ -2782,19 +2845,17 @@ export class HttpDispatcher { * re-raised unbranded, for the resolver to answer as * `AuthzStoreUnavailableError` (503). * - * The chain order is scoped lookup on the host kernel first, then the - * request's own kernel — `resolveService`'s order before #22944 — so WHICH - * registry answers is unchanged; only what a rejection MEANS is. ⚠️ #22944 - * moved the probe's order on a `kernel-resolver` host (the request's own - * kernel first) and deliberately NOT this one: this lookup decides which - * kernel's `tenancy` answers the identity step, which is a separate - * question from where a data-plane row is read. A host with no async accessor + * The chain order is the probe's: a request with a kernel of its own asks + * that kernel first, and only that kernel unless the caller passes + * `reach: 'host-fallback'` ({@link ServiceReach}); a request without one + * asks the host kernel's scoped lookup and then the host kernel, which are + * its own. Only what a rejection MEANS differs from the probe. A host with no async accessor * (`KernelBase`-shaped, e.g. `LiteKernel`) supports no service factories, * so "not registered" is the only fault it can report — it keeps the quiet * probe, which is the same classification rather than a second collapse. */ - private async resolveServiceOrLoud(kernel: any, name: string, scopeId?: string): Promise { - const classified = await this.classifyService(kernel, name, scopeId); + private async resolveServiceOrLoud(kernel: any, name: string, scopeId?: string, reach: ServiceReach = 'own-kernel'): Promise { + const classified = await this.classifyService(kernel, name, scopeId, reach); return classified.outcome === 'resolved' ? classified.value : undefined; } @@ -2874,6 +2935,7 @@ export class HttpDispatcher { kernel: any, name: string, scopeId?: string, + reach: ServiceReach = 'own-kernel', ): Promise { /** * One registry read, split three ways. A value is the answer; the @@ -2902,10 +2964,23 @@ export class HttpDispatcher { if (answer.outcome === 'no-instance-in-scope') miss = answer; }; - if (scopeId && typeof this.defaultKernel.getServiceAsync === 'function') { + // The host kernel's scoped lookup. For a request with no kernel of its + // own it is that request's own scoped slot, asked first as it always + // was; for a request with a kernel of its own it is ANOTHER kernel, so + // it runs after that kernel, and only on an explicit reach. + const ownsKernel = this.ownsKernel(kernel); + const hostScoped = async (): Promise => { + if (!scopeId || typeof this.defaultKernel.getServiceAsync !== 'function') return undefined; const scoped = await read(() => this.defaultKernel.getServiceAsync(name, scopeId)); if (scoped.outcome === 'resolved') return scoped; remember(scoped); + return undefined; + }; + const hostReached = !ownsKernel || reach === 'host-fallback'; + + if (!ownsKernel) { + const scoped = await hostScoped(); + if (scoped) return scoped; } if (typeof kernel?.getServiceAsync === 'function') { // ⭐ [#16402] `scopeId` — the whole repair. Dropped here, this leg @@ -2913,23 +2988,63 @@ export class HttpDispatcher { const own = await read(() => kernel.getServiceAsync(name, scopeId)); if (own.outcome === 'resolved') return own; remember(own); + if (ownsKernel && hostReached) { + const scoped = await hostScoped(); + if (scoped) return scoped; + } return miss; } + if (ownsKernel && hostReached) { + const scoped = await hostScoped(); + if (scoped) return scoped; + } // A `KernelBase`-shaped host (e.g. `LiteKernel`) supports no service // factories, so it has no scoped registrations and "not registered" is // the only miss it can produce — the quiet probe, unchanged. - const probed = await this.resolveService(kernel, name, scopeId); + const probed = await this.resolveService(kernel, name, scopeId, reach); return probed != null ? { outcome: 'resolved', value: probed } : miss; } + /** + * Whether `kernel` is a request kernel of its own: a `kernel-resolver` + * host placed the request on a kernel that is not this dispatcher's host + * kernel. Such a request is served by its own kernel alone unless a caller + * passes `reach: 'host-fallback'` ({@link ServiceReach}). + */ + private ownsKernel(kernel: any): boolean { + return kernel != null && kernel !== this.defaultKernel; + } + + /** + * The `auth` service a request's identity is judged with, read per caller + * and never recorded: the identity step's session read and the API-key + * lifecycle policy admission judges a key by, the authentication gate, + * the `/keys` signing door (so a key is signed under the policy it is + * admitted under) and the declarative-endpoint step (so "who is calling" + * has one answer per request). + * + * The request's own kernel answers when it registers `auth`. One that is + * registered and fails to resolve is the authorization-store outage + * (`503`), ⛔ never answered by another kernel. A request kernel that + * registers none is answered by the host kernel's (`ServiceReach` ①); + * `undefined` when neither does. + */ + async resolveIdentityAuth(context: HttpProtocolContext): Promise { + try { + return await this.resolveServiceOrLoud(this.requestKernel(context), 'auth', context.environmentId, 'host-fallback'); + } catch (err) { + throw new AuthzStoreUnavailableError('auth', err); + } + } + /** * Get the ObjectQL service which provides access to SchemaRegistry. * Tries multiple access patterns since kernel structure varies. */ - private async getObjectQLService(kernel: any, scopeId?: string): Promise { + private async getObjectQLService(kernel: any, scopeId?: string, reach: ServiceReach = 'own-kernel'): Promise { // 1. Try via resolveService (handles scoped, async factories, sync, context, and map) try { - const svc = await this.resolveService(kernel, 'objectql', scopeId); + const svc = await this.resolveService(kernel, 'objectql', scopeId, reach); if (svc?.registry) return svc; } catch { /* service not available */ } return null; diff --git a/packages/runtime/src/security/resolve-execution-context.ts b/packages/runtime/src/security/resolve-execution-context.ts index d9f77dd25cc..0f6550205e2 100644 --- a/packages/runtime/src/security/resolve-execution-context.ts +++ b/packages/runtime/src/security/resolve-execution-context.ts @@ -28,7 +28,7 @@ import type { IAuthService, ServiceSlotContract, ServiceSlotContracts } from '@o import { scopesToAgentPermissionSets, MCP_OAUTH_SCOPE_ACTIONS } from '@objectstack/spec/ai'; import { preferredLocaleFromHeader } from '@objectstack/spec/system'; -import { resolveRequestExecutionContext, type RequestAdmission } from '@objectstack/core'; +import { resolveRequestExecutionContext, rethrowAuthzStoreUnavailable, type RequestAdmission } from '@objectstack/core'; import { presentedForwardCredential, redeemForwardCredential, type ForwardAgentProvenance } from '@objectstack/rest'; import { isOAuthSubjectBanned } from './oauth-subject-ban.js'; @@ -152,8 +152,11 @@ export async function resolveExecutionContext(opts: ResolveOptions): Promise undefined); + // lifecycle sources. A lookup that rejects is a host with no auth service, + // except the authorization-store outage (an `auth` that is registered and + // failed to resolve), which is re-raised: identity is never judged with an + // input that could not be read. + const authService = await Promise.resolve(opts.getService('auth')).catch(rethrowAuthzStoreUnavailable); // ── OAuth 2.1 access-token provenance (MCP surface only, #2698) ── // Verified BEFORE session resolution so the presented credential decides