Skip to content

The open-source agent harness - the runtime layer that turns an LLM into a working agent.

[AuthZ: 3/N] enforce external authorizer on agent access (#586)

Chirag Jain4b1aa554d249
diff --git a/.changeset/enforce-agent-authorizer.md b/.changeset/enforce-agent-authorizer.md
new file mode 100644
index 000000000..d6835f50e
--- /dev/null
+++ b/.changeset/enforce-agent-authorizer.md
@@ -0,0 +1,5 @@
+---
+'@truefoundry/trueforge': minor
+---
+
+Enforce external agent authorization on agent list, get, snippets, update, delete, and referenced-agent use.
diff --git a/.github/fern/generators.yml b/.github/fern/generators.yml
index 5eba78c0c..eecb97c80 100644
--- a/.github/fern/generators.yml
+++ b/.github/fern/generators.yml
@@ -66,17 +66,17 @@ groups:
# Generated source is not exactOptionalPropertyTypes-clean, and pointing
# `types` at src/ would pull it into every consumer's tsc program.
exports:
- ".":
- "trueforge-dev":
- types: "./dist/cjs/index.d.ts"
- default: "./src/index.ts"
+ '.':
+ 'trueforge-dev':
+ types: './dist/cjs/index.d.ts'
+ default: './src/index.ts'
import:
- types: "./dist/esm/index.d.mts"
- default: "./dist/esm/index.mjs"
+ types: './dist/esm/index.d.mts'
+ default: './dist/esm/index.mjs'
require:
- types: "./dist/cjs/index.d.ts"
- default: "./dist/cjs/index.js"
- default: "./dist/cjs/index.js"
+ types: './dist/cjs/index.d.ts'
+ default: './dist/cjs/index.js'
+ default: './dist/cjs/index.js'
allowExtraFields: true
allowCustomFetcher: true
enableInlineTypes: false
diff --git a/.github/fern/openapi/openapi.json b/.github/fern/openapi/openapi.json
index b694ef13f..ecb50ae24 100644
--- a/.github/fern/openapi/openapi.json
+++ b/.github/fern/openapi/openapi.json
@@ -5282,7 +5282,7 @@
},
"/api/v1/agents/{agent_id}": {
"delete": {
- "description": "Delete a configured agent by immutable id. Idempotent if already gone.",
+ "description": "Delete a configured agent by immutable id.",
"parameters": [
{
"description": "Immutable agent identifier.",
@@ -5317,6 +5317,16 @@
}
},
"description": "OIDC is configured and the request has no valid session cookie."
+ },
+ "404": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Agent not found."
}
},
"summary": "Delete an agent",
@@ -6371,7 +6381,17 @@
}
}
},
- "description": "Unknown agent or invalid cron."
+ "description": "Invalid cron or timezone."
+ },
+ "404": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Named agent not found."
},
"409": {
"content": {
@@ -7460,7 +7480,7 @@
}
}
},
- "description": "Session or prior turn not found."
+ "description": "Session, prior turn, or referenced agent not found."
},
"412": {
"content": {
diff --git a/docs/openapi.json b/docs/openapi.json
index b694ef13f..ecb50ae24 100644
--- a/docs/openapi.json
+++ b/docs/openapi.json
@@ -5282,7 +5282,7 @@
},
"/api/v1/agents/{agent_id}": {
"delete": {
- "description": "Delete a configured agent by immutable id. Idempotent if already gone.",
+ "description": "Delete a configured agent by immutable id.",
"parameters": [
{
"description": "Immutable agent identifier.",
@@ -5317,6 +5317,16 @@
}
},
"description": "OIDC is configured and the request has no valid session cookie."
+ },
+ "404": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Agent not found."
}
},
"summary": "Delete an agent",
@@ -6371,7 +6381,17 @@
}
}
},
- "description": "Unknown agent or invalid cron."
+ "description": "Invalid cron or timezone."
+ },
+ "404": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Named agent not found."
},
"409": {
"content": {
@@ -7460,7 +7480,7 @@
}
}
},
- "description": "Session or prior turn not found."
+ "description": "Session, prior turn, or referenced agent not found."
},
"412": {
"content": {
diff --git a/packages/trueforge-sdk/reference.md b/packages/trueforge-sdk/reference.md
index 969921470..caa96468f 100644
--- a/packages/trueforge-sdk/reference.md
+++ b/packages/trueforge-sdk/reference.md
@@ -277,7 +277,7 @@ await client.agents.update("agent_id", {
<dl>
<dd>
-Delete a configured agent by immutable id. Idempotent if already gone.
+Delete a configured agent by immutable id.
</dd>
</dl>
</dd>
diff --git a/packages/trueforge-sdk/src/api/resources/agents/client/Client.ts b/packages/trueforge-sdk/src/api/resources/agents/client/Client.ts
index 1a7da9886..fbf595c8c 100644
--- a/packages/trueforge-sdk/src/api/resources/agents/client/Client.ts
+++ b/packages/trueforge-sdk/src/api/resources/agents/client/Client.ts
@@ -437,12 +437,13 @@ export class AgentsClient {
}
/**
- * Delete a configured agent by immutable id. Idempotent if already gone.
+ * Delete a configured agent by immutable id.
*
* @param {string} agent_id - Immutable agent identifier.
* @param {AgentsClient.RequestOptions} requestOptions - Request-specific configuration.
*
* @throws {@link TrueForge.UnauthorizedError}
+ * @throws {@link TrueForge.NotFoundError}
* @throws {@link errors.TrueForgeError}
* @throws {@link errors.TrueForgeTimeoutError}
*
@@ -507,6 +508,17 @@ export class AgentsClient {
}),
_response.rawResponse,
);
+ case 404:
+ throw new TrueForge.NotFoundError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
default:
throw new errors.TrueForgeError({
statusCode: _response.error.statusCode,
diff --git a/packages/trueforge-sdk/src/api/resources/schedules/client/Client.ts b/packages/trueforge-sdk/src/api/resources/schedules/client/Client.ts
index 00a56f546..ee0001d92 100644
--- a/packages/trueforge-sdk/src/api/resources/schedules/client/Client.ts
+++ b/packages/trueforge-sdk/src/api/resources/schedules/client/Client.ts
@@ -144,6 +144,7 @@ export class SchedulesClient {
* @param {SchedulesClient.RequestOptions} requestOptions - Request-specific configuration.
*
* @throws {@link TrueForge.BadRequestError}
+ * @throws {@link TrueForge.NotFoundError}
* @throws {@link TrueForge.ConflictError}
* @throws {@link errors.TrueForgeError}
* @throws {@link errors.TrueForgeTimeoutError}
@@ -227,6 +228,17 @@ export class SchedulesClient {
}),
_response.rawResponse,
);
+ case 404:
+ throw new TrueForge.NotFoundError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
case 409:
throw new TrueForge.ConflictError(
serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
diff --git a/packages/trueforge-sdk/tests/wire/agents.test.ts b/packages/trueforge-sdk/tests/wire/agents.test.ts
index b154eb84f..c4b00174b 100644
--- a/packages/trueforge-sdk/tests/wire/agents.test.ts
+++ b/packages/trueforge-sdk/tests/wire/agents.test.ts
@@ -502,4 +502,23 @@ describe("AgentsClient", () => {
return await client.agents.delete("agent_id");
}).rejects.toThrow(TrueForgeTypes.UnauthorizedError);
});
+
+ test("delete (3)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
+
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .delete("/api/v1/agents/agent_id")
+ .respondWith()
+ .statusCode(404)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.agents.delete("agent_id");
+ }).rejects.toThrow(TrueForgeTypes.NotFoundError);
+ });
});
diff --git a/packages/trueforge-sdk/tests/wire/schedules.test.ts b/packages/trueforge-sdk/tests/wire/schedules.test.ts
index 11627f819..51bf027bc 100644
--- a/packages/trueforge-sdk/tests/wire/schedules.test.ts
+++ b/packages/trueforge-sdk/tests/wire/schedules.test.ts
@@ -187,6 +187,33 @@ describe("SchedulesClient", () => {
const rawRequestBody = { agent_name: "xy", manifest: { cron: "cron", task: "x" }, name: "xy" };
const rawResponseBody = { error: { message: "message" } };
+ server
+ .mockEndpoint()
+ .post("/api/v1/schedules")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(404)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.schedules.create({
+ agentName: "xy",
+ manifest: {
+ cron: "cron",
+ task: "x",
+ },
+ name: "xy",
+ });
+ }).rejects.toThrow(TrueForgeTypes.NotFoundError);
+ });
+
+ test("create (4)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
+ const rawRequestBody = { agent_name: "xy", manifest: { cron: "cron", task: "x" }, name: "xy" };
+ const rawResponseBody = { error: { message: "message" } };
+
server
.mockEndpoint()
.post("/api/v1/schedules")
diff --git a/packages/trueforge/.env.example b/packages/trueforge/.env.example
index 3d97eafca..a9f646a15 100644
--- a/packages/trueforge/.env.example
+++ b/packages/trueforge/.env.example
@@ -23,9 +23,10 @@ PORT=8790
## When unset, the catalog inlined at build time (catalog/model-catalog.yaml) is used.
# MODEL_CATALOG_PATH=/path/to/model-catalog.yaml
-## TrueFoundry mode. When set, GET /models lists tenant-enabled chat models from the TrueFoundry
-## ServiceFoundry server (caller token) and turns call the tenant's default AI Gateway. Unset = local
-## API-key model catalog. Mutually exclusive with OIDC.
+## TrueFoundry mode (STANDALONE=false only; ignored when STANDALONE=true). When set, GET /models
+## lists tenant-enabled chat models from the TrueFoundry ServiceFoundry server (caller token) and
+## turns call the tenant's default AI Gateway. Unset = local API-key model catalog. Mutually
+## exclusive with OIDC.
# TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL=https://servicefoundry-server.truefoundry.svc.cluster.local
## Max ms for non-agent ServiceFoundry HTTP calls. Default 10000.
# TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_TIMEOUT_MS=10000
diff --git a/packages/trueforge/src/apis/agentAccess.ts b/packages/trueforge/src/apis/agentAccess.ts
new file mode 100644
index 000000000..52d60c6be
--- /dev/null
+++ b/packages/trueforge/src/apis/agentAccess.ts
@@ -0,0 +1,43 @@
+/**
+ * Agent store reads narrowed by the authorizer, shared by the agent, session,
+ * and schedule handlers. Lives in the API layer because stores must stay free
+ * of request identity.
+ */
+import type { AgentAction, Authorizer } from '../auth/authorizer';
+import type { RequestContext } from '../auth/identity';
+import type { AgentRecord, IAgentStore } from '../db/agentStore';
+
+/** The agent only when the caller may act on it, so callers answer 404 for missing and forbidden alike. */
+export async function agentIfAccessible(input: {
+ authorizer: Authorizer;
+ context: RequestContext;
+ action: AgentAction;
+ agent: AgentRecord | undefined;
+}): Promise<AgentRecord | undefined> {
+ if (input.agent === undefined) {
+ return undefined;
+ }
+ const allowed = await input.authorizer.canAccessAgent({
+ context: input.context,
+ action: input.action,
+ agent: input.agent,
+ });
+ return allowed ? input.agent : undefined;
+}
+
+/** Resolve the authorizer list scope against the agent store without extra store filters. */
+export async function listAccessibleAgents<TTransaction>(input: {
+ store: IAgentStore<TTransaction>;
+ context: RequestContext;
+ authorizer: Authorizer;
+ action: AgentAction;
+}): Promise<AgentRecord[]> {
+ const access = await input.authorizer.listAgentAccess({ context: input.context, action: input.action });
+ if (access.kind === 'all') {
+ return input.store.listAgents({ tenant_id: input.context.tenant_id });
+ }
+ return input.store.listAgents({
+ tenant_id: input.context.tenant_id,
+ external_ids: access.agent_external_ids,
+ });
+}
diff --git a/packages/trueforge/src/apis/agents.ts b/packages/trueforge/src/apis/agents.ts
index 02fc2f315..0f5f4b123 100644
--- a/packages/trueforge/src/apis/agents.ts
+++ b/packages/trueforge/src/apis/agents.ts
@@ -4,6 +4,7 @@
import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';
import type { AgentSpec } from '@truefoundry/trueforge-core/agent-session';
import type { Context } from 'hono';
+import type { Authorizer } from '../auth/authorizer';
import { createdBySubjectFromRequestContext, type ResolveRequestContext } from '../auth/identity';
import {
AgentExternalIdConflictError,
@@ -26,6 +27,7 @@ import {
} from '../routes/agentRoutes';
import { validateAgentSpec } from '../runtime/sessionResources';
import { type Agent, type CreateAgentRequest } from '../schemas/agent';
+import { agentIfAccessible, listAccessibleAgents } from './agentAccess';
import { buildAgentCodeSnippets } from './agentCodeSnippets';
export interface AgentsRouterDeps<TTransaction> {
@@ -36,6 +38,7 @@ export interface AgentsRouterDeps<TTransaction> {
sandboxProviderStore: ISandboxProviderStore<TTransaction>;
withTransaction: WithTransaction<TTransaction>;
resolveRequestContext: ResolveRequestContext;
+ authorizer: Authorizer;
}
/** Wire view: identity columns plus nested manifest. */
@@ -75,7 +78,12 @@ async function validateManifest<TTransaction>({
export function createAgentsRouter<TTransaction>(deps: AgentsRouterDeps<TTransaction>) {
const listHandler: RouteHandler<typeof listAgentsRoute> = async c => {
const requestContext = deps.resolveRequestContext(c);
- const records = await deps.resolveAgentStore(c).listAgents({ tenant_id: requestContext.tenant_id });
+ const records = await listAccessibleAgents({
+ store: deps.resolveAgentStore(c),
+ context: requestContext,
+ authorizer: deps.authorizer,
+ action: 'read',
+ });
return c.json({ data: records.map(toWireAgent) }, 200);
};
@@ -109,9 +117,11 @@ export function createAgentsRouter<TTransaction>(deps: AgentsRouterDeps<TTransac
const getHandler: RouteHandler<typeof getAgentRoute> = async c => {
const { agent_id: agentId } = c.req.valid('param');
const requestContext = deps.resolveRequestContext(c);
- const record = await deps.resolveAgentStore(c).getAgent({
- tenant_id: requestContext.tenant_id,
- id: agentId,
+ const record = await agentIfAccessible({
+ authorizer: deps.authorizer,
+ context: requestContext,
+ action: 'read',
+ agent: await deps.resolveAgentStore(c).getAgent({ tenant_id: requestContext.tenant_id, id: agentId }),
});
if (record === undefined) {
return c.json({ error: { message: `Agent not found: ${agentId}` } }, 404);
@@ -122,9 +132,11 @@ export function createAgentsRouter<TTransaction>(deps: AgentsRouterDeps<TTransac
const getCodeSnippetsHandler: RouteHandler<typeof getAgentCodeSnippetsRoute> = async c => {
const { agent_id: agentId } = c.req.valid('param');
const requestContext = deps.resolveRequestContext(c);
- const record = await deps.resolveAgentStore(c).getAgent({
- tenant_id: requestContext.tenant_id,
- id: agentId,
+ const record = await agentIfAccessible({
+ authorizer: deps.authorizer,
+ context: requestContext,
+ action: 'read',
+ agent: await deps.resolveAgentStore(c).getAgent({ tenant_id: requestContext.tenant_id, id: agentId }),
});
if (record === undefined) {
return c.json({ error: { message: `Agent not found: ${agentId}` } }, 404);
@@ -143,6 +155,15 @@ export function createAgentsRouter<TTransaction>(deps: AgentsRouterDeps<TTransac
const deleteHandler: RouteHandler<typeof deleteAgentRoute> = async c => {
const { agent_id: agentId } = c.req.valid('param');
const requestContext = deps.resolveRequestContext(c);
+ const existing = await agentIfAccessible({
+ authorizer: deps.authorizer,
+ context: requestContext,
+ action: 'manage',
+ agent: await deps.resolveAgentStore(c).getAgent({ tenant_id: requestContext.tenant_id, id: agentId }),
+ });
+ if (existing === undefined) {
+ return c.json({ error: { message: `Agent not found: ${agentId}` } }, 404);
+ }
await deps.resolveAgentStore(c).deleteAgent({ tenant_id: requestContext.tenant_id, id: agentId });
return c.json({}, 200);
};
@@ -151,6 +172,15 @@ export function createAgentsRouter<TTransaction>(deps: AgentsRouterDeps<TTransac
const { agent_id: agentId } = c.req.valid('param');
const body = c.req.valid('json');
const requestContext = deps.resolveRequestContext(c);
+ const existing = await agentIfAccessible({
+ authorizer: deps.authorizer,
+ context: requestContext,
+ action: 'manage',
+ agent: await deps.resolveAgentStore(c).getAgent({ tenant_id: requestContext.tenant_id, id: agentId }),
+ });
+ if (existing === undefined) {
+ return c.json({ error: { message: `Agent not found: ${agentId}` } }, 404);
+ }
const manifest = await validateManifest({
spec: body.manifest,
deps,
diff --git a/packages/trueforge/src/apis/schedules.ts b/packages/trueforge/src/apis/schedules.ts
index d03cd542f..72e59cd56 100644
--- a/packages/trueforge/src/apis/schedules.ts
+++ b/packages/trueforge/src/apis/schedules.ts
@@ -4,6 +4,7 @@
import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';
import { InvalidPageTokenError, type Sessions } from '@truefoundry/trueforge-core/agent-session';
import type { Context } from 'hono';
+import type { Authorizer } from '../auth/authorizer';
import {
createdBySubjectFromRequestContext,
hasAdminRole,
@@ -38,15 +39,17 @@ import {
type ScheduleManifest,
type ScheduleRun,
} from '../schemas/schedule';
+import { agentIfAccessible } from './agentAccess';
import { getTurnExecutionError, startTurnInProcess, type BeginTurnExecutionDeps } from './turns';
export interface SchedulesRouterDeps<TTransaction> {
scheduleStore: IScheduleStore<TTransaction>;
resolveAgentStore: (c: Context) => IAgentStore<TTransaction>;
sessions: Sessions;
- turnDeps: BeginTurnExecutionDeps;
+ resolveTurnDeps: (c: Context) => BeginTurnExecutionDeps;
withTransaction: WithTransaction<TTransaction>;
resolveRequestContext: ResolveRequestContext;
+ authorizer: Authorizer;
}
function toWireSchedule(record: ScheduleRecord): Schedule {
@@ -178,6 +181,20 @@ export function createSchedulesRouter<TTransaction>(deps: SchedulesRouterDeps<TT
return c.json({ error: { message: FORBIDDEN_SCHEDULE_ACCESS } }, 403);
}
+ // Schedule ownership alone must not invoke an agent the caller cannot read.
+ const agent = await agentIfAccessible({
+ authorizer: deps.authorizer,
+ context: requestContext,
+ action: 'read',
+ agent: await deps.resolveAgentStore(c).getAgent({
+ tenant_id: requestContext.tenant_id,
+ name: schedule.agent_name,
+ }),
+ });
+ if (agent === undefined) {
+ return c.json({ error: { message: `Agent not found: ${schedule.agent_name}` } }, 404);
+ }
+
const now = new Date();
let run: ScheduleRunRecord;
try {
@@ -203,7 +220,7 @@ export function createSchedulesRouter<TTransaction>(deps: SchedulesRouterDeps<TT
sessions: deps.sessions,
agentStore: deps.resolveAgentStore(c),
startTurn: async turnParams => {
- await startTurnInProcess({ ...turnParams, deps: deps.turnDeps });
+ await startTurnInProcess({ ...turnParams, deps: deps.resolveTurnDeps(c) });
},
});
} catch (error) {
@@ -236,12 +253,14 @@ export function createSchedulesRouter<TTransaction>(deps: SchedulesRouterDeps<TT
validateManifest(body.manifest);
- const agent = await deps.resolveAgentStore(c).getAgent({
- tenant_id: requestContext.tenant_id,
- name: body.agent_name,
+ const agent = await agentIfAccessible({
+ authorizer: deps.authorizer,
+ context: requestContext,
+ action: 'read',
+ agent: await deps.resolveAgentStore(c).getAgent({ tenant_id: requestContext.tenant_id, name: body.agent_name }),
});
if (agent === undefined) {
- return c.json({ error: { message: `Agent not found: ${body.agent_name}` } }, 400);
+ return c.json({ error: { message: `Agent not found: ${body.agent_name}` } }, 404);
}
let record: ScheduleRecord;
diff --git a/packages/trueforge/src/apis/sessions.ts b/packages/trueforge/src/apis/sessions.ts
index 9848656a2..2ae0dd260 100644
--- a/packages/trueforge/src/apis/sessions.ts
+++ b/packages/trueforge/src/apis/sessions.ts
@@ -21,6 +21,7 @@ import type { Context } from 'hono';
import type { RedisClientType } from 'redis';
import type { Logger } from 'winston';
import { z } from 'zod';
+import type { Authorizer } from '../auth/authorizer';
import { createdBySubjectFromRequestContext, type ResolveRequestContext } from '../auth/identity';
import configuration from '../config';
import type { IAgentStore } from '../db/agentStore';
@@ -43,6 +44,7 @@ import { executorFromTurnId } from '../runtime/peeringIds';
import { validateAgentSpec } from '../runtime/sessionResources';
import { isSessionAgentNameRef, type Session } from '../schemas/session';
import { newId } from '../utils/id';
+import { agentIfAccessible } from './agentAccess';
/** Request-reply path a replica serves to cancel a turn it owns. */
export const SESSIONS_CANCEL_PATH = 'sessions/cancel';
@@ -81,6 +83,7 @@ export interface SessionsRouterDeps {
requestReplyRouter: RequestReplyRouter;
resolveRequestContext: ResolveRequestContext;
logger: Logger;
+ authorizer: Authorizer;
}
function cancelTurnOnThisExecutor(
@@ -233,6 +236,7 @@ type InternalSessionsRouterDeps = Pick<
| 'resolveAgentStore'
| 'sandboxProviderStore'
| 'resolveRequestContext'
+ | 'authorizer'
>;
function createGetOrCreateSessionByExternalIdHandler(
@@ -260,9 +264,14 @@ function createGetOrCreateSessionByExternalIdHandler(
let agent: SessionRecord['agent'];
if (isSessionAgentNameRef(body.agent)) {
- const named = await deps.resolveAgentStore(c).getAgent({
- tenant_id: requestContext.tenant_id,
- name: body.agent.name,
+ const named = await agentIfAccessible({
+ authorizer: deps.authorizer,
+ context: requestContext,
+ action: 'read',
+ agent: await deps.resolveAgentStore(c).getAgent({
+ tenant_id: requestContext.tenant_id,
+ name: body.agent.name,
+ }),
});
if (named === undefined) {
return c.json({ error: { message: `Agent not found: ${body.agent.name}` } }, 404);
@@ -314,9 +323,14 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {
const requestContext = deps.resolveRequestContext(c);
if (isSessionAgentNameRef(body.agent)) {
- const agent = await deps.resolveAgentStore(c).getAgent({
- tenant_id: requestContext.tenant_id,
- name: body.agent.name,
+ const agent = await agentIfAccessible({
+ authorizer: deps.authorizer,
+ context: requestContext,
+ action: 'read',
+ agent: await deps.resolveAgentStore(c).getAgent({
+ tenant_id: requestContext.tenant_id,
+ name: body.agent.name,
+ }),
});
if (agent === undefined) {
return c.json({ error: { message: `Agent not found: ${body.agent.name}` } }, 404);
diff --git a/packages/trueforge/src/apis/turns.ts b/packages/trueforge/src/apis/turns.ts
index b4ca00eba..efe40a574 100644
--- a/packages/trueforge/src/apis/turns.ts
+++ b/packages/trueforge/src/apis/turns.ts
@@ -29,6 +29,7 @@ import type { Context } from 'hono';
import { HTTPException } from 'hono/http-exception';
import { streamSSE } from 'hono/streaming';
import type { Logger } from 'winston';
+import type { Authorizer } from '../auth/authorizer';
import type { ResolveRequestContext } from '../auth/identity';
import configuration from '../config';
import type { IAgentStore } from '../db/agentStore';
@@ -112,12 +113,13 @@ export interface TurnsRouterDeps {
sandboxProviderStore: ISandboxProviderStore;
logger: Logger;
resolveRequestContext: ResolveRequestContext;
+ authorizer: Authorizer;
}
/**
- * Deps needed to create a turn and drain events in-process (no HTTP). Unlike the HTTP path, this
- * carries already-resolved `modelProviderStore` / `mcpServerStore` / `agentStore` (the scheduler has no request
- * context to resolve them).
+ * Deps needed to create a turn and drain events in-process (no HTTP). Carries already-resolved
+ * `modelProviderStore` / `mcpServerStore` / `agentStore`, so callers must resolve them from the
+ * caller's request context to keep TrueFoundry mode token-bound.
*/
export type BeginTurnExecutionDeps = Pick<
TurnsRouterDeps,
@@ -713,6 +715,25 @@ export function createTurnsRouter(deps: TurnsRouterDeps) {
return c.json({ error: { message: FORBIDDEN_CREATE_TURN } }, 403);
}
+ if (session.record.agent.type === 'reference') {
+ const agentId = session.record.agent.id;
+ const agent = await deps.resolveAgentStore(c).getAgent({
+ tenant_id: requestContext.tenant_id,
+ id: agentId,
+ });
+ if (agent === undefined) {
+ return c.json({ error: { message: `Agent not found: ${agentId}` } }, 422);
+ }
+ const canReadAgent = await deps.authorizer.canAccessAgent({
+ context: requestContext,
+ action: 'read',
+ agent,
+ });
+ if (!canReadAgent) {
+ return c.json({ error: { message: `Agent not found: ${agentId}` } }, 404);
+ }
+ }
+
const turnParams = {
session,
input: body.input,
diff --git a/packages/trueforge/src/app.ts b/packages/trueforge/src/app.ts
index e3a6b7ffd..361a0ec66 100644
--- a/packages/trueforge/src/app.ts
+++ b/packages/trueforge/src/app.ts
@@ -31,7 +31,7 @@ import type { McpCatalog } from './catalog/McpCatalog';
import type { ModelCatalog } from './catalog/ModelCatalog';
import type { SandboxCatalog } from './catalog/SandboxCatalog';
import type { SkillCatalog } from './catalog/SkillCatalog';
-import configuration, { getTrueForgeMode, TrueForgeMode } from './config';
+import configuration, { getTrueForgeAuthMode, TrueForgeAuthMode } from './config';
import type { IAgentStore } from './db/agentStore';
import type { IMcpServerWithAuthStore } from './db/mcpServerStore';
import type { IModelProviderStore } from './db/modelProviderStore';
@@ -166,21 +166,15 @@ export interface ServerDeps<TTransaction> {
mcpCatalog: McpCatalog;
skillCatalog: SkillCatalog;
sandboxCatalog: SandboxCatalog;
+ /** Per-request store: DB singleton, or a token-bound TrueFoundry store in TrueFoundry mode. */
+ resolveModelProviderStore: (c: Context) => IModelProviderStore<TTransaction>;
/**
* Per-request store: DB singleton, or a token-bound TrueFoundry store in TrueFoundry mode.
- * Called without a context (e.g. the scheduler) it returns the DB persistence store.
- */
- resolveModelProviderStore: (c?: Context) => IModelProviderStore<TTransaction>;
- /**
- * Per-request store: DB singleton, or a token-bound TrueFoundry store in TrueFoundry mode.
- * Called without a context (e.g. the scheduler / OAuth callback) it returns the DB persistence store.
+ * The unauthenticated OAuth callback has no context and gets the DB persistence store.
*/
resolveMcpServerStore: (c?: Context) => IMcpServerWithAuthStore<TTransaction>;
- /**
- * Per-request store: DB singleton, or a token-bound TrueFoundry decorator in TrueFoundry mode.
- * Called without a context (e.g. the scheduler) it returns the DB persistence store.
- */
- resolveAgentStore: (c?: Context) => IAgentStore<TTransaction>;
+ /** Per-request store: DB singleton, or a token-bound TrueFoundry decorator in TrueFoundry mode. */
+ resolveAgentStore: (c: Context) => IAgentStore<TTransaction>;
withTransaction: WithTransaction<TTransaction>;
tokenStore: IOAuthTokenStore<TTransaction>;
skillStore: ISkillStore<TTransaction>;
@@ -209,7 +203,7 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
const app = new OpenAPIHono({ defaultHook: zodValidationHook });
const authMiddleware = createAuthMiddleware(deps.authenticator);
const adminAuthMiddleware = createAdminAuthMiddleware(deps.authenticator);
- const authEnabled = getTrueForgeMode() !== TrueForgeMode.Standalone;
+ const authEnabled = getTrueForgeAuthMode() !== TrueForgeAuthMode.Standalone;
if (configuration.ACCESS_LOGS) {
app.use('*', createAccessLogMiddleware(deps.logger));
@@ -309,6 +303,7 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
sandboxProviderStore: deps.sandboxProviderStore,
withTransaction: deps.withTransaction,
resolveRequestContext,
+ authorizer: deps.authorizer,
}),
authMiddleware,
),
@@ -320,18 +315,19 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
scheduleStore: deps.scheduleStore,
resolveAgentStore: deps.resolveAgentStore,
sessions: deps.sessions,
- turnDeps: {
+ resolveTurnDeps: c => ({
activeTurns: deps.activeTurns,
eventSubscriptions: deps.eventSubscriptions,
- modelProviderStore: deps.resolveModelProviderStore(),
- mcpServerStore: deps.resolveMcpServerStore(),
+ modelProviderStore: deps.resolveModelProviderStore(c),
+ mcpServerStore: deps.resolveMcpServerStore(c),
skillStore: deps.skillStore,
- agentStore: deps.resolveAgentStore(),
+ agentStore: deps.resolveAgentStore(c),
sandboxProviderStore: deps.sandboxProviderStore,
logger: deps.logger,
- },
+ }),
withTransaction: deps.withTransaction,
resolveRequestContext,
+ authorizer: deps.authorizer,
}),
authMiddleware,
),
@@ -363,6 +359,7 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
resolveAgentStore: deps.resolveAgentStore,
sandboxProviderStore: deps.sandboxProviderStore,
resolveRequestContext,
+ authorizer: deps.authorizer,
}),
authMiddleware,
),
@@ -393,6 +390,7 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
requestReplyRouter: deps.requestReplyRouter,
resolveRequestContext,
logger: deps.logger,
+ authorizer: deps.authorizer,
}),
authMiddleware,
),
@@ -412,6 +410,7 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
sandboxProviderStore: deps.sandboxProviderStore,
logger: deps.logger,
resolveRequestContext,
+ authorizer: deps.authorizer,
}),
authMiddleware,
),
diff --git a/packages/trueforge/src/auth/createAuthenticator.ts b/packages/trueforge/src/auth/createAuthenticator.ts
index f6c4156ed..281198888 100644
--- a/packages/trueforge/src/auth/createAuthenticator.ts
+++ b/packages/trueforge/src/auth/createAuthenticator.ts
@@ -1,25 +1,23 @@
-import { TrueForgeMode } from '../config';
+import { TrueForgeAuthMode } from '../config';
import type { TrueFoundryServiceFoundryServerClient } from '../truefoundry/TrueFoundryServiceFoundryServerClient';
import type { Authenticator } from './authenticator';
import { OidcAuthenticator } from './oidcAuthenticator';
import { StandaloneAuthenticator } from './standaloneAuthenticator';
import { TrueFoundryAuthenticator } from './trueFoundryAuthenticator';
-export { TrueForgeMode };
-
export type CreateAuthenticatorParams =
- | { mode: TrueForgeMode.Standalone }
- | { mode: TrueForgeMode.Oidc }
- | { mode: TrueForgeMode.TrueFoundry; trueFoundryClient: TrueFoundryServiceFoundryServerClient };
+ | { mode: TrueForgeAuthMode.Standalone }
+ | { mode: TrueForgeAuthMode.Oidc }
+ | { mode: TrueForgeAuthMode.TrueFoundry; serviceFoundryClient: TrueFoundryServiceFoundryServerClient };
/** Build the single process authenticator from resolved auth mode. */
export function createAuthenticator(params: CreateAuthenticatorParams): Authenticator {
switch (params.mode) {
- case TrueForgeMode.TrueFoundry:
- return new TrueFoundryAuthenticator(params.trueFoundryClient);
- case TrueForgeMode.Oidc:
+ case TrueForgeAuthMode.TrueFoundry:
+ return new TrueFoundryAuthenticator(params.serviceFoundryClient);
+ case TrueForgeAuthMode.Oidc:
return new OidcAuthenticator();
- case TrueForgeMode.Standalone:
+ case TrueForgeAuthMode.Standalone:
return new StandaloneAuthenticator();
}
}
diff --git a/packages/trueforge/src/auth/identity.ts b/packages/trueforge/src/auth/identity.ts
index 6436542d1..9a55ab5a6 100644
--- a/packages/trueforge/src/auth/identity.ts
+++ b/packages/trueforge/src/auth/identity.ts
@@ -1,7 +1,7 @@
import type { CreatedBySubject } from '@truefoundry/trueforge-core/agent-session';
import type { Context } from 'hono';
-import configuration, { getTrueForgeMode, isOidcConfigured, TrueForgeMode } from '../config';
+import configuration, { getTrueForgeAuthMode, isOidcConfigured, TrueForgeAuthMode } from '../config';
/** Standalone / default TrueForge admin role string. */
export const STANDALONE_ADMIN_ROLE = 'admin';
@@ -49,24 +49,24 @@ export function resolveRequestContext(c: Context): RequestContext {
/**
* Whether the caller is treated as admin for settings, capabilities, and schedule bypass.
- * Mode and OIDC admin claim value come from process config ({@link getTrueForgeMode}).
+ * Mode and OIDC admin claim value come from process config ({@link getTrueForgeAuthMode}).
* - Standalone: `roles` includes `admin`
* - OIDC: `roles` includes configured `OIDC_ADMIN_ROLE_VALUE`
* - TrueFoundry: no tenant-wide TrueForge admin
*/
// TODO (chiragjn): hasAdminRole will be renamed to canAccessSettings once all authorizer changes are done
export function hasAdminRole(requestContext: Pick<RequestContext, 'roles'>): boolean {
- switch (getTrueForgeMode()) {
- case TrueForgeMode.TrueFoundry:
+ switch (getTrueForgeAuthMode()) {
+ case TrueForgeAuthMode.TrueFoundry:
return false;
- case TrueForgeMode.Oidc: {
+ case TrueForgeAuthMode.Oidc: {
if (!isOidcConfigured(configuration)) {
- // this is technically unreachable since case TrueForgeMode.Oidc already ensures OIDC is configured
+ // this is technically unreachable since case TrueForgeAuthMode.Oidc already ensures OIDC is configured
return false;
}
return requestContext.roles.includes(configuration.OIDC.OIDC_ADMIN_ROLE_VALUE);
}
- case TrueForgeMode.Standalone:
+ case TrueForgeAuthMode.Standalone:
return requestContext.roles.includes(STANDALONE_ADMIN_ROLE);
}
}
diff --git a/packages/trueforge/src/config.ts b/packages/trueforge/src/config.ts
index 0c87a9579..de569a071 100644
--- a/packages/trueforge/src/config.ts
+++ b/packages/trueforge/src/config.ts
@@ -496,29 +496,6 @@ export interface SharedServerConfiguration {
* `TRUEFORGE_MTLS_ENABLED` is true. Env: `TRUEFORGE_MTLS_CERTS_DIR`. Default `/etc/tls`.
*/
TRUEFORGE_MTLS_CERTS_DIR: string;
- /**
- * When set, models are listed from the TrueFoundry ServiceFoundry server and invoked
- * via the AI Gateway with the caller's token. Unset = local model-provider store.
- * Env: `TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL`.
- */
- TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL: string | undefined;
- /** Max ms for non-agent ServiceFoundry HTTP calls. Env: `TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_TIMEOUT_MS`. Default 10000. */
- TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_TIMEOUT_MS: number;
- /** Max ms for agent CRUD ServiceFoundry HTTP calls. Env: `TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_AGENT_TIMEOUT_MS`. Default 3000. */
- TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_AGENT_TIMEOUT_MS: number;
- /**
- * Present this pod's client certificate on outbound calls to the ServiceFoundry server (internal
- * mutual TLS) and upgrade a mesh-direct peer URL from http to https. Off by default, so an
- * unconfigured deployment keeps calling over plain HTTP exactly as before.
- * Env: `TRUEFOUNDRY_MTLS_ENABLED`. Default false.
- */
- TRUEFOUNDRY_MTLS_ENABLED: boolean;
- /**
- * Directory holding the internal mTLS material used when `TRUEFOUNDRY_MTLS_ENABLED` is true — the
- * cert triple `tls.crt` / `tls.key` / `ca.crt`, so one chart value configures every component.
- * Env: `TRUEFOUNDRY_MTLS_CERTS_DIR`. Default `/etc/tls/truefoundry`.
- */
- TRUEFOUNDRY_MTLS_CERTS_DIR: string;
}
export type StandaloneServerConfiguration = SharedServerConfiguration & {
@@ -575,6 +552,29 @@ export type DistributedServerConfiguration = SharedServerConfiguration & {
* Undefined means browser login is disabled.
*/
OIDC: OIDCConfig | undefined;
+ /**
+ * When set, models/MCP/agents are backed by the TrueFoundry ServiceFoundry server with the
+ * caller's token. Unset = local Postgres stores. Mutually exclusive with OIDC.
+ * Env: `TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL`.
+ */
+ TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL: string | undefined;
+ /** Max ms for non-agent ServiceFoundry HTTP calls. Env: `TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_TIMEOUT_MS`. Default 10000. */
+ TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_TIMEOUT_MS: number;
+ /** Max ms for agent CRUD ServiceFoundry HTTP calls. Env: `TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_AGENT_TIMEOUT_MS`. Default 3000. */
+ TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_AGENT_TIMEOUT_MS: number;
+ /**
+ * Present this pod's client certificate on outbound calls to the ServiceFoundry server (internal
+ * mutual TLS) and upgrade a mesh-direct peer URL from http to https. Off by default, so an
+ * unconfigured deployment keeps calling over plain HTTP exactly as before.
+ * Env: `TRUEFOUNDRY_MTLS_ENABLED`. Default false.
+ */
+ TRUEFOUNDRY_MTLS_ENABLED: boolean;
+ /**
+ * Directory holding the internal mTLS material used when `TRUEFOUNDRY_MTLS_ENABLED` is true — the
+ * cert triple `tls.crt` / `tls.key` / `ca.crt`, so one chart value configures every component.
+ * Env: `TRUEFOUNDRY_MTLS_CERTS_DIR`. Default `/etc/tls/truefoundry`.
+ */
+ TRUEFOUNDRY_MTLS_CERTS_DIR: string;
};
export type ServerConfiguration = StandaloneServerConfiguration | DistributedServerConfiguration;
@@ -686,24 +686,6 @@ const shared: SharedServerConfiguration = {
defaultValue: false,
}),
TRUEFORGE_MTLS_CERTS_DIR: getEnv('TRUEFORGE_MTLS_CERTS_DIR', { defaultValue: '/etc/tls' }) ?? '/etc/tls',
- TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL: getEnv('TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL', { required: false }),
- TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_TIMEOUT_MS: parsePositiveInt({
- envKey: 'TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_TIMEOUT_MS',
- raw: getEnv('TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_TIMEOUT_MS'),
- defaultValue: 10_000,
- }),
- TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_AGENT_TIMEOUT_MS: parsePositiveInt({
- envKey: 'TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_AGENT_TIMEOUT_MS',
- raw: getEnv('TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_AGENT_TIMEOUT_MS'),
- defaultValue: 3_000,
- }),
- TRUEFOUNDRY_MTLS_ENABLED: parseBoolean({
- envKey: 'TRUEFOUNDRY_MTLS_ENABLED',
- raw: getEnv('TRUEFOUNDRY_MTLS_ENABLED'),
- defaultValue: false,
- }),
- TRUEFOUNDRY_MTLS_CERTS_DIR:
- getEnv('TRUEFOUNDRY_MTLS_CERTS_DIR', { defaultValue: '/etc/tls/truefoundry' }) ?? '/etc/tls/truefoundry',
};
const configuration: ServerConfiguration = standalone
@@ -735,6 +717,24 @@ const configuration: ServerConfiguration = standalone
}),
REDIS_URL: resolveRedisUrl(),
OIDC: resolveOIDCConfig(),
+ TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL: getEnv('TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL', { required: false }),
+ TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_TIMEOUT_MS: parsePositiveInt({
+ envKey: 'TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_TIMEOUT_MS',
+ raw: getEnv('TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_TIMEOUT_MS'),
+ defaultValue: 10_000,
+ }),
+ TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_AGENT_TIMEOUT_MS: parsePositiveInt({
+ envKey: 'TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_AGENT_TIMEOUT_MS',
+ raw: getEnv('TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_AGENT_TIMEOUT_MS'),
+ defaultValue: 3_000,
+ }),
+ TRUEFOUNDRY_MTLS_ENABLED: parseBoolean({
+ envKey: 'TRUEFOUNDRY_MTLS_ENABLED',
+ raw: getEnv('TRUEFOUNDRY_MTLS_ENABLED'),
+ defaultValue: false,
+ }),
+ TRUEFOUNDRY_MTLS_CERTS_DIR:
+ getEnv('TRUEFOUNDRY_MTLS_CERTS_DIR', { defaultValue: '/etc/tls/truefoundry' }) ?? '/etc/tls/truefoundry',
};
export function isOidcConfigured(
@@ -744,38 +744,37 @@ export function isOidcConfigured(
}
/**
- * TrueFoundry mode: trueforge is backed by the ServiceFoundry server (models today, MCP and other
- * resources later) rather than its local catalog. Gated on `TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL`.
+ * TrueFoundry mode: ServiceFoundry-backed models/MCP/agents. Only available on
+ * distributed config when `TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL` is set.
*/
export function isTrueFoundryModeEnabled(
config: ServerConfiguration = configuration,
-): config is ServerConfiguration & { TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL: string } {
- return config.TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL !== undefined;
+): config is DistributedServerConfiguration & { TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL: string } {
+ return !config.STANDALONE && config.TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL !== undefined;
}
/** Runtime auth/integration mode for this process. */
-export enum TrueForgeMode {
+export enum TrueForgeAuthMode {
Standalone = 'standalone',
Oidc = 'oidc',
TrueFoundry = 'truefoundry',
}
/**
- * Resolve the active {@link TrueForgeMode} from configuration.
+ * Resolve the active {@link TrueForgeAuthMode} from configuration.
* TrueFoundry wins over OIDC when both would otherwise be set (startup already rejects that combo).
*/
-export function getTrueForgeMode(config: ServerConfiguration = configuration): TrueForgeMode {
+export function getTrueForgeAuthMode(config: ServerConfiguration = configuration): TrueForgeAuthMode {
if (isTrueFoundryModeEnabled(config)) {
- return TrueForgeMode.TrueFoundry;
+ return TrueForgeAuthMode.TrueFoundry;
}
if (isOidcConfigured(config)) {
- return TrueForgeMode.Oidc;
+ return TrueForgeAuthMode.Oidc;
}
- return TrueForgeMode.Standalone;
+ return TrueForgeAuthMode.Standalone;
}
-// TrueFoundry mode authenticates each caller with their own gateway token, so browser SSO must be
-// off — the two auth models are mutually exclusive.
+// TrueFoundry authenticates each caller with their own gateway token, so browser SSO must be off.
if (isTrueFoundryModeEnabled(configuration) && isOidcConfigured(configuration)) {
throw new Error(
'TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL (TrueFoundry mode) and OIDC (SSO) cannot both be enabled at once.',
diff --git a/packages/trueforge/src/main.ts b/packages/trueforge/src/main.ts
index 2c17cc5f2..999f7f330 100644
--- a/packages/trueforge/src/main.ts
+++ b/packages/trueforge/src/main.ts
@@ -24,16 +24,16 @@ import { setCachedLocalSandboxSupport } from './sandbox/localRuntime';
let configuration: typeof import('./config').default;
let isOidcConfigured: typeof import('./config').isOidcConfigured;
let isTrueFoundryModeEnabled: typeof import('./config').isTrueFoundryModeEnabled;
-let getTrueForgeMode: typeof import('./config').getTrueForgeMode;
-let TrueForgeMode: typeof import('./config').TrueForgeMode;
+let getTrueForgeAuthMode: typeof import('./config').getTrueForgeAuthMode;
+let TrueForgeAuthMode: typeof import('./config').TrueForgeAuthMode;
try {
({
default: configuration,
isOidcConfigured,
isTrueFoundryModeEnabled,
- getTrueForgeMode,
- TrueForgeMode,
+ getTrueForgeAuthMode,
+ TrueForgeAuthMode,
} = await import('./config'));
} catch (error) {
console.error(
@@ -97,9 +97,9 @@ import { TrueFoundryServiceFoundryServerClient } from './truefoundry/TrueFoundry
interface ServerPersistence<TTransaction> {
sessionStore: ISessionStore;
sessionMetricsStore: ISessionMetricsStore;
- resolveModelProviderStore: (c?: Context) => IModelProviderStore<TTransaction>;
+ resolveModelProviderStore: (c: Context) => IModelProviderStore<TTransaction>;
resolveMcpServerStore: (c?: Context) => IMcpServerWithAuthStore<TTransaction>;
- resolveAgentStore: (c?: Context) => IAgentStore<TTransaction>;
+ resolveAgentStore: (c: Context) => IAgentStore<TTransaction>;
withTransaction: WithTransaction<TTransaction>;
tokenStore: IOAuthTokenStore<TTransaction>;
skillStore: ISkillStore<TTransaction>;
@@ -107,6 +107,8 @@ interface ServerPersistence<TTransaction> {
scheduleStore: IScheduleStore<TTransaction>;
destroyDb: () => Promise<void>;
redis: RedisClientType | undefined;
+ /** One shared client for TrueFoundry store resolvers + auth; undefined when TrueFoundry mode is off. */
+ serviceFoundryClient: TrueFoundryServiceFoundryServerClient | undefined;
}
function requireRequestCredentialToken(c: Context): string {
@@ -119,10 +121,7 @@ function requireRequestCredentialToken(c: Context): string {
return credential;
}
-/**
- * Shared ServiceFoundry HTTP client for TrueFoundry-mode store resolvers (models, MCP, agents).
- * Undefined when TrueFoundry mode is off — resolvers then use persistence only.
- */
+/** Shared ServiceFoundry HTTP client when TrueFoundry mode is on; otherwise undefined. */
function createServiceFoundryServerClient(logger: Logger): TrueFoundryServiceFoundryServerClient | undefined {
if (!isTrueFoundryModeEnabled(configuration)) {
return undefined;
@@ -136,84 +135,71 @@ function createServiceFoundryServerClient(logger: Logger): TrueFoundryServiceFou
});
}
-/**
- * Per-request model-provider store resolver. In TrueFoundry mode every request gets a token-bound
- * store over a shared (mTLS) ServiceFoundry client; otherwise the persistence store is reused as-is.
- */
+/** Per-request model-provider store over a shared ServiceFoundry client, else {@link persistenceStore}. */
function buildResolveModelProviderStore<TTransaction>(options: {
persistenceStore: IModelProviderStore<TTransaction>;
client: TrueFoundryServiceFoundryServerClient | undefined;
-}): (c?: Context) => IModelProviderStore<TTransaction> {
- const { persistenceStore, client } = options;
- if (!client) {
- return () => persistenceStore;
- }
- // No request context (e.g. the scheduler) means no caller token, so TrueFoundry models are
- // unavailable there; fall back to the persistence store.
- return c =>
- c
- ? new TrueFoundryModelProviderStore<TTransaction>({ client, accessToken: requireRequestCredentialToken(c) })
- : persistenceStore;
+}): (c: Context) => IModelProviderStore<TTransaction> {
+ return (c: Context) => {
+ const { persistenceStore, client } = options;
+ if (client) {
+ return new TrueFoundryModelProviderStore<TTransaction>({
+ client,
+ accessToken: requireRequestCredentialToken(c),
+ });
+ }
+ return persistenceStore;
+ };
}
/**
- * Per-request MCP store resolver. Local mode wraps DB persistence with
- * {@link McpServerWithAuthStore}. TrueFoundry mode returns a token-bound
- * {@link TrueFoundryMcpServerStore} (implements auth UX stubs); without request
- * context (scheduler / OAuth callback) falls back to the local with-auth store.
+ * Per-request MCP store over ServiceFoundry. Without request context (scheduler / OAuth callback)
+ * falls back to the local with-auth store.
*/
function buildResolveMcpServerStore<TTransaction>(options: {
persistenceStore: IMcpServerStore<TTransaction>;
tokenStore: IOAuthTokenStore<TTransaction>;
client: TrueFoundryServiceFoundryServerClient | undefined;
}): (c?: Context) => IMcpServerWithAuthStore<TTransaction> {
- const withAuthPersistence = new McpServerWithAuthStore<TTransaction>({
- store: options.persistenceStore,
- tokenStore: options.tokenStore,
- clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME,
- });
- const { client } = options;
- if (!client) {
- return () => withAuthPersistence;
- }
- return c => {
- if (!c) {
- return withAuthPersistence;
+ return (c?: Context) => {
+ const { persistenceStore, tokenStore, client } = options;
+ if (c && client) {
+ const requestContext = resolveRequestContext(c);
+ const rawPerServerHeaders = c.req.header(X_TFG_MCP_HEADERS);
+ return new TrueFoundryMcpServerStore<TTransaction>({
+ client,
+ accessToken: requireRequestCredentialToken(c),
+ subject: requestContext.subject,
+ perServerHeaders: rawPerServerHeaders ? parsePerServerMcpHeaders(rawPerServerHeaders) : {},
+ });
}
- const requestContext = resolveRequestContext(c);
- const rawPerServerHeaders = c.req.header(X_TFG_MCP_HEADERS);
- return new TrueFoundryMcpServerStore<TTransaction>({
- client,
- accessToken: requireRequestCredentialToken(c),
- subject: requestContext.subject,
- perServerHeaders: rawPerServerHeaders ? parsePerServerMcpHeaders(rawPerServerHeaders) : {},
+ const withAuthMcpPersistenceStore = new McpServerWithAuthStore<TTransaction>({
+ store: persistenceStore,
+ tokenStore,
+ clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME,
});
+ return withAuthMcpPersistenceStore;
};
}
-/**
- * Per-request agent store resolver. In TrueFoundry mode every request gets a token-bound
- * decorator over DB persistence; otherwise the persistence store is reused as-is.
- */
+/** Per-request agent store decorator over DB persistence, else {@link persistenceStore}. */
function buildResolveAgentStore(options: {
persistenceStore: PostgresAgentStore;
- client: TrueFoundryServiceFoundryServerClient | undefined;
db: Kysely<PostgresDatabase>;
-}): (c?: Context) => IAgentStore<Transaction<PostgresDatabase>> {
+ client: TrueFoundryServiceFoundryServerClient | undefined;
+}): (c: Context) => IAgentStore<Transaction<PostgresDatabase>> {
const { persistenceStore, client, db } = options;
- if (!client) {
- return () => persistenceStore;
- }
- // No request context (e.g. the scheduler) means no caller token, so fall back to persistence.
- return c =>
- c
- ? new TrueFoundryAgentStore({
- inner: persistenceStore,
- client,
- accessToken: requireRequestCredentialToken(c),
- db,
- })
- : persistenceStore;
+ return (c: Context) => {
+ if (client) {
+ return new TrueFoundryAgentStore({
+ inner: persistenceStore,
+ client,
+ accessToken: requireRequestCredentialToken(c),
+ db,
+ });
+ }
+ return persistenceStore;
+ };
}
/** SQLite stores; Redis unused (executor peering disabled). */
@@ -257,18 +243,17 @@ async function createStandalonePersistence(options: {
const tokenStore = new SqliteOAuthTokenStore(db);
const agentStore = new SqliteAgentStore(db);
+ const modelProviderStore = new SqliteModelProviderStore(db);
+ const mcpServerStore = new McpServerWithAuthStore({
+ store: new SqliteMcpServerStore(db),
+ tokenStore,
+ clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME,
+ });
return {
sessionStore: new SqliteSessionStore(db),
sessionMetricsStore: new SqliteSessionMetricsStore(db),
- resolveModelProviderStore: buildResolveModelProviderStore({
- persistenceStore: new SqliteModelProviderStore(db),
- client: undefined,
- }),
- resolveMcpServerStore: buildResolveMcpServerStore({
- persistenceStore: new SqliteMcpServerStore(db),
- tokenStore,
- client: undefined,
- }),
+ resolveModelProviderStore: () => modelProviderStore,
+ resolveMcpServerStore: () => mcpServerStore,
resolveAgentStore: () => agentStore,
withTransaction: callback => db.transaction().execute(callback),
tokenStore,
@@ -277,6 +262,7 @@ async function createStandalonePersistence(options: {
scheduleStore: new SqliteScheduleStore(db),
destroyDb: () => db.destroy(),
redis: undefined,
+ serviceFoundryClient: undefined,
};
}
@@ -335,23 +321,25 @@ async function createDistributedPersistence(options: {
const tokenStore = new PostgresOAuthTokenStore(db);
const agentStore = new PostgresAgentStore(db);
+ const modelProviderStore = new PostgresModelProviderStore(db);
+ const mcpServerStore = new PostgresMcpServerStore(db);
const serviceFoundryClient = createServiceFoundryServerClient(logger);
return {
sessionStore: new PostgresSessionStore(db),
sessionMetricsStore: new PostgresSessionMetricsStore(db),
resolveModelProviderStore: buildResolveModelProviderStore({
- persistenceStore: new PostgresModelProviderStore(db),
+ persistenceStore: modelProviderStore,
client: serviceFoundryClient,
}),
resolveMcpServerStore: buildResolveMcpServerStore({
- persistenceStore: new PostgresMcpServerStore(db),
+ persistenceStore: mcpServerStore,
tokenStore,
client: serviceFoundryClient,
}),
resolveAgentStore: buildResolveAgentStore({
persistenceStore: agentStore,
- client: serviceFoundryClient,
db,
+ client: serviceFoundryClient,
}),
withTransaction: callback => db.transaction().execute(callback),
tokenStore,
@@ -360,6 +348,7 @@ async function createDistributedPersistence(options: {
scheduleStore: new PostgresScheduleStore(db),
destroyDb: () => db.destroy(),
redis: await connectRedis({ url: redisUrl, logger }),
+ serviceFoundryClient,
};
}
@@ -378,6 +367,7 @@ async function createServerRuntime<TTransaction>(persistence: ServerPersistence<
scheduleStore,
destroyDb,
redis,
+ serviceFoundryClient,
} = persistence;
const activeTurns = new ActiveTurnRegistry();
@@ -394,28 +384,21 @@ async function createServerRuntime<TTransaction>(persistence: ServerPersistence<
let authenticator;
let authorizer: Authorizer;
- const mode = getTrueForgeMode(configuration);
- if (mode === TrueForgeMode.TrueFoundry) {
- if (!isTrueFoundryModeEnabled(configuration)) {
+ const mode = getTrueForgeAuthMode(configuration);
+ if (mode === TrueForgeAuthMode.TrueFoundry) {
+ if (serviceFoundryClient === undefined) {
throw new Error('TrueFoundry mode requires TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL');
}
- const trueFoundryClient = new TrueFoundryServiceFoundryServerClient({
- serviceFoundryServerUrl: configuration.TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL,
- logger,
- httpTimeoutMs: configuration.TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_TIMEOUT_MS,
- httpAgentTimeoutMs: configuration.TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_AGENT_TIMEOUT_MS,
- tls: { enabled: configuration.TRUEFOUNDRY_MTLS_ENABLED, dir: configuration.TRUEFOUNDRY_MTLS_CERTS_DIR },
- });
authenticator = createAuthenticator({
- mode: TrueForgeMode.TrueFoundry,
- trueFoundryClient,
+ mode: TrueForgeAuthMode.TrueFoundry,
+ serviceFoundryClient,
});
- authorizer = new TrueFoundryAuthorizer(trueFoundryClient);
- } else if (mode === TrueForgeMode.Oidc) {
- authenticator = createAuthenticator({ mode: TrueForgeMode.Oidc });
+ authorizer = new TrueFoundryAuthorizer(serviceFoundryClient);
+ } else if (mode === TrueForgeAuthMode.Oidc) {
+ authenticator = createAuthenticator({ mode: TrueForgeAuthMode.Oidc });
authorizer = new TrueForgeAuthorizer();
} else {
- authenticator = createAuthenticator({ mode: TrueForgeMode.Standalone });
+ authenticator = createAuthenticator({ mode: TrueForgeAuthMode.Standalone });
authorizer = new TrueForgeAuthorizer();
}
diff --git a/packages/trueforge/src/routes/agentRoutes.ts b/packages/trueforge/src/routes/agentRoutes.ts
index 23c0a4f5f..113463292 100644
--- a/packages/trueforge/src/routes/agentRoutes.ts
+++ b/packages/trueforge/src/routes/agentRoutes.ts
@@ -127,7 +127,7 @@ export const deleteAgentRoute = createRoute({
path: '/{agent_id}',
tags: [OpenApiTag.AGENTS],
summary: 'Delete an agent',
- description: 'Delete a configured agent by immutable id. Idempotent if already gone.',
+ description: 'Delete a configured agent by immutable id.',
'x-fern-sdk-group-name': ['agents'],
'x-fern-sdk-method-name': 'delete',
request: {
@@ -142,6 +142,10 @@ export const deleteAgentRoute = createRoute({
content: { 'application/json': { schema: RequestErrorResponseSchema } },
description: 'OIDC is configured and the request has no valid session cookie.',
},
+ 404: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Agent not found.',
+ },
},
});
diff --git a/packages/trueforge/src/routes/scheduleRoutes.ts b/packages/trueforge/src/routes/scheduleRoutes.ts
index 1a85405a0..0f0da751b 100644
--- a/packages/trueforge/src/routes/scheduleRoutes.ts
+++ b/packages/trueforge/src/routes/scheduleRoutes.ts
@@ -166,7 +166,11 @@ export const createScheduleRoute = createRoute({
},
400: {
content: { 'application/json': { schema: RequestErrorResponseSchema } },
- description: 'Unknown agent or invalid cron.',
+ description: 'Invalid cron or timezone.',
+ },
+ 404: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Named agent not found.',
},
409: {
content: { 'application/json': { schema: RequestErrorResponseSchema } },
diff --git a/packages/trueforge/src/routes/turnRoutes.ts b/packages/trueforge/src/routes/turnRoutes.ts
index af377371a..14f9b9398 100644
--- a/packages/trueforge/src/routes/turnRoutes.ts
+++ b/packages/trueforge/src/routes/turnRoutes.ts
@@ -221,7 +221,7 @@ Use \`previous_turn_id\` to chain to the session's last turn (defaults to \`auto
},
404: {
content: { 'application/json': { schema: RequestErrorResponseSchema } },
- description: 'Session or prior turn not found.',
+ description: 'Session, prior turn, or referenced agent not found.',
},
412: {
content: { 'application/json': { schema: RequestErrorResponseSchema } },
diff --git a/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts b/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts
index cc17d7a1b..5701a837f 100644
--- a/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts
+++ b/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts
@@ -466,7 +466,7 @@ export class TrueFoundryServiceFoundryServerClient {
cause: error,
});
}
- this.#logger.info('TrueFoundry ServiceFoundry server request completed', {
+ this.#logger.debug('TrueFoundry ServiceFoundry server request completed', {
url: input.url.href,
method: input.method,
status: response.status,
diff --git a/packages/trueforge/tests/unit/apis/agents.test.ts b/packages/trueforge/tests/unit/apis/agents.test.ts
index 2f5475632..60b315626 100644
--- a/packages/trueforge/tests/unit/apis/agents.test.ts
+++ b/packages/trueforge/tests/unit/apis/agents.test.ts
@@ -1,4 +1,5 @@
import { createAgentsRouter } from '../../../src/apis/agents';
+import { TrueForgeAuthorizer, type Authorizer } from '../../../src/auth/authorizer';
import { STANDALONE_REQUEST_CONTEXT } from '../../../src/auth/identity';
import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';
import { SqliteAgentStore } from '../../../src/db/sqlite/agent-store/SqliteAgentStore';
@@ -68,16 +69,21 @@ function jsonInit(method: string, body: unknown): RequestInit {
};
}
+const denyAllAuthorizer: Authorizer = {
+ listAgentAccess: () => Promise.resolve({ kind: 'agent_external_ids', agent_external_ids: [] }),
+ canAccessAgent: () => Promise.resolve(false),
+};
+
describe('agents router', () => {
let router: ReturnType<typeof createAgentsRouter>;
- let agentStore: SqliteAgentStore;
+ let deniedRouter: ReturnType<typeof createAgentsRouter>;
beforeAll(async () => {
const db = createSqliteDb(':memory:');
await migrateSqliteToLatest(db);
const modelProviderStore = new SqliteModelProviderStore(db);
await modelProviderStore.upsertProvider({ tenant_id: 'default', name: 'anthropic', manifest: modelProvider });
- agentStore = new SqliteAgentStore(db);
+ const agentStore = new SqliteAgentStore(db);
router = createAgentsRouter({
resolveAgentStore: () => agentStore,
resolveModelProviderStore: () => modelProviderStore,
@@ -86,6 +92,17 @@ describe('agents router', () => {
sandboxProviderStore: new SqliteSandboxProviderStore(db),
withTransaction: callback => db.transaction().execute(callback),
resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT,
+ authorizer: new TrueForgeAuthorizer(),
+ });
+ deniedRouter = createAgentsRouter({
+ resolveAgentStore: () => agentStore,
+ resolveModelProviderStore: () => modelProviderStore,
+ resolveMcpServerStore: () => new SqliteMcpServerStore(db),
+ skillStore: new SqliteSkillStore(db),
+ sandboxProviderStore: new SqliteSandboxProviderStore(db),
+ withTransaction: callback => db.transaction().execute(callback),
+ resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT,
+ authorizer: denyAllAuthorizer,
});
});
@@ -151,7 +168,7 @@ describe('agents router', () => {
expect(body.data.snippets.length).toBeGreaterThan(0);
});
- it('DELETE removes an agent by id and is idempotent', async () => {
+ it('DELETE removes an agent by id and returns 404 when already gone', async () => {
const created = await router.request('/', jsonInit('POST', { ...writeBody, name: 'deletable' }));
expect(created.status).toBe(201);
const { data } = (await created.json()) as { data: { id: string } };
@@ -162,8 +179,7 @@ describe('agents router', () => {
expect((await router.request(`/${data.id}`)).status).toBe(404);
const deletedAgain = await router.request(`/${data.id}`, { method: 'DELETE' });
- expect(deletedAgain.status).toBe(200);
- expect(await deletedAgain.json()).toEqual({});
+ expect(deletedAgain.status).toBe(404);
});
it('POST rejects invalid bodies, unknown models, and duplicate names', async () => {
@@ -191,4 +207,20 @@ describe('agents router', () => {
const clash = await router.request('/', jsonInit('POST', { ...writeBody, name: 'alpha' }));
expect(clash.status).toBe(409);
});
+
+ it('lists, gets, updates, and deletes as not found when the authorizer denies the agent', async () => {
+ const created = await router.request('/', jsonInit('POST', { ...writeBody, name: 'denied-agent' }));
+ expect(created.status).toBe(201);
+ const { data } = (await created.json()) as { data: { id: string } };
+
+ const listed = await deniedRouter.request('/');
+ expect(listed.status).toBe(200);
+ expect(((await listed.json()) as { data: WireAgent[] }).data).toEqual([]);
+
+ expect((await deniedRouter.request(`/${data.id}`)).status).toBe(404);
+ expect((await deniedRouter.request(`/${data.id}/code-snippets`)).status).toBe(404);
+ expect((await deniedRouter.request(`/${data.id}`, jsonInit('PUT', updateBody))).status).toBe(404);
+ expect((await deniedRouter.request(`/${data.id}`, { method: 'DELETE' })).status).toBe(404);
+ expect((await router.request(`/${data.id}`)).status).toBe(200);
+ });
});
diff --git a/packages/trueforge/tests/unit/apis/deletedSessionCrud.test.ts b/packages/trueforge/tests/unit/apis/deletedSessionCrud.test.ts
index fb1a4d058..03ebf907e 100644
--- a/packages/trueforge/tests/unit/apis/deletedSessionCrud.test.ts
+++ b/packages/trueforge/tests/unit/apis/deletedSessionCrud.test.ts
@@ -5,6 +5,7 @@ import { createClient } from 'redis';
import { createLogger } from 'winston';
import { createSessionsRouter } from '../../../src/apis/sessions';
import { createTurnsRouter } from '../../../src/apis/turns';
+import { TrueForgeAuthorizer } from '../../../src/auth/authorizer';
import { STANDALONE_REQUEST_CONTEXT } from '../../../src/auth/identity';
import { McpServerWithAuthStore } from '../../../src/db/McpServerWithAuthStore';
import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';
@@ -54,6 +55,7 @@ describe('public CRUD after session deletion', () => {
requestReplyRouter: new RequestReplyRouter(),
resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT,
logger: createLogger({ silent: true }),
+ authorizer: new TrueForgeAuthorizer(),
}),
);
app.route(
@@ -70,6 +72,7 @@ describe('public CRUD after session deletion', () => {
sandboxProviderStore,
logger: createLogger({ silent: true }),
resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT,
+ authorizer: new TrueForgeAuthorizer(),
}),
);
diff --git a/packages/trueforge/tests/unit/apis/sandboxFileDownload.test.ts b/packages/trueforge/tests/unit/apis/sandboxFileDownload.test.ts
index fb6a9f2a6..a10343333 100644
--- a/packages/trueforge/tests/unit/apis/sandboxFileDownload.test.ts
+++ b/packages/trueforge/tests/unit/apis/sandboxFileDownload.test.ts
@@ -3,6 +3,7 @@ import type { AgentSpec } from '@truefoundry/trueforge-core/agent-session';
import { AgentSpecSchema, Sessions } from '@truefoundry/trueforge-core/agent-session';
import { createLogger } from 'winston';
import { createTurnsRouter, toContentDisposition } from '../../../src/apis/turns';
+import { TrueForgeAuthorizer } from '../../../src/auth/authorizer';
import { STANDALONE_REQUEST_CONTEXT } from '../../../src/auth/identity';
import { McpServerWithAuthStore } from '../../../src/db/McpServerWithAuthStore';
import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';
@@ -52,6 +53,7 @@ async function buildApp() {
sandboxProviderStore: new SqliteSandboxProviderStore(db),
logger: createLogger({ silent: true }),
resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT,
+ authorizer: new TrueForgeAuthorizer(),
}),
);
diff --git a/packages/trueforge/tests/unit/apis/schedules.test.ts b/packages/trueforge/tests/unit/apis/schedules.test.ts
index 6d5b3d243..5ae75fe7c 100644
--- a/packages/trueforge/tests/unit/apis/schedules.test.ts
+++ b/packages/trueforge/tests/unit/apis/schedules.test.ts
@@ -1,6 +1,7 @@
import { OpenAPIHono } from '@hono/zod-openapi';
import { AgentSpecSchema } from '@truefoundry/trueforge-core/agent-session';
import { createSchedulesRouter } from '../../../src/apis/schedules';
+import { TrueForgeAuthorizer, type Authorizer } from '../../../src/auth/authorizer';
import type { RequestContext } from '../../../src/auth/identity';
import { ScheduleAgentNotFoundError, startScheduleRun } from '../../../src/controller/scheduleDispatch';
import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';
@@ -47,7 +48,7 @@ const scheduleBody = {
manifest: { task: 'Say hi', cron: '0 13 * * *', timezone: 'UTC' },
};
-async function setup() {
+async function setup(authorizer: Authorizer = new TrueForgeAuthorizer()) {
const db = createSqliteDb(':memory:');
await migrateSqliteToLatest(db);
const agentStore = new SqliteAgentStore(db);
@@ -65,6 +66,7 @@ async function setup() {
});
let current: RequestContext = ALICE;
+ let currentAuthorizer = authorizer;
const app = new OpenAPIHono();
app.route(
'/',
@@ -74,7 +76,7 @@ async function setup() {
sessions: {
getOrCreateByExternalId: () => Promise.reject(new Error('sessions stub: unexpected call')),
} as never,
- turnDeps: {
+ resolveTurnDeps: () => ({
activeTurns: {} as never,
eventSubscriptions: {} as never,
modelProviderStore: {} as never,
@@ -83,19 +85,26 @@ async function setup() {
agentStore,
sandboxProviderStore: {} as never,
logger: { error: jest.fn(), warn: jest.fn(), info: jest.fn(), debug: jest.fn() } as never,
- },
+ }),
withTransaction: callback => db.transaction().execute(callback),
resolveRequestContext: () => current,
+ authorizer: {
+ listAgentAccess: input => currentAuthorizer.listAgentAccess(input),
+ canAccessAgent: input => currentAuthorizer.canAccessAgent(input),
+ },
}),
);
const asUser = (user: RequestContext) => {
current = user;
};
+ const setAuthorizer = (next: Authorizer) => {
+ currentAuthorizer = next;
+ };
const postJson = (path: string, method: string, body: unknown) =>
app.request(path, { method, headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
- return { app, asUser, postJson, agentStore, scheduleStore };
+ return { app, asUser, setAuthorizer, postJson, agentStore, scheduleStore };
}
describe('schedule RBAC — creator-scoped, admin sees all', () => {
@@ -349,4 +358,36 @@ describe('create schedule run', () => {
const runNow = runs.find(r => r.name.startsWith('manual-'));
expect(runNow?.status).toBe('failed');
});
+
+ it('returns 404 when creating a schedule for an agent the caller cannot read', async () => {
+ const denyAll: Authorizer = {
+ listAgentAccess: () => Promise.resolve({ kind: 'agent_external_ids', agent_external_ids: [] }),
+ canAccessAgent: () => Promise.resolve(false),
+ };
+ const { postJson } = await setup(denyAll);
+ const res = await postJson('/', 'POST', scheduleBody);
+ expect(res.status).toBe(404);
+ expect(((await res.json()) as { error: { message: string } }).error.message).toBe('Agent not found: reporter');
+ });
+
+ it('returns 404 on run-now when the caller can access the schedule but not the agent', async () => {
+ const { asUser, setAuthorizer, postJson, scheduleStore } = await setup();
+
+ asUser(ALICE);
+ const created = await postJson('/', 'POST', scheduleBody);
+ const { id: scheduleId } = ((await created.json()) as { data: { id: string } }).data;
+
+ setAuthorizer({
+ listAgentAccess: () => Promise.resolve({ kind: 'agent_external_ids', agent_external_ids: [] }),
+ canAccessAgent: () => Promise.resolve(false),
+ });
+
+ const res = await postJson('/runs', 'POST', { schedule_id: scheduleId });
+ expect(res.status).toBe(404);
+ expect(((await res.json()) as { error: { message: string } }).error.message).toBe('Agent not found: reporter');
+ expect(mockedStartScheduleRun).not.toHaveBeenCalled();
+
+ const runs = await scheduleStore.listRuns({ tenant_id: 'default', schedule_id: scheduleId });
+ expect(runs.some(r => r.name.startsWith('manual-'))).toBe(false);
+ });
});
diff --git a/packages/trueforge/tests/unit/apis/sessionHttp.test.ts b/packages/trueforge/tests/unit/apis/sessionHttp.test.ts
index e7ad30b62..0d4396a4a 100644
--- a/packages/trueforge/tests/unit/apis/sessionHttp.test.ts
+++ b/packages/trueforge/tests/unit/apis/sessionHttp.test.ts
@@ -9,6 +9,7 @@ import {
createSessionsRouter,
type SessionsRouterDeps,
} from '../../../src/apis/sessions';
+import { TrueForgeAuthorizer, type Authorizer } from '../../../src/auth/authorizer';
import { STANDALONE_REQUEST_CONTEXT } from '../../../src/auth/identity';
import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';
import { SqliteAgentStore } from '../../../src/db/sqlite/agent-store/SqliteAgentStore';
@@ -39,10 +40,16 @@ function jsonInit(method: string, body: unknown): RequestInit {
};
}
+const denyAllAuthorizer: Authorizer = {
+ listAgentAccess: () => Promise.resolve({ kind: 'agent_external_ids', agent_external_ids: [] }),
+ canAccessAgent: () => Promise.resolve(false),
+};
+
describe('sessions HTTP agent binding', () => {
let app: OpenAPIHono;
let agentStore: SqliteAgentStore;
let sessionStore: SqliteSessionStore;
+ let sessionDeps: SessionsRouterDeps;
beforeEach(async () => {
const db = createSqliteDb(':memory:');
@@ -73,7 +80,6 @@ describe('sessions HTTP agent binding', () => {
},
});
- app = new OpenAPIHono();
const deps: SessionsRouterDeps = {
sessions,
sessionStore,
@@ -87,7 +93,10 @@ describe('sessions HTTP agent binding', () => {
requestReplyRouter: new RequestReplyRouter(),
resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT,
logger: createLogger({ silent: true }),
+ authorizer: new TrueForgeAuthorizer(),
};
+ sessionDeps = deps;
+ app = new OpenAPIHono();
app.route('/', createSessionsRouter(deps));
app.route('/api/internal/sessions', createInternalSessionsRouter(deps));
app.route(
@@ -460,6 +469,40 @@ describe('sessions HTTP agent binding', () => {
});
});
+ it('returns 404 when creating a session for a named agent the caller cannot read', async () => {
+ const agent = await agentStore.createAgent({
+ tenant_id: 'default',
+ created_by_subject: {
+ subject_id: STANDALONE_REQUEST_CONTEXT.subject.id,
+ subject_type: STANDALONE_REQUEST_CONTEXT.subject.type,
+ subject_display_name: STANDALONE_REQUEST_CONTEXT.subject.display_name,
+ },
+ name: 'forbidden-agent',
+ manifest: inlineSpec,
+ external_id: null,
+ });
+
+ const denyApp = new OpenAPIHono();
+ const deniedDeps = {
+ ...sessionDeps,
+ requestReplyRouter: new RequestReplyRouter(),
+ authorizer: denyAllAuthorizer,
+ };
+ denyApp.route('/', createSessionsRouter(deniedDeps));
+ denyApp.route('/api/internal/sessions', createInternalSessionsRouter(deniedDeps));
+
+ const created = await denyApp.request('/', jsonInit('POST', { agent: { name: agent.name } }));
+ expect(created.status).toBe(404);
+ expect(await created.json()).toEqual({ error: { message: `Agent not found: ${agent.name}` } });
+
+ const getOrCreate = await denyApp.request(
+ '/api/internal/sessions/get-or-create-by-external-id',
+ jsonInit('POST', { external_id: 'denied-run', agent: { name: agent.name } }),
+ );
+ expect(getOrCreate.status).toBe(404);
+ expect(await getOrCreate.json()).toEqual({ error: { message: `Agent not found: ${agent.name}` } });
+ });
+
it('rejects create bodies that mix name and AgentSpec fields', async () => {
const both = await app.request('/', jsonInit('POST', { agent: { name: 'named-agent', ...inlineSpec } }));
expect(both.status).toBe(400);
diff --git a/packages/trueforge/tests/unit/apis/turnHarnessErrorStatus.test.ts b/packages/trueforge/tests/unit/apis/turnHarnessErrorStatus.test.ts
index af43ae0a1..4b2051b28 100644
--- a/packages/trueforge/tests/unit/apis/turnHarnessErrorStatus.test.ts
+++ b/packages/trueforge/tests/unit/apis/turnHarnessErrorStatus.test.ts
@@ -3,6 +3,7 @@ import type { Sessions } from '@truefoundry/trueforge-core/agent-session';
import { AgentHarnessError } from '@truefoundry/trueforge-core/core';
import { createLogger } from 'winston';
import { createTurnsRouter } from '../../../src/apis/turns';
+import { TrueForgeAuthorizer } from '../../../src/auth/authorizer';
import { STANDALONE_REQUEST_CONTEXT } from '../../../src/auth/identity';
import { McpServerWithAuthStore } from '../../../src/db/McpServerWithAuthStore';
import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';
@@ -53,6 +54,7 @@ async function postTurnRejectingWith(error: AgentHarnessError): Promise<Response
subject_type: STANDALONE_REQUEST_CONTEXT.subject.type,
subject_display_name: STANDALONE_REQUEST_CONTEXT.subject.display_name,
},
+ agent: { type: 'inline', spec: { model: { name: 'test-provider/test-model' } } },
},
createTurn: () => Promise.reject(error),
}),
@@ -79,6 +81,7 @@ async function postTurnRejectingWith(error: AgentHarnessError): Promise<Response
sandboxProviderStore: new SqliteSandboxProviderStore(db),
logger: createLogger({ silent: true }),
resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT,
+ authorizer: new TrueForgeAuthorizer(),
}),
);
diff --git a/packages/trueforge/tests/unit/apis/turns.test.ts b/packages/trueforge/tests/unit/apis/turns.test.ts
index 50dc51e6f..cdfda7bf3 100644
--- a/packages/trueforge/tests/unit/apis/turns.test.ts
+++ b/packages/trueforge/tests/unit/apis/turns.test.ts
@@ -8,6 +8,7 @@ import {
import type { Kysely } from 'kysely';
import { createLogger } from 'winston';
import { createTurnsRouter, turnStreamId } from '../../../src/apis/turns';
+import { TrueForgeAuthorizer, type Authorizer } from '../../../src/auth/authorizer';
import { STANDALONE_REQUEST_CONTEXT } from '../../../src/auth/identity';
import { McpServerWithAuthStore } from '../../../src/db/McpServerWithAuthStore';
import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';
@@ -71,6 +72,7 @@ describe('turns', () => {
sandboxProviderStore: new SqliteSandboxProviderStore(db),
logger: createLogger({ silent: true }),
resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT,
+ authorizer: new TrueForgeAuthorizer(),
}),
);
@@ -153,6 +155,10 @@ describe('turns', () => {
subject_type: STANDALONE_REQUEST_CONTEXT.subject.type,
subject_display_name: STANDALONE_REQUEST_CONTEXT.subject.display_name,
},
+ agent: {
+ type: 'inline',
+ spec: AgentSpecSchema.parse({ model: { name: 'test-provider/test-model' } }),
+ },
},
createTurn: () =>
Promise.resolve({
@@ -198,6 +204,7 @@ describe('turns', () => {
sandboxProviderStore: new SqliteSandboxProviderStore(db),
logger,
resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT,
+ authorizer: new TrueForgeAuthorizer(),
}),
);
@@ -304,6 +311,7 @@ describe('turns', () => {
sandboxProviderStore: new SqliteSandboxProviderStore(db),
logger,
resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT,
+ authorizer: new TrueForgeAuthorizer(),
}),
);
@@ -323,4 +331,89 @@ describe('turns', () => {
).toBe(true);
});
});
+
+ describe('create turn referenced agent', () => {
+ const denyAllAuthorizer: Authorizer = {
+ listAgentAccess: () => Promise.resolve({ kind: 'agent_external_ids', agent_external_ids: [] }),
+ canAccessAgent: () => Promise.resolve(false),
+ };
+
+ async function referencedAgentHarness(authorizer: Authorizer) {
+ const db = createSqliteDb(':memory:');
+ await migrateSqliteToLatest(db);
+ const sessionStore = new SqliteSessionStore(db);
+ const sessions = new Sessions({ sessionStore });
+ const agentStore = new SqliteAgentStore(db);
+ const agent = await agentStore.createAgent({
+ tenant_id: 'default',
+ created_by_subject: {
+ subject_id: STANDALONE_REQUEST_CONTEXT.subject.id,
+ subject_type: STANDALONE_REQUEST_CONTEXT.subject.type,
+ subject_display_name: STANDALONE_REQUEST_CONTEXT.subject.display_name,
+ },
+ name: 'named-for-turn',
+ manifest: AgentSpecSchema.parse({
+ model: { name: 'test-provider/test-model' },
+ instructions: 'test',
+ }),
+ external_id: null,
+ });
+ await sessionStore.createSession({
+ tenant_id: 'default',
+ session_id: 's1',
+ created_by_subject: {
+ subject_id: STANDALONE_REQUEST_CONTEXT.subject.id,
+ subject_type: STANDALONE_REQUEST_CONTEXT.subject.type,
+ subject_display_name: STANDALONE_REQUEST_CONTEXT.subject.display_name,
+ },
+ agent: { type: 'reference', id: agent.id, name: agent.name },
+ custom: null,
+ metadata: {},
+ external_id: null,
+ });
+ const tokenStore = new SqliteOAuthTokenStore(db);
+ const app = new OpenAPIHono();
+ app.route(
+ '/',
+ createTurnsRouter({
+ sessions,
+ sessionStore,
+ activeTurns: new ActiveTurnRegistry(),
+ resolveModelProviderStore: () => new SqliteModelProviderStore(db),
+ resolveMcpServerStore: () => mcpServerStoreWithAuth(db, tokenStore),
+ skillStore: new SqliteSkillStore(db),
+ resolveAgentStore: () => agentStore,
+ eventSubscriptions: new EventSubscriptionRegistry(undefined),
+ sandboxProviderStore: new SqliteSandboxProviderStore(db),
+ logger: createLogger({ silent: true }),
+ resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT,
+ authorizer,
+ }),
+ );
+ return { app, agent, agentStore };
+ }
+
+ it('returns 422 when the referenced agent no longer exists', async () => {
+ const { app, agent, agentStore } = await referencedAgentHarness(new TrueForgeAuthorizer());
+ await agentStore.deleteAgent({ tenant_id: 'default', id: agent.id });
+ const response = await app.request('/s1/turns', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ stream: false }),
+ });
+ expect(response.status).toBe(422);
+ expect(await response.json()).toEqual({ error: { message: `Agent not found: ${agent.id}` } });
+ });
+
+ it('returns 404 when the caller cannot read the referenced agent', async () => {
+ const { app, agent } = await referencedAgentHarness(denyAllAuthorizer);
+ const response = await app.request('/s1/turns', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ stream: false }),
+ });
+ expect(response.status).toBe(404);
+ expect(await response.json()).toEqual({ error: { message: `Agent not found: ${agent.id}` } });
+ });
+ });
});