Skip to content

Commit fd116ba

Browse files
committed
feat(runtime, rest, plugin-auth): an OAuth agent's api-action forward carries a server-minted forward credential (ADR-0090 D10 rule 5)
The two cells the #28367 amendment flips, and nothing else: an agent connected over OAuth, forwarded to an identity route or to another same-origin route, now reaches the target as the same agent principal instead of being refused by name. The platform cell is bounded by the scope-family rule. api_key x identity keeps refusing by name. - @objectstack/rest forward-credential: mint, bind (method, route, run), spend on first presentation, revoke when the forward answers, expire, and redeem only inside the forward's own async chain. - runtime action door: the table's two flipped cells, the scope-family predicate shared by run_action, the REST action door and list_actions, no caller identity header on an agent's forward, no rotated credential relayed back. - runtime dispatcher and REST face: a redeemed credential is the agent's provenance for the shared assembler; no admission is reported for it. - plugin-auth identity mount: a request-scoped, in-memory view of the delegating user for better-auth, no session row, the agent's client carried as performedBy on identity writes. - ADR-0090: the two sentences the amendment names are corrected. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L9qibyagSyLB5ckJsKghoa
1 parent 9b1dc99 commit fd116ba

27 files changed

Lines changed: 1898 additions & 126 deletions
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
---
2+
'@objectstack/rest': patch
3+
'@objectstack/runtime': patch
4+
'@objectstack/plugin-auth': patch
5+
---
6+
7+
feat(runtime, rest, plugin-auth): an AI agent connected over OAuth can run `api` actions that forward to identity routes and other same-origin routes, as the agent
8+
9+
Clause-②: yes (widening, at the two named cells only)
10+
Metadata-protocol: none
11+
12+
An `api` action runs by forwarding a request to its `target` inside the server. Until now an agent connected over OAuth was refused by name before that forward unless the target was the MCP endpoint, because its access token is honoured there alone. So the identity actions ADR-0011 exposes to agents (update my profile, the confirmed admin actions) never ran for one.
13+
14+
Now, per ADR-0090 D10 rule 5, the forward carries a credential the server mints for that one forward instead of the agent's token. It is bound to the forward's method and route and to the action run, spent by its first use, revoked when the target answers, and redeemable only inside the server's own in-process call. At the target it resolves to the same agent: its scope ceiling, the user it acts for and its client. At the identity routes, the auth library is shown the delegating user for that one request only; no session is created, and the user's own permissions there still decide. Writes the agent makes are recorded with both the agent and its user.
15+
16+
What changes, at exactly two cells of the forward table:
17+
18+
- an agent at an identity route: refused by name before, now forwarded as the agent;
19+
- an agent at any other same-origin route: refused by name before, now forwarded as the agent when the connection holds `actions:execute` and `data:write`.
20+
21+
What does not change:
22+
23+
- An API key is still refused by name at an identity route.
24+
- A state-changing request to the metadata endpoint is never forwarded for an agent; it is refused `403` by name.
25+
- An agent without `data:write` is refused `403` by name, and `list_actions` marks those actions the same way.
26+
- Nothing the target mints, such as a rotated session token or cookie, comes back to an agent.
27+
- An OAuth access token presented directly to the data API or to an identity route is still refused.

‎content/docs/ai/actions-as-tools.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ through the metadata API.
113113
|:---|:---|:---|
114114
| `script` | `IDataEngine.executeAction(object, target, ctx)` — the same call Studio makes | open (MCP) + ObjectOS |
115115
| `flow` | automation flow runner — `execute(target, automationContext)` (caller identity forwarded so `runAs` engages) | open (MCP) + ObjectOS; needs the `automation` service registered |
116-
| `api` | same-origin `target` (a path starting with `/`): forwarded in-process through the action door to that target, after the door's gates, with the caller's own credentials; a credential rotation the target emits comes back as the bearer-lane headers only (`set-auth-token` / `set-admin-session-token`), never a `Set-Cookie` line. The forward carries only a credential the target's door accepts: an identity route (`/api/v1/auth/…`) reads a signed-in session only, every other target a session or an API key, and an OAuth access token is honoured on the MCP endpoint only. Any other caller is refused `401` `UNAUTHENTICATED` before the forward, with a sentence naming the action, its target and what would let it run: an API key on an identity route, and an agent connected over OAuth on any target outside the MCP endpoint | open (MCP) + ObjectOS; an `api` action whose `target` is on another origin stays browser-only and is not listed |
116+
| `api` | same-origin `target` (a path starting with `/`): forwarded in-process through the action door to that target, after the door's gates, with the caller's own credentials; a credential rotation the target emits comes back as the bearer-lane headers only (`set-auth-token` / `set-admin-session-token`), never a `Set-Cookie` line. The forward carries only a credential the target's door accepts: an identity route (`/api/v1/auth/…`) reads a signed-in session only, every other target a session or an API key, and an OAuth access token is honoured on the MCP endpoint only. An API key on an identity route is refused `401` `UNAUTHENTICATED` before the forward, with a sentence naming the action, its target and what would let it run. An agent connected over OAuth is forwarded with a credential the server mints for that one forward instead of its token, and the target reads the same agent (its scope ceiling, the user it acts for, its client). Outside the MCP endpoint that needs the `actions:execute` and `data:write` scopes, since every `api` action's method changes state, and a state-changing request to the metadata endpoint (`/api/v1/meta/…`) is never forwarded for an agent: those are refused `403` `PERMISSION_DENIED` by name, before the forward. Nothing the target mints, such as a rotated session, comes back to an agent | open (MCP) + ObjectOS; an `api` action whose `target` is on another origin stays browser-only and is not listed |
117117

118118
Console-only types (`url`, `modal`, `form`) are always skipped.
119119

