Skip to content

Commit 1672aed

Browse files
[AuthZ: 2/N] Add external agent authorizer (#585)
* fix(trueforge): remove TrueFoundry global admin Co-authored-by: Cursor <cursoragent@cursor.com> * feat(trueforge): add external agent authorizer Co-authored-by: Cursor <cursoragent@cursor.com> * Address review comments * Address review comments * Fix api path * Fix permissions parsing --------- Co-authored-by: Cursor <cursoragent@cursor.com>
1 parent c4ee138 commit 1672aed

6 files changed

Lines changed: 137 additions & 7 deletions

File tree

‎packages/trueforge/scripts/write-openapi.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { mkdirSync, writeFileSync } from 'node:fs';
1414
import path from 'node:path';
1515
import winston from 'winston';
1616
import { buildOpenApiDocument, createServerApp } from '../src/app';
17+
import { TrueForgeAuthorizer } from '../src/auth/authorizer';
1718
import { StandaloneAuthenticator } from '../src/auth/standaloneAuthenticator';
1819
import { McpCatalog } from '../src/catalog/McpCatalog';
1920
import { ModelCatalog } from '../src/catalog/ModelCatalog';
@@ -88,6 +89,7 @@ const app = createServerApp({
8889
logger: winston.createLogger({ silent: true }),
8990
oidcClient: undefined,
9091
authenticator: new StandaloneAuthenticator(),
92+
authorizer: new TrueForgeAuthorizer(),
9193
});
9294

9395
// Runtime apps only advertise BearerAuth when OIDC is configured. The committed

‎packages/trueforge/src/app.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import { createSettingsRouter } from './apis/settings';
2424
import { createAvailableSkillsRouter } from './apis/skills';
2525
import { createTurnsRouter } from './apis/turns';
2626
import type { Authenticator } from './auth/authenticator';
27+
import type { Authorizer } from './auth/authorizer';
2728
import { resolveRequestContext } from './auth/identity';
2829
import { createAdminAuthMiddleware, createAuthMiddleware } from './auth/middleware';
2930
import type { McpCatalog } from './catalog/McpCatalog';
@@ -199,6 +200,8 @@ export interface ServerDeps<TTransaction> {
199200
oidcClient: Configuration | undefined;
200201
/** Startup-selected authenticator; middleware is built from this once per app. */
201202
authenticator: Authenticator;
203+
/** Startup-selected agent authorization policy. */
204+
authorizer: Authorizer;
202205
}
203206

204207
export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import type { AgentRecord } from '../db/agentStore';
2+
import type { RequestContext } from './identity';
3+
4+
export type AgentAction = 'read' | 'manage';
5+
6+
export type AgentListAccess = { kind: 'all' } | { kind: 'agent_external_ids'; agent_external_ids: readonly string[] };
7+
8+
export interface Authorizer {
9+
listAgentAccess(input: { context: RequestContext; action: AgentAction }): Promise<AgentListAccess>;
10+
canAccessAgent(input: { context: RequestContext; action: AgentAction; agent: AgentRecord }): Promise<boolean>;
11+
}
12+
13+
/** Standalone and OIDC: tenant-local agents. Read is unconstrained; manage is creator-only. */
14+
export class TrueForgeAuthorizer implements Authorizer {
15+
listAgentAccess(): Promise<AgentListAccess> {
16+
return Promise.resolve({ kind: 'all' });
17+
}
18+
19+
canAccessAgent(input: { context: RequestContext; action: AgentAction; agent: AgentRecord }): Promise<boolean> {
20+
if (input.action === 'read') {
21+
return Promise.resolve(true);
22+
}
23+
return Promise.resolve(input.agent.created_by_subject.subject_id === input.context.subject.id);
24+
}
25+
}

‎packages/trueforge/src/main.ts‎

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ import type { RedisClientType } from 'redis';
5656
import type { Logger } from 'winston';
5757

5858
import { createServerApp } from './app';
59+
import { TrueForgeAuthorizer, type Authorizer } from './auth/authorizer';
5960
import { createAuthenticator } from './auth/createAuthenticator';
6061
import { resolveRequestContext } from './auth/identity';
6162
import { initOidc } from './auth/oidc';
@@ -86,6 +87,7 @@ import { EventSubscriptionRegistry } from './runtime/event-subscription';
8687
import { printStandaloneStartupBanner } from './startupBanner';
8788
import { parsePerServerMcpHeaders, X_TFG_MCP_HEADERS } from './truefoundry/perServerMcpHeaders';
8889
import { TrueFoundryAgentStore } from './truefoundry/TrueFoundryAgentStore';
90+
import { TrueFoundryAuthorizer } from './truefoundry/TrueFoundryAuthorizer';
8991
import { TrueFoundryMcpServerStore } from './truefoundry/TrueFoundryMcpServerStore';
9092
import { TrueFoundryModelProviderStore } from './truefoundry/TrueFoundryModelProviderStore';
9193
import { TrueFoundryServiceFoundryServerClient } from './truefoundry/TrueFoundryServiceFoundryServerClient';
@@ -387,25 +389,30 @@ async function createServerRuntime<TTransaction>(persistence: ServerPersistence<
387389
const oidcClient = await initOidc(oidc);
388390

389391
let authenticator;
392+
let authorizer: Authorizer;
390393
const mode = getTrueForgeMode(configuration);
391394
if (mode === TrueForgeMode.TrueFoundry) {
392395
if (!isTrueFoundryModeEnabled(configuration)) {
393396
throw new Error('TrueFoundry mode requires TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL');
394397
}
398+
const trueFoundryClient = new TrueFoundryServiceFoundryServerClient({
399+
serviceFoundryServerUrl: configuration.TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL,
400+
logger,
401+
httpTimeoutMs: configuration.TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_TIMEOUT_MS,
402+
httpAgentTimeoutMs: configuration.TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_AGENT_TIMEOUT_MS,
403+
tls: { enabled: configuration.TRUEFOUNDRY_MTLS_ENABLED, dir: configuration.TRUEFOUNDRY_MTLS_CERTS_DIR },
404+
});
395405
authenticator = createAuthenticator({
396406
mode: TrueForgeMode.TrueFoundry,
397-
trueFoundryClient: new TrueFoundryServiceFoundryServerClient({
398-
serviceFoundryServerUrl: configuration.TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL,
399-
logger,
400-
httpTimeoutMs: configuration.TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_TIMEOUT_MS,
401-
httpAgentTimeoutMs: configuration.TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_AGENT_TIMEOUT_MS,
402-
tls: { enabled: configuration.TRUEFOUNDRY_MTLS_ENABLED, dir: configuration.TRUEFOUNDRY_MTLS_CERTS_DIR },
403-
}),
407+
trueFoundryClient,
404408
});
409+
authorizer = new TrueFoundryAuthorizer(trueFoundryClient);
405410
} else if (mode === TrueForgeMode.Oidc) {
406411
authenticator = createAuthenticator({ mode: TrueForgeMode.Oidc });
412+
authorizer = new TrueForgeAuthorizer();
407413
} else {
408414
authenticator = createAuthenticator({ mode: TrueForgeMode.Standalone });
415+
authorizer = new TrueForgeAuthorizer();
409416
}
410417

411418
// Standalone is one process, so it owns the control loops too.
@@ -441,6 +448,7 @@ async function createServerRuntime<TTransaction>(persistence: ServerPersistence<
441448
logger,
442449
oidcClient,
443450
authenticator,
451+
authorizer,
444452
});
445453

446454
return { activeTurns, app, controller, destroyDb, redis, requestReplyRouter };
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import { HTTPException } from 'hono/http-exception';
2+
3+
import type { AgentAction, AgentListAccess, Authorizer } from '../auth/authorizer';
4+
import type { RequestContext } from '../auth/identity';
5+
import type { AgentRecord } from '../db/agentStore';
6+
import type { AgentPermission, TrueFoundryServiceFoundryServerClient } from './TrueFoundryServiceFoundryServerClient';
7+
8+
function allowsAction(permissions: readonly AgentPermission[], action: AgentAction): boolean {
9+
return action === 'manage'
10+
? permissions.includes('MANAGE_AGENT')
11+
: permissions.includes('READ_AGENT') || permissions.includes('MANAGE_AGENT');
12+
}
13+
14+
function requireUserCredential(context: RequestContext): string {
15+
if (context.user_credential === null) {
16+
throw new HTTPException(401, { message: 'Authentication token required for agent authorization' });
17+
}
18+
return context.user_credential;
19+
}
20+
21+
export class TrueFoundryAuthorizer implements Authorizer {
22+
readonly #client: TrueFoundryServiceFoundryServerClient;
23+
24+
constructor(client: TrueFoundryServiceFoundryServerClient) {
25+
this.#client = client;
26+
}
27+
28+
async listAgentAccess(input: { context: RequestContext; action: AgentAction }): Promise<AgentListAccess> {
29+
const permissions = await this.#client.getAgentPermissions({
30+
accessToken: requireUserCredential(input.context),
31+
});
32+
return {
33+
kind: 'agent_external_ids',
34+
agent_external_ids: Object.entries(permissions)
35+
.filter(([, granted]) => allowsAction(granted, input.action))
36+
.map(([externalId]) => externalId),
37+
};
38+
}
39+
40+
async canAccessAgent(input: { context: RequestContext; action: AgentAction; agent: AgentRecord }): Promise<boolean> {
41+
if (input.agent.external_id === null) {
42+
return false;
43+
}
44+
const permissions = await this.#client.getAgentPermissions({
45+
accessToken: requireUserCredential(input.context),
46+
externalIds: [input.agent.external_id],
47+
});
48+
return allowsAction(permissions[input.agent.external_id] ?? [], input.action);
49+
}
50+
}

‎packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ const INSTALLATIONS_PATH = 'v1/llm-gateway/installations';
1313
const MCP_SERVERS_PATH = 'v1/mcp';
1414
const TFG_AGENTS_PATH = 'internal/tfg/agents';
1515
const SESSION_PATH = 'v1/session';
16+
const AGENT_PERMISSIONS_PATH = 'v1/authorize/permissions';
1617
const INTEGRATIONS_PAGE_SIZE = 1000;
1718

1819
/**
@@ -61,6 +62,21 @@ const PutRemoteAgentResponseSchema = z.object({
6162
agentId: z.string().min(1),
6263
});
6364

65+
const AgentPermissionSchema = z.enum(['READ_AGENT', 'MANAGE_AGENT']);
66+
export type AgentPermission = z.infer<typeof AgentPermissionSchema>;
67+
68+
/** ServiceFoundry may return grants we do not use; drop them instead of failing. */
69+
const AgentPermissionsSchema = z.record(
70+
z.string(),
71+
z.array(z.string()).transform(permissions =>
72+
permissions.flatMap(permission => {
73+
const parsed = AgentPermissionSchema.safeParse(permission);
74+
return parsed.success ? [parsed.data] : [];
75+
}),
76+
),
77+
);
78+
export type AgentPermissions = z.infer<typeof AgentPermissionsSchema>;
79+
6480
export interface PutRemoteAgentInput {
6581
accessToken: string;
6682
name: string;
@@ -355,6 +371,32 @@ export class TrueFoundryServiceFoundryServerClient {
355371
return { user: parsed.data.user };
356372
}
357373

374+
async getAgentPermissions(input: {
375+
accessToken: string;
376+
externalIds?: readonly string[];
377+
}): Promise<AgentPermissions> {
378+
const payload = await this.#requestJson({
379+
url: this.#url(AGENT_PERMISSIONS_PATH, {
380+
resourceType: 'agent',
381+
v2: 'true',
382+
...(input.externalIds === undefined ? {} : { resourceIds: JSON.stringify(input.externalIds) }),
383+
}),
384+
accessToken: input.accessToken,
385+
method: 'GET',
386+
});
387+
const parsed = AgentPermissionsSchema.safeParse(payload);
388+
if (!parsed.success) {
389+
this.#logger.error('TrueFoundry ServiceFoundry agent permissions response was malformed', {
390+
...extractErrorLogFields(parsed.error),
391+
});
392+
throw new HTTPException(424, {
393+
message: 'TrueFoundry ServiceFoundry agent permissions response was malformed',
394+
cause: parsed.error,
395+
});
396+
}
397+
return parsed.data;
398+
}
399+
358400
#parseListResponse(payload: unknown): ListResponse {
359401
const parsed = ListResponseSchema.safeParse(payload);
360402
if (!parsed.success) {

0 commit comments

Comments
 (0)