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: 2 additions & 0 deletions packages/trueforge/scripts/write-openapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { mkdirSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import winston from 'winston';
import { buildOpenApiDocument, createServerApp } from '../src/app';
import { TrueForgeAuthorizer } from '../src/auth/authorizer';
import { StandaloneAuthenticator } from '../src/auth/standaloneAuthenticator';
import { McpCatalog } from '../src/catalog/McpCatalog';
import { ModelCatalog } from '../src/catalog/ModelCatalog';
Expand Down Expand Up @@ -88,6 +89,7 @@ const app = createServerApp({
logger: winston.createLogger({ silent: true }),
oidcClient: undefined,
authenticator: new StandaloneAuthenticator(),
authorizer: new TrueForgeAuthorizer(),
});

// Runtime apps only advertise BearerAuth when OIDC is configured. The committed
Expand Down
3 changes: 3 additions & 0 deletions packages/trueforge/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { createSettingsRouter } from './apis/settings';
import { createAvailableSkillsRouter } from './apis/skills';
import { createTurnsRouter } from './apis/turns';
import type { Authenticator } from './auth/authenticator';
import type { Authorizer } from './auth/authorizer';
import { resolveRequestContext } from './auth/identity';
import { createAdminAuthMiddleware, createAuthMiddleware } from './auth/middleware';
import type { McpCatalog } from './catalog/McpCatalog';
Expand Down Expand Up @@ -199,6 +200,8 @@ export interface ServerDeps<TTransaction> {
oidcClient: Configuration | undefined;
/** Startup-selected authenticator; middleware is built from this once per app. */
authenticator: Authenticator;
/** Startup-selected agent authorization policy. */
authorizer: Authorizer;
}

export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
Expand Down
25 changes: 25 additions & 0 deletions packages/trueforge/src/auth/authorizer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import type { AgentRecord } from '../db/agentStore';
import type { RequestContext } from './identity';

export type AgentAction = 'read' | 'manage';

export type AgentListAccess = { kind: 'all' } | { kind: 'agent_external_ids'; agent_external_ids: readonly string[] };

export interface Authorizer {
listAgentAccess(input: { context: RequestContext; action: AgentAction }): Promise<AgentListAccess>;
canAccessAgent(input: { context: RequestContext; action: AgentAction; agent: AgentRecord }): Promise<boolean>;
}

/** Standalone and OIDC: tenant-local agents. Read is unconstrained; manage is creator-only. */
export class TrueForgeAuthorizer implements Authorizer {
listAgentAccess(): Promise<AgentListAccess> {
return Promise.resolve({ kind: 'all' });
}

canAccessAgent(input: { context: RequestContext; action: AgentAction; agent: AgentRecord }): Promise<boolean> {
if (input.action === 'read') {
return Promise.resolve(true);
}
return Promise.resolve(input.agent.created_by_subject.subject_id === input.context.subject.id);
}
}
Comment thread
chiragjn marked this conversation as resolved.
Resolved
22 changes: 15 additions & 7 deletions packages/trueforge/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ import type { RedisClientType } from 'redis';
import type { Logger } from 'winston';

import { createServerApp } from './app';
import { TrueForgeAuthorizer, type Authorizer } from './auth/authorizer';
import { createAuthenticator } from './auth/createAuthenticator';
import { resolveRequestContext } from './auth/identity';
import { initOidc } from './auth/oidc';
Expand Down Expand Up @@ -86,6 +87,7 @@ import { EventSubscriptionRegistry } from './runtime/event-subscription';
import { printStandaloneStartupBanner } from './startupBanner';
import { parsePerServerMcpHeaders, X_TFG_MCP_HEADERS } from './truefoundry/perServerMcpHeaders';
import { TrueFoundryAgentStore } from './truefoundry/TrueFoundryAgentStore';
import { TrueFoundryAuthorizer } from './truefoundry/TrueFoundryAuthorizer';
import { TrueFoundryMcpServerStore } from './truefoundry/TrueFoundryMcpServerStore';
import { TrueFoundryModelProviderStore } from './truefoundry/TrueFoundryModelProviderStore';
import { TrueFoundryServiceFoundryServerClient } from './truefoundry/TrueFoundryServiceFoundryServerClient';
Expand Down Expand Up @@ -387,25 +389,30 @@ async function createServerRuntime<TTransaction>(persistence: ServerPersistence<
const oidcClient = await initOidc(oidc);

let authenticator;
let authorizer: Authorizer;
const mode = getTrueForgeMode(configuration);
if (mode === TrueForgeMode.TrueFoundry) {
if (!isTrueFoundryModeEnabled(configuration)) {
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: 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 },
}),
trueFoundryClient,
});
authorizer = new TrueFoundryAuthorizer(trueFoundryClient);
} else if (mode === TrueForgeMode.Oidc) {
authenticator = createAuthenticator({ mode: TrueForgeMode.Oidc });
authorizer = new TrueForgeAuthorizer();
} else {
authenticator = createAuthenticator({ mode: TrueForgeMode.Standalone });
authorizer = new TrueForgeAuthorizer();
}

// Standalone is one process, so it owns the control loops too.
Expand Down Expand Up @@ -441,6 +448,7 @@ async function createServerRuntime<TTransaction>(persistence: ServerPersistence<
logger,
oidcClient,
authenticator,
authorizer,
});

return { activeTurns, app, controller, destroyDb, redis, requestReplyRouter };
Expand Down
50 changes: 50 additions & 0 deletions packages/trueforge/src/truefoundry/TrueFoundryAuthorizer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { HTTPException } from 'hono/http-exception';

import type { AgentAction, AgentListAccess, Authorizer } from '../auth/authorizer';
import type { RequestContext } from '../auth/identity';
import type { AgentRecord } from '../db/agentStore';
import type { AgentPermission, TrueFoundryServiceFoundryServerClient } from './TrueFoundryServiceFoundryServerClient';

function allowsAction(permissions: readonly AgentPermission[], action: AgentAction): boolean {
return action === 'manage'
? permissions.includes('MANAGE_AGENT')
: permissions.includes('READ_AGENT') || permissions.includes('MANAGE_AGENT');
}

function requireUserCredential(context: RequestContext): string {
if (context.user_credential === null) {
throw new HTTPException(401, { message: 'Authentication token required for agent authorization' });
}
return context.user_credential;
}

export class TrueFoundryAuthorizer implements Authorizer {
readonly #client: TrueFoundryServiceFoundryServerClient;

constructor(client: TrueFoundryServiceFoundryServerClient) {
this.#client = client;
}

async listAgentAccess(input: { context: RequestContext; action: AgentAction }): Promise<AgentListAccess> {
const permissions = await this.#client.getAgentPermissions({
accessToken: requireUserCredential(input.context),
});
return {
kind: 'agent_external_ids',
agent_external_ids: Object.entries(permissions)
.filter(([, granted]) => allowsAction(granted, input.action))
.map(([externalId]) => externalId),
};
}

async canAccessAgent(input: { context: RequestContext; action: AgentAction; agent: AgentRecord }): Promise<boolean> {
if (input.agent.external_id === null) {
return false;
}
const permissions = await this.#client.getAgentPermissions({
accessToken: requireUserCredential(input.context),
externalIds: [input.agent.external_id],
});
return allowsAction(permissions[input.agent.external_id] ?? [], input.action);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const INSTALLATIONS_PATH = 'v1/llm-gateway/installations';
const MCP_SERVERS_PATH = 'v1/mcp';
const TFG_AGENTS_PATH = 'internal/tfg/agents';
const SESSION_PATH = 'v1/session';
const AGENT_PERMISSIONS_PATH = 'v1/authorize/permissions';
const INTEGRATIONS_PAGE_SIZE = 1000;

/**
Expand Down Expand Up @@ -61,6 +62,21 @@ const PutRemoteAgentResponseSchema = z.object({
agentId: z.string().min(1),
});

const AgentPermissionSchema = z.enum(['READ_AGENT', 'MANAGE_AGENT']);
export type AgentPermission = z.infer<typeof AgentPermissionSchema>;

/** ServiceFoundry may return grants we do not use; drop them instead of failing. */
const AgentPermissionsSchema = z.record(
z.string(),
z.array(z.string()).transform(permissions =>
permissions.flatMap(permission => {
const parsed = AgentPermissionSchema.safeParse(permission);
return parsed.success ? [parsed.data] : [];
}),
),
);
export type AgentPermissions = z.infer<typeof AgentPermissionsSchema>;

export interface PutRemoteAgentInput {
accessToken: string;
name: string;
Expand Down Expand Up @@ -355,6 +371,32 @@ export class TrueFoundryServiceFoundryServerClient {
return { user: parsed.data.user };
}

async getAgentPermissions(input: {
accessToken: string;
externalIds?: readonly string[];
}): Promise<AgentPermissions> {
const payload = await this.#requestJson({
url: this.#url(AGENT_PERMISSIONS_PATH, {
resourceType: 'agent',
v2: 'true',
...(input.externalIds === undefined ? {} : { resourceIds: JSON.stringify(input.externalIds) }),
}),
accessToken: input.accessToken,
method: 'GET',
});
const parsed = AgentPermissionsSchema.safeParse(payload);
if (!parsed.success) {
this.#logger.error('TrueFoundry ServiceFoundry agent permissions response was malformed', {
...extractErrorLogFields(parsed.error),
});
throw new HTTPException(424, {
message: 'TrueFoundry ServiceFoundry agent permissions response was malformed',
cause: parsed.error,
});
}
return parsed.data;
}

#parseListResponse(payload: unknown): ListResponse {
const parsed = ListResponseSchema.safeParse(payload);
if (!parsed.success) {
Expand Down