Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): channels - let trustedForwarders check what a forwarder asserts (#3732)

Andrew Barbaa490d885391e
diff --git a/.changeset/forwarded-principal-assertion.md b/.changeset/forwarded-principal-assertion.md
new file mode 100644
index 000000000..5bdbd06ff
--- /dev/null
+++ b/.changeset/forwarded-principal-assertion.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+`eveChannel({ trustedForwarders })` now receives what the forwarder asserts as a second argument. `assertion.principal` holds the stamped `current` and `initiator` contexts the forwarder asserts, so a receiver can limit a trusted forwarder to the identities it may speak for instead of accepting any principal it asserts.
diff --git a/docs/guides/auth-and-route-protection.md b/docs/guides/auth-and-route-protection.md
index 8a191ddaa..05b965609 100644
--- a/docs/guides/auth-and-route-protection.md
+++ b/docs/guides/auth-and-route-protection.md
@@ -239,9 +239,41 @@ export default eveChannel({
`trustedForwarders` authorizes the verified forwarder to supply eve delegation context: principal identity, parent session lineage, and, with principal forwarding, trace-content constraints. Match it precisely: `() => true` grants this authority to every caller that passes route auth, including preview deployments accepted by `vercelOidc()`. The framework default channel rejects forwarded principals and ignores the other context.
+### Limiting what a forwarder may assert
+
+A forwarder accepted on its identity alone can assert any principal, including identities your tools trust directly, such as a Slack user or an app principal. When a forwarder should speak only for its own users, check what it asserts with the predicate's second argument:
+
+```ts title="agent/channels/eve.ts"
+import { eveChannel } from "eve/channels/eve";
+import { vercelOidc, vercelSubject } from "eve/channels/auth";
+import type { SessionAuthContext } from "eve/context";
+
+const router = vercelSubject({ teamSlug: "acme", projectName: "router" });
+
+/** The router forwards only users signed in through its own identity provider. */
+function isRouterUser(context: SessionAuthContext): boolean {
+ return (
+ context.authenticator === "router-sso" &&
+ context.issuer === "router" &&
+ context.principalType === "user"
+ );
+}
+
+export default eveChannel({
+ auth: [vercelOidc()],
+ trustedForwarders: (forwarder, assertion) =>
+ forwarder.subject === router &&
+ assertion.principal !== undefined &&
+ isRouterUser(assertion.principal.current) &&
+ isRouterUser(assertion.principal.initiator),
+});
+```
+
+`assertion.principal` holds the `current` and `initiator` contexts the forwarder asserts, already stamped with `eve:forwarded-by`. `initiator` equals `current` when the sender omits it. `initiator` takes effect only on session creation; on continuation the predicate still sees the asserted `initiator`, but the session keeps its original initiator, so checking it does not constrain that pinned value. Attributes are asserted too, so check any attribute your tools trust. `assertion.principal` is absent when the predicate decides parent session lineage for a request that forwards no principal; a predicate that requires it accepts that forwarder's lineage only alongside a principal it accepts. The `ForwardedAssertion` and `TrustedForwarders` types are exported from `eve/channels/eve` for named predicates.
+
When the predicate accepts a create request, `ctx.session.auth.current` and `.initiator` carry the forwarded user exactly as if they had called your deployment directly. On continuation, only `auth.current` is replaced; `auth.initiator` remains the session creator. User-scoped connections, local subagents, and further `forwardPrincipal` hops therefore see the active turn's caller.
-The forwarder is recorded on accepted contexts as the `eve:forwarded-by` attribute (always overwritten by the receiver, so a forwarder cannot falsify it). Forwarded identity rejections fail loud: a forwarded body without `trustedForwarders` configured or with a forwarder the predicate refuses is a `403`, and a malformed payload is a `400`. Only principal metadata is ever accepted — tokens and credentials never cross the hop.
+The forwarder is recorded on accepted contexts as the `eve:forwarded-by` attribute (always overwritten by the receiver, so a forwarder cannot falsify it). Forwarded identity rejections fail loud: a forwarded body without `trustedForwarders` configured, or with a forwarder or assertion the predicate refuses, is a `403`, and a malformed payload is a `400`. Only principal metadata is ever accepted — tokens and credentials never cross the hop.
Trusted parent session lineage populates `ctx.session.parent` and preserves the root session across the delegation chain. Untrusted lineage is ignored, and accepted lineage does not remove the normal root-session token cap.
diff --git a/docs/guides/remote-agents.md b/docs/guides/remote-agents.md
index 5c8e1e54c..6277b0aa5 100644
--- a/docs/guides/remote-agents.md
+++ b/docs/guides/remote-agents.md
@@ -138,7 +138,7 @@ This makes caller authority turn-scoped even when the remote child session is pe
Identity forwarding does not make a persistent session private to one caller. Conversation history, tool outputs, and other child-session state still persist. If those values must not be visible across users, give each user a distinct child session or enforce that ownership at the application boundary.
-Forwarding identity is explicit on both sides. The receiver names which deployments it trusts with `eveChannel({ trustedForwarders })` (see [Auth & route protection](./auth-and-route-protection#accepting-forwarded-identity-from-another-deployment)); refusing the forwarder rejects a forwarded principal with a 403. The same trust decision covers parent session lineage and, with principal forwarding, trace-content constraints.
+Forwarding identity is explicit on both sides. The receiver names which deployments it trusts with `eveChannel({ trustedForwarders })` and can limit each one to the principals it may assert (see [Auth & route protection](./auth-and-route-protection#accepting-forwarded-identity-from-another-deployment)); refusing the forwarder or what it asserts rejects a forwarded principal with a 403. The same trust decision covers parent session lineage and, with principal forwarding, trace-content constraints.
## Trace propagation
diff --git a/packages/eve/src/channel/forwarded-principal.ts b/packages/eve/src/channel/forwarded-principal.ts
index a09c4c56c..8d523dd27 100644
--- a/packages/eve/src/channel/forwarded-principal.ts
+++ b/packages/eve/src/channel/forwarded-principal.ts
@@ -25,11 +25,35 @@ export interface ForwardedPrincipal {
}
/**
- * Authorizes which transport-authenticated forwarders may assert a forwarded
- * principal. Receives the *verified* route-auth principal (who is asserting),
- * never the forwarded identity (what is asserted).
+ * What a forwarder asks the receiving deployment to adopt, passed to
+ * {@link TrustedForwarders} next to the verified forwarder.
*/
-export type TrustedForwarders = (forwarder: SessionAuthContext) => boolean | Promise<boolean>;
+export interface ForwardedAssertion {
+ /**
+ * The session principals the forwarder asserts, present when it forwards a
+ * principal and absent when only remote parent lineage is being trusted.
+ * Both contexts are already stamped with {@link FORWARDED_BY_ATTRIBUTE}, and
+ * `initiator` is `current` when the sender omitted it. `initiator` takes
+ * effect only on session creation: continuation requests install only
+ * `current`, so there `initiator` is the asserted value, not the session's
+ * pinned initiator.
+ */
+ readonly principal?: {
+ readonly current: SessionAuthContext;
+ readonly initiator: SessionAuthContext;
+ };
+}
+
+/**
+ * Authorizes a transport-authenticated forwarder to supply eve delegation
+ * context. Receives the *verified* route-auth principal (who is asserting) and
+ * the principals it asserts, so a receiver can limit each forwarder to the
+ * identities it may speak for.
+ */
+export type TrustedForwarders = (
+ forwarder: SessionAuthContext,
+ assertion: ForwardedAssertion,
+) => boolean | Promise<boolean>;
export type ForwardedPrincipalParseResult =
| {
@@ -88,8 +112,8 @@ const forwardedPrincipalSchema = z
* Gates the `forwardedPrincipal` body field and resolves the
* effective session principals. Returns the failure `Response` on rejection:
* 403 when the channel accepts no forwarded principal or the predicate
- * refuses the forwarder, 400 on a malformed payload, 500 when the authored
- * predicate throws. Accepted contexts are stamped with
+ * refuses the forwarder or what it asserts, 400 on a malformed payload, 500
+ * when the authored predicate throws. Accepted contexts are stamped with
* {@link FORWARDED_BY_ATTRIBUTE} before they are returned, so a custom
* `onMessage` always sees the transport forwarder on the replaced principal.
*/
@@ -113,9 +137,17 @@ export async function resolveForwardedPrincipal(input: {
return Response.json({ error: parsed.message, ok: false }, { status: 400 });
}
+ const current = stampForwardedBy(parsed.forwardedPrincipal.current, input.forwarder.principalId);
+ const initiator =
+ parsed.forwardedPrincipal.initiator === undefined
+ ? current
+ : stampForwardedBy(parsed.forwardedPrincipal.initiator, input.forwarder.principalId);
+
let accepted: boolean;
try {
- accepted = await input.trustedForwarders(input.forwarder);
+ accepted = await input.trustedForwarders(input.forwarder, {
+ principal: { current, initiator },
+ });
} catch (error) {
const errorId = logError(log, "trustedForwarders handler failed", error, {
forwarder: input.forwarder.principalId,
@@ -132,11 +164,6 @@ export async function resolveForwardedPrincipal(input: {
);
}
- const current = stampForwardedBy(parsed.forwardedPrincipal.current, input.forwarder.principalId);
- const initiator =
- parsed.forwardedPrincipal.initiator === undefined
- ? current
- : stampForwardedBy(parsed.forwardedPrincipal.initiator, input.forwarder.principalId);
return { accepted: true, auth: current, initiatorAuth: initiator };
}
diff --git a/packages/eve/src/eve-channel/index.ts b/packages/eve/src/eve-channel/index.ts
index c531a6076..155840087 100644
--- a/packages/eve/src/eve-channel/index.ts
+++ b/packages/eve/src/eve-channel/index.ts
@@ -179,7 +179,7 @@ export function eveChannel(input: EveChannelInput): EveChannel {
let accepted = forwarded.accepted;
if (!accepted && input.trustedForwarders !== undefined) {
try {
- accepted = await input.trustedForwarders(authResult);
+ accepted = await input.trustedForwarders(authResult, {});
} catch (error) {
const errorId = logError(log, "trustedForwarders handler failed", error, {
forwarder: authResult.principalId,
diff --git a/packages/eve/src/eve-channel/types.ts b/packages/eve/src/eve-channel/types.ts
index 8e2860a94..62335e2bf 100644
--- a/packages/eve/src/eve-channel/types.ts
+++ b/packages/eve/src/eve-channel/types.ts
@@ -13,6 +13,8 @@ import type {
} from "#public/definitions/channel.js";
import type { ChannelAudience } from "#shared/channel-audience.js";
+export type { ForwardedAssertion, TrustedForwarders } from "#channel/forwarded-principal.js";
+
/**
* Event-handler channel context exposed by `eveChannel({ events })`. The default eve HTTP channel
* has no platform-specific state, so handlers receive optional continuation routing here and the
@@ -114,12 +116,19 @@ export interface EveChannelInput {
* The trusted-forwarders policy: which transport-authenticated callers may
* assert a forwarded principal, callback-marked public trace audience, or
* remote parent lineage. The predicate receives the *verified* route-auth
- * principal of the forwarder — who is asserting, never what is asserted —
- * and must match it precisely (for example `(forwarder) =>
- * forwarder.subject === vercelSubject({ teamSlug, projectName })`). A
- * permissive predicate lets any authenticated forwarder assert any principal,
+ * principal of the forwarder and must match it precisely (for example
+ * `(forwarder) => forwarder.subject === vercelSubject({ teamSlug, projectName })`).
+ * A permissive predicate lets any authenticated forwarder assert any principal,
* public trace audience, or remote lineage.
*
+ * The second argument carries what the forwarder asserts. `assertion.principal`
+ * holds the stamped `current` and `initiator` contexts the forwarder asserts,
+ * so a receiver can limit a forwarder to the identities it may speak for, such as
+ * one authenticator and issuer. `initiator` takes effect only on session
+ * creation; on continuation it is the asserted value, not the session's pinned
+ * initiator. `assertion.principal` is absent when the predicate decides remote
+ * parent lineage for a request that forwards no principal.
+ *
* When a trusted forwarder's assertion is accepted on session creation, the
* forwarded principal replaces `session.auth.current` and
* `session.auth.initiator`. On continuation, only `session.auth.current`
diff --git a/packages/eve/src/public/channels/eve-session-routes.test.ts b/packages/eve/src/public/channels/eve-session-routes.test.ts
index f1e2b29c2..8b2017b68 100644
--- a/packages/eve/src/public/channels/eve-session-routes.test.ts
+++ b/packages/eve/src/public/channels/eve-session-routes.test.ts
@@ -6,7 +6,7 @@ import { attachRouteSessionCreator } from "#internal/nitro/routes/channel-route-
import { mockChannelContext } from "#internal/testing/mocks/mock-channel-operations.js";
import { writeForwardedParentSessionBaggage } from "#protocol/baggage.js";
import { none } from "#public/channels/auth.js";
-import { eveChannel } from "#public/channels/eve.js";
+import { eveChannel, type TrustedForwarders } from "#public/channels/eve.js";
function route(
method: "GET" | "POST",
@@ -348,7 +348,7 @@ describe("eve ID-addressed session routes", () => {
sessionId: "wrun_A",
});
const args = attachRouteSessionCreator(createArgs(), createSession);
- const trustedForwarders = vi.fn(() => trusted);
+ const trustedForwarders = vi.fn<TrustedForwarders>(() => trusted);
const parent = {
callId: "call-1",
rootSessionId: "root-session",
@@ -381,6 +381,8 @@ describe("eve ID-addressed session routes", () => {
expect(response.status).toBe(202);
expect(trustedForwarders).toHaveBeenCalledTimes(1);
+ // Lineage-only requests assert no principal.
+ expect(trustedForwarders).toHaveBeenCalledWith(expect.anything(), {});
expect(createSession).toHaveBeenCalledWith(
expect.objectContaining({
parent: trusted ? parent : undefined,
diff --git a/packages/eve/src/public/channels/eve.test.ts b/packages/eve/src/public/channels/eve.test.ts
index 80c017e38..db1d5d1a8 100644
--- a/packages/eve/src/public/channels/eve.test.ts
+++ b/packages/eve/src/public/channels/eve.test.ts
@@ -8,7 +8,13 @@ import { readClientContext } from "#internal/client-context.js";
import { attachRouteSessionCreator } from "#internal/nitro/routes/channel-route-context.js";
import { mockChannelContext } from "#internal/testing/mocks/mock-channel-operations.js";
import { type AuthFn, none } from "#public/channels/auth.js";
-import { eveChannel, defaultEveAuth, type EveChannelInput } from "#public/channels/eve.js";
+import {
+ eveChannel,
+ defaultEveAuth,
+ type EveChannelInput,
+ type ForwardedAssertion,
+ type TrustedForwarders,
+} from "#public/channels/eve.js";
import type { RunInput, SessionAuthContext } from "#channel/types.js";
import type { RouteHandlerArgs, SendPayload } from "#channel/routes.js";
import type { Session } from "#channel/session.js";
@@ -2040,10 +2046,35 @@ describe("eveChannel — forwarded principal", () => {
subject: "U999",
};
+ const PASSPORT_USER: SessionAuthContext = {
+ attributes: {},
+ authenticator: "vercel-passport",
+ issuer: "router",
+ principalId: "user-1",
+ principalType: "user",
+ };
+
function forwardedRequest(forwardedPrincipal: unknown): Request {
return createJsonMessageRequest({ forwardedPrincipal, message: "hi", mode: "task" });
}
+ function stamped(context: SessionAuthContext): SessionAuthContext {
+ return {
+ ...context,
+ attributes: { ...context.attributes, "eve:forwarded-by": ROUTER_CALLER.principalId },
+ };
+ }
+
+ /** The router may forward only its own Passport users, never Slack or other identities. */
+ function routerMayAssert(forwarder: SessionAuthContext, assertion: ForwardedAssertion): boolean {
+ if (forwarder.principalId !== ROUTER_CALLER.principalId) return false;
+ if (assertion.principal === undefined) return false;
+ const { current, initiator } = assertion.principal;
+ return (
+ current.authenticator === "vercel-passport" && initiator.authenticator === "vercel-passport"
+ );
+ }
+
it("rejects a forwarded body when the channel has no trustedForwarders", async () => {
const handler = createEveCreateHandler({ auth: () => ROUTER_CALLER });
@@ -2058,8 +2089,8 @@ describe("eveChannel — forwarded principal", () => {
});
it("rejects a caller the predicate refuses", async () => {
- const trustedForwarders = vi.fn(
- (caller: SessionAuthContext) => caller.principalId === "someone-else",
+ const trustedForwarders = vi.fn<TrustedForwarders>(
+ (caller) => caller.principalId === "someone-else",
);
const handler = createEveCreateHandler({
trustedForwarders,
@@ -2069,7 +2100,9 @@ describe("eveChannel — forwarded principal", () => {
const response = await handler.fetch(forwardedRequest({ current: FORWARDED_CURRENT }));
expect(response.status).toBe(403);
- expect(trustedForwarders).toHaveBeenCalledWith(ROUTER_CALLER);
+ expect(trustedForwarders).toHaveBeenCalledWith(ROUTER_CALLER, {
+ principal: { current: stamped(FORWARDED_CURRENT), initiator: stamped(FORWARDED_CURRENT) },
+ });
expect(handler.send).not.toHaveBeenCalled();
await expect(response.json()).resolves.toMatchObject({
error: "Caller is not authorized to assert a forwarded principal.",
@@ -2077,6 +2110,38 @@ describe("eveChannel — forwarded principal", () => {
});
});
+ it.each([
+ { name: "a Slack current principal", forwarded: { current: FORWARDED_CURRENT } },
+ {
+ name: "a Slack initiator",
+ forwarded: { current: PASSPORT_USER, initiator: FORWARDED_INITIATOR },
+ },
+ ])("rejects a trusted forwarder asserting $name it may not assert", async ({ forwarded }) => {
+ const handler = createEveCreateHandler({
+ trustedForwarders: routerMayAssert,
+ auth: () => ROUTER_CALLER,
+ });
+
+ const response = await handler.fetch(forwardedRequest(forwarded));
+
+ expect(response.status).toBe(403);
+ expect(handler.send).not.toHaveBeenCalled();
+ });
+
+ it("accepts a trusted forwarder asserting a principal it may assert", async () => {
+ const handler = createEveCreateHandler({
+ trustedForwarders: routerMayAssert,
+ auth: () => ROUTER_CALLER,
+ });
+
+ const response = await handler.fetch(forwardedRequest({ current: PASSPORT_USER }));
+
+ expect(response.status).toBe(202);
+ const options = handler.send.mock.calls[0]?.[1] as MockSendOptions;
+ expect(options.auth).toEqual(stamped(PASSPORT_USER));
+ expect(options.initiatorAuth).toEqual(stamped(PASSPORT_USER));
+ });
+
it("rejects a malformed forwarded payload with 400", async () => {
const handler = createEveCreateHandler({
trustedForwarders: () => true,
@@ -2319,6 +2384,24 @@ describe("eveChannel — forwarded principal", () => {
);
});
+ it("rejects a continuation asserting a principal the forwarder may not assert", async () => {
+ const handler = createEveContinueHandler({
+ auth: () => ROUTER_CALLER,
+ trustedForwarders: routerMayAssert,
+ });
+
+ const response = await handler.fetch(
+ new Request("https://example.com/eve/v1/session/test-session-id", {
+ body: JSON.stringify({ forwardedPrincipal: { current: FORWARDED_CURRENT }, message: "hi" }),
+ headers: { "content-type": "application/json" },
+ method: "POST",
+ }),
+ );
+
+ expect(response.status).toBe(403);
+ expect(handler.send).not.toHaveBeenCalled();
+ });
+
it("rejects a forwarded continuation when the channel has no trustedForwarders", async () => {
const handler = createEveContinueHandler({ auth: () => ROUTER_CALLER });
diff --git a/packages/eve/test/scenarios/remote-agent-principal-forwarding.scenario.test.ts b/packages/eve/test/scenarios/remote-agent-principal-forwarding.scenario.test.ts
index 0c1ec6612..f11b77f09 100644
--- a/packages/eve/test/scenarios/remote-agent-principal-forwarding.scenario.test.ts
+++ b/packages/eve/test/scenarios/remote-agent-principal-forwarding.scenario.test.ts
@@ -17,7 +17,8 @@ import { startEveDev } from "./dev-server-harness.js";
* `trustedForwarders`. The receiver's `onMessage` asserts that the
* forwarded principal — not the transport caller — became the effective
* session caller, with the `eve:forwarded-by` audit attribute stamped from
- * the verified transport principal.
+ * the verified transport principal. The predicate also limits the router to
+ * Slack principals, so an assertion of any other identity type is refused.
*/
const scenarioApp = useScenarioApp();
@@ -50,7 +51,11 @@ export default eveChannel({
principalType: "service",
};
},
- trustedForwarders: (caller) => caller.principalId === "router-app",
+ // The router may speak only for Slack users, never for other identity types.
+ trustedForwarders: (caller, assertion) =>
+ caller.principalId === "router-app" &&
+ assertion.principal?.current.authenticator === "slack-webhook" &&
+ assertion.principal.initiator.authenticator === "slack-webhook",
onMessage(ctx) {
const caller = ctx.eve.caller;
if (
@@ -79,9 +84,16 @@ const FORWARDED_USER: SessionAuthContext = {
subject: "U123",
};
+const APP_PRINCIPAL: SessionAuthContext = {
+ attributes: {},
+ authenticator: "app",
+ principalId: "app",
+ principalType: "service",
+};
+
describe("remote agent auth forwarding", () => {
it(
- "asserts the forwarded principal across the hop and rejects untrusted forwarders",
+ "asserts the forwarded principal across the hop and rejects untrusted forwarders and assertions",
async () => {
const receiverApp = await scenarioApp(RECEIVER_DESCRIPTOR);
const receiver = await startEveDev(receiverApp.appRoot);
@@ -112,6 +124,19 @@ describe("remote agent auth forwarding", () => {
session: createParentSession(),
}),
).rejects.toThrow(/HTTP 403/);
+
+ // Over-reach: the trusted router asserts an identity type it may not
+ // speak for, so the receiver refuses what is asserted.
+ await expect(
+ startRemoteAgentSession({
+ action: createAction(),
+ auth: APP_PRINCIPAL,
+ callbackBaseUrl: "https://caller.example.com",
+ initiatorAuth: APP_PRINCIPAL,
+ remote: createRemote({ token: ROUTER_TOKEN, url: receiver.url }),
+ session: createParentSession(),
+ }),
+ ).rejects.toThrow(/HTTP 403/);
} catch (error) {
throw new Error(
[`receiver stdout:\n${receiver.stdout()}`, `receiver stderr:\n${receiver.stderr()}`].join(
diff --git a/research/remote-agent-auth-forwarding.md b/research/remote-agent-auth-forwarding.md
deleted file mode 100644
index 861befaf8..000000000
--- a/research/remote-agent-auth-forwarding.md
+++ /dev/null
@@ -1,214 +0,0 @@
----
-issue: https://github.com/vercel/eve/issues/604
-status: implemented
-last_updated: "2026-08-20"
----
-
-# Forwarding end-user identity across remote agent hops
-
-## Summary
-
-A `defineRemoteAgent` hop drops the caller principal. Local subagent dispatch threads `auth` and
-`initiatorAuth` onto the child `RunInput` (`execution/subagent-tool.ts`), so a child session sees
-the same end user as its parent. The remote branch sends only
-`{ callback, message, mode, outputSchema }` (`execution/remote-agent-dispatch.ts`), so the only
-identity that can cross the hop is deployment-level trust. The receiving deployment authenticates
-the _calling app_ (`principalType: "runtime"` / `"service"`), never the end user.
-
-This breaks per-user workloads split across deployments — most directly per-user Vercel Connect:
-`resolveConnectionPrincipal` requires `session.auth.current.principalType === "user"` and fails
-with `principal_required` when the session principal is the calling service. A router deployment
-that authenticates end users over Slack cannot delegate to a `site-ops` deployment where each user
-has OAuthed their own Datadog / GitHub / Vercel connection.
-
-This plan adds explicit, opt-in principal forwarding on both sides of the hop. Only principal
-_metadata_ (`SessionAuthContext`) crosses the wire — never tokens or credentials. The trust model
-is "trusted forwarder": the route's `auth` authenticates the asserting deployment as usual, and
-the receiver authorizes forwarding with a predicate over that verified transport principal — the
-same shape as `X-Forwarded-*` behind a trusted proxy, without token-exchange machinery.
-
-Persistent remote children also accept continuation requests. Those requests must forward the
-active parent turn's principal through the same trust gate: otherwise the child sees only the
-calling deployment's service identity and per-user connections fail. A continuation replaces
-only `auth.current`; `auth.initiator` remains pinned to the principal that created the child.
-
-```text
-Slack user U ── router deployment ──────────────► site-ops deployment
- auth.current = U POST /eve/v1/session
- headers: OIDC (router app identity)
- body.forwardedPrincipal: { current: U, initiator: U }
- │
- eveChannel auth: verifies router app
- trustedForwarders(caller): router app may forward
- │
- session.auth.current = U ──► per-user Connect,
- local subagents,
- further remote hops
-```
-
-## Authoring API
-
-### Sender: `forwardPrincipal` on `defineRemoteAgent`
-
-```ts
-// agent/subagents/site-ops.ts
-import { defineRemoteAgent } from "eve";
-import { vercelOidc } from "eve/agents/auth";
-
-export default defineRemoteAgent({
- url: "https://site-ops.example.com",
- description: "Executes site operations as the requesting user.",
- auth: vercelOidc(), // transport trust: authenticates *this* deployment
- forwardPrincipal: true, // identity: asserts the current session principal
-});
-```
-
-- `forwardPrincipal?: boolean`, default `false`. Forwarding identity to another deployment is an
- explicit decision, never ambient.
-- When `true`, creation serializes the parent turn's `AuthKey` / `InitiatorAuthKey` into a
- `forwardedPrincipal` field: `{ current: SessionAuthContext, initiator?: SessionAuthContext }`.
- Continuation serializes only the active `AuthKey`: `{ current: SessionAuthContext }`.
-- The field is omitted only when `AuthKey` is `null` (the request was accepted with no
- credentials); the call then proceeds on transport trust alone. Any non-null context is forwarded as-is — including anonymous
- (`principalType: "anonymous"` from `none()`), schedule (`SCHEDULE_APP_AUTH`), and service
- principals — exact parity with how local subagent dispatch threads `auth`. Non-user principals
- still fail `principal_required` at Connect on the receiver, which is the correct outcome.
-- The flag rides the module-backed runtime definition next to `auth` and `headers`; the compiled
- manifest node is unchanged.
-
-### Receiver: `trustedForwarders` on `eveChannel`
-
-```ts
-// agent/channels/eve.ts (site-ops deployment)
-import { eveChannel, vercelOidc, vercelSubject } from "eve";
-
-export default eveChannel({
- auth: [vercelOidc()],
- // Only the router deployment may assert a forwarded principal.
- trustedForwarders: (forwarder) =>
- forwarder.subject === vercelSubject({ teamSlug: "acme", projectName: "router" }),
-});
-```
-
-- `trustedForwarders?: (caller: SessionAuthContext) => boolean | Promise<boolean>`. The
- predicate authorizes the _verified transport principal_ (who is asserting), not the forwarded
- identity (what is asserted). The route's `auth` walk has already authenticated the request; the
- forwarding decision is authorization over its result, so there is no second token verification
- and no new auth machinery.
-- A predicate — rather than a second `AuthFn` walk — makes the Vercel OIDC always-on
- current-project bypass structurally irrelevant: the bypass lives inside `vercelOidc()` closures
- and cannot be disabled from the outside, and with a predicate the author must write an explicit
- match against the verified principal. Same-project callers (including preview deployments of
- the receiving project) get a transport principal whose `subject` simply does not match the named
- forwarder. `vercelSubject()` already produces the exact `sub` string to compare.
-- The forwarded `SessionAuthContext` values are validated against a strict wire schema in a new
- `channel/forwarded-principal.ts`, mirroring how `callback` is validated today
- (`channel/session-callback.ts`). The schema is strict on keys but **must keep `authenticator`
- and `principalType` as open non-empty strings** (matching the public `SessionAuthContext`
- interface) with attribute values `string | string[]`. It must not mirror the private runtime
- schema in `runtime/sessions/auth.ts`, whose enums (`"http-basic" | "jwt-hmac" | ...`) would
- reject the flagship use case — a Slack-authenticated user has `authenticator: "slack-webhook"`.
-
-## Semantics
-
-- **Accepted forwarding replaces the active session principal.** On creation,
- `session.auth.current` = forwarded `current` and `session.auth.initiator` = forwarded
- `initiator` ?? forwarded `current`. On continuation, only `session.auth.current` changes;
- `session.auth.initiator` remains pinned. Everything downstream works unchanged:
- `resolveConnectionPrincipal` sees the active turn's user (per-user Connect resolves), local
- subagents inherit that principal, and a further `forwardPrincipal: true` remote hop chains it.
-- **Caller authority is turn-scoped.** Local continuation always carries `SessionCommand.auth`,
- including `null`, so a later unauthenticated turn clears rather than inherits the previous
- caller. Remote continuation omits the assertion for `null` and the receiver uses its verified
- transport principal. Connection bearer caches are keyed by principal and virtual to one step;
- an upstream provider may retain each user's grant, but a turn can resolve only its current
- principal's grant.
-- **Audit trail is receiver-written.** The receiver records the transport caller on the accepted
- contexts as attribute `eve:forwarded-by` = the _verified_ transport `principalId`, always
- overwriting any sender-supplied value — a forwarder must not be able to falsify the trail. On
- multi-hop chains (A→B→C) the attribute names the most recent hop only. Attributes do not affect
- Connect token-cache keying (`principalKey` uses issuer + id only).
-- **`onMessage` still runs last, after stamping.** `eve:forwarded-by` is written before
- `onMessage` runs. `EveHandle.caller` is the forwarded principal once accepted, so
- `caller.attributes["eve:forwarded-by"]` is the window a custom `onMessage` has onto the
- transport caller; `defaultEveAuth` passes the forwarded principal through, and a custom
- `onMessage` can still override or drop, same as today.
-- **Rejections fail loud.** A body carrying `forwardedPrincipal` when the channel has no
- `trustedForwarders` option → 403 ("this deployment does not accept a forwarded
- principal"). Predicate returns `false` → 403. Malformed `forwardedPrincipal` payload → 400. Each
- fails the sender's dispatch inline.
-- **Mixed versions fail closed.** A receiver that supports forwarding only on session creation
- rejects a forwarded continuation with HTTP 400. The sender must not retry without the field:
- doing so would run the turn as the transport principal and silently change authority. The parent
- preserves the child handle, so the same session can be retried after the receiver is upgraded. A
- receiver that predates all principal forwarding may instead drop the unknown field and run as
- the transport principal, surfacing as `principal_required` at per-user Connect. Deploy both
- sides before resuming persistent remote sessions.
-- **What never crosses the wire:** tokens, credentials, claims. Only the `SessionAuthContext`
- shape (`attributes`, `authenticator`, `issuer`, `principalId`, `principalType`, `subject`).
- Per-user provider credentials always live on the receiving deployment via its own Connect
- authorizations.
-- **Events unchanged.** `subagent.called` and callbacks are untouched; forwarding is invisible to
- the parent stream. The cancel path is untouched: it authenticates with the definition's existing
- `auth` / `headers` and carries no forwarded identity.
-
-## Boundaries and surfaces
-
-| Surface | Change |
-| ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
-| `public/definitions/remote-agent.ts` | `forwardPrincipal?: boolean` |
-| `execution/dispatch-runtime-actions-step.ts` | pass `auth` / `initiatorAuth` (already in scope) to remote dispatch |
-| `execution/tasks/parent/dispatch-task-step.ts`, `harness/handles/dispatch.ts` | pass active `auth` through persistent local and remote continuation |
-| `execution/remote-agent-dispatch.ts` | build `forwardedPrincipal` body field |
-| `channel/forwarded-principal.ts` (new) | strict wire schema for `{ current, initiator? }` (open `authenticator` / `principalType`), beside `session-callback.ts` |
-| `public/channels/eve.ts` | `trustedForwarders` option; forwarded-principal gate + principal replacement on create and continuation routes |
-| `docs/guides/remote-agents.md`, `docs/guides/auth-and-route-protection.md` | forwarding section on each side + trust-model warning |
-
-Docs must carry the security guidance explicitly: match the transport principal precisely (e.g.
-`subject === vercelSubject({ teamSlug, projectName })`); a permissive predicate (`() => true`)
-lets any authenticated caller assert any principal. Docs must also note that the framework default
-channel has no `trustedForwarders`, so a receiving deployment must author its own
-`agent/channels/eve.ts` to accept forwarded identity — forwarded bodies 403 until it does.
-
-## Out of scope
-
-- Token exchange, delegation tokens, or forwarding credentials of any kind — the receiver mints
- its own per-user credentials via Connect.
-- A context-aware `OutboundAuthFn` (passing the dispatching turn's principals so custom schemes
- can mint per-user credentials for non-eve receivers). Adding a parameter to the function type
- later is fully non-breaking — zero-arg implementations remain assignable and eve is the only
- caller — so this waits for a concrete need. It would also have to define what context the
- cancel path passes, since `cancelRemoteAgentTurn` resolves headers through the same
- `resolveRemoteAgentRequestHeaders`.
-- Per-call forwarding decisions (the flag is per remote-agent definition).
-- Reduced-scope or transformed principals (an `onMessage` override on the receiver already covers
- reshaping).
-- Cross-principal visibility of persistent child history, tool outputs, and artifacts. Principal
- forwarding selects the active turn's credential authority; applications that require private
- history must key child sessions by principal or enforce a same-principal ownership policy.
-- A response acknowledgment (`forwardedPrincipal: "accepted"` on the 202) letting the sender
- detect a receiver that cannot apply the assertion. Considered and dropped: create-only receivers
- already reject forwarded continuations, the sender preserves the child handle for a retry after
- upgrade, and deployment docs make the coordinated-upgrade requirement explicit. Permanent wire
- surface was not justified by a transitional, pre-1.0 skew window.
-
-## Delivery and verification
-
-Single PR with a **patch** changeset: both options are additive; no public API breaks.
-
-- Unit: wire schema (strict on keys, open `authenticator` / `principalType`, channel-produced
- contexts like `slack-webhook` accepted, malformed rejection), dispatch body construction with
- and without `forwardPrincipal` and with null auth (field omitted), receiver matrix (field
- without option → 403, predicate false → 403, predicate true → principal replaced,
- `eve:forwarded-by` stamped from the verified transport principal and sender-supplied values
- overwritten, stamping visible to `onMessage`).
-- Unit/integration: continuation sends only active `current` when forwarding is enabled; the
- receiver applies the same trust gate, changes only `auth.current`, and local delivery replaces
- or clears the previous turn's `AuthKey`. Cover both persistent-session and tasks dispatch.
-- Integration: create route end-to-end in memory — forwarded principal becomes
- `session.auth.current` / `.initiator` and reaches `resolveConnectionPrincipal` as a `user`
- principal.
-- E2E: the `agent-subagents` loopback remote runs through a real HTTP hop. One parent turn creates
- the child as user A; a second, user-B-authenticated turn continues the same `childSessionId`.
- The child reports `auth.current` as B, keeps A as `auth.initiator`, and carries the
- receiver-written `eve:forwarded-by` attribute on both turns.