Skip to content
Merged
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
2 changes: 1 addition & 1 deletion .changeset/33808-ai-door-confirmation-in-app.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
---
'@objectstack/spec': minor
---
Expand Down Expand Up @@ -27,4 +27,4 @@
What changes for a caller, from the release whose in-app door implements it:

- FROM an operator or administrator approving another user's in-app pending action in the inbox TO the person the call ran as approving it; a second approver is a `held` item in the approvals engine.
- FROM approving or rejecting through `POST /api/v1/ai/pending-actions/:id/approve|reject` with an API key or bearer token TO the person's signed-in session to the app.
- FROM approving or rejecting through `POST /api/v1/ai/pending-actions/:id/approve|reject` with an API key, an OAuth token or another service credential TO the person's signed-in session to the app, whether its session token rides in the cookie or in an `Authorization: Bearer` header.
16 changes: 16 additions & 0 deletions .changeset/34184-ai-route-user-credential.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
'@objectstack/spec': patch
'@objectstack/runtime': patch
---

feat(spec,runtime): an AI route's `req.user` says who is acting and which credential admitted them

Clause-②: yes
Metadata-protocol: none

A door reserved to the person, such as the in-app approval of a pending action that only the person the call ran as may give, can now tell an impersonating administrator or an API key from the person, without reading request headers.

- `@objectstack/spec/contracts` declares the AI-route caller: `AIRouteUser`, the `req.user` an AI route handler receives (the `EvalUser` core, the id and display-name aliases, the two authority channels), and two new facts on it, `impersonatedBy` and `credential`. `AIRouteCredentialKind` is the credential vocabulary: `session`, `api_key` or `oauth`.
- `@objectstack/runtime` fills both on every AI route. `impersonatedBy` is the session's impersonating administrator (`ExecutionContext.impersonatedBy`), carried as is; it is a fact the door judges, never the authorization subject, and absent when the user acts themselves. `credential` is `session` for a signed-in session whether its token rides in the cookie or in an `Authorization: Bearer` header, `api_key` for an API key, and `oauth` for an OAuth token or the in-process forward of an OAuth-connected agent; it is absent when the request recorded no admitting credential, which a door reads as "not a session". Ruled on #34184 (record 6942875153): Q1 A, Q2 A.

Nothing changes for an existing handler: both keys are new, and every other key of `req.user` keeps its value. The REST `/actions` and MCP `run_action` `ctx.user` are unchanged.
218 changes: 218 additions & 0 deletions packages/runtime/src/domains/ai-request-user-credential.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* #34184 — an AI route's `req.user` carries the session's `impersonatedBy`
* and the kind of credential that admitted the caller (`AIRouteUser` in
* `@objectstack/spec/contracts`).
*
* A door reserved to the person (an in-app pending action only the person the
* call ran as may decide) has to tell an impersonating administrator, or an
* API key, from the person. Before this, the route saw only "as whom" and had
* to read request headers for the rest.
*
* Ruled on the card (record 6942875153): Q1 A, the vocabulary stays
* `session | api_key | oauth` and a login session carried in an
* `Authorization: Bearer` header is `session`; Q2 A, `impersonatedBy` is
* carried to the door as is and the door judges it.
*
* ## Through `dispatch()` (the real identity step)
*
* - a session cookie: `credential: 'session'`, no `impersonatedBy` key;
* - an impersonated session: `credential: 'session'` and `impersonatedBy`
* naming the administrator, while `id` stays the impersonated user;
* - an API key: `credential: 'api_key'`, no `impersonatedBy` key, even with
* an impersonated session cookie riding beside it (the key admitted);
* - the same session token in an `Authorization: Bearer` header:
* `credential: 'session'`, the same user, the same `impersonatedBy`.
*
* The fake auth service plays better-auth's bearer plugin: it answers one
* session read for the session token whether the token arrives as the cookie
* or as a bearer header.
*
* ## At the handler (`handleAIRequest`)
*
* - an agent principal carrying OAuth scopes (an OAuth token, or the
* in-process forward credential): `credential: 'oauth'`;
* - an authenticated context with no admission recorded: no `credential`
* key, which the contract tells a door to read as "not a session";
* - a blank `impersonatedBy` adds no key.
*/

import { describe, expect, it, vi } from 'vitest';

// Paid at collection, not inside a case's clock (check:test-source-alias).
import '@objectstack/metadata';

import { hashApiKey } from '@objectstack/core';

import { HttpDispatcher, type HttpProtocolContext } from '../http-dispatcher.js';
import type { DomainHandlerDeps } from '../domain-handler-registry.js';
import { handleAIRequest } from './ai.js';

const ORIGIN = 'http://tenant.example';
const ROUTE = '/api/v1/ai/pending-actions/:id/approve';
const KEY = 'osk_ai_route_credential_pin_0001';
const KEY_OWNER = 'u_key_owner';
const PERSON = 'u_person';
const ADMIN = 'u_admin';
const OWN_TOKEN = 'sess_tok_own';
const IMPERSONATED_TOKEN = 'sess_tok_impersonated';

/** A data engine that knows one live API key, owned by `KEY_OWNER`. */
function engine() {
const keyHash = hashApiKey(KEY);
return {
find: vi.fn(async (object: string, q: any) => (
object === 'sys_api_key' && q?.where?.key === keyHash
? [{ id: 'key_1', key: keyHash, user_id: KEY_OWNER, revoked: false, scopes: '[]' }]
: object === 'sys_user' && (q?.where?.id === KEY_OWNER || q?.where?.id === PERSON)
? [{ id: q.where.id }]
: []
)),
getObjects: vi.fn().mockReturnValue({}),
registry: {
getObject: vi.fn().mockReturnValue(null),
getRegisteredTypes: vi.fn().mockReturnValue([]),
},
};
}

/** The session token a request presents, from the cookie or from a bearer header. */
function sessionTokenOf(headers: Headers): string | undefined {
const cookie = headers.get('cookie')?.match(/(?:^|;\s*)session=([^;]+)/)?.[1];
if (cookie) return cookie;
const bearer = headers.get('authorization')?.match(/^Bearer\s+(.+)$/i)?.[1];
return bearer && !bearer.startsWith('osk_') ? bearer : undefined;
}

/** One session read per token, whichever carrier brought it (better-auth's bearer plugin). */
function authService() {
const getSession = vi.fn(async ({ headers }: { headers: Headers }) => {
const token = sessionTokenOf(headers);
if (token === OWN_TOKEN) {
return { user: { id: PERSON }, session: { id: 'sess_own', userId: PERSON, token } };
}
if (token === IMPERSONATED_TOKEN) {
return { user: { id: PERSON }, session: { id: 'sess_imp', userId: PERSON, token, impersonatedBy: ADMIN } };
}
return null;
});
return { isAuthGateActive: () => false, getApi: async () => ({ getSession }) };
}

async function approveThroughDispatch(headers: Record<string, string>) {
const seen: { req?: any } = {};
const services: Record<string, unknown> = { objectql: engine(), auth: authService(), ai: {} };
const kernel: any = {
getState: () => 'running',
getService: (n: string) => services[n] ?? null,
getServiceAsync: async (n: string) => services[n] ?? null,
context: { getService: (n: string) => services[n] ?? null },
__aiRoutes: [{
method: 'POST',
path: ROUTE,
auth: true,
handler: async (req: any) => {
seen.req = req;
return { status: 200, body: { success: true, data: { ok: true } } };
},
}],
};
const dispatcher = new HttpDispatcher(kernel, undefined, { enforceProjectMembership: false });
(dispatcher as any).domainDeps.logger = { error: vi.fn(), warn: vi.fn(), info: vi.fn(), debug: vi.fn() };
const request = new Request(`${ORIGIN}/api/v1/ai/pending-actions/pa_1/approve`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...headers },
body: '{}',
});
const ctx: HttpProtocolContext = { request };
const result: any = await dispatcher.dispatch('POST', '/ai/pending-actions/pa_1/approve', {}, {}, ctx);
return { result, user: seen.req?.user };
}

describe('[#34184] AI route req.user — through dispatch()', () => {
it('a session cookie: credential `session`, no impersonatedBy key', async () => {
const { result, user } = await approveThroughDispatch({ cookie: `session=${OWN_TOKEN}` });
expect(result.response?.status).toBe(200);
expect(user).toMatchObject({ id: PERSON, userId: PERSON, credential: 'session' });
expect('impersonatedBy' in user).toBe(false);
});

it('an impersonated session: credential `session`, impersonatedBy names the administrator, id stays the user', async () => {
const { result, user } = await approveThroughDispatch({ cookie: `session=${IMPERSONATED_TOKEN}` });
expect(result.response?.status).toBe(200);
expect(user).toMatchObject({ id: PERSON, userId: PERSON, credential: 'session', impersonatedBy: ADMIN });
});

it('an API key: credential `api_key`, no impersonatedBy key', async () => {
const { result, user } = await approveThroughDispatch({ 'x-api-key': KEY });
expect(result.response?.status).toBe(200);
expect(user).toMatchObject({ id: KEY_OWNER, credential: 'api_key' });
expect('impersonatedBy' in user).toBe(false);
});

it('an API key beside an impersonated session cookie: the key admitted, so `api_key` and no impersonatedBy', async () => {
const { user } = await approveThroughDispatch({ 'x-api-key': KEY, cookie: `session=${IMPERSONATED_TOKEN}` });
expect(user).toMatchObject({ id: KEY_OWNER, credential: 'api_key' });
expect('impersonatedBy' in user).toBe(false);
});

it('the session token in an Authorization: Bearer header is the same session: `session`', async () => {
const { result, user } = await approveThroughDispatch({ authorization: `Bearer ${OWN_TOKEN}` });
expect(result.response?.status).toBe(200);
expect(user).toMatchObject({ id: PERSON, credential: 'session' });
expect('impersonatedBy' in user).toBe(false);
});

it('an impersonated session token in a bearer header carries impersonatedBy too', async () => {
const { user } = await approveThroughDispatch({ authorization: `Bearer ${IMPERSONATED_TOKEN}` });
expect(user).toMatchObject({ id: PERSON, credential: 'session', impersonatedBy: ADMIN });
});
});

/** Dispatch the route straight at the handler, under a hand-built request context. */
async function approveAtHandler(context: Partial<HttpProtocolContext>) {
const seen: { req?: any } = {};
const deps = {
resolveService: (async (_ctx: HttpProtocolContext, name: string) => (name === 'ai' ? {} : undefined)) as any,
getRegisteredAiRoutes: () => [{
method: 'POST',
path: ROUTE,
auth: true,
handler: async (req: any) => {
seen.req = req;
return { status: 200, body: { success: true } };
},
}],
getObjectQL: async () => undefined,
success: (data: any) => ({ status: 200, body: { success: true, data } }),
error: (message: string, httpStatus = 500) => ({ status: httpStatus, body: { success: false, error: { message } } }),
routeNotFound: (route: string) => ({ status: 404, body: { success: false, error: { code: 'ROUTE_NOT_FOUND', route } } }),
} as unknown as DomainHandlerDeps;
await handleAIRequest(deps, '/ai/pending-actions/pa_1/approve', 'POST', {}, {}, context as HttpProtocolContext);
return seen.req?.user;
}

describe('[#34184] AI route req.user — at the handler', () => {
it('an agent principal carrying OAuth scopes: credential `oauth`', async () => {
const user = await approveAtHandler({
executionContext: { userId: PERSON, principalKind: 'agent', oauthScopes: ['data:read'] } as any,
});
expect(user).toMatchObject({ id: PERSON, credential: 'oauth' });
});

it('an authenticated context with no admission recorded carries no credential key', async () => {
const user = await approveAtHandler({ executionContext: { userId: PERSON } as any });
expect(user).toMatchObject({ id: PERSON });
expect('credential' in user).toBe(false);
});

it('a blank impersonatedBy adds no key', async () => {
const user = await approveAtHandler({
executionContext: { userId: PERSON, impersonatedBy: ' ' } as any,
admission: { credential: 'session', authGate: undefined },
});
expect(user).toMatchObject({ id: PERSON, credential: 'session' });
expect('impersonatedBy' in user).toBe(false);
});
});
37 changes: 32 additions & 5 deletions packages/runtime/src/domains/ai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,10 @@ import {
} from '@objectstack/core';
import { isServiceServeable } from '../service-serveable.js';
import { actorUserFromExecutionContext, resolveActorDisplayName } from '../security/actor-user.js';
import { admittingCredentialKind } from '../security/admitting-credential.js';
import { capabilityUnavailable } from './unavailable.js';
import { buildApiError } from '../error-envelope.js';
import type { IAIService } from '@objectstack/spec/contracts';
import type { AIRouteUser, IAIService } from '@objectstack/spec/contracts';
import type { HttpProtocolContext, HttpDispatcherResult } from '../http-dispatcher.js';
import type { DomainHandlerDeps, DomainRoute } from '../domain-handler-registry.js';
import { readDispatchedBody } from '../deferred-request-body.js';
Expand Down Expand Up @@ -268,15 +269,41 @@ export async function handleAIRequest(deps: DomainHandlerDeps, subPath: string,
// principal: an AI route handler distinguishes "no caller" by the
// absence of `user`, and this route only reaches anonymous when the
// deployment does not require auth.
const user = ec?.userId
? actorUserFromExecutionContext(
//
// [#34184, ruling 6942875153 Q1 A · Q2 A] Two facts are the AI
// route's own, beside the actor envelope (`AIRouteUser` in
// `@objectstack/spec/contracts`), so a door reserved to the person can
// tell who is acting and how they came in without reading headers:
//
// - `impersonatedBy` — `ec.impersonatedBy` as the shared resolver set
// it off the session read, carried as is. A fact for the consuming
// door to judge; nothing here reads it, and `id` stays the
// impersonated user.
// - `credential` — the ONE reading the membership gate and the
// api-action forward take (`admittingCredentialKind`): a session
// is `session` whether its token rode in the cookie or in an
// `Authorization: Bearer` header.
//
// Both keys are ABSENT, never `undefined`, when there is nothing to
// say, so `'impersonatedBy' in user` answers "an administrator is
// acting" with no second reading.
let user: AIRouteUser | undefined;
if (ec?.userId) {
const actor = actorUserFromExecutionContext(
ec,
await resolveActorDisplayName(
() => deps.getObjectQL(context, context?.environmentId),
ec,
),
)
: undefined;
);
const impersonatedBy = typeof ec.impersonatedBy === 'string' ? ec.impersonatedBy.trim() : '';
const credential = admittingCredentialKind(context);
user = {
...actor,
...(impersonatedBy ? { impersonatedBy } : {}),
...(credential ? { credential } : {}),
};
}

const result = await route.handler({
body: admittedBody,
Expand Down
8 changes: 7 additions & 1 deletion packages/runtime/src/security/admitting-credential.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

import type { AIRouteCredentialKind } from '@objectstack/spec/contracts';

/**
* Which kind of credential admitted a request's caller: the one reading the
* dispatcher's environment-membership gate and the api-action forward both
Expand All @@ -10,8 +12,12 @@
* endpoint alone, and an in-process forward of it carries them too);
* - else what the identity step's admission recorded: `api_key` or `session`;
* - `undefined` when it recorded nothing (an anonymous caller).
*
* The three values are the spec's {@link AIRouteCredentialKind}, the one
* vocabulary an AI route's `req.user.credential` carries too (#34184), so a
* gate here and a door there cannot spell a credential two ways.
*/
export type AdmittingCredentialKind = 'session' | 'api_key' | 'oauth';
export type AdmittingCredentialKind = AIRouteCredentialKind;

/** The two request facts {@link admittingCredentialKind} reads. */
export interface AdmittingCredentialFacts {
Expand Down
2 changes: 2 additions & 0 deletions packages/spec/api-surface/contracts.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
"AIRequestOptions (interface)",
"AIRequestOptionsWithTools (type)",
"AIResult (interface)",
"AIRouteCredentialKind (type)",
"AIRouteUser (interface)",
"AIStreamEvent (type)",
"AIToolCall (type)",
"AIToolDefinition (interface)",
Expand Down
2 changes: 2 additions & 0 deletions packages/spec/export-origins/contracts.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
"AIRequestOptions": "src/contracts/ai-service.ts#AIRequestOptions (interface)",
"AIRequestOptionsWithTools": "src/contracts/ai-service.ts#AIRequestOptionsWithTools (type)",
"AIResult": "src/contracts/ai-service.ts#AIResult (interface)",
"AIRouteCredentialKind": "src/contracts/ai-service.ts#AIRouteCredentialKind (type)",
"AIRouteUser": "src/contracts/ai-service.ts#AIRouteUser (interface)",
"AIStreamEvent": "src/contracts/ai-service.ts#AIStreamEvent (type)",
"AIToolCall": "src/contracts/ai-service.ts#AIToolCall (type)",
"AIToolDefinition": "src/contracts/ai-service.ts#AIToolDefinition (interface)",
Expand Down
Loading
Loading