‎docs/adr/0090-permission-model-v2-concept-convergence.md‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -418,8 +418,10 @@ depends on:
418418
agent may *initiate*, not what it may *complete alone*.
419419
4. **Dual attribution**: every write **by an agent principal** records `performed_by` (agent) +
420420
`on_behalf_of` (user) + run id; explain (D6) reports both sides of the intersection. An
421-
agent principal is a caller a door resolves to `principalKind: 'agent'` — today the OAuth /
422-
MCP client door alone. A caller of any other kind records the principal it authenticates as,
421+
agent principal is a caller a door resolves to `principalKind: 'agent'`: the OAuth / MCP
422+
client door, and (since #28367) a door serving an `api` action's forward that carries the
423+
forward credential of rule 5, which is minted only for an agent that first door admitted.
424+
A caller of any other kind records the principal it authenticates as,
423425
and the missing `performed_by` is itself the record that the principal acted for itself; for
424426
the API-key case see the 2026-09-16 note at the end of this decision.
425427
5. **A forward carries the agent, never the user** (amended 2026-10-31): when an agent runs an
@@ -454,10 +456,11 @@ alias tax on every API.
454456
> on **every** door that runs
455457
> `packages/core/src/security/resolve-authz-context.ts#resolveAuthzContext` — REST, the runtime /
456458
> MCP **HTTP** dispatcher, and the MCP **stdio** transport — and none of the three turns one into
457-
> an agent, by two different mechanisms. REST and stdio hand the assembler
458-
> `oauth: undefined` **by construction** (`packages/rest/src/rest-server.ts`,
459-
> `packages/mcp/src/plugin.ts#resolveStdioExecutionContext`), so agent provenance is not
460-
> representable on either. On the HTTP dispatcher — the one door that does mint agent principals —
459+
> an agent, by two different mechanisms. stdio hands the assembler `oauth: undefined` **by
460+
> construction** (`packages/mcp/src/plugin.ts#resolveStdioExecutionContext`), so agent provenance
461+
> is not representable there; REST did the same until #28367, and since then represents it for
462+
> one caller only, a request carrying a rule 5 forward credential
463+
> (`packages/rest/src/rest-server.ts`), never for a key. On the HTTP dispatcher — the one door that does mint agent principals —
461464
> it is a **guard** rather than a structural impossibility:
462465
> `packages/runtime/src/security/resolve-execution-context.ts#extractJwtBearer` refuses an
463466
> `osk_`-prefixed bearer and anything that is not a three-segment JWS, so no OAuth provenance is
Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
// [ADR-0090 D10 rule 5, #28367] The identity mount's request-scoped view of
4+
// the delegating user. Pinned here at the seam (the mount middleware and the
5+
// session-lookup plugin); end to end through better-auth in
6+
// `packages/qa/dogfood/test/mcp-oauth-api-action-forward.dogfood.test.ts`.
7+
8+
import { describe, it, expect, vi } from 'vitest';
9+
import { FORWARD_CREDENTIAL_HEADER, withForwardCredential } from '@objectstack/rest';
10+
import {
11+
agentForwardIdentityViewPlugin,
12+
agentForwardPerformedBy,
13+
serveAgentForwardAtIdentityMount,
14+
} from './agent-forward-identity-view.js';
15+
import { authSystemWriteContext } from './auth-actor-attribution.js';
16+
17+
const AGENT = { userId: 'u_mia', clientId: 'agent-client-1', scopes: ['actions:execute', 'data:write'], organizationId: 'org_alpha' };
18+
const URL_ = 'http://localhost/api/v1/auth/update-user';
19+
const bind = { method: 'POST', path: '/api/v1/auth/update-user', run: { objectName: 'sys_user', actionName: 'update_my_profile' }, agent: AGENT };
20+
21+
/** A Hono-shaped context: `c.req.raw` and a writable `c.res`. */
22+
const honoCtx = (headers: Record<string, string>) => ({
23+
req: { raw: new Request(URL_, { method: 'POST', headers, body: JSON.stringify({ name: 'x' }) }) },
24+
res: undefined as Response | undefined,
25+
});
26+
27+
/** The plugin's wrapped adapter over an inner one that knows one user and no session. */
28+
const wrappedAdapter = (user: Record<string, unknown> | null = { id: 'u_mia', email: 'mia@example.com', banned: false }) => {
29+
const inner = {
30+
findOne: vi.fn(async (args: any) => (args.model === 'user' ? user : null)),
31+
create: vi.fn(),
32+
};
33+
const out: any = agentForwardIdentityViewPlugin().init({ adapter: inner, sessionConfig: { expiresIn: 604800 } });
34+
return { inner, adapter: out.context.adapter };
35+
};
36+
37+
describe('[ADR-0090 D10 rule 5] the identity mount: a forward credential becomes a request-scoped view of the delegating user', () => {
38+
it('a redeemed credential: better-auth reads one opaque bearer and none of the caller\'s identity headers; its lookup answers the delegating user in the consent\'s organization', async () => {
39+
const { adapter, inner } = wrappedAdapter();
40+
let seen: { authorization: string | null; cookie: string | null; forward: string | null; apiKey: string | null } | undefined;
41+
let session: any;
42+
let performedBy: unknown;
43+
let writeCtx: unknown;
44+
45+
await withForwardCredential(bind, async (handle) => {
46+
const c = honoCtx({ [FORWARD_CREDENTIAL_HEADER]: handle, cookie: 'better-auth.session_token=ambient', 'x-api-key': 'osk_x' });
47+
await serveAgentForwardAtIdentityMount(c, async () => {
48+
const h = c.req.raw.headers;
49+
seen = { authorization: h.get('authorization'), cookie: h.get('cookie'), forward: h.get(FORWARD_CREDENTIAL_HEADER), apiKey: h.get('x-api-key') };
50+
const token = String(seen.authorization).replace(/^Bearer /, '');
51+
session = await adapter.findOne({ model: 'session', where: [{ field: 'token', value: token }], join: { user: true } });
52+
performedBy = agentForwardPerformedBy();
53+
writeCtx = await authSystemWriteContext();
54+
c.res = new Response('{}', { headers: { 'set-cookie': 'better-auth.session_token=minted', 'set-auth-token': 'minted', 'content-type': 'application/json' } });
55+
});
56+
// Nothing that carries a credential leaves the mount for an agent caller.
57+
expect(c.res!.headers.get('set-cookie')).toBeNull();
58+
expect(c.res!.headers.get('set-auth-token')).toBeNull();
59+
expect(c.res!.headers.get('content-type')).toBe('application/json');
60+
});
61+
62+
expect(seen!.authorization).toMatch(/^Bearer [A-Za-z0-9_-]{32}$/);
63+
expect(seen!.cookie).toBeNull();
64+
expect(seen!.apiKey).toBeNull();
65+
expect(seen!.forward).toBeNull();
66+
expect(session).toMatchObject({ userId: 'u_mia', activeOrganizationId: 'org_alpha', user: { id: 'u_mia' } });
67+
expect(session.expiresAt.getTime()).toBeGreaterThan(Date.now());
68+
// No session of record: the view never wrote one.
69+
expect(inner.create).not.toHaveBeenCalled();
70+
expect(performedBy).toEqual({ clientId: 'agent-client-1' });
71+
expect(writeCtx).toMatchObject({ isSystem: true, performedBy: { clientId: 'agent-client-1' } });
72+
});
73+
74+
it('the view\'s bearer is no session anywhere else: outside the request\'s own chain the lookup passes through and finds nothing', async () => {
75+
const { adapter, inner } = wrappedAdapter();
76+
let token = '';
77+
await withForwardCredential(bind, async (handle) => {
78+
const c = honoCtx({ [FORWARD_CREDENTIAL_HEADER]: handle });
79+
await serveAgentForwardAtIdentityMount(c, async () => {
80+
token = String(c.req.raw.headers.get('authorization')).replace(/^Bearer /, '');
81+
});
82+
});
83+
expect(await adapter.findOne({ model: 'session', where: [{ field: 'token', value: token }], join: { user: true } })).toBeNull();
84+
expect(inner.findOne).toHaveBeenCalledWith(expect.objectContaining({ model: 'session' }));
85+
expect(agentForwardPerformedBy()).toBeUndefined();
86+
});
87+
88+
it('a banned or missing delegating user has no view', async () => {
89+
for (const user of [{ id: 'u_mia', banned: true, banExpires: null }, null]) {
90+
const { adapter } = wrappedAdapter(user);
91+
await withForwardCredential(bind, async (handle) => {
92+
const c = honoCtx({ [FORWARD_CREDENTIAL_HEADER]: handle });
93+
await serveAgentForwardAtIdentityMount(c, async () => {
94+
const token = String(c.req.raw.headers.get('authorization')).replace(/^Bearer /, '');
95+
expect(await adapter.findOne({ model: 'session', where: [{ field: 'token', value: token }], join: { user: true } })).toBeNull();
96+
});
97+
});
98+
}
99+
});
100+
101+
it('a credential that does not redeem (from outside, or for another route) is dropped and the request resolves on its other headers alone', async () => {
102+
const outside = honoCtx({ [FORWARD_CREDENTIAL_HEADER]: 'A'.repeat(43), cookie: 'c=1' });
103+
await serveAgentForwardAtIdentityMount(outside, async () => {
104+
expect(outside.req.raw.headers.get(FORWARD_CREDENTIAL_HEADER)).toBeNull();
105+
expect(outside.req.raw.headers.get('authorization')).toBeNull();
106+
expect(outside.req.raw.headers.get('cookie')).toBe('c=1');
107+
expect(agentForwardPerformedBy()).toBeUndefined();
108+
});
109+
110+
await withForwardCredential({ ...bind, path: '/api/v1/auth/admin/ban-user' }, async (handle) => {
111+
const c = honoCtx({ [FORWARD_CREDENTIAL_HEADER]: handle });
112+
await serveAgentForwardAtIdentityMount(c, async () => {
113+
expect(c.req.raw.headers.get('authorization')).toBeNull();
114+
expect(agentForwardPerformedBy()).toBeUndefined();
115+
});
116+
});
117+
});
118+
119+
it('no credential presented: the request passes through untouched', async () => {
120+
const c = honoCtx({ authorization: 'Bearer person_session' });
121+
const before = c.req.raw;
122+
await serveAgentForwardAtIdentityMount(c, async () => undefined);
123+
expect(c.req.raw).toBe(before);
124+
});
125+
});

0 commit comments

Comments
 (0)