Skip to content
Draft
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
19 changes: 19 additions & 0 deletions .changeset/door-reads-own-kernel.md
Original file line number Diff line number Diff line change
@@ -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

<!-- adr-0087: not-required (no-migration-prescription) no authored metadata, stored row or public export changes; the rule is about which kernel a dispatcher door reads a service from, and a host composes its kernels in code -->

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.
Original file line number Diff line number Diff line change
@@ -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<string, typeof MFA_REQUIRED | undefined>, 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<string, unknown> = {
metadata: {
list: async () => [],
matchEndpoint: async (q: { path: string; method: string }): Promise<ApiEndpointMatch | undefined> =>
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<IHttpServer>('http.server').getPort!()}`;
}, 60_000);

afterAll(async () => {
if (!kernel) return;
await Promise.race([kernel.shutdown(), new Promise<void>((resolve) => setTimeout(resolve, 10_000))]);
}, 60_000);

beforeEach(() => {
observed.flowRuns = 0;
observed.hostSessionReads = 0;
});

const call = (headers: Record<string, string>) => 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);
});
35 changes: 25 additions & 10 deletions packages/runtime/src/dispatcher-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<IAuthService>(ctx, 'auth'),
Expand Down Expand Up @@ -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<IAuthService>(ctx, 'auth'),
headers as Record<string, unknown>,
);
if (admitted) return admitted.userId;
const authService = await dispatcher.resolveIdentityAuth(protocolContext)
.catch(() => undefined) as IAuthService | undefined;
return resolveSessionPrincipalId(authService, headers as Record<string, unknown>);
},
// ADR-0069: the session the authentication-policy
// gate is asked about, read only while a gate feature
Expand All @@ -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<IAuthService>(ctx, 'auth'),
await dispatcher.resolveIdentityAuth(protocolContext) as IAuthService | undefined,
headers as Record<string, unknown>,
// The posture off the identity step's
// read, for a principal the request's
Expand Down
25 changes: 25 additions & 0 deletions packages/runtime/src/domain-handler-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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<ClassifiedServiceLookup>;
/**
* 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<any>;
/**
* Unscoped service lookup on the current kernel, typed by the slot.
*
Expand Down
10 changes: 5 additions & 5 deletions packages/runtime/src/domains/automation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading