Skip to content

Commit 91aaad0

Browse files
committed
fix(runtime): a scoped-URL REST or MCP request's api forward is placed in the environment it ran in
On a multi-kernel host the placement step records the environment the host's kernel-resolver placed each request in (never the control plane, nothing without a resolver), and the api arm writes it onto the forward as X-Environment-Id, replacing the caller's spelling. One writer for all three doors: the host door's own header write is folded into it. Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016WV4cykhsWAtSL6Sr4VWFG
1 parent e0c6fac commit 91aaad0

5 files changed

Lines changed: 92 additions & 32 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/runtime': patch
3+
---
4+
5+
fix(runtime): on a multi-kernel host, a same-origin `type: 'api'` action run by a REST or MCP request placed only by its scoped URL forwards into the environment the request ran in
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
- **The forward is placed where the request ran, at every door.** A same-origin `type: 'api'` action forwards into the host's raw app, which places the forwarded request as it places any request. A request placed by its bound hostname or by its `X-Environment-Id` carries that signal into its forward. A request placed only by its scoped URL (`POST /environments/:env/actions/:object/:action`, or `run_action` on `/environments/:env/mcp`) did not, because the forward targets the action's own path: on a shared origin with no hostname binding the forward landed in no environment, and its target answered a member who may run the action `401`. On a host with a `kernel-resolver`, the forward from the REST, MCP and `dispatchAction` doors now carries the environment the resolver placed the request in as `X-Environment-Id`, replacing any `X-Environment-Id` the caller sent. A request placed in no environment, or in `platform` (the control plane), and every request on a host with no `kernel-resolver`, forwards exactly as before.

‎packages/runtime/src/action-dispatch.test.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,10 @@
1919
* REST door's scoped path is served from, through the same placement
2020
* step, and a failing resolver refuses it at both doors.
2121
* 1c. On a hosted environment kernel, a same-origin `type: 'api'` action's
22-
* forward is placed in the environment the call ran in, through both
23-
* doors; an environment's own kernel, handed to `dispatchAction`, has no
24-
* socket to forward through and is refused 503.
22+
* forward is placed in the environment the call ran in, through every
23+
* door (REST and MCP placed only by a scoped URL on a shared origin
24+
* included); an environment's own kernel, handed to `dispatchAction`, has
25+
* no socket to forward through and is refused 503.
2526
* 2. The MCP refusals that change because the bridge now runs the REST
2627
* door's sequence (the PR's "Served refusal codes that change"): each
2728
* was refused before and stays refused; only the code, or the detail
@@ -567,7 +568,9 @@ describe('a same-origin api action on a hosted environment kernel forwards as th
567568

568569
const answer = await h.viaScoped('/mcp');
569570

570-
expect({ status: answer.status, body: answer.body }).toEqual({ status: 200, body: { ok: true, result: { echoed: {} } } });
571+
// The bridge's own answer wraps the forward's result (`{ ok, action, objectName, result }`).
572+
expect({ status: answer.status, ok: answer.body?.ok, result: answer.body?.result?.result })
573+
.toEqual({ status: 200, ok: true, result: { echoed: {} } });
571574
expect(h.forwards.map((f) => ({ url: f.url, placed: f.placed, environment: f.headers['x-environment-id'] })))
572575
.toEqual([{ url: `http://${SHARED_HOST}${probe.target}`, placed: true, environment: ENV_T }]);
573576
});

‎packages/runtime/src/action-dispatch.ts‎

Lines changed: 19 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ import { actorUserFromExecutionContext, resolveActorDisplayName } from './securi
7474
import { validationFailure, validationFailureDetails, VALIDATION_FAILED_STATUS } from './validation-failure.js';
7575
import { objectValueFailure } from './object-value-shape.js';
7676
import { apiErrorResponse } from './error-envelope.js';
77-
import { HttpDispatcher, type HttpProtocolContext, type HttpDispatcherResult } from './http-dispatcher.js';
77+
import { HttpDispatcher, resolverPlacedEnvironmentOf, type HttpProtocolContext, type HttpDispatcherResult } from './http-dispatcher.js';
7878
import type { DomainHandlerDeps } from './domain-handler-registry.js';
7979
// [ADR-0106 D1] The run doors' visibility question: the `/meta` projection's.
8080
import { actionRunFieldVisibilityRefusal, actionRunMasker, projectActionForCaller } from './action-run-visibility.js';
@@ -529,10 +529,17 @@ async function dispatchAdmittedAction(
529529
recordId, record: actionExec.apiForwardSubjectRecord(recordId, subject), params, ec,
530530
});
531531
if ('message' in built) return { kind: 'refused', refusal: { message: built.message, status: built.status } };
532+
// [#32658, #32887] On a multi-kernel host the forward is placed in
533+
// the environment the host's resolver placed THIS request in,
534+
// whichever door asked and whatever signal placed it (a bound
535+
// hostname, the environment header, a scoped URL, the host door's
536+
// named environment): the forward targets the action's own path,
537+
// so a scoped URL's environment does not cross with it.
538+
const placedEnvironment = resolverPlacedEnvironmentOf(requestContext);
532539
const forward = await actionExec.forwardApiAction(inject, requestContext, built, {
533540
objectName, actionName, target: actionDef?.target,
534541
...(recordId ? { recordId: String(recordId) } : {}),
535-
});
542+
}, placedEnvironment !== undefined ? { environmentId: placedEnvironment } : undefined);
536543
if (forward.status >= 200 && forward.status < 300) {
537544
return { kind: 'answered', result: actionExec.apiActionResultOf(forward), headers: forward.headers };
538545
}
@@ -910,14 +917,6 @@ function actionRoutePath(namespace: string | undefined, objectName: string, acti
910917
return `/actions${namespace !== undefined ? `/${segment(namespace)}` : ''}/${segment(objectName)}/${segment(actionName)}`;
911918
}
912919

913-
/**
914-
* The declared environment header (`X-Environment-Id`, lower-case as the
915-
* forward's header bag spells it), which a host's `kernel-resolver` reads to
916-
* place a request in its environment and which the api forward carries across
917-
* from its request (`action-execution.ts`'s forward allow-list).
918-
*/
919-
const FORWARD_ENVIRONMENT_HEADER = 'x-environment-id';
920-
921920
/**
922921
* The host door over a dispatcher's deps: the REST door's sequence for a
923922
* call that arrived as values, not as a path. Writes the invocation row with
@@ -979,24 +978,16 @@ export async function dispatchActionRequest(
979978
} catch (err) {
980979
return deps.errorFromThrown(err, 500);
981980
}
982-
// [#32658] THE FORWARD'S ROUTING IDENTITY. A same-origin `type: 'api'`
983-
// action forwards into the host's raw app, which places the forwarded
984-
// request as it places any request it receives. A REST request placed by
985-
// its hostname or its `X-Environment-Id` carries that signal into its
986-
// forward, so the forward lands in the environment the call ran in. This
987-
// door's request carries neither: on a multi-kernel host its forward
988-
// reached the raw app as `Host: localhost`, which places it in no
989-
// environment, and the target answered the caller 401. The environment the
990-
// host's resolver placed the call in is written as the declared
991-
// environment header, so the forward is placed where the call ran. It is
992-
// the resolver's answer, never the caller's: it replaces any spelling the
993-
// credential headers carried. Read before the no-resolver fallbacks below
994-
// write an environment, so a host that placed nothing (a single kernel)
995-
// routes nothing; `platform` is the control plane, not an environment.
996-
const placedEnvironment = context.environmentId;
997-
if (typeof placedEnvironment === 'string' && placedEnvironment !== '' && placedEnvironment !== 'platform') {
998-
headers[FORWARD_ENVIRONMENT_HEADER] = placedEnvironment;
999-
}
981+
// [#32658] THE FORWARD'S ROUTING IDENTITY. This door's request carries no
982+
// hostname and no environment header, so on a multi-kernel host its api
983+
// forward reached the raw app as `Host: localhost`, placed in no
984+
// environment. The placement step above records the environment the
985+
// host's resolver placed the call in, and the api arm writes it onto the
986+
// forward as it does at the REST and MCP doors
987+
// (`resolverPlacedEnvironmentOf`), replacing any spelling the credential
988+
// headers carried. Recorded before the no-resolver fallbacks below write
989+
// an environment, so a host that placed nothing (a single kernel) routes
990+
// nothing; `platform` is the control plane, not an environment.
1000991
// On a host with NO resolver nothing places the call, so the environment
1001992
// the host named is carried as it always was — never silently dropped for
1002993
// the default one. Written after placement, so the scope touch, which this

‎packages/runtime/src/action-execution.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1328,6 +1328,15 @@ const API_FORWARD_IDENTITY_HEADERS: ReadonlySet<string> = new Set([
13281328
*/
13291329
export const API_FORWARD_MARK_HEADER = 'x-objectstack-action-forward';
13301330

1331+
/**
1332+
* [#32658, #32887] The declared environment header (`X-Environment-Id`,
1333+
* lower-case as the forward's header bag spells it): what a host's
1334+
* `kernel-resolver` reads to place a request in its environment, written onto
1335+
* a forward from the environment its request was placed in
1336+
* ({@link forwardApiAction}'s `routing`).
1337+
*/
1338+
const API_FORWARD_ENVIRONMENT_HEADER = 'x-environment-id';
1339+
13311340
/** The response headers relayed back to the caller — the credential rotations. */
13321341
const API_FORWARD_RELAYED_RESPONSE_HEADERS: readonly string[] = [
13331342
// better-auth's bearer lane (`bearer()` emits `set-auth-token`; #8243's
@@ -2078,6 +2087,16 @@ export function apiActionForwardLoopError(action: any, mark: string): string {
20782087
* A caller whose credential the target's door cannot read is never
20792088
* forwarded ({@link apiForwardCredentialRefusal}).
20802089
*
2090+
* [#32658, #32887] `routing.environmentId` is the environment a multi-kernel
2091+
* host's resolver placed the request in. The forward targets the action's own
2092+
* path, so a scoped URL's environment does not cross with it, and the host
2093+
* door's request has no hostname at all: the forward carries the placement as
2094+
* the declared environment header, which places it in the same environment at
2095+
* the raw app. It replaces any spelling the caller sent, so the forward cannot
2096+
* be steered anywhere the request did not run. Absent (a single kernel, no
2097+
* placement, the control plane), nothing is written and the caller's own
2098+
* allow-listed headers cross as they always did.
2099+
*
20812100
* [ADR-0090 D10 rule 5] An AI agent principal is the one caller whose own
20822101
* credential is never carried. At the two cells the table flips
20832102
* ({@link API_FORWARD_AGENT_CREDENTIAL_DOORS}) the forward drops every caller
@@ -2102,6 +2121,7 @@ export async function forwardApiAction(
21022121
requestContext: HttpProtocolContext,
21032122
req: ApiActionRequest,
21042123
mark: { objectName: string; actionName: string; target?: string; recordId?: string },
2124+
routing?: { environmentId?: string },
21052125
): Promise<ApiActionForwardAnswer> {
21062126
// A caller whose credential the target's door cannot read (the table,
21072127
// {@link API_FORWARD_DOOR_ACCEPTS}) is refused here, before the target is
@@ -2135,6 +2155,7 @@ export async function forwardApiAction(
21352155
if (agent && API_FORWARD_IDENTITY_HEADERS.has(key)) continue;
21362156
headers[key] = Array.isArray(v) ? v.join(', ') : String(v);
21372157
}
2158+
if (routing?.environmentId) headers[API_FORWARD_ENVIRONMENT_HEADER] = routing.environmentId;
21382159
headers.accept = 'application/json';
21392160
headers[API_FORWARD_MARK_HEADER] = `${mark.objectName}/${mark.actionName}`;
21402161
const init: RequestInit = { method: req.method, headers };

‎packages/runtime/src/http-dispatcher.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -410,6 +410,34 @@ type ClassifiedServiceLookup =
410410
| { readonly outcome: 'never-registered' }
411411
| { readonly outcome: 'no-instance-in-scope'; readonly scopeId: string };
412412

413+
/**
414+
* [#32887] The environment a host's {@link KernelResolver} placed each request
415+
* in, kept beside the request and readable only through
416+
* {@link resolverPlacedEnvironmentOf}.
417+
*
418+
* A same-origin `type: 'api'` action forwards into the host's raw app, which
419+
* places the forwarded request as it places any request it receives. The
420+
* forward needs the placement's answer, not the signal that produced it: a
421+
* request placed by its bound hostname or its `X-Environment-Id` carries that
422+
* signal across, but one placed only by its scoped URL
423+
* (`/environments/:id/…`) does not — the forward targets the action's own
424+
* path — so on a shared origin it was placed in no environment. Kept off
425+
* {@link HttpProtocolContext} on purpose: a caller builds that object, and the
426+
* forward's routing identity must be the resolver's answer, never a field a
427+
* caller could pre-write.
428+
*/
429+
const resolverPlacements = new WeakMap<HttpProtocolContext, string>();
430+
431+
/**
432+
* The environment the host's {@link KernelResolver} placed this request in, as
433+
* the placement step left it: `undefined` when no resolver is wired (a single
434+
* kernel), when it placed the request in no environment, or in `platform` (the
435+
* control plane, not an environment).
436+
*/
437+
export function resolverPlacedEnvironmentOf(context: HttpProtocolContext | undefined): string | undefined {
438+
return context ? resolverPlacements.get(context) : undefined;
439+
}
440+
413441
/**
414442
* The HTTP dispatch engine — translates an inbound (method, path, body, ctx)
415443
* request into a kernel response. Used directly by the framework's HTTP adapters
@@ -784,6 +812,13 @@ export class HttpDispatcher {
784812
// request onto the second one's environment.
785813
if (this.kernelResolver) {
786814
context.kernel = (await this.kernelResolver.resolveKernel(context, this.defaultKernel)) ?? this.defaultKernel;
815+
// [#32887] What the resolver answered, kept for the api forward
816+
// ({@link resolverPlacedEnvironmentOf}). Read here, before any door
817+
// writes a fallback environment, so a request nothing placed
818+
// routes nothing.
819+
const placed = context.environmentId;
820+
if (typeof placed === 'string' && placed !== '' && placed !== 'platform') resolverPlacements.set(context, placed);
821+
else resolverPlacements.delete(context);
787822
} else {
788823
context.kernel = this.defaultKernel;
789824
}

0 commit comments

Comments
 (0)