Skip to content

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

feat: Introduce a unified RequestContext for standalone, OIDC, and TrueFoundry authentication (#565)

Sujai Kumar Gupta4137af1c2074
diff --git a/.changeset/unified-request-context-auth.md b/.changeset/unified-request-context-auth.md
new file mode 100644
index 000000000..df05ca6e8
--- /dev/null
+++ b/.changeset/unified-request-context-auth.md
@@ -0,0 +1,5 @@
+---
+'@truefoundry/trueforge': minor
+---
+
+Unify request-scoped RequestContext across standalone, OIDC, and TrueFoundry auth. `/auth/me` returns `{ data: { type, tenant_id, subject, roles } }` (`type` is `oidc-connected` | `default`; OpenAPI/SDK regen deferred to CI).
diff --git a/.github/fern/openapi/openapi.json b/.github/fern/openapi/openapi.json
index 410fd969b..3df5d5a89 100644
--- a/.github/fern/openapi/openapi.json
+++ b/.github/fern/openapi/openapi.json
@@ -1342,27 +1342,34 @@
},
"GetMeResponse": {
"properties": {
- "email": {
- "description": "User email from the ID token when connected; `\"default\"` when anonymous.",
+ "data": {
+ "$ref": "#/components/schemas/Me"
+ }
+ },
+ "required": [
+ "data"
+ ],
+ "type": "object"
+ },
+ "GetMeSubject": {
+ "properties": {
+ "display_name": {
+ "description": "Human-readable name for the caller.",
"type": "string"
},
- "role": {
- "description": "Caller role.",
+ "id": {
+ "description": "Stable subject identifier for the caller.",
"type": "string"
},
"type": {
- "description": "Session kind: `default` when no valid OIDC session; `oidc-connected` after a successful browser login.",
- "enum": [
- "default",
- "oidc-connected"
- ],
+ "description": "Subject kind as returned by the identity provider (stored as-is).",
"type": "string"
}
},
"required": [
+ "id",
"type",
- "email",
- "role"
+ "display_name"
],
"type": "object"
},
@@ -2243,6 +2250,42 @@
],
"type": "object"
},
+ "Me": {
+ "properties": {
+ "roles": {
+ "description": "Roles for the authenticated caller.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "subject": {
+ "$ref": "#/components/schemas/GetMeSubject"
+ },
+ "tenant_id": {
+ "description": "Tenant scope for the authenticated caller.",
+ "type": "string"
+ },
+ "type": {
+ "$ref": "#/components/schemas/MeSessionType"
+ }
+ },
+ "required": [
+ "type",
+ "tenant_id",
+ "subject",
+ "roles"
+ ],
+ "type": "object"
+ },
+ "MeSessionType": {
+ "description": "`oidc-connected` when the process is running with browser OIDC login; `default` for standalone or TrueFoundry token auth.",
+ "enum": [
+ "default",
+ "oidc-connected"
+ ],
+ "type": "string"
+ },
"MetricsUnit": {
"enum": [
"count",
@@ -4823,14 +4866,14 @@
"securitySchemes": {
"BearerAuth": {
"bearerFormat": "JWT",
- "description": "ID token (`Authorization: Bearer <id_token>`). Required on protected routes. Browser sessions may use the HttpOnly `id_token` cookie instead.",
+ "description": "Caller credential (`Authorization: Bearer <token>`). Required on protected routes when auth is enabled. Browser sessions may use the HttpOnly `id_token` or `accessToken` cookie instead.",
"scheme": "bearer",
"type": "http"
}
}
},
"info": {
- "description": "HTTP API for the TrueForge agent server (`/api/v1`). Interactive docs are served at `/api/v1/docs` (OpenAPI JSON at `/api/v1/openapi.json`).\n\n**Authentication:** Standalone deployments (no OIDC) accept requests without credentials — middleware stamps a local default user. When OIDC is configured, protected routes require a valid `id_token` cookie or `Authorization: Bearer` ID token. There is no built-in API-key scheme; pass custom headers only if your reverse proxy or IdP layer requires them.\n\nCovers DB-backed sessions, the agent registry, settings catalogs, and model/MCP/skill/sandbox providers.",
+ "description": "HTTP API for the TrueForge agent server (`/api/v1`). Interactive docs are served at `/api/v1/docs` (OpenAPI JSON at `/api/v1/openapi.json`).\n\n**Authentication:** Standalone auth accepts requests without credentials — middleware stamps a local default user. When OIDC or TrueFoundry auth is configured, protected routes require a valid cookie or `Authorization: Bearer` token. There is no built-in API-key scheme; pass custom headers only if your reverse proxy or IdP layer requires them.\n\nCovers DB-backed sessions, the agent registry, settings catalogs, and model/MCP/skill/sandbox providers.",
"title": "TrueForge API",
"version": "0.2.0-rc.0"
},
@@ -5529,7 +5572,7 @@
},
"/api/v1/auth/me": {
"get": {
- "description": "Returns the authenticated caller identity. When auth is enabled this requires a valid `id_token` cookie or `Authorization: Bearer` ID token (401 otherwise). When auth is disabled, returns the default identity.",
+ "description": "Returns the authenticated caller identity (`type`, `tenant_id`, `subject`, `roles`) wrapped as `{ data }`. `type` is `oidc-connected` when browser OIDC is enabled, otherwise `default`. When auth is enabled this requires a valid `id_token` cookie or `Authorization: Bearer` token (401 otherwise). When auth is disabled, returns the standalone default identity.",
"responses": {
"200": {
"content": {
@@ -5539,7 +5582,7 @@
}
}
},
- "description": "Session type and identity for the current request."
+ "description": "Caller identity for the current request."
},
"401": {
"content": {
@@ -5549,7 +5592,7 @@
}
}
},
- "description": "Auth is enabled and the request has no valid cookie or Bearer ID token."
+ "description": "Auth is enabled and the request has no valid cookie or Bearer token."
}
},
"summary": "Current session",
diff --git a/charts/trueforge/README.md b/charts/trueforge/README.md
index 029b30cbb..129d09abe 100644
--- a/charts/trueforge/README.md
+++ b/charts/trueforge/README.md
@@ -138,6 +138,7 @@ configs:
key: client-secret
# optional claim overrides (defaults shown):
# userReferenceClaim: sub
+ # userDisplayNameClaim: name
# userRoleClaim: groups
# adminRoleValue: admin
# scopes: "openid,profile,email,groups"
diff --git a/charts/trueforge/templates/_helpers.tpl b/charts/trueforge/templates/_helpers.tpl
index a5618d7f9..19c86df5f 100644
--- a/charts/trueforge/templates/_helpers.tpl
+++ b/charts/trueforge/templates/_helpers.tpl
@@ -215,6 +215,7 @@ fields, wires bundled Postgres/Redis, optional OIDC, then server.extraEnv.
{{- $env = append $env (dict "name" "OIDC_CLIENT_ID" "value" .Values.configs.oidc.clientId) -}}
{{- $env = append $env (include "trueforge.env.fromStringOrValueFrom" (dict "name" "OIDC_CLIENT_SECRET" "field" "configs.oidc.clientSecret" "value" .Values.configs.oidc.clientSecret) | fromJson) -}}
{{- $env = append $env (dict "name" "OIDC_USER_REFERENCE_CLAIM" "value" .Values.configs.oidc.userReferenceClaim) -}}
+{{- $env = append $env (dict "name" "OIDC_USER_DISPLAY_NAME_CLAIM" "value" .Values.configs.oidc.userDisplayNameClaim) -}}
{{- $env = append $env (dict "name" "OIDC_USER_ROLE_CLAIM" "value" .Values.configs.oidc.userRoleClaim) -}}
{{- $env = append $env (dict "name" "OIDC_ADMIN_ROLE_VALUE" "value" .Values.configs.oidc.adminRoleValue) -}}
{{- $env = append $env (dict "name" "OIDC_SCOPES" "value" .Values.configs.oidc.scopes) -}}
diff --git a/charts/trueforge/values.yaml b/charts/trueforge/values.yaml
index 5b13fad53..c0acd56ff 100644
--- a/charts/trueforge/values.yaml
+++ b/charts/trueforge/values.yaml
@@ -106,6 +106,7 @@ configs:
# name: trueforge-oidc
# key: client-secret
userReferenceClaim: sub
+ userDisplayNameClaim: name
userRoleClaim: groups
adminRoleValue: admin
scopes: "openid,profile,email"
diff --git a/docs/authentication/overview.mdx b/docs/authentication/overview.mdx
index 284ba4f39..996a13400 100644
--- a/docs/authentication/overview.mdx
+++ b/docs/authentication/overview.mdx
@@ -73,6 +73,7 @@ The default. Do **not** set any `OIDC_*` variables, run TrueForge as usual ([Qui
OIDC_CLIENT_ID=0oa...
OIDC_CLIENT_SECRET=...
OIDC_USER_REFERENCE_CLAIM=email
+ OIDC_USER_DISPLAY_NAME_CLAIM=name
OIDC_USER_ROLE_CLAIM=groups
OIDC_ADMIN_ROLE_VALUE=harness-admin
OIDC_SCOPES=openid,profile,email,groups
@@ -104,6 +105,7 @@ The default. Do **not** set any `OIDC_*` variables, run TrueForge as usual ([Qui
OIDC_CLIENT_ID=<application-client-id>
OIDC_CLIENT_SECRET=...
OIDC_USER_REFERENCE_CLAIM=email
+ OIDC_USER_DISPLAY_NAME_CLAIM=name
OIDC_USER_ROLE_CLAIM=groups
OIDC_ADMIN_ROLE_VALUE=<admin-group-object-id>
OIDC_SCOPES=openid,profile,email
@@ -124,6 +126,7 @@ The default. Do **not** set any `OIDC_*` variables, run TrueForge as usual ([Qui
| `OIDC_CLIENT_ID` | Yes | OIDC client ID |
| `OIDC_CLIENT_SECRET` | Yes | OIDC client secret |
| `OIDC_USER_REFERENCE_CLAIM` | No (default `sub`) | Claim used as the user id for session ownership |
+ | `OIDC_USER_DISPLAY_NAME_CLAIM` | No (default `name`) | Claim used as the user's display name |
| `OIDC_USER_ROLE_CLAIM` | No (default `groups`) | Claim inspected for admin membership |
| `OIDC_ADMIN_ROLE_VALUE` | No (default `admin`) | Exact string that grants `admin` (case-sensitive) |
| `OIDC_SCOPES` | No (default `openid,profile,email`) | Scopes for the authorize request |
@@ -141,6 +144,7 @@ The default. Do **not** set any `OIDC_*` variables, run TrueForge as usual ([Qui
OIDC_CLIENT_ID=0oa...
OIDC_CLIENT_SECRET=...
OIDC_USER_REFERENCE_CLAIM=email
+ OIDC_USER_DISPLAY_NAME_CLAIM=name
OIDC_USER_ROLE_CLAIM=groups
OIDC_ADMIN_ROLE_VALUE=harness-admin
OIDC_SCOPES=openid,profile,email,groups
@@ -167,6 +171,7 @@ The default. Do **not** set any `OIDC_*` variables, run TrueForge as usual ([Qui
name: trueforge-oidc
key: client-secret
userReferenceClaim: email
+ userDisplayNameClaim: name
userRoleClaim: groups
adminRoleValue: harness-admin
scopes: "openid,profile,email,groups"
diff --git a/docs/openapi.json b/docs/openapi.json
index 410fd969b..3df5d5a89 100644
--- a/docs/openapi.json
+++ b/docs/openapi.json
@@ -1342,27 +1342,34 @@
},
"GetMeResponse": {
"properties": {
- "email": {
- "description": "User email from the ID token when connected; `\"default\"` when anonymous.",
+ "data": {
+ "$ref": "#/components/schemas/Me"
+ }
+ },
+ "required": [
+ "data"
+ ],
+ "type": "object"
+ },
+ "GetMeSubject": {
+ "properties": {
+ "display_name": {
+ "description": "Human-readable name for the caller.",
"type": "string"
},
- "role": {
- "description": "Caller role.",
+ "id": {
+ "description": "Stable subject identifier for the caller.",
"type": "string"
},
"type": {
- "description": "Session kind: `default` when no valid OIDC session; `oidc-connected` after a successful browser login.",
- "enum": [
- "default",
- "oidc-connected"
- ],
+ "description": "Subject kind as returned by the identity provider (stored as-is).",
"type": "string"
}
},
"required": [
+ "id",
"type",
- "email",
- "role"
+ "display_name"
],
"type": "object"
},
@@ -2243,6 +2250,42 @@
],
"type": "object"
},
+ "Me": {
+ "properties": {
+ "roles": {
+ "description": "Roles for the authenticated caller.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "subject": {
+ "$ref": "#/components/schemas/GetMeSubject"
+ },
+ "tenant_id": {
+ "description": "Tenant scope for the authenticated caller.",
+ "type": "string"
+ },
+ "type": {
+ "$ref": "#/components/schemas/MeSessionType"
+ }
+ },
+ "required": [
+ "type",
+ "tenant_id",
+ "subject",
+ "roles"
+ ],
+ "type": "object"
+ },
+ "MeSessionType": {
+ "description": "`oidc-connected` when the process is running with browser OIDC login; `default` for standalone or TrueFoundry token auth.",
+ "enum": [
+ "default",
+ "oidc-connected"
+ ],
+ "type": "string"
+ },
"MetricsUnit": {
"enum": [
"count",
@@ -4823,14 +4866,14 @@
"securitySchemes": {
"BearerAuth": {
"bearerFormat": "JWT",
- "description": "ID token (`Authorization: Bearer <id_token>`). Required on protected routes. Browser sessions may use the HttpOnly `id_token` cookie instead.",
+ "description": "Caller credential (`Authorization: Bearer <token>`). Required on protected routes when auth is enabled. Browser sessions may use the HttpOnly `id_token` or `accessToken` cookie instead.",
"scheme": "bearer",
"type": "http"
}
}
},
"info": {
- "description": "HTTP API for the TrueForge agent server (`/api/v1`). Interactive docs are served at `/api/v1/docs` (OpenAPI JSON at `/api/v1/openapi.json`).\n\n**Authentication:** Standalone deployments (no OIDC) accept requests without credentials — middleware stamps a local default user. When OIDC is configured, protected routes require a valid `id_token` cookie or `Authorization: Bearer` ID token. There is no built-in API-key scheme; pass custom headers only if your reverse proxy or IdP layer requires them.\n\nCovers DB-backed sessions, the agent registry, settings catalogs, and model/MCP/skill/sandbox providers.",
+ "description": "HTTP API for the TrueForge agent server (`/api/v1`). Interactive docs are served at `/api/v1/docs` (OpenAPI JSON at `/api/v1/openapi.json`).\n\n**Authentication:** Standalone auth accepts requests without credentials — middleware stamps a local default user. When OIDC or TrueFoundry auth is configured, protected routes require a valid cookie or `Authorization: Bearer` token. There is no built-in API-key scheme; pass custom headers only if your reverse proxy or IdP layer requires them.\n\nCovers DB-backed sessions, the agent registry, settings catalogs, and model/MCP/skill/sandbox providers.",
"title": "TrueForge API",
"version": "0.2.0-rc.0"
},
@@ -5529,7 +5572,7 @@
},
"/api/v1/auth/me": {
"get": {
- "description": "Returns the authenticated caller identity. When auth is enabled this requires a valid `id_token` cookie or `Authorization: Bearer` ID token (401 otherwise). When auth is disabled, returns the default identity.",
+ "description": "Returns the authenticated caller identity (`type`, `tenant_id`, `subject`, `roles`) wrapped as `{ data }`. `type` is `oidc-connected` when browser OIDC is enabled, otherwise `default`. When auth is enabled this requires a valid `id_token` cookie or `Authorization: Bearer` token (401 otherwise). When auth is disabled, returns the standalone default identity.",
"responses": {
"200": {
"content": {
@@ -5539,7 +5582,7 @@
}
}
},
- "description": "Session type and identity for the current request."
+ "description": "Caller identity for the current request."
},
"401": {
"content": {
@@ -5549,7 +5592,7 @@
}
}
},
- "description": "Auth is enabled and the request has no valid cookie or Bearer ID token."
+ "description": "Auth is enabled and the request has no valid cookie or Bearer token."
}
},
"summary": "Current session",
diff --git a/packages/frontend/README.md b/packages/frontend/README.md
index b1159021b..b37912669 100644
--- a/packages/frontend/README.md
+++ b/packages/frontend/README.md
@@ -47,7 +47,8 @@ already bound, dev exits instead of picking another. Proxy wiring lives in
[`authFetch.ts`](src/authFetch.ts) wraps `fetch` and redirects to OIDC login on HTTP 401.
[`authSession.ts`](src/authSession.ts) probes `/me` with a non-redirecting client so the
-welcome screen can show before login. Pass the auth-aware `fetch` into
+welcome screen can show before login. Logout chrome appears when `me().data.type` is
+`oidc-connected`. Pass the auth-aware `fetch` into
`server={{ type: 'trueforge', fetch }}` so the built-in Harness adapter shares the same
session cookies.
diff --git a/packages/frontend/src/LogoutButton.tsx b/packages/frontend/src/LogoutButton.tsx
index 2db69ef08..cc83dcedb 100644
--- a/packages/frontend/src/LogoutButton.tsx
+++ b/packages/frontend/src/LogoutButton.tsx
@@ -6,7 +6,7 @@ import { UI_BASE_PATH } from './publicPath';
/**
* Icon button next to Settings (via `ShellActionsActionSlot` override).
- * Shown only when `auth.me()` returns `type: "oidc-connected"`.
+ * Shown only when `auth.me()` returns `data.type: "oidc-connected"`.
* Uses a module cache so remounts of the action slot do not hide the control during refetches.
*/
export function LogoutButton() {
diff --git a/packages/frontend/src/authSession.ts b/packages/frontend/src/authSession.ts
index 1eb1bb2a7..4d9f73d4c 100644
--- a/packages/frontend/src/authSession.ts
+++ b/packages/frontend/src/authSession.ts
@@ -37,12 +37,12 @@ export function resetOidcSessionCacheForTests(): void {
}
/**
- * True when the current session is a browser OIDC login (`type: "oidc-connected"`).
+ * True when the current session is a browser OIDC login (`data.type: "oidc-connected"`).
* When auth is enabled, unauthenticated callers get HTTP 401 from `/me`.
*/
export async function isOidcConnectedSession(client: TrueForge = authClient): Promise<boolean> {
- const session = await client.auth.me();
- const isConnected = session.type === 'oidc-connected';
+ const { data } = await client.auth.me();
+ const isConnected = data.type === 'oidc-connected';
cachedIsOidcConnected = isConnected;
return isConnected;
}
diff --git a/packages/frontend/tests/authSession.test.ts b/packages/frontend/tests/authSession.test.ts
index e9102ac59..7d068e229 100644
--- a/packages/frontend/tests/authSession.test.ts
+++ b/packages/frontend/tests/authSession.test.ts
@@ -15,9 +15,12 @@ function createClient(params: { type?: 'default' | 'oidc-connected'; meError?: E
me: async () => {
if (params.meError != null) throw params.meError;
return {
- type: params.type ?? 'default',
- email: '[email protected]',
- role: 'user',
+ data: {
+ type: params.type ?? 'default',
+ tenantId: 'default',
+ subject: { id: 'user-1', type: 'user', displayName: 'user-1' },
+ roles: [],
+ },
};
},
},
diff --git a/packages/trueforge-sdk/reference.md b/packages/trueforge-sdk/reference.md
index 513a83723..556d2dc31 100644
--- a/packages/trueforge-sdk/reference.md
+++ b/packages/trueforge-sdk/reference.md
@@ -341,7 +341,7 @@ await client.agents.delete("agent_id");
<dl>
<dd>
-Returns the authenticated caller identity. When auth is enabled this requires a valid `id_token` cookie or `Authorization: Bearer` ID token (401 otherwise). When auth is disabled, returns the default identity.
+Returns the authenticated caller identity (`type`, `tenant_id`, `subject`, `roles`) wrapped as `{ data }`. `type` is `oidc-connected` when browser OIDC is enabled, otherwise `default`. When auth is enabled this requires a valid `id_token` cookie or `Authorization: Bearer` token (401 otherwise). When auth is disabled, returns the standalone default identity.
</dd>
</dl>
</dd>
diff --git a/packages/trueforge-sdk/src/api/resources/auth/client/Client.ts b/packages/trueforge-sdk/src/api/resources/auth/client/Client.ts
index 6b9e64e21..b2575feed 100644
--- a/packages/trueforge-sdk/src/api/resources/auth/client/Client.ts
+++ b/packages/trueforge-sdk/src/api/resources/auth/client/Client.ts
@@ -23,7 +23,7 @@ export class AuthClient {
}
/**
- * Returns the authenticated caller identity. When auth is enabled this requires a valid `id_token` cookie or `Authorization: Bearer` ID token (401 otherwise). When auth is disabled, returns the default identity.
+ * Returns the authenticated caller identity (`type`, `tenant_id`, `subject`, `roles`) wrapped as `{ data }`. `type` is `oidc-connected` when browser OIDC is enabled, otherwise `default`. When auth is enabled this requires a valid `id_token` cookie or `Authorization: Bearer` token (401 otherwise). When auth is disabled, returns the standalone default identity.
*
* @param {AuthClient.RequestOptions} requestOptions - Request-specific configuration.
*
diff --git a/packages/trueforge-sdk/src/api/types/GetMeResponse.ts b/packages/trueforge-sdk/src/api/types/GetMeResponse.ts
index 9eed69410..b44c06271 100644
--- a/packages/trueforge-sdk/src/api/types/GetMeResponse.ts
+++ b/packages/trueforge-sdk/src/api/types/GetMeResponse.ts
@@ -3,10 +3,5 @@
import type * as TrueForge from "../index.js";
export interface GetMeResponse {
- /** User email from the ID token when connected; `"default"` when anonymous. */
- email: string;
- /** Caller role. */
- role: string;
- /** Session kind: `default` when no valid OIDC session; `oidc-connected` after a successful browser login. */
- type: TrueForge.GetMeResponseType;
+ data: TrueForge.Me;
}
diff --git a/packages/trueforge-sdk/src/api/types/GetMeResponseType.ts b/packages/trueforge-sdk/src/api/types/GetMeResponseType.ts
deleted file mode 100644
index 1779fa3af..000000000
--- a/packages/trueforge-sdk/src/api/types/GetMeResponseType.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-// This file was auto-generated by Fern from our API Definition.
-
-/** Session kind: `default` when no valid OIDC session; `oidc-connected` after a successful browser login. */
-export const GetMeResponseType = {
- Default: "default",
- OidcConnected: "oidc-connected",
-} as const;
-export type GetMeResponseType = (typeof GetMeResponseType)[keyof typeof GetMeResponseType];
diff --git a/packages/trueforge-sdk/src/api/types/GetMeSubject.ts b/packages/trueforge-sdk/src/api/types/GetMeSubject.ts
new file mode 100644
index 000000000..31c352947
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/types/GetMeSubject.ts
@@ -0,0 +1,10 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface GetMeSubject {
+ /** Human-readable name for the caller. */
+ displayName: string;
+ /** Stable subject identifier for the caller. */
+ id: string;
+ /** Subject kind as returned by the identity provider (stored as-is). */
+ type: string;
+}
diff --git a/packages/trueforge-sdk/src/api/types/Me.ts b/packages/trueforge-sdk/src/api/types/Me.ts
new file mode 100644
index 000000000..d79c8dbd8
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/types/Me.ts
@@ -0,0 +1,12 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueForge from "../index.js";
+
+export interface Me {
+ /** Roles for the authenticated caller. */
+ roles: string[];
+ subject: TrueForge.GetMeSubject;
+ /** Tenant scope for the authenticated caller. */
+ tenantId: string;
+ type: TrueForge.MeSessionType;
+}
diff --git a/packages/trueforge-sdk/src/api/types/MeSessionType.ts b/packages/trueforge-sdk/src/api/types/MeSessionType.ts
new file mode 100644
index 000000000..5abebac03
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/types/MeSessionType.ts
@@ -0,0 +1,8 @@
+// This file was auto-generated by Fern from our API Definition.
+
+/** `oidc-connected` when the process is running with browser OIDC login; `default` for standalone or TrueFoundry token auth. */
+export const MeSessionType = {
+ Default: "default",
+ OidcConnected: "oidc-connected",
+} as const;
+export type MeSessionType = (typeof MeSessionType)[keyof typeof MeSessionType];
diff --git a/packages/trueforge-sdk/src/api/types/index.ts b/packages/trueforge-sdk/src/api/types/index.ts
index 5449fdeb5..124434e09 100644
--- a/packages/trueforge-sdk/src/api/types/index.ts
+++ b/packages/trueforge-sdk/src/api/types/index.ts
@@ -61,7 +61,7 @@ export * from "./GetCapabilitiesResponse.js";
export * from "./GetMcpServerCatalogResponse.js";
export * from "./GetMcpServerResponse.js";
export * from "./GetMeResponse.js";
-export * from "./GetMeResponseType.js";
+export * from "./GetMeSubject.js";
export * from "./GetModelProviderCatalogResponse.js";
export * from "./GetModelProviderResponse.js";
export * from "./GetSandboxProviderCatalogResponse.js";
@@ -113,6 +113,8 @@ export * from "./McpServerManifestAuth.js";
export * from "./McpServerToolSelector.js";
export * from "./McpServerType.js";
export * from "./McpToolInfo.js";
+export * from "./Me.js";
+export * from "./MeSessionType.js";
export * from "./MetricsUnit.js";
export * from "./Model.js";
export * from "./ModelMessageDeltaEvent.js";
diff --git a/packages/trueforge-sdk/src/serialization/types/GetMeResponse.ts b/packages/trueforge-sdk/src/serialization/types/GetMeResponse.ts
index b723498a8..93b608ee8 100644
--- a/packages/trueforge-sdk/src/serialization/types/GetMeResponse.ts
+++ b/packages/trueforge-sdk/src/serialization/types/GetMeResponse.ts
@@ -3,19 +3,15 @@
import type * as TrueForge from "../../api/index.js";
import * as core from "../../core/index.js";
import type * as serializers from "../index.js";
-import { GetMeResponseType } from "./GetMeResponseType.js";
+import { Me } from "./Me.js";
export const GetMeResponse: core.serialization.ObjectSchema<serializers.GetMeResponse.Raw, TrueForge.GetMeResponse> =
core.serialization.object({
- email: core.serialization.string(),
- role: core.serialization.string(),
- type: GetMeResponseType,
+ data: Me,
});
export declare namespace GetMeResponse {
export interface Raw {
- email: string;
- role: string;
- type: GetMeResponseType.Raw;
+ data: Me.Raw;
}
}
diff --git a/packages/trueforge-sdk/src/serialization/types/GetMeSubject.ts b/packages/trueforge-sdk/src/serialization/types/GetMeSubject.ts
new file mode 100644
index 000000000..280d57393
--- /dev/null
+++ b/packages/trueforge-sdk/src/serialization/types/GetMeSubject.ts
@@ -0,0 +1,20 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueForge from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const GetMeSubject: core.serialization.ObjectSchema<serializers.GetMeSubject.Raw, TrueForge.GetMeSubject> =
+ core.serialization.object({
+ displayName: core.serialization.property("display_name", core.serialization.string()),
+ id: core.serialization.string(),
+ type: core.serialization.string(),
+ });
+
+export declare namespace GetMeSubject {
+ export interface Raw {
+ display_name: string;
+ id: string;
+ type: string;
+ }
+}
diff --git a/packages/trueforge-sdk/src/serialization/types/Me.ts b/packages/trueforge-sdk/src/serialization/types/Me.ts
new file mode 100644
index 000000000..08ec4faf9
--- /dev/null
+++ b/packages/trueforge-sdk/src/serialization/types/Me.ts
@@ -0,0 +1,23 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueForge from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { GetMeSubject } from "./GetMeSubject.js";
+import { MeSessionType } from "./MeSessionType.js";
+
+export const Me: core.serialization.ObjectSchema<serializers.Me.Raw, TrueForge.Me> = core.serialization.object({
+ roles: core.serialization.list(core.serialization.string()),
+ subject: GetMeSubject,
+ tenantId: core.serialization.property("tenant_id", core.serialization.string()),
+ type: MeSessionType,
+});
+
+export declare namespace Me {
+ export interface Raw {
+ roles: string[];
+ subject: GetMeSubject.Raw;
+ tenant_id: string;
+ type: MeSessionType.Raw;
+ }
+}
diff --git a/packages/trueforge-sdk/src/serialization/types/GetMeResponseType.ts b/packages/trueforge-sdk/src/serialization/types/MeSessionType.ts
similarity index 53%
rename from packages/trueforge-sdk/src/serialization/types/GetMeResponseType.ts
rename to packages/trueforge-sdk/src/serialization/types/MeSessionType.ts
index 9e9a17458..f42cdabba 100644
--- a/packages/trueforge-sdk/src/serialization/types/GetMeResponseType.ts
+++ b/packages/trueforge-sdk/src/serialization/types/MeSessionType.ts
@@ -4,11 +4,9 @@ import type * as TrueForge from "../../api/index.js";
import * as core from "../../core/index.js";
import type * as serializers from "../index.js";
-export const GetMeResponseType: core.serialization.Schema<
- serializers.GetMeResponseType.Raw,
- TrueForge.GetMeResponseType
-> = core.serialization.enum_(["default", "oidc-connected"]);
+export const MeSessionType: core.serialization.Schema<serializers.MeSessionType.Raw, TrueForge.MeSessionType> =
+ core.serialization.enum_(["default", "oidc-connected"]);
-export declare namespace GetMeResponseType {
+export declare namespace MeSessionType {
export type Raw = "default" | "oidc-connected";
}
diff --git a/packages/trueforge-sdk/src/serialization/types/index.ts b/packages/trueforge-sdk/src/serialization/types/index.ts
index 5449fdeb5..124434e09 100644
--- a/packages/trueforge-sdk/src/serialization/types/index.ts
+++ b/packages/trueforge-sdk/src/serialization/types/index.ts
@@ -61,7 +61,7 @@ export * from "./GetCapabilitiesResponse.js";
export * from "./GetMcpServerCatalogResponse.js";
export * from "./GetMcpServerResponse.js";
export * from "./GetMeResponse.js";
-export * from "./GetMeResponseType.js";
+export * from "./GetMeSubject.js";
export * from "./GetModelProviderCatalogResponse.js";
export * from "./GetModelProviderResponse.js";
export * from "./GetSandboxProviderCatalogResponse.js";
@@ -113,6 +113,8 @@ export * from "./McpServerManifestAuth.js";
export * from "./McpServerToolSelector.js";
export * from "./McpServerType.js";
export * from "./McpToolInfo.js";
+export * from "./Me.js";
+export * from "./MeSessionType.js";
export * from "./MetricsUnit.js";
export * from "./Model.js";
export * from "./ModelMessageDeltaEvent.js";
diff --git a/packages/trueforge-sdk/tests/wire/auth.test.ts b/packages/trueforge-sdk/tests/wire/auth.test.ts
index d204c308c..677841a41 100644
--- a/packages/trueforge-sdk/tests/wire/auth.test.ts
+++ b/packages/trueforge-sdk/tests/wire/auth.test.ts
@@ -9,15 +9,29 @@ describe("AuthClient", () => {
const server = mockServerPool.createServer();
const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
- const rawResponseBody = { email: "email", role: "role", type: "default" };
+ const rawResponseBody = {
+ data: {
+ roles: ["roles"],
+ subject: { display_name: "display_name", id: "id", type: "type" },
+ tenant_id: "tenant_id",
+ type: "default",
+ },
+ };
server.mockEndpoint().get("/api/v1/auth/me").respondWith().statusCode(200).jsonBody(rawResponseBody).build();
const response = await client.auth.me();
expect(response).toEqual({
- email: "email",
- role: "role",
- type: "default",
+ data: {
+ roles: ["roles"],
+ subject: {
+ displayName: "display_name",
+ id: "id",
+ type: "type",
+ },
+ tenantId: "tenant_id",
+ type: "default",
+ },
});
});
diff --git a/packages/trueforge/scripts/write-openapi.ts b/packages/trueforge/scripts/write-openapi.ts
index 5d227f936..ee491b2ec 100644
--- a/packages/trueforge/scripts/write-openapi.ts
+++ b/packages/trueforge/scripts/write-openapi.ts
@@ -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 { StandaloneAuthenticator } from '../src/auth/standaloneAuthenticator';
import { McpCatalog } from '../src/catalog/McpCatalog';
import { ModelCatalog } from '../src/catalog/ModelCatalog';
import { SandboxCatalog } from '../src/catalog/SandboxCatalog';
@@ -85,6 +86,7 @@ const app = createServerApp({
eventSubscriptions: new EventSubscriptionRegistry<TurnStreamingEvent>(undefined),
logger: winston.createLogger({ silent: true }),
oidcClient: undefined,
+ authenticator: new StandaloneAuthenticator(),
});
// Runtime apps only advertise BearerAuth when OIDC is configured. The committed
diff --git a/packages/trueforge/src/apis/agents.ts b/packages/trueforge/src/apis/agents.ts
index f9cb16fc0..0bf65fe21 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 { ResolveRequestContext } from '../auth/identity';
import { AgentNameConflictError, type AgentRecord, type IAgentStore } from '../db/agentStore';
import type { IMcpServerStore } from '../db/mcpServerStore';
import type { IModelProviderStore } from '../db/modelProviderStore';
@@ -21,7 +22,6 @@ import {
import { validateAgentSpec } from '../runtime/sessionResources';
import { type Agent, type CreateAgentRequest } from '../schemas/agent';
import { buildAgentCodeSnippets } from './agentCodeSnippets';
-import { TENANT_ID } from './sessions';
export interface AgentsRouterDeps<TTransaction> {
agentStore: IAgentStore<TTransaction>;
@@ -30,6 +30,7 @@ export interface AgentsRouterDeps<TTransaction> {
skillStore: ISkillStore<TTransaction>;
sandboxProviderStore: ISandboxProviderStore<TTransaction>;
withTransaction: WithTransaction<TTransaction>;
+ resolveRequestContext: ResolveRequestContext;
}
/** Wire view: identity columns plus nested manifest. */
@@ -46,15 +47,17 @@ async function validateManifest<TTransaction>({
deps,
modelProviderStore,
mcpServerStore,
+ tenant_id,
}: {
spec: AgentSpec;
deps: AgentsRouterDeps<TTransaction>;
modelProviderStore: IModelProviderStore<TTransaction>;
mcpServerStore: IMcpServerStore<TTransaction>;
+ tenant_id: string;
}): Promise<AgentSpec> {
await validateAgentSpec({
spec,
- tenant_id: TENANT_ID,
+ tenant_id,
modelProviderStore,
mcpServerStore,
skillStore: deps.skillStore,
@@ -65,21 +68,24 @@ async function validateManifest<TTransaction>({
export function createAgentsRouter<TTransaction>(deps: AgentsRouterDeps<TTransaction>) {
const listHandler: RouteHandler<typeof listAgentsRoute> = async c => {
- const records = await deps.agentStore.listAgents(TENANT_ID);
+ const requestContext = deps.resolveRequestContext(c);
+ const records = await deps.agentStore.listAgents(requestContext.tenant_id);
return c.json({ data: records.map(toWireAgent) }, 200);
};
const createHandler: RouteHandler<typeof createAgentRoute> = async c => {
const body: CreateAgentRequest = c.req.valid('json');
+ const requestContext = deps.resolveRequestContext(c);
const manifest = await validateManifest({
spec: body.manifest,
deps,
modelProviderStore: deps.resolveModelProviderStore(c),
mcpServerStore: deps.resolveMcpServerStore(c),
+ tenant_id: requestContext.tenant_id,
});
try {
const record = await deps.agentStore.createAgent({
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
name: body.name,
manifest,
external_id: null,
@@ -95,7 +101,11 @@ export function createAgentsRouter<TTransaction>(deps: AgentsRouterDeps<TTransac
const getHandler: RouteHandler<typeof getAgentRoute> = async c => {
const { agent_id: agentId } = c.req.valid('param');
- const record = await deps.agentStore.getAgent({ tenant_id: TENANT_ID, id: agentId });
+ const requestContext = deps.resolveRequestContext(c);
+ const record = await deps.agentStore.getAgent({
+ tenant_id: requestContext.tenant_id,
+ id: agentId,
+ });
if (record === undefined) {
return c.json({ error: { message: `Agent not found: ${agentId}` } }, 404);
}
@@ -104,7 +114,11 @@ export function createAgentsRouter<TTransaction>(deps: AgentsRouterDeps<TTransac
const getCodeSnippetsHandler: RouteHandler<typeof getAgentCodeSnippetsRoute> = async c => {
const { agent_id: agentId } = c.req.valid('param');
- const record = await deps.agentStore.getAgent({ tenant_id: TENANT_ID, id: agentId });
+ const requestContext = deps.resolveRequestContext(c);
+ const record = await deps.agentStore.getAgent({
+ tenant_id: requestContext.tenant_id,
+ id: agentId,
+ });
if (record === undefined) {
return c.json({ error: { message: `Agent not found: ${agentId}` } }, 404);
}
@@ -121,21 +135,24 @@ export function createAgentsRouter<TTransaction>(deps: AgentsRouterDeps<TTransac
const deleteHandler: RouteHandler<typeof deleteAgentRoute> = async c => {
const { agent_id: agentId } = c.req.valid('param');
- await deps.agentStore.deleteAgent({ tenant_id: TENANT_ID, id: agentId });
+ const requestContext = deps.resolveRequestContext(c);
+ await deps.agentStore.deleteAgent({ tenant_id: requestContext.tenant_id, id: agentId });
return c.json({}, 200);
};
const putHandler: RouteHandler<typeof putAgentRoute> = async c => {
const { agent_id: agentId } = c.req.valid('param');
const body = c.req.valid('json');
+ const requestContext = deps.resolveRequestContext(c);
const manifest = await validateManifest({
spec: body.manifest,
deps,
modelProviderStore: deps.resolveModelProviderStore(c),
mcpServerStore: deps.resolveMcpServerStore(c),
+ tenant_id: requestContext.tenant_id,
});
const record = await deps.agentStore.updateAgent({
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
id: agentId,
manifest,
});
diff --git a/packages/trueforge/src/apis/auth.ts b/packages/trueforge/src/apis/auth.ts
index 0a224aaa3..c7a89c599 100644
--- a/packages/trueforge/src/apis/auth.ts
+++ b/packages/trueforge/src/apis/auth.ts
@@ -1,12 +1,12 @@
import { OpenAPIHono } from '@hono/zod-openapi';
import { extractErrorLogFields } from '@truefoundry/trueforge-core/core';
-import type { Context } from 'hono';
+import type { Context, MiddlewareHandler } from 'hono';
import type { Configuration } from 'openid-client';
import type { Logger } from 'winston';
import { clearAuthCookie, ID_TOKEN_COOKIE, OAUTH_STATE_COOKIE, readOAuthStateCookie } from '../auth/cookies';
-import { resolveUserContext } from '../auth/identity';
-import { authMiddleware, resolveAuthUser } from '../auth/middleware';
-import { buildLoginAuthorization, exchangeAuthorizationCode, getOidcVerify } from '../auth/oidc';
+import { resolveRequestContext } from '../auth/identity';
+import { resolveOidcRequestContext } from '../auth/middleware';
+import { buildLoginAuthorization, exchangeAuthorizationCode } from '../auth/oidc';
import { safeReturnTo } from '../auth/safeReturnTo';
import { authLoginRoute, authLogoutRoute, meRoute, oAuthCallbackRoute } from '../routes/authRoutes';
import type { GetMeResponse } from '../schemas/auth';
@@ -26,7 +26,7 @@ async function redirectIfAlreadyAuthenticated(params: {
whenAuthenticated: string;
}): Promise<Response | undefined> {
try {
- if (await resolveAuthUser(params.context)) {
+ if (await resolveOidcRequestContext(params.context)) {
return params.context.redirect(params.whenAuthenticated, 302);
}
} catch {
@@ -38,9 +38,13 @@ async function redirectIfAlreadyAuthenticated(params: {
/**
* Auth surfaces mounted at /api/v1/auth: login, callback, logout, me.
- * Login, callback, and logout stay public; me requires {@link authMiddleware}.
+ * Login, callback, and logout stay public; me requires the injected {@link authMiddleware}.
*/
-export function createAuthRouter(params: { oidcClient: Configuration | undefined; logger: Logger }) {
+export function createAuthRouter(params: {
+ oidcClient: Configuration | undefined;
+ logger: Logger;
+ authMiddleware: MiddlewareHandler;
+}) {
const router = new OpenAPIHono();
router.openapi(authLoginRoute, async c => {
@@ -115,12 +119,18 @@ export function createAuthRouter(params: { oidcClient: Configuration | undefined
});
const gated = new OpenAPIHono();
- gated.use('*', authMiddleware);
+ gated.use('*', params.authMiddleware);
gated.openapi(meRoute, c => {
- const user = resolveUserContext(c);
- const body: GetMeResponse = getOidcVerify()
- ? { type: 'oidc-connected', email: user.userRef, role: user.role }
- : { type: 'default', email: user.userRef, role: user.role };
+ const requestContext = resolveRequestContext(c);
+ const body: GetMeResponse = {
+ data: {
+ // FE logout chrome keys off `oidc-connected` (browser SSO cookie session).
+ type: params.oidcClient !== undefined ? 'oidc-connected' : 'default',
+ tenant_id: requestContext.tenant_id,
+ subject: requestContext.subject,
+ roles: requestContext.roles,
+ },
+ };
return c.json(body, 200);
});
router.route('/', gated);
diff --git a/packages/trueforge/src/apis/capabilities.ts b/packages/trueforge/src/apis/capabilities.ts
index 1149a3024..f3cecde2f 100644
--- a/packages/trueforge/src/apis/capabilities.ts
+++ b/packages/trueforge/src/apis/capabilities.ts
@@ -1,14 +1,13 @@
import { OpenAPIHono } from '@hono/zod-openapi';
import { extractErrorLogFields } from '@truefoundry/trueforge-core/core';
import type { Logger } from 'winston';
-import { isAdmin, resolveUserContext } from '../auth/identity';
+import { hasAdminRole, type ResolveRequestContext } from '../auth/identity';
import type { ISandboxProviderStore } from '../db/sandboxProviderStore';
import type { WithTransaction } from '../db/transaction';
import { getCapabilitiesRoute } from '../routes/capabilityRoutes';
import { isLocalSandboxFallbackEnabled } from '../sandbox/localRuntime';
import { checkSnapshotStatus } from '../sandbox/providerUtils';
import type { SandboxBuildStatus } from '../schemas/sandboxProvider';
-import { TENANT_ID } from './sessions';
/**
* Why skills are unavailable, keyed off the sandbox build status.
@@ -25,16 +24,18 @@ export function createCapabilitiesRouter<TTransaction>(deps: {
sandboxProviderStore: ISandboxProviderStore<TTransaction>;
withTransaction: WithTransaction<TTransaction>;
logger: Logger;
+ resolveRequestContext: ResolveRequestContext;
}) {
const router = new OpenAPIHono();
router.openapi(getCapabilitiesRoute, async c => {
+ const requestContext = deps.resolveRequestContext(c);
// Sandbox is usable only when a provider is configured AND its image build reports ready.
// Refresh the persisted status (and re-activate an idle snapshot); fail closed (disabled) if it throws.
let status: SandboxBuildStatus | undefined;
try {
const refreshed = await checkSnapshotStatus({
store: deps.sandboxProviderStore,
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
logger: deps.logger,
});
status = refreshed?.status;
@@ -42,7 +43,7 @@ export function createCapabilitiesRouter<TTransaction>(deps: {
deps.logger.warn('Sandbox image status check failed; reporting sandbox disabled', extractErrorLogFields(error));
}
const sandboxEnabled = status === 'ready' || (status === undefined && isLocalSandboxFallbackEnabled());
- const settingsEnabled = isAdmin(resolveUserContext(c));
+ const settingsEnabled = hasAdminRole(requestContext);
return c.json(
{
data: {
diff --git a/packages/trueforge/src/apis/mcpServers.ts b/packages/trueforge/src/apis/mcpServers.ts
index 5427d88a2..805a51b92 100644
--- a/packages/trueforge/src/apis/mcpServers.ts
+++ b/packages/trueforge/src/apis/mcpServers.ts
@@ -2,7 +2,7 @@ import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';
import { extractErrorLogFields, isAuthRequired, McpConnectionError, RemoteMCP } from '@truefoundry/trueforge-core/core';
import type { Context } from 'hono';
import type { Logger } from 'winston';
-import type { ResolveUserContext } from '../auth/identity';
+import type { ResolveRequestContext } from '../auth/identity';
import { safeReturnTo } from '../auth/safeReturnTo';
import configuration from '../config';
import {
@@ -35,14 +35,13 @@ import type {
UpdateMcpServerRequest,
} from '../schemas/mcpServer';
import { MissingStoredSecretError, resolveStoredSecretValue, toRedactedSecretValue } from '../utils/secretRedaction';
-import { TENANT_ID } from './sessions';
export interface McpServersRouterDeps<TTransaction> {
resolveMcpServerStore: (c: Context) => IMcpServerWithAuthStore<TTransaction>;
tokenStore: IOAuthTokenStore<TTransaction>;
withTransaction: WithTransaction<TTransaction>;
logger: Logger;
- resolveUserContext: ResolveUserContext;
+ resolveRequestContext: ResolveRequestContext;
}
/** Omits keys whose value is `undefined` so wire objects satisfy JSONValue index signatures. */
@@ -119,9 +118,10 @@ async function toConfiguredMcpServer<TTransaction>(params: {
/** Admin/settings MCP CRUD (mounted at /api/v1/settings/mcp-servers). */
export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRouterDeps<TTransaction>) {
const listHandler: RouteHandler<typeof listMcpServersRoute> = async c => {
- const userRef = deps.resolveUserContext(c).userRef;
+ const requestContext = deps.resolveRequestContext(c);
+ const userRef = requestContext.subject.id;
const records = await deps.resolveMcpServerStore(c).listServers({
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
names: undefined,
});
const statuses = await deps.resolveMcpServerStore(c).resolveAuthStatuses({
@@ -138,9 +138,10 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRou
const getHandler: RouteHandler<typeof getMcpServerRoute> = async c => {
const { name } = c.req.valid('param');
- const userRef = deps.resolveUserContext(c).userRef;
+ const requestContext = deps.resolveRequestContext(c);
+ const userRef = requestContext.subject.id;
const record = await deps.resolveMcpServerStore(c).getServer({
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
name,
});
if (!record) {
@@ -154,6 +155,7 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRou
const createHandler: RouteHandler<typeof createMcpServerRoute> = async c => {
const body: CreateMcpServerRequest = c.req.valid('json');
+ const requestContext = deps.resolveRequestContext(c);
const incomingManifest = body.manifest;
// DCR finishes before the txn (remote I/O stays out of withTransaction on create).
@@ -193,7 +195,7 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRou
const record = await deps.withTransaction(async transaction => {
const saved = await deps.resolveMcpServerStore(c).createServer(
{
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
name: manifest.name,
manifest,
},
@@ -210,7 +212,7 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRou
data: await toConfiguredMcpServer({
store: deps.resolveMcpServerStore(c),
record,
- userRef: deps.resolveUserContext(c).userRef,
+ userRef: requestContext.subject.id,
}),
},
201,
@@ -224,7 +226,8 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRou
};
const putHandler: RouteHandler<typeof putMcpServerRoute> = async c => {
- const userRef = deps.resolveUserContext(c).userRef;
+ const requestContext = deps.resolveRequestContext(c);
+ const userRef = requestContext.subject.id;
const body: UpdateMcpServerRequest = c.req.valid('json');
const incomingManifest = body.manifest;
@@ -237,7 +240,7 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRou
const record = await deps.withTransaction(async transaction => {
const existing = await deps
.resolveMcpServerStore(c)
- .getServerForUpdate({ tenant_id: TENANT_ID, name: incomingManifest.name }, transaction);
+ .getServerForUpdate({ tenant_id: requestContext.tenant_id, name: incomingManifest.name }, transaction);
const manifest = resolveMcpServerManifestForWrite({
incoming: incomingManifest,
existing: existing?.manifest,
@@ -265,7 +268,7 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRou
const saved = await deps.resolveMcpServerStore(c).upsertServer(
{
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
name: manifest.name,
manifest,
},
@@ -315,7 +318,8 @@ export function createMcpServersRouter<TTransaction>(deps: McpServersRouterDeps<
const authorizeHandler: RouteHandler<typeof authorizeMcpServerRoute> = async c => {
const { name } = c.req.valid('param');
const { return_to: returnTo } = c.req.valid('query');
- const userRef = deps.resolveUserContext(c).userRef;
+ const requestContext = deps.resolveRequestContext(c);
+ const userRef = requestContext.subject.id;
if (returnTo && safeReturnTo(returnTo) !== returnTo) {
return c.json({ error: { message: 'Invalid return_to: must be a same-origin relative path' } }, 400);
@@ -323,7 +327,7 @@ export function createMcpServersRouter<TTransaction>(deps: McpServersRouterDeps<
try {
const authStatus: McpAuthStatus = await deps.resolveMcpServerStore(c).authorize({
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
name,
userRef,
...(returnTo !== undefined ? { returnTo } : {}),
@@ -353,10 +357,11 @@ export function createMcpServersRouter<TTransaction>(deps: McpServersRouterDeps<
const listToolsHandler: RouteHandler<typeof listMcpServerToolsRoute> = async c => {
const { name } = c.req.valid('param');
- const userRef = deps.resolveUserContext(c).userRef;
+ const requestContext = deps.resolveRequestContext(c);
+ const userRef = requestContext.subject.id;
// Same url + header resolution as turn execution (store Bearer, DCR, or static headers).
const connection = await getMcpConnection({
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
name,
store: deps.resolveMcpServerStore(c),
tokenStore: deps.tokenStore,
@@ -397,17 +402,18 @@ export function createMcpServersRouter<TTransaction>(deps: McpServersRouterDeps<
const deleteAuthorizationHandler: RouteHandler<typeof deleteAuthorizationMcpServerRoute> = async c => {
const { name } = c.req.valid('param');
- const userRef = deps.resolveUserContext(c).userRef;
+ const requestContext = deps.resolveRequestContext(c);
+ const userRef = requestContext.subject.id;
try {
const record = await deps.resolveMcpServerStore(c).getServer({
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
name,
});
if (!record) {
return c.json({ error: { message: `MCP server not found: ${name}` } }, 404);
}
await deps.resolveMcpServerStore(c).deleteAuthorization({
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
name,
userRef,
});
@@ -427,9 +433,10 @@ export function createMcpServersRouter<TTransaction>(deps: McpServersRouterDeps<
const router = new OpenAPIHono();
router.openapi(listAvailableMcpServersRoute, async c => {
- const userRef = deps.resolveUserContext(c).userRef;
+ const requestContext = deps.resolveRequestContext(c);
+ const userRef = requestContext.subject.id;
const records = await deps.resolveMcpServerStore(c).listServers({
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
names: undefined,
});
const statuses = await deps.resolveMcpServerStore(c).resolveAuthStatuses({
diff --git a/packages/trueforge/src/apis/modelProviders.ts b/packages/trueforge/src/apis/modelProviders.ts
index 8be433fba..d73e6bb83 100644
--- a/packages/trueforge/src/apis/modelProviders.ts
+++ b/packages/trueforge/src/apis/modelProviders.ts
@@ -1,5 +1,6 @@
import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';
import type { Context } from 'hono';
+import type { ResolveRequestContext } from '../auth/identity';
import {
ModelProviderNameConflictError,
type IModelProviderStore,
@@ -19,11 +20,11 @@ import {
type UpdateModelProviderRequest,
} from '../schemas/modelProvider';
import { MissingStoredSecretError, resolveStoredSecretValue, toRedactedSecretValue } from '../utils/secretRedaction';
-import { TENANT_ID } from './sessions';
export interface ModelProvidersRouterDeps<TTransaction> {
resolveModelProviderStore: (c: Context) => IModelProviderStore<TTransaction>;
withTransaction: WithTransaction<TTransaction>;
+ resolveRequestContext: ResolveRequestContext;
}
function redactModelProvider(manifest: ModelProviderManifest): ModelProviderManifest {
@@ -67,18 +68,24 @@ function toWireProvider(record: ModelProviderRecord): ConfiguredModelProvider {
export function createModelProvidersRouter<TTransaction>(deps: ModelProvidersRouterDeps<TTransaction>) {
const listHandler: RouteHandler<typeof listModelProvidersRoute> = async c => {
- const records = await deps.resolveModelProviderStore(c).listProviders({ tenant_id: TENANT_ID });
+ const requestContext = deps.resolveRequestContext(c);
+ const records = await deps.resolveModelProviderStore(c).listProviders({ tenant_id: requestContext.tenant_id });
return c.json({ data: records.map(toWireProvider) }, 200);
};
const createHandler: RouteHandler<typeof createModelProviderRoute> = async c => {
const body: CreateModelProviderRequest = c.req.valid('json');
+ const requestContext = deps.resolveRequestContext(c);
const provider = body.manifest;
const name = modelProviderName(provider);
try {
// Create has no prior row; redacted keep resolves to MissingStoredSecretError → 400.
const manifest = resolveModelProviderManifestForWrite({ incoming: provider, existing: undefined });
- const record = await deps.resolveModelProviderStore(c).createProvider({ tenant_id: TENANT_ID, name, manifest });
+ const record = await deps.resolveModelProviderStore(c).createProvider({
+ tenant_id: requestContext.tenant_id,
+ name,
+ manifest,
+ });
return c.json({ data: toWireProvider(record) }, 201);
} catch (error) {
if (error instanceof MissingStoredSecretError) {
@@ -94,18 +101,19 @@ export function createModelProvidersRouter<TTransaction>(deps: ModelProvidersRou
const putHandler: RouteHandler<typeof putModelProviderRoute> = async c => {
const store = deps.resolveModelProviderStore(c);
const body: UpdateModelProviderRequest = c.req.valid('json');
+ const requestContext = deps.resolveRequestContext(c);
const provider = body.manifest;
const name = modelProviderName(provider);
try {
// Lock → resolve secret from that snapshot → upsert, all in one txn so concurrent keep
// cannot re-write a secret over a rotate that committed in between.
const record = await deps.withTransaction(async transaction => {
- const existing = await store.getProviderForUpdate({ tenant_id: TENANT_ID, name }, transaction);
+ const existing = await store.getProviderForUpdate({ tenant_id: requestContext.tenant_id, name }, transaction);
const manifest = resolveModelProviderManifestForWrite({
incoming: provider,
existing: existing?.manifest,
});
- return store.upsertProvider({ tenant_id: TENANT_ID, name, manifest }, transaction);
+ return store.upsertProvider({ tenant_id: requestContext.tenant_id, name, manifest }, transaction);
});
return c.json({ data: toWireProvider(record) }, 200);
} catch (error) {
diff --git a/packages/trueforge/src/apis/models.ts b/packages/trueforge/src/apis/models.ts
index 67172b04e..847d37d59 100644
--- a/packages/trueforge/src/apis/models.ts
+++ b/packages/trueforge/src/apis/models.ts
@@ -1,19 +1,21 @@
import { OpenAPIHono } from '@hono/zod-openapi';
import type { Context } from 'hono';
+import type { ResolveRequestContext } from '../auth/identity';
import type { IModelProviderStore } from '../db/modelProviderStore';
import type { WithTransaction } from '../db/transaction';
import { listAvailableModelsRoute } from '../routes/modelRoutes';
-import { TENANT_ID } from './sessions';
/** Chat slim list (mounted at /api/v1/models) — mirrors GET /api/v1/skills. */
export function createModelsRouter<TTransaction>(deps: {
resolveModelProviderStore: (c: Context) => IModelProviderStore<TTransaction>;
withTransaction: WithTransaction<TTransaction>;
+ resolveRequestContext: ResolveRequestContext;
}) {
const router = new OpenAPIHono();
router.openapi(listAvailableModelsRoute, async c => {
const store = deps.resolveModelProviderStore(c);
- return c.json({ data: await store.listModels({ tenant_id: TENANT_ID }) }, 200);
+ const requestContext = deps.resolveRequestContext(c);
+ return c.json({ data: await store.listModels({ tenant_id: requestContext.tenant_id }) }, 200);
});
return router;
}
diff --git a/packages/trueforge/src/apis/sandboxProviders.ts b/packages/trueforge/src/apis/sandboxProviders.ts
index a4a77aad7..843810115 100644
--- a/packages/trueforge/src/apis/sandboxProviders.ts
+++ b/packages/trueforge/src/apis/sandboxProviders.ts
@@ -1,6 +1,7 @@
import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';
import { withTimeout } from '@truefoundry/trueforge-core/core';
import type { Logger } from 'winston';
+import type { ResolveRequestContext } from '../auth/identity';
import type { ISandboxProviderStore, SandboxProviderRecord } from '../db/sandboxProviderStore';
import type { WithTransaction } from '../db/transaction';
import { getSandboxProviderRoute, putSandboxProviderRoute } from '../routes/sandboxProviderRoutes';
@@ -13,7 +14,6 @@ import {
} from '../sandbox/providerUtils';
import type { SandboxProviderManifest, UpdateSandboxProviderRequest } from '../schemas/sandboxProvider';
import { MissingStoredSecretError, resolveStoredSecretValue, toRedactedSecretValue } from '../utils/secretRedaction';
-import { TENANT_ID } from './sessions';
/** Cap the Daytona register round-trip so a slow/unreachable provider can't hold the request (or DB txn) open. */
const BUILD_REQUEST_TIMEOUT_MS = 3_000;
@@ -22,6 +22,7 @@ export interface SandboxProvidersRouterDeps<TTransaction> {
sandboxProviderStore: ISandboxProviderStore<TTransaction>;
withTransaction: WithTransaction<TTransaction>;
logger: Logger;
+ resolveRequestContext: ResolveRequestContext;
}
function redactSandboxProvider(manifest: SandboxProviderManifest): SandboxProviderManifest {
@@ -34,14 +35,15 @@ function redactSandboxProvider(manifest: SandboxProviderManifest): SandboxProvid
/** Admin/settings sandbox provider surface (mounted at /api/v1/settings/sandbox-providers). */
export function createSandboxProvidersRouter<TTransaction>(deps: SandboxProvidersRouterDeps<TTransaction>) {
const getHandler: RouteHandler<typeof getSandboxProviderRoute> = async c => {
- const record = await deps.sandboxProviderStore.getSandboxProvider(TENANT_ID);
+ const requestContext = deps.resolveRequestContext(c);
+ const record = await deps.sandboxProviderStore.getSandboxProvider(requestContext.tenant_id);
if (record === undefined) {
return c.json({ error: { message: 'No sandbox provider configured' } }, 404);
}
// Refresh the persisted build status (and re-activate an idle snapshot) on every GET.
const status = await checkSnapshotStatus({
store: deps.sandboxProviderStore,
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
logger: deps.logger,
});
return c.json(
@@ -58,6 +60,7 @@ export function createSandboxProvidersRouter<TTransaction>(deps: SandboxProvider
const putHandler: RouteHandler<typeof putSandboxProviderRoute> = async c => {
const body: UpdateSandboxProviderRequest = c.req.valid('json');
+ const requestContext = deps.resolveRequestContext(c);
const incoming = body.manifest;
const resolveManifest = (existing: SandboxProviderRecord | undefined): SandboxProviderManifest => ({
...incoming,
@@ -71,13 +74,16 @@ export function createSandboxProvidersRouter<TTransaction>(deps: SandboxProvider
try {
// NOTE: build (Daytona network I/O) runs inside the transaction for now; the design is being revisited.
const { manifest, status } = await deps.withTransaction(async transaction => {
- const locked = await deps.sandboxProviderStore.getSandboxProviderForUpdate(TENANT_ID, transaction);
+ const locked = await deps.sandboxProviderStore.getSandboxProviderForUpdate(
+ requestContext.tenant_id,
+ transaction,
+ );
const resolved = resolveManifest(locked);
// Pass persisted build_metadata so a settings re-save does not start a new snapshot for a
// bumped SANDBOX_IMAGE_URI (upgrades are unsupported — first configure has no metadata).
const provider = toDaytonaSandboxProvider({
manifest: resolved,
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
logger: deps.logger,
...(locked ? { build_metadata: locked.build_metadata } : {}),
});
@@ -85,7 +91,7 @@ export function createSandboxProvidersRouter<TTransaction>(deps: SandboxProvider
await withTimeout(provider.buildImage(), BUILD_REQUEST_TIMEOUT_MS, 'sandbox buildImage'),
);
await deps.sandboxProviderStore.upsertSandboxProvider(
- { tenant_id: TENANT_ID, manifest: resolved, ...built },
+ { tenant_id: requestContext.tenant_id, manifest: resolved, ...built },
transaction,
);
return { manifest: resolved, status: built };
diff --git a/packages/trueforge/src/apis/schedules.ts b/packages/trueforge/src/apis/schedules.ts
index 68a3b4183..5f5b5a13e 100644
--- a/packages/trueforge/src/apis/schedules.ts
+++ b/packages/trueforge/src/apis/schedules.ts
@@ -3,8 +3,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 { UserContext } from '../auth/identity';
+import { hasAdminRole, type RequestContext, type ResolveRequestContext } from '../auth/identity';
import { ScheduleAgentNotFoundError, startScheduleRun } from '../controller/scheduleDispatch';
import type { IAgentStore } from '../db/agentStore';
import {
@@ -33,7 +32,6 @@ import {
type ScheduleManifest,
type ScheduleRun,
} from '../schemas/schedule';
-import { TENANT_ID } from './sessions';
import { getTurnExecutionError, startTurnInProcess, type BeginTurnExecutionDeps } from './turns';
export interface SchedulesRouterDeps<TTransaction> {
@@ -42,7 +40,7 @@ export interface SchedulesRouterDeps<TTransaction> {
sessions: Sessions;
turnDeps: BeginTurnExecutionDeps;
withTransaction: WithTransaction<TTransaction>;
- resolveUserContext: (c: Context) => UserContext;
+ resolveRequestContext: ResolveRequestContext;
}
function toWireSchedule(record: ScheduleRecord): Schedule {
@@ -104,29 +102,28 @@ export function validateManifest(manifest: Pick<ScheduleManifest, 'cron' | 'time
const FORBIDDEN_SCHEDULE_ACCESS = 'Only the schedule creator can access this schedule';
/**
- * A schedule is visible to its creator, and to any admin.
+ * A schedule is visible to its creator, and to any admin ({@link hasAdminRole}).
*
- * The role is read directly rather than via {@link isAdmin}, which reports admin
- * whenever auth is disabled — irrelevant here, since the sole standalone identity
- * already carries the admin role and owns everything it created.
+ * Standalone auth stamps `roles: ['admin']` on the sole identity, which already
+ * owns everything it created — so admin bypass is a no-op there.
*/
-function canAccessSchedule(user: UserContext, createdBy: string): boolean {
- return user.role === 'admin' || user.userRef === createdBy;
+function canAccessSchedule(requestContext: Pick<RequestContext, 'roles' | 'subject'>, createdBy: string): boolean {
+ return hasAdminRole(requestContext) || requestContext.subject.id === createdBy;
}
export function createSchedulesRouter<TTransaction>(deps: SchedulesRouterDeps<TTransaction>) {
const listHandler: RouteHandler<typeof listSchedulesRoute> = async c => {
const { agent_names: agentNames, limit, page_token: pageToken } = c.req.valid('query');
- const user = deps.resolveUserContext(c);
+ const requestContext = deps.resolveRequestContext(c);
// Admins see every schedule; a regular user is scoped to their own via the
// store's `created_by` filter (never a client-supplied param).
try {
const { data, pagination } = await deps.scheduleStore.listSchedules({
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
limit,
page_token: pageToken,
agent_names: agentNames,
- created_by: user.role === 'admin' ? undefined : user.userRef,
+ created_by: hasAdminRole(requestContext) ? undefined : requestContext.subject.id,
});
return c.json({ data: data.map(toWireSchedule), pagination }, 200);
} catch (error) {
@@ -139,26 +136,36 @@ export function createSchedulesRouter<TTransaction>(deps: SchedulesRouterDeps<TT
const listRunsHandler: RouteHandler<typeof listScheduleRunsRoute> = async c => {
const { schedule_id: scheduleId } = c.req.valid('param');
- const schedule = await deps.scheduleStore.getSchedule({ tenant_id: TENANT_ID, id: scheduleId });
+ const requestContext = deps.resolveRequestContext(c);
+ const schedule = await deps.scheduleStore.getSchedule({
+ tenant_id: requestContext.tenant_id,
+ id: scheduleId,
+ });
if (schedule === undefined) {
return c.json({ error: { message: `Schedule not found: ${scheduleId}` } }, 404);
}
- if (!canAccessSchedule(deps.resolveUserContext(c), schedule.created_by)) {
+ if (!canAccessSchedule(requestContext, schedule.created_by)) {
return c.json({ error: { message: FORBIDDEN_SCHEDULE_ACCESS } }, 403);
}
- const records = await deps.scheduleStore.listRuns({ tenant_id: TENANT_ID, schedule_id: scheduleId });
+ const records = await deps.scheduleStore.listRuns({
+ tenant_id: requestContext.tenant_id,
+ schedule_id: scheduleId,
+ });
return c.json({ data: records.map(toWireScheduleRun) }, 200);
};
const createScheduleRunHandler: RouteHandler<typeof createScheduleRunRoute> = async c => {
const { schedule_id: scheduleId } = c.req.valid('json');
- const user = deps.resolveUserContext(c);
+ const requestContext = deps.resolveRequestContext(c);
- const schedule = await deps.scheduleStore.getSchedule({ tenant_id: TENANT_ID, id: scheduleId });
+ const schedule = await deps.scheduleStore.getSchedule({
+ tenant_id: requestContext.tenant_id,
+ id: scheduleId,
+ });
if (schedule === undefined) {
return c.json({ error: { message: `Schedule not found: ${scheduleId}` } }, 404);
}
- if (!canAccessSchedule(user, schedule.created_by)) {
+ if (!canAccessSchedule(requestContext, schedule.created_by)) {
return c.json({ error: { message: FORBIDDEN_SCHEDULE_ACCESS } }, 403);
}
@@ -166,12 +173,12 @@ export function createSchedulesRouter<TTransaction>(deps: SchedulesRouterDeps<TT
let run: ScheduleRunRecord;
try {
run = await deps.scheduleStore.createRun({
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
schedule_id: schedule.id,
name: manualRunName(),
scheduled_for: now,
status: 'triggered',
- triggered_by: user.userRef,
+ triggered_by: requestContext.subject.id,
triggered_at: now,
});
} catch (error) {
@@ -192,7 +199,7 @@ export function createSchedulesRouter<TTransaction>(deps: SchedulesRouterDeps<TT
});
} catch (error) {
await deps.scheduleStore.updateRunStatus({
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
id: run.id,
status: 'failed',
});
@@ -207,17 +214,23 @@ export function createSchedulesRouter<TTransaction>(deps: SchedulesRouterDeps<TT
throw error;
}
- const latest = await deps.scheduleStore.getRun({ tenant_id: TENANT_ID, id: run.id });
+ const latest = await deps.scheduleStore.getRun({
+ tenant_id: requestContext.tenant_id,
+ id: run.id,
+ });
return c.json({ data: toWireScheduleRun(latest ?? run) }, 201);
};
const createHandler: RouteHandler<typeof createScheduleRoute> = async c => {
const body = c.req.valid('json');
- const user = deps.resolveUserContext(c);
+ const requestContext = deps.resolveRequestContext(c);
validateManifest(body.manifest);
- const agent = await deps.agentStore.getAgent({ tenant_id: TENANT_ID, name: body.agent_name });
+ const agent = await deps.agentStore.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);
}
@@ -227,11 +240,11 @@ export function createSchedulesRouter<TTransaction>(deps: SchedulesRouterDeps<TT
record = await deps.withTransaction(async transaction => {
const { schedule } = await deps.scheduleStore.createScheduleAndRun(
{
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
agent_name: agent.name,
name: body.name,
manifest: body.manifest,
- created_by: user.userRef,
+ created_by: requestContext.subject.id,
runFrom: new Date(),
},
transaction,
@@ -253,11 +266,15 @@ export function createSchedulesRouter<TTransaction>(deps: SchedulesRouterDeps<TT
const getHandler: RouteHandler<typeof getScheduleRoute> = async c => {
const { schedule_id: scheduleId } = c.req.valid('param');
- const record = await deps.scheduleStore.getSchedule({ tenant_id: TENANT_ID, id: scheduleId });
+ const requestContext = deps.resolveRequestContext(c);
+ const record = await deps.scheduleStore.getSchedule({
+ tenant_id: requestContext.tenant_id,
+ id: scheduleId,
+ });
if (record === undefined) {
return c.json({ error: { message: `Schedule not found: ${scheduleId}` } }, 404);
}
- if (!canAccessSchedule(deps.resolveUserContext(c), record.created_by)) {
+ if (!canAccessSchedule(requestContext, record.created_by)) {
return c.json({ error: { message: FORBIDDEN_SCHEDULE_ACCESS } }, 403);
}
return c.json({ data: toWireSchedule(record) }, 200);
@@ -276,14 +293,18 @@ export function createSchedulesRouter<TTransaction>(deps: SchedulesRouterDeps<TT
const putHandler: RouteHandler<typeof putScheduleRoute> = async c => {
const { schedule_id: scheduleId } = c.req.valid('param');
const body = c.req.valid('json');
+ const requestContext = deps.resolveRequestContext(c);
validateManifest(body.manifest);
- const existing = await deps.scheduleStore.getSchedule({ tenant_id: TENANT_ID, id: scheduleId });
+ const existing = await deps.scheduleStore.getSchedule({
+ tenant_id: requestContext.tenant_id,
+ id: scheduleId,
+ });
if (existing === undefined) {
return c.json({ error: { message: `Schedule not found: ${scheduleId}` } }, 404);
}
- if (!canAccessSchedule(deps.resolveUserContext(c), existing.created_by)) {
+ if (!canAccessSchedule(requestContext, existing.created_by)) {
return c.json({ error: { message: FORBIDDEN_SCHEDULE_ACCESS } }, 403);
}
@@ -292,7 +313,7 @@ export function createSchedulesRouter<TTransaction>(deps: SchedulesRouterDeps<TT
record = await deps.withTransaction(async transaction => {
const result = await deps.scheduleStore.updateScheduleAndRun(
{
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
id: scheduleId,
name: body.name,
manifest: body.manifest,
@@ -320,14 +341,21 @@ export function createSchedulesRouter<TTransaction>(deps: SchedulesRouterDeps<TT
const deleteHandler: RouteHandler<typeof deleteScheduleRoute> = async c => {
const { schedule_id: scheduleId } = c.req.valid('param');
- const record = await deps.scheduleStore.getSchedule({ tenant_id: TENANT_ID, id: scheduleId });
+ const requestContext = deps.resolveRequestContext(c);
+ const record = await deps.scheduleStore.getSchedule({
+ tenant_id: requestContext.tenant_id,
+ id: scheduleId,
+ });
if (record === undefined) {
return c.json({}, 200);
}
- if (!canAccessSchedule(deps.resolveUserContext(c), record.created_by)) {
+ if (!canAccessSchedule(requestContext, record.created_by)) {
return c.json({ error: { message: FORBIDDEN_SCHEDULE_ACCESS } }, 403);
}
- await deps.scheduleStore.deleteSchedule({ tenant_id: TENANT_ID, id: scheduleId });
+ await deps.scheduleStore.deleteSchedule({
+ tenant_id: requestContext.tenant_id,
+ id: scheduleId,
+ });
return c.json({}, 200);
};
diff --git a/packages/trueforge/src/apis/sessionMetrics.ts b/packages/trueforge/src/apis/sessionMetrics.ts
index 7e9b5d9b6..c3a4181ac 100644
--- a/packages/trueforge/src/apis/sessionMetrics.ts
+++ b/packages/trueforge/src/apis/sessionMetrics.ts
@@ -2,18 +2,17 @@
* Internal session metrics APIs (mounted at /api/internal/metrics).
*/
import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';
-import type { ResolveUserContext } from '../auth/identity';
+import type { ResolveRequestContext } from '../auth/identity';
import { buildSessionMetricsCharts, type ISessionMetricsStore } from '../db/sessionMetricsStore';
import {
getSessionMetricsChartsDataRoute,
getSessionMetricsChartsRoute,
getSessionMetricsMetersRoute,
} from '../routes/sessionMetricsRoutes';
-import { TENANT_ID } from './sessions';
export interface InternalMetricsRouterDeps {
sessionMetricsStore: ISessionMetricsStore;
- resolveUserContext: ResolveUserContext;
+ resolveRequestContext: ResolveRequestContext;
}
export function createInternalMetricsRouter(deps: InternalMetricsRouterDeps) {
@@ -21,11 +20,11 @@ export function createInternalMetricsRouter(deps: InternalMetricsRouterDeps) {
const getSessionMetricsMetersHandler: RouteHandler<typeof getSessionMetricsMetersRoute> = async c => {
const query = c.req.valid('query');
- const user = deps.resolveUserContext(c);
+ const requestContext = deps.resolveRequestContext(c);
const metrics = await deps.sessionMetricsStore.getSessionMetricsMeters({
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
agent_id: query.agent_id,
- created_by: user.userRef,
+ created_by: requestContext.subject.id,
start_timestamp: query.start_timestamp,
end_timestamp: query.end_timestamp,
});
@@ -38,11 +37,11 @@ export function createInternalMetricsRouter(deps: InternalMetricsRouterDeps) {
const getSessionMetricsChartsDataHandler: RouteHandler<typeof getSessionMetricsChartsDataRoute> = async c => {
const query = c.req.valid('query');
- const user = deps.resolveUserContext(c);
+ const requestContext = deps.resolveRequestContext(c);
const chartData = await deps.sessionMetricsStore.getSessionMetricsChartData({
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
agent_id: query.agent_id,
- created_by: user.userRef,
+ created_by: requestContext.subject.id,
start_timestamp: query.start_timestamp,
end_timestamp: query.end_timestamp,
chart_name: query.chart_name,
diff --git a/packages/trueforge/src/apis/sessions.ts b/packages/trueforge/src/apis/sessions.ts
index daefc34c1..d38dd691e 100644
--- a/packages/trueforge/src/apis/sessions.ts
+++ b/packages/trueforge/src/apis/sessions.ts
@@ -21,7 +21,7 @@ import type { Context } from 'hono';
import type { RedisClientType } from 'redis';
import type { Logger } from 'winston';
import { z } from 'zod';
-import type { ResolveUserContext } from '../auth/identity';
+import type { ResolveRequestContext } from '../auth/identity';
import configuration from '../config';
import type { IAgentStore } from '../db/agentStore';
import type { IMcpServerStore } from '../db/mcpServerStore';
@@ -44,9 +44,6 @@ import { validateAgentSpec } from '../runtime/sessionResources';
import { isSessionAgentNameRef, type Session } from '../schemas/session';
import { newId } from '../utils/id';
-/** The server is single-tenant; every record lives under one fixed tenant scope. */
-export const TENANT_ID = 'default';
-
/** Request-reply path a replica serves to cancel a turn it owns. */
export const SESSIONS_CANCEL_PATH = 'sessions/cancel';
@@ -82,7 +79,7 @@ export interface SessionsRouterDeps {
sandboxProviderStore: ISandboxProviderStore;
redis?: RedisClientType | undefined;
requestReplyRouter: RequestReplyRouter;
- resolveUserContext: ResolveUserContext;
+ resolveRequestContext: ResolveRequestContext;
logger: Logger;
}
@@ -217,8 +214,8 @@ async function freezeTurnIgnoringMissing(
const FORBIDDEN_SESSION_ACCESS = 'Only the session creator can access this session';
-function checkSessionAccess({ userRef, createdBy }: { userRef: string; createdBy: string }): boolean {
- return userRef === createdBy;
+function checkSessionAccess({ subject_id, createdBy }: { subject_id: string; createdBy: string }): boolean {
+ return subject_id === createdBy;
}
type InternalSessionsRouterDeps = Pick<
@@ -229,7 +226,7 @@ type InternalSessionsRouterDeps = Pick<
| 'skillStore'
| 'agentStore'
| 'sandboxProviderStore'
- | 'resolveUserContext'
+ | 'resolveRequestContext'
>;
function createGetOrCreateSessionByExternalIdHandler(
@@ -237,14 +234,14 @@ function createGetOrCreateSessionByExternalIdHandler(
): RouteHandler<typeof getOrCreateSessionByExternalIdRoute> {
return async c => {
const body = c.req.valid('json');
- const user = deps.resolveUserContext(c);
+ const requestContext = deps.resolveRequestContext(c);
const existing = await deps.sessions.getByExternalId({
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
external_id: body.external_id,
});
if (existing !== undefined) {
- if (!checkSessionAccess({ userRef: user.userRef, createdBy: existing.record.created_by })) {
+ if (!checkSessionAccess({ subject_id: requestContext.subject.id, createdBy: existing.record.created_by })) {
return c.json({ error: { message: FORBIDDEN_SESSION_ACCESS } }, 403);
}
return c.json({ data: toWireSession(existing.record) }, 200);
@@ -252,7 +249,10 @@ function createGetOrCreateSessionByExternalIdHandler(
let agent: SessionRecord['agent'];
if (isSessionAgentNameRef(body.agent)) {
- const named = await deps.agentStore.getAgent({ tenant_id: TENANT_ID, name: body.agent.name });
+ const named = await deps.agentStore.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);
}
@@ -260,7 +260,7 @@ function createGetOrCreateSessionByExternalIdHandler(
} else {
await validateAgentSpec({
spec: body.agent.spec,
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
modelProviderStore: deps.resolveModelProviderStore(c),
mcpServerStore: deps.resolveMcpServerStore(c),
skillStore: deps.skillStore,
@@ -270,12 +270,15 @@ function createGetOrCreateSessionByExternalIdHandler(
}
const { session, created } = await deps.sessions.getOrCreateByExternalId({
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
external_id: body.external_id,
- created_by: user.userRef,
+ created_by: requestContext.subject.id,
agent,
});
- if (!created && !checkSessionAccess({ userRef: user.userRef, createdBy: session.record.created_by })) {
+ if (
+ !created &&
+ !checkSessionAccess({ subject_id: requestContext.subject.id, createdBy: session.record.created_by })
+ ) {
return c.json({ error: { message: FORBIDDEN_SESSION_ACCESS } }, 403);
}
return c.json({ data: toWireSession(session.record) }, created ? 201 : 200);
@@ -294,17 +297,20 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {
const createSessionHandler: RouteHandler<typeof createSessionRoute> = async c => {
const body = c.req.valid('json');
const sessionId = newId();
+ const requestContext = deps.resolveRequestContext(c);
if (isSessionAgentNameRef(body.agent)) {
- const agent = await deps.agentStore.getAgent({ tenant_id: TENANT_ID, name: body.agent.name });
+ const agent = await deps.agentStore.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);
}
- const user = deps.resolveUserContext(c);
const session = await deps.sessions.create({
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
session_id: sessionId,
- created_by: user.userRef,
+ created_by: requestContext.subject.id,
agent: { type: 'reference', id: agent.id, name: agent.name },
metadata: body.metadata,
external_id: null,
@@ -314,17 +320,16 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {
await validateAgentSpec({
spec: body.agent.spec,
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
modelProviderStore: deps.resolveModelProviderStore(c),
mcpServerStore: deps.resolveMcpServerStore(c),
skillStore: deps.skillStore,
sandboxProviderStore: deps.sandboxProviderStore,
});
- const user = deps.resolveUserContext(c);
const session = await deps.sessions.create({
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
session_id: sessionId,
- created_by: user.userRef,
+ created_by: requestContext.subject.id,
agent: { type: 'inline', spec: body.agent.spec },
metadata: body.metadata,
external_id: null,
@@ -334,11 +339,15 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {
const getSessionHandler: RouteHandler<typeof getSessionRoute> = async c => {
const { session_id: sessionId } = c.req.valid('param');
- const record = await deps.sessionStore.getSession({ tenant_id: TENANT_ID, session_id: sessionId });
+ const requestContext = deps.resolveRequestContext(c);
+ const record = await deps.sessionStore.getSession({
+ tenant_id: requestContext.tenant_id,
+ session_id: sessionId,
+ });
if (!record) {
return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);
}
- if (!checkSessionAccess({ userRef: deps.resolveUserContext(c).userRef, createdBy: record.created_by })) {
+ if (!checkSessionAccess({ subject_id: requestContext.subject.id, createdBy: record.created_by })) {
return c.json({ error: { message: FORBIDDEN_SESSION_ACCESS } }, 403);
}
return c.json({ data: toWireSession(record) }, 200);
@@ -346,26 +355,37 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {
const deleteSessionHandler: RouteHandler<typeof deleteSessionRoute> = async c => {
const { session_id: sessionId } = c.req.valid('param');
- const record = await deps.sessionStore.getSession({ tenant_id: TENANT_ID, session_id: sessionId });
+ const requestContext = deps.resolveRequestContext(c);
+ const record = await deps.sessionStore.getSession({
+ tenant_id: requestContext.tenant_id,
+ session_id: sessionId,
+ });
if (!record) {
// Idempotent delete when already gone.
return c.body(null, 204);
}
- if (!checkSessionAccess({ userRef: deps.resolveUserContext(c).userRef, createdBy: record.created_by })) {
+ if (!checkSessionAccess({ subject_id: requestContext.subject.id, createdBy: record.created_by })) {
return c.json({ error: { message: FORBIDDEN_SESSION_ACCESS } }, 403);
}
- await deps.sessionStore.deleteSession({ tenant_id: TENANT_ID, session_id: sessionId });
+ await deps.sessionStore.deleteSession({
+ tenant_id: requestContext.tenant_id,
+ session_id: sessionId,
+ });
return c.body(null, 204);
};
const updateSessionHandler: RouteHandler<typeof updateSessionRoute> = async c => {
const { session_id: sessionId } = c.req.valid('param');
const body = c.req.valid('json');
- const existing = await deps.sessionStore.getSession({ tenant_id: TENANT_ID, session_id: sessionId });
+ const requestContext = deps.resolveRequestContext(c);
+ const existing = await deps.sessionStore.getSession({
+ tenant_id: requestContext.tenant_id,
+ session_id: sessionId,
+ });
if (!existing) {
return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);
}
- if (!checkSessionAccess({ userRef: deps.resolveUserContext(c).userRef, createdBy: existing.created_by })) {
+ if (!checkSessionAccess({ subject_id: requestContext.subject.id, createdBy: existing.created_by })) {
return c.json({ error: { message: FORBIDDEN_SESSION_ACCESS } }, 403);
}
// Inline sessions may replace their agent; named (reference) sessions
@@ -373,7 +393,7 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {
if (body.agent !== undefined) {
await validateAgentSpec({
spec: body.agent.spec,
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
modelProviderStore: deps.resolveModelProviderStore(c),
mcpServerStore: deps.resolveMcpServerStore(c),
skillStore: deps.skillStore,
@@ -382,7 +402,7 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {
}
try {
await deps.sessionStore.updateSession({
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
session_id: sessionId,
agent: body.agent === undefined ? undefined : { type: 'inline', spec: body.agent.spec },
title: undefined,
@@ -397,7 +417,10 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {
}
throw error;
}
- const record = await deps.sessionStore.getSession({ tenant_id: TENANT_ID, session_id: sessionId });
+ const record = await deps.sessionStore.getSession({
+ tenant_id: requestContext.tenant_id,
+ session_id: sessionId,
+ });
if (!record) {
return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);
}
@@ -406,12 +429,12 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {
const listSessionsHandler: RouteHandler<typeof listSessionsRoute> = async c => {
const query = c.req.valid('query');
- const user = deps.resolveUserContext(c);
+ const requestContext = deps.resolveRequestContext(c);
try {
const { data, pagination } = await deps.sessionStore.listSessions({
agent_id: query.agent_id,
- created_by: user.userRef,
- tenant_id: TENANT_ID,
+ created_by: requestContext.subject.id,
+ tenant_id: requestContext.tenant_id,
limit: query.limit,
order: query.order,
page_token: query.page_token,
@@ -429,11 +452,15 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {
const cancelSessionHandler: RouteHandler<typeof cancelSessionRoute> = async c => {
const { session_id: sessionId } = c.req.valid('param');
- const session = await deps.sessions.get({ tenant_id: TENANT_ID, session_id: sessionId });
+ const requestContext = deps.resolveRequestContext(c);
+ const session = await deps.sessions.get({
+ tenant_id: requestContext.tenant_id,
+ session_id: sessionId,
+ });
if (!session) {
return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);
}
- if (!checkSessionAccess({ userRef: deps.resolveUserContext(c).userRef, createdBy: session.record.created_by })) {
+ if (!checkSessionAccess({ subject_id: requestContext.subject.id, createdBy: session.record.created_by })) {
return c.json({ error: { message: FORBIDDEN_SESSION_ACCESS } }, 403);
}
const turnId = session.record.last_turn_id;
@@ -448,11 +475,15 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {
const listSessionEventsHandler: RouteHandler<typeof listSessionEventsRoute> = async c => {
const { session_id: sessionId } = c.req.valid('param');
const query = c.req.valid('query');
- const session = await deps.sessions.get({ tenant_id: TENANT_ID, session_id: sessionId });
+ const requestContext = deps.resolveRequestContext(c);
+ const session = await deps.sessions.get({
+ tenant_id: requestContext.tenant_id,
+ session_id: sessionId,
+ });
if (!session) {
return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);
}
- if (!checkSessionAccess({ userRef: deps.resolveUserContext(c).userRef, createdBy: session.record.created_by })) {
+ if (!checkSessionAccess({ subject_id: requestContext.subject.id, createdBy: session.record.created_by })) {
return c.json({ error: { message: FORBIDDEN_SESSION_ACCESS } }, 403);
}
try {
diff --git a/packages/trueforge/src/apis/settings.ts b/packages/trueforge/src/apis/settings.ts
index 79cd13434..e1f08654a 100644
--- a/packages/trueforge/src/apis/settings.ts
+++ b/packages/trueforge/src/apis/settings.ts
@@ -6,7 +6,7 @@
import { OpenAPIHono } from '@hono/zod-openapi';
import type { Context } from 'hono';
import type { Logger } from 'winston';
-import type { ResolveUserContext } from '../auth/identity';
+import type { ResolveRequestContext } from '../auth/identity';
import type { IMcpServerWithAuthStore } from '../db/mcpServerStore';
import type { IModelProviderStore } from '../db/modelProviderStore';
import type { ISandboxProviderStore } from '../db/sandboxProviderStore';
@@ -26,7 +26,7 @@ export interface SettingsRouterDeps<TTransaction> {
sandboxProviderStore: ISandboxProviderStore<TTransaction>;
withTransaction: WithTransaction<TTransaction>;
logger: Logger;
- resolveUserContext: ResolveUserContext;
+ resolveRequestContext: ResolveRequestContext;
}
export function createSettingsRouter<TTransaction>(deps: SettingsRouterDeps<TTransaction>) {
@@ -36,6 +36,7 @@ export function createSettingsRouter<TTransaction>(deps: SettingsRouterDeps<TTra
createModelProvidersRouter({
resolveModelProviderStore: deps.resolveModelProviderStore,
withTransaction: deps.withTransaction,
+ resolveRequestContext: deps.resolveRequestContext,
}),
);
router.route(
@@ -45,7 +46,7 @@ export function createSettingsRouter<TTransaction>(deps: SettingsRouterDeps<TTra
tokenStore: deps.tokenStore,
withTransaction: deps.withTransaction,
logger: deps.logger,
- resolveUserContext: deps.resolveUserContext,
+ resolveRequestContext: deps.resolveRequestContext,
}),
);
router.route(
@@ -53,6 +54,7 @@ export function createSettingsRouter<TTransaction>(deps: SettingsRouterDeps<TTra
createSkillsRouter({
skillStore: deps.skillStore,
withTransaction: deps.withTransaction,
+ resolveRequestContext: deps.resolveRequestContext,
}),
);
router.route(
@@ -61,6 +63,7 @@ export function createSettingsRouter<TTransaction>(deps: SettingsRouterDeps<TTra
sandboxProviderStore: deps.sandboxProviderStore,
withTransaction: deps.withTransaction,
logger: deps.logger,
+ resolveRequestContext: deps.resolveRequestContext,
}),
);
return router;
diff --git a/packages/trueforge/src/apis/skills.ts b/packages/trueforge/src/apis/skills.ts
index d5b6b9aa3..da729377d 100644
--- a/packages/trueforge/src/apis/skills.ts
+++ b/packages/trueforge/src/apis/skills.ts
@@ -1,4 +1,5 @@
import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';
+import type { ResolveRequestContext } from '../auth/identity';
import { SkillNameConflictError, type ISkillStore, type SkillRecord } from '../db/skillStore';
import type { WithTransaction } from '../db/transaction';
import {
@@ -8,11 +9,11 @@ import {
putSkillRoute,
} from '../routes/skillRoutes';
import type { ConfiguredSkill, CreateSkillRequest, UpdateSkillRequest } from '../schemas/skill';
-import { TENANT_ID } from './sessions';
export interface SkillsRouterDeps<TTransaction> {
skillStore: ISkillStore<TTransaction>;
withTransaction: WithTransaction<TTransaction>;
+ resolveRequestContext: ResolveRequestContext;
}
/** Wire view of a stored skill: identity `name` plus nested manifest. */
@@ -26,16 +27,21 @@ function toConfiguredSkill(record: SkillRecord): ConfiguredSkill {
/** Admin/settings skills CRUD (mounted at /api/v1/settings/skills). */
export function createSkillsRouter<TTransaction>(deps: SkillsRouterDeps<TTransaction>) {
const listConfiguredHandler: RouteHandler<typeof listConfiguredSkillsRoute> = async c => {
- const records = await deps.skillStore.listSkills({ tenant_id: TENANT_ID, names: undefined });
+ const requestContext = deps.resolveRequestContext(c);
+ const records = await deps.skillStore.listSkills({
+ tenant_id: requestContext.tenant_id,
+ names: undefined,
+ });
return c.json({ data: records.map(toConfiguredSkill) }, 200);
};
const createHandler: RouteHandler<typeof createSkillRoute> = async c => {
const body: CreateSkillRequest = c.req.valid('json');
+ const requestContext = deps.resolveRequestContext(c);
const manifest = body.manifest;
try {
const record = await deps.skillStore.createSkill({
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
name: manifest.name,
manifest,
});
@@ -50,9 +56,10 @@ export function createSkillsRouter<TTransaction>(deps: SkillsRouterDeps<TTransac
const putHandler: RouteHandler<typeof putSkillRoute> = async c => {
const body: UpdateSkillRequest = c.req.valid('json');
+ const requestContext = deps.resolveRequestContext(c);
const manifest = body.manifest;
const record = await deps.skillStore.upsertSkill({
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
name: manifest.name,
manifest,
});
@@ -70,10 +77,15 @@ export function createSkillsRouter<TTransaction>(deps: SkillsRouterDeps<TTransac
export function createAvailableSkillsRouter<TTransaction>(deps: {
skillStore: ISkillStore<TTransaction>;
withTransaction: WithTransaction<TTransaction>;
+ resolveRequestContext: ResolveRequestContext;
}) {
const router = new OpenAPIHono();
router.openapi(listAvailableSkillsRoute, async c => {
- const records = await deps.skillStore.listSkills({ tenant_id: TENANT_ID, names: undefined });
+ const requestContext = deps.resolveRequestContext(c);
+ const records = await deps.skillStore.listSkills({
+ tenant_id: requestContext.tenant_id,
+ names: undefined,
+ });
return c.json(
{
data: records.map(record => ({
diff --git a/packages/trueforge/src/apis/turns.ts b/packages/trueforge/src/apis/turns.ts
index f026fd5a4..f7f3afb9f 100644
--- a/packages/trueforge/src/apis/turns.ts
+++ b/packages/trueforge/src/apis/turns.ts
@@ -29,7 +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 { ResolveUserContext, UserContext } from '../auth/identity';
+import type { ResolveRequestContext } from '../auth/identity';
import configuration from '../config';
import type { IAgentStore } from '../db/agentStore';
import type { IMcpServerWithAuthStore } from '../db/mcpServerStore';
@@ -57,7 +57,6 @@ import {
resolveSandboxProvider,
} from '../runtime/sessionResources';
import { checkSnapshotStatus } from '../sandbox/providerUtils';
-import { TENANT_ID } from './sessions';
export function toWireTurn(record: TurnRecordWithoutSnapshot): Turn {
return {
@@ -114,7 +113,7 @@ export interface TurnsRouterDeps {
eventSubscriptions: EventSubscriptionRegistry<TurnStreamingEvent>;
sandboxProviderStore: ISandboxProviderStore;
logger: Logger;
- resolveUserContext: ResolveUserContext;
+ resolveRequestContext: ResolveRequestContext;
}
/**
@@ -143,6 +142,7 @@ function createTurnResolver(deps: {
modelProviderStore: IModelProviderStore;
logger: Logger;
signal: AbortSignal;
+ tenant_id: string;
userRef: string;
sessionId: string;
}): TurnResourceResolver {
@@ -155,13 +155,14 @@ function createTurnResolver(deps: {
modelProviderStore,
logger,
signal,
+ tenant_id,
userRef,
sessionId,
} = deps;
return new TurnResourceResolver({
llm: async name => {
const resolved = await getModelDetails({
- tenant_id: TENANT_ID,
+ tenant_id,
name,
store: modelProviderStore,
});
@@ -177,7 +178,7 @@ function createTurnResolver(deps: {
},
mcp: async name => {
const connection = await getMcpConnection({
- tenant_id: TENANT_ID,
+ tenant_id,
name,
store: mcpServerStore,
tokenStore,
@@ -195,7 +196,7 @@ function createTurnResolver(deps: {
mcpConnectTimeoutMs: configuration.MCP_CONNECT_TIMEOUT_MS,
sandboxProvider: async ({ spec, existingSandboxId, tracing }) => {
const provider = await resolveSandboxProvider({
- tenant_id: TENANT_ID,
+ tenant_id,
store: sandboxProviderStore,
logger,
sessionId,
@@ -213,7 +214,7 @@ function createTurnResolver(deps: {
// Restoring an existing sandbox goes through daytona.get and never touches the snapshot.
// Local fallback has no image build.
if (carriedSandboxId === undefined && provider.type !== 'local') {
- const status = await checkSnapshotStatus({ store: sandboxProviderStore, tenant_id: TENANT_ID, logger });
+ const status = await checkSnapshotStatus({ store: sandboxProviderStore, tenant_id, logger });
if (status?.status !== 'ready') {
throw new HTTPException(422, {
message:
@@ -224,7 +225,7 @@ function createTurnResolver(deps: {
}
}
const gitSkills = await resolveGitSkills({
- tenant_id: TENANT_ID,
+ tenant_id,
skills: spec.skills ?? [],
store: skillStore,
});
@@ -238,7 +239,7 @@ function createTurnResolver(deps: {
});
},
agent: async agentId => {
- const record = await agentStore.getAgent({ tenant_id: TENANT_ID, id: agentId });
+ const record = await agentStore.getAgent({ tenant_id, id: agentId });
if (record === undefined) {
throw new HTTPException(422, { message: `Agent not found: ${agentId}` });
}
@@ -374,6 +375,7 @@ export async function beginTurnExecution(params: {
const sessionId = session.session_id;
const abortController = new AbortController();
+ const tenant_id = session.tenant_id;
const resolver = createTurnResolver({
mcpServerStore: deps.mcpServerStore,
tokenStore: deps.tokenStore,
@@ -383,6 +385,7 @@ export async function beginTurnExecution(params: {
modelProviderStore: deps.modelProviderStore,
logger: deps.logger,
signal: abortController.signal,
+ tenant_id,
userRef,
sessionId,
});
@@ -415,7 +418,7 @@ export async function beginTurnExecution(params: {
});
// Held for the whole turn; the stream's sequence counter dies with it.
- const turnEventStream = deps.eventSubscriptions.get(turnStreamId(TENANT_ID, sessionId, turn.id));
+ const turnEventStream = deps.eventSubscriptions.get(turnStreamId(tenant_id, sessionId, turn.id));
return {
turn,
@@ -512,9 +515,9 @@ export function resolveAfterSequenceNumber(c: Context, bodyAfterSequenceNumber?:
return bodyAfterSequenceNumber;
}
-/** True when `user` is the session creator (`created_by`). */
-function checkTurnAccess(user: UserContext, createdBy: string): boolean {
- return createdBy === user.userRef;
+/** True when the subject is the session creator (`created_by`). */
+function checkTurnAccess({ subject_id, createdBy }: { subject_id: string; createdBy: string }): boolean {
+ return createdBy === subject_id;
}
const FORBIDDEN_SESSION_ACCESS = 'Only the session creator can access this session';
@@ -525,11 +528,20 @@ export function createTurnsRouter(deps: TurnsRouterDeps) {
const listTurnsHandler: RouteHandler<typeof listTurnsRoute> = async c => {
const { session_id: sessionId } = c.req.valid('param');
const query = c.req.valid('query');
- const session = await deps.sessions.get({ tenant_id: TENANT_ID, session_id: sessionId });
+ const requestContext = deps.resolveRequestContext(c);
+ const session = await deps.sessions.get({
+ tenant_id: requestContext.tenant_id,
+ session_id: sessionId,
+ });
if (!session) {
return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);
}
- if (!checkTurnAccess(deps.resolveUserContext(c), session.record.created_by)) {
+ if (
+ !checkTurnAccess({
+ subject_id: requestContext.subject.id,
+ createdBy: session.record.created_by,
+ })
+ ) {
return c.json({ error: { message: FORBIDDEN_SESSION_ACCESS } }, 403);
}
try {
@@ -548,11 +560,20 @@ export function createTurnsRouter(deps: TurnsRouterDeps) {
const getTurnHandler: RouteHandler<typeof getTurnRoute> = async c => {
const { session_id: sessionId, turn_id: turnId } = c.req.valid('param');
- const session = await deps.sessions.get({ tenant_id: TENANT_ID, session_id: sessionId });
+ const requestContext = deps.resolveRequestContext(c);
+ const session = await deps.sessions.get({
+ tenant_id: requestContext.tenant_id,
+ session_id: sessionId,
+ });
if (!session) {
return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);
}
- if (!checkTurnAccess(deps.resolveUserContext(c), session.record.created_by)) {
+ if (
+ !checkTurnAccess({
+ subject_id: requestContext.subject.id,
+ createdBy: session.record.created_by,
+ })
+ ) {
return c.json({ error: { message: FORBIDDEN_SESSION_ACCESS } }, 403);
}
const turn = await session.getTurn(turnId);
@@ -571,11 +592,20 @@ export function createTurnsRouter(deps: TurnsRouterDeps) {
// Cheapest first: a malformed path costs no store read and no provider round-trip.
validateSandboxFilePath(path);
- const session = await deps.sessions.get({ tenant_id: TENANT_ID, session_id: sessionId });
+ const requestContext = deps.resolveRequestContext(c);
+ const session = await deps.sessions.get({
+ tenant_id: requestContext.tenant_id,
+ session_id: sessionId,
+ });
if (!session) {
return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);
}
- if (!checkTurnAccess(deps.resolveUserContext(c), session.record.created_by)) {
+ if (
+ !checkTurnAccess({
+ subject_id: requestContext.subject.id,
+ createdBy: session.record.created_by,
+ })
+ ) {
return c.json({ error: { message: FORBIDDEN_SESSION_ACCESS } }, 403);
}
@@ -591,7 +621,7 @@ export function createTurnsRouter(deps: TurnsRouterDeps) {
}
const provider = await resolveSandboxProvider({
- tenant_id: TENANT_ID,
+ tenant_id: requestContext.tenant_id,
store: deps.sandboxProviderStore,
logger: deps.logger,
sessionId,
@@ -627,11 +657,20 @@ export function createTurnsRouter(deps: TurnsRouterDeps) {
const listTurnEventsHandler: RouteHandler<typeof listTurnEventsRoute> = async c => {
const { session_id: sessionId, turn_id: turnId } = c.req.valid('param');
const query = c.req.valid('query');
- const session = await deps.sessions.get({ tenant_id: TENANT_ID, session_id: sessionId });
+ const requestContext = deps.resolveRequestContext(c);
+ const session = await deps.sessions.get({
+ tenant_id: requestContext.tenant_id,
+ session_id: sessionId,
+ });
if (!session) {
return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);
}
- if (!checkTurnAccess(deps.resolveUserContext(c), session.record.created_by)) {
+ if (
+ !checkTurnAccess({
+ subject_id: requestContext.subject.id,
+ createdBy: session.record.created_by,
+ })
+ ) {
return c.json({ error: { message: FORBIDDEN_SESSION_ACCESS } }, 403);
}
const turn = await session.getTurn(turnId);
@@ -656,21 +695,29 @@ export function createTurnsRouter(deps: TurnsRouterDeps) {
const createAndExecuteTurnHandler: RouteHandler<typeof createAndExecuteTurnRoute> = async c => {
const { session_id: sessionId } = c.req.valid('param');
const body = c.req.valid('json');
+ const requestContext = deps.resolveRequestContext(c);
- const session = await deps.sessions.get({ tenant_id: TENANT_ID, session_id: sessionId });
+ const session = await deps.sessions.get({
+ tenant_id: requestContext.tenant_id,
+ session_id: sessionId,
+ });
if (!session) {
return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);
}
- if (!checkTurnAccess(deps.resolveUserContext(c), session.record.created_by)) {
+ if (
+ !checkTurnAccess({
+ subject_id: requestContext.subject.id,
+ createdBy: session.record.created_by,
+ })
+ ) {
return c.json({ error: { message: FORBIDDEN_CREATE_TURN } }, 403);
}
- const userRef = deps.resolveUserContext(c).userRef;
const turnParams = {
session,
input: body.input,
previous_turn_id: body.previous_turn_id,
- userRef,
+ userRef: requestContext.subject.id,
deps: {
...deps,
modelProviderStore: deps.resolveModelProviderStore(c),
@@ -720,12 +767,21 @@ export function createTurnsRouter(deps: TurnsRouterDeps) {
const { session_id: sessionId, turn_id: turnId } = c.req.valid('param');
const query = c.req.valid('query');
const afterSequenceNumber = resolveAfterSequenceNumber(c, query.after_sequence_number);
+ const requestContext = deps.resolveRequestContext(c);
- const session = await deps.sessions.get({ tenant_id: TENANT_ID, session_id: sessionId });
+ const session = await deps.sessions.get({
+ tenant_id: requestContext.tenant_id,
+ session_id: sessionId,
+ });
if (!session) {
return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);
}
- if (!checkTurnAccess(deps.resolveUserContext(c), session.record.created_by)) {
+ if (
+ !checkTurnAccess({
+ subject_id: requestContext.subject.id,
+ createdBy: session.record.created_by,
+ })
+ ) {
return c.json({ error: { message: FORBIDDEN_SESSION_ACCESS } }, 403);
}
const turn = await session.getTurn(turnId);
@@ -733,7 +789,7 @@ export function createTurnsRouter(deps: TurnsRouterDeps) {
return c.json({ error: { message: `Turn not found: ${turnId}` } }, 404);
}
- const turnEventStream = deps.eventSubscriptions.get(turnStreamId(TENANT_ID, sessionId, turnId));
+ const turnEventStream = deps.eventSubscriptions.get(turnStreamId(requestContext.tenant_id, sessionId, turnId));
// Admission check before SSE headers are sent, so it can still map to HTTP 412.
try {
diff --git a/packages/trueforge/src/app.ts b/packages/trueforge/src/app.ts
index 930ae409b..b123a7630 100644
--- a/packages/trueforge/src/app.ts
+++ b/packages/trueforge/src/app.ts
@@ -23,13 +23,14 @@ import { createInternalSessionsRouter, createSessionsRouter } from './apis/sessi
import { createSettingsRouter } from './apis/settings';
import { createAvailableSkillsRouter } from './apis/skills';
import { createTurnsRouter } from './apis/turns';
-import { resolveUserContext } from './auth/identity';
-import { adminAuthMiddleware, authMiddleware } from './auth/middleware';
+import type { Authenticator } from './auth/authenticator';
+import { resolveRequestContext } from './auth/identity';
+import { createAdminAuthMiddleware, createAuthMiddleware } from './auth/middleware';
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 from './config';
+import configuration, { getTrueForgeMode, TrueForgeMode } from './config';
import type { IAgentStore } from './db/agentStore';
import type { IMcpServerWithAuthStore } from './db/mcpServerStore';
import type { IModelProviderStore } from './db/modelProviderStore';
@@ -48,6 +49,20 @@ import { zodErrorResponse, zodValidationHook } from './zodErrorResponse';
const BEARER_AUTH_SCHEME = 'BearerAuth';
+function withAuth(router: OpenAPIHono, middleware: MiddlewareHandler): OpenAPIHono {
+ const shell = new OpenAPIHono();
+ shell.use('*', middleware);
+ shell.route('/', router);
+ return shell;
+}
+
+function withAdminAuth(router: OpenAPIHono, middleware: MiddlewareHandler): OpenAPIHono {
+ const shell = new OpenAPIHono();
+ shell.use('*', middleware);
+ shell.route('/', router);
+ return shell;
+}
+
/** One line per request: method, path, status, duration. Skips `/healthz`. */
export function createAccessLogMiddleware(logger: Logger): MiddlewareHandler {
return async (c, next) => {
@@ -103,9 +118,9 @@ const openApiDocConfig = {
description:
'HTTP API for the TrueForge agent server (`/api/v1`). Interactive docs are served at `/api/v1/docs` ' +
'(OpenAPI JSON at `/api/v1/openapi.json`).\n\n' +
- '**Authentication:** Standalone deployments (no OIDC) accept requests without credentials — middleware ' +
- 'stamps a local default user. When OIDC is configured, protected routes require a valid `id_token` cookie ' +
- 'or `Authorization: Bearer` ID token. There is no built-in API-key scheme; ' +
+ '**Authentication:** Standalone auth accepts requests without credentials — middleware ' +
+ 'stamps a local default user. When OIDC or TrueFoundry auth is configured, protected routes require a valid ' +
+ 'cookie or `Authorization: Bearer` token. There is no built-in API-key scheme; ' +
'pass custom headers only if your reverse proxy or IdP layer requires them.\n\n' +
'Covers DB-backed sessions, the agent registry, settings catalogs, and model/MCP/skill/sandbox providers.',
version: PACKAGE_VERSION,
@@ -120,8 +135,8 @@ export function registerOpenApiBearerAuth(app: OpenAPIHono): void {
scheme: 'bearer',
bearerFormat: 'JWT',
description:
- 'ID token (`Authorization: Bearer <id_token>`). Required on protected routes. ' +
- 'Browser sessions may use the HttpOnly `id_token` cookie instead.',
+ 'Caller credential (`Authorization: Bearer <token>`). Required on protected routes when auth is enabled. ' +
+ 'Browser sessions may use the HttpOnly `id_token` or `accessToken` cookie instead.',
});
}
@@ -144,22 +159,6 @@ function routeNotFound(c: Context) {
return c.json({ error: { message: `Route not found: ${c.req.method} ${c.req.path}` } }, 404);
}
-/** Sub-app shell: `.use('*', authMiddleware)` then child routes — same as gateway routers. */
-function withAuth(router: OpenAPIHono): OpenAPIHono {
- const shell = new OpenAPIHono();
- shell.use('*', authMiddleware);
- shell.route('/', router);
- return shell;
-}
-
-/** Admin-only routes: local admin when auth is disabled; with OIDC requires an authenticated admin. */
-function withAdminAuth(router: OpenAPIHono): OpenAPIHono {
- const shell = new OpenAPIHono();
- shell.use('*', adminAuthMiddleware);
- shell.route('/', router);
- return shell;
-}
-
export interface ServerDeps<TTransaction> {
modelCatalog: ModelCatalog;
mcpCatalog: McpCatalog;
@@ -194,11 +193,15 @@ export interface ServerDeps<TTransaction> {
logger: Logger;
/** Discovered openid-client configuration; undefined when browser login is disabled. */
oidcClient: Configuration | undefined;
+ /** Startup-selected authenticator; middleware is built from this once per app. */
+ authenticator: Authenticator;
}
export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
const app = new OpenAPIHono({ defaultHook: zodValidationHook });
- const authEnabled = deps.oidcClient != null;
+ const authMiddleware = createAuthMiddleware(deps.authenticator);
+ const adminAuthMiddleware = createAdminAuthMiddleware(deps.authenticator);
+ const authEnabled = getTrueForgeMode() !== TrueForgeMode.Standalone;
if (configuration.ACCESS_LOGS) {
app.use('*', createAccessLogMiddleware(deps.logger));
@@ -207,7 +210,14 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
app.get('/healthz', c => c.json({ status: 'ok', version: PACKAGE_VERSION }));
- app.route('/api/v1/auth', createAuthRouter({ oidcClient: deps.oidcClient, logger: deps.logger }));
+ app.route(
+ '/api/v1/auth',
+ createAuthRouter({
+ oidcClient: deps.oidcClient,
+ logger: deps.logger,
+ authMiddleware,
+ }),
+ );
app.route(
'/api/v1/capabilities',
withAuth(
@@ -215,7 +225,9 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
sandboxProviderStore: deps.sandboxProviderStore,
withTransaction: deps.withTransaction,
logger: deps.logger,
+ resolveRequestContext,
}),
+ authMiddleware,
),
);
app.route(
@@ -224,7 +236,9 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
createModelsRouter({
resolveModelProviderStore: deps.resolveModelProviderStore,
withTransaction: deps.withTransaction,
+ resolveRequestContext,
}),
+ authMiddleware,
),
);
app.route(
@@ -236,6 +250,7 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
skillCatalog: deps.skillCatalog,
sandboxCatalog: deps.sandboxCatalog,
}),
+ authMiddleware,
),
);
// Public MCP OAuth callback must be registered before the gated `/mcp-servers` mount so
@@ -256,8 +271,9 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
tokenStore: deps.tokenStore,
withTransaction: deps.withTransaction,
logger: deps.logger,
- resolveUserContext,
+ resolveRequestContext,
}),
+ authMiddleware,
),
);
app.route(
@@ -266,7 +282,9 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
createAvailableSkillsRouter({
skillStore: deps.skillStore,
withTransaction: deps.withTransaction,
+ resolveRequestContext,
}),
+ authMiddleware,
),
);
app.route(
@@ -279,7 +297,9 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
skillStore: deps.skillStore,
sandboxProviderStore: deps.sandboxProviderStore,
withTransaction: deps.withTransaction,
+ resolveRequestContext,
}),
+ authMiddleware,
),
);
app.route(
@@ -301,8 +321,9 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
logger: deps.logger,
},
withTransaction: deps.withTransaction,
- resolveUserContext,
+ resolveRequestContext,
}),
+ authMiddleware,
),
);
app.route(
@@ -316,8 +337,9 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
sandboxProviderStore: deps.sandboxProviderStore,
withTransaction: deps.withTransaction,
logger: deps.logger,
- resolveUserContext,
+ resolveRequestContext,
}),
+ adminAuthMiddleware,
),
);
app.route(
@@ -330,8 +352,9 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
skillStore: deps.skillStore,
agentStore: deps.agentStore,
sandboxProviderStore: deps.sandboxProviderStore,
- resolveUserContext,
+ resolveRequestContext,
}),
+ authMiddleware,
),
);
app.route(
@@ -339,8 +362,9 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
withAuth(
createInternalMetricsRouter({
sessionMetricsStore: deps.sessionMetricsStore,
- resolveUserContext,
+ resolveRequestContext,
}),
+ authMiddleware,
),
);
app.route(
@@ -357,9 +381,10 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
sandboxProviderStore: deps.sandboxProviderStore,
redis: deps.redis,
requestReplyRouter: deps.requestReplyRouter,
- resolveUserContext: resolveUserContext,
+ resolveRequestContext,
logger: deps.logger,
}),
+ authMiddleware,
),
);
app.route(
@@ -377,8 +402,9 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
eventSubscriptions: deps.eventSubscriptions,
sandboxProviderStore: deps.sandboxProviderStore,
logger: deps.logger,
- resolveUserContext: resolveUserContext,
+ resolveRequestContext,
}),
+ authMiddleware,
),
);
diff --git a/packages/trueforge/src/auth/authenticator.ts b/packages/trueforge/src/auth/authenticator.ts
new file mode 100644
index 000000000..e7b06b862
--- /dev/null
+++ b/packages/trueforge/src/auth/authenticator.ts
@@ -0,0 +1,7 @@
+import type { Context } from 'hono';
+
+import type { RequestContext } from './identity';
+
+export interface Authenticator {
+ authenticate(c: Context): Promise<RequestContext>;
+}
diff --git a/packages/trueforge/src/auth/claims.ts b/packages/trueforge/src/auth/claims.ts
index 1978183c9..91ecbc6f5 100644
--- a/packages/trueforge/src/auth/claims.ts
+++ b/packages/trueforge/src/auth/claims.ts
@@ -1,6 +1,6 @@
import type { OIDCConfig } from '../config';
import { assertEmailAllowed } from './emailAllowlist';
-import type { Role, UserContext } from './identity';
+import type { RequestContext } from './identity';
/** Raw claims from a decoded ID token; values are untyped until read here. */
export type IdTokenClaims = Record<string, unknown>;
@@ -23,13 +23,22 @@ export function claimValues(claim: unknown): string[] {
return [];
}
+/** Non-empty string claim, or undefined when absent / empty / wrong type. */
+export function resolveOptionalStringClaim(claims: IdTokenClaims, claimName: string): string | undefined {
+ const value = claims[claimName];
+ if (typeof value !== 'string' || value === '') {
+ return undefined;
+ }
+ return value;
+}
+
/**
* The stable identity key for this caller. An identity that can't be resolved
* means the token can't be trusted to identify anyone, so this throws.
*/
export function resolveUserRef(claims: IdTokenClaims, config: OIDCConfig): string {
- const value = claims[config.OIDC_USER_REFERENCE_CLAIM];
- if (typeof value !== 'string' || value === '') {
+ const value = resolveOptionalStringClaim(claims, config.OIDC_USER_REFERENCE_CLAIM);
+ if (value === undefined) {
throw new Error(
`ID token is missing a non-empty "${config.OIDC_USER_REFERENCE_CLAIM}" claim (OIDC_USER_REFERENCE_CLAIM).`,
);
@@ -41,16 +50,29 @@ export function resolveUserRef(claims: IdTokenClaims, config: OIDCConfig): strin
* Admin iff the configured role claim's values include the configured admin
* value, exact case-sensitive string match.
*/
-export function resolveRole(claims: IdTokenClaims, config: OIDCConfig): Role {
+export function resolveRole(claims: IdTokenClaims, config: OIDCConfig): 'admin' | 'user' {
return claimValues(claims[config.OIDC_USER_ROLE_CLAIM]).includes(config.OIDC_ADMIN_ROLE_VALUE) ? 'admin' : 'user';
}
-/** Everything `/callback` (and later `/me`, once sessions are real) needs from a set of claims. */
-export function toUserContext(claims: IdTokenClaims, config: OIDCConfig): UserContext {
+/** Map verified ID-token claims onto a {@link RequestContext}. */
+export function toRequestContext(params: {
+ claims: IdTokenClaims;
+ config: OIDCConfig;
+ user_credential: string;
+}): RequestContext {
+ const { claims, config, user_credential } = params;
assertEmailAllowed(claims, config);
+ const subjectId = resolveUserRef(claims, config);
+ const displayName = resolveOptionalStringClaim(claims, config.OIDC_USER_DISPLAY_NAME_CLAIM) ?? subjectId;
return {
- userRef: resolveUserRef(claims, config),
- role: resolveRole(claims, config),
+ tenant_id: 'default',
+ subject: {
+ id: subjectId,
+ type: 'user',
+ display_name: displayName,
+ },
+ roles: claimValues(claims[config.OIDC_USER_ROLE_CLAIM]),
+ user_credential,
};
}
@@ -63,10 +85,10 @@ export interface AuthorizationRequestParams {
/**
* Scopes + `claims` parameter for the authorization request, derived
* from configured claim names and {@link OIDCConfig.OIDC_SCOPES}.
- * `essential: true` on the role claim makes the IdP reject the
- * login outright if it can't actually produce that claim (e.g. a broken
- * claim mapping) instead of silently omitting it and defaulting the user to
- * non-admin.
+ * `essential: true` on identity claims makes the IdP reject the
+ * login outright if it can't actually produce that claim.
+ * Display name is requested via scopes/claims mapping but is not essential —
+ * {@link toRequestContext} falls back to the subject id when it is absent.
* When an email allowlist is configured, `email` is also marked essential so
* the IdP cannot complete login without a usable address to check.
*/
diff --git a/packages/trueforge/src/auth/createAuthenticator.ts b/packages/trueforge/src/auth/createAuthenticator.ts
new file mode 100644
index 000000000..f6c4156ed
--- /dev/null
+++ b/packages/trueforge/src/auth/createAuthenticator.ts
@@ -0,0 +1,25 @@
+import { TrueForgeMode } 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 };
+
+/** 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:
+ return new OidcAuthenticator();
+ case TrueForgeMode.Standalone:
+ return new StandaloneAuthenticator();
+ }
+}
diff --git a/packages/trueforge/src/auth/identity.ts b/packages/trueforge/src/auth/identity.ts
index fc46a1ab6..9761e3530 100644
--- a/packages/trueforge/src/auth/identity.ts
+++ b/packages/trueforge/src/auth/identity.ts
@@ -1,41 +1,73 @@
import type { Context } from 'hono';
-import { getOidcVerify } from './oidc';
-export type Role = 'admin' | 'user';
+import configuration, { getTrueForgeMode, isOidcConfigured, TrueForgeMode } from '../config';
-export interface UserContext {
- userRef: string;
- role: Role;
+/** TrueFoundry Control Plane role treated as admin until mapping is settled. */
+export const TRUEFOUNDRY_ADMIN_ROLE = 'tenant-admin';
+
+/** Standalone / default TrueForge admin role string. */
+export const STANDALONE_ADMIN_ROLE = 'admin';
+
+export interface RequestSubject {
+ id: string;
+ type: string;
+ display_name: string;
}
-/**
- * Fixed identity when no identity provider is configured (standalone / auth disabled).
- * Stamped onto sessions as `created_by` and used for ownership checks.
- */
-export const LOCAL_USER_CONTEXT: UserContext = {
- userRef: 'trueforge-default',
- role: 'admin',
+export interface RequestContext {
+ tenant_id: string;
+ subject: RequestSubject;
+ roles: string[];
+ /** Raw bearer token for the caller, or `null` when standalone has no credential. */
+ user_credential: string | null;
+}
+
+export const STANDALONE_REQUEST_CONTEXT: RequestContext = {
+ tenant_id: 'default',
+ subject: {
+ id: 'trueforge-default',
+ type: 'user',
+ display_name: 'trueforge-default',
+ },
+ roles: [STANDALONE_ADMIN_ROLE],
+ user_credential: null,
};
-/** Auth disabled: always true. Auth enabled: admin role only. */
-export function isAdmin(user: UserContext): boolean {
- if (!getOidcVerify()) {
- return true;
+export type ResolveRequestContext = (c: Context) => RequestContext;
+
+declare module 'hono' {
+ interface ContextVariableMap {
+ request_context?: RequestContext;
}
- return user.role === 'admin';
}
-/** Resolves the caller identity from the request context. Injected on session/turn routers. */
-export type ResolveUserContext = (c: Context) => UserContext;
+export function resolveRequestContext(c: Context): RequestContext {
+ const requestContext = c.get('request_context');
+ if (requestContext === undefined) {
+ throw new Error('RequestContext missing; auth middleware did not run');
+ }
+ return requestContext;
+}
/**
- * Caller {@link UserContext} for the current request.
- * Requires auth middleware to have set `c.var.user`.
+ * 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}).
+ * - Standalone: `roles` includes `admin`
+ * - OIDC: `roles` includes configured `OIDC_ADMIN_ROLE_VALUE`
+ * - TrueFoundry: `roles` includes `tenant-admin` (temporary; revisit mapping later)
*/
-export function resolveUserContext(c: Context): UserContext {
- const uc = c.get('user_context');
- if (uc === undefined) {
- throw new Error('UserContext missing; auth middleware did not run');
+export function hasAdminRole(requestContext: Pick<RequestContext, 'roles'>): boolean {
+ switch (getTrueForgeMode()) {
+ case TrueForgeMode.TrueFoundry:
+ // TODO: stop treating `tenant-admin` as TrueForge admin once TFY role mapping is settled.
+ return requestContext.roles.includes(TRUEFOUNDRY_ADMIN_ROLE);
+ case TrueForgeMode.Oidc: {
+ const adminValue = isOidcConfigured(configuration)
+ ? configuration.OIDC.OIDC_ADMIN_ROLE_VALUE
+ : STANDALONE_ADMIN_ROLE;
+ return requestContext.roles.includes(adminValue);
+ }
+ case TrueForgeMode.Standalone:
+ return requestContext.roles.includes(STANDALONE_ADMIN_ROLE);
}
- return uc;
}
diff --git a/packages/trueforge/src/auth/middleware.ts b/packages/trueforge/src/auth/middleware.ts
index 2d2bf2f94..64ee2bf65 100644
--- a/packages/trueforge/src/auth/middleware.ts
+++ b/packages/trueforge/src/auth/middleware.ts
@@ -1,69 +1,48 @@
import type { Context, MiddlewareHandler } from 'hono';
import { HTTPException } from 'hono/http-exception';
import { jwtVerify } from 'jose';
-import { toUserContext, type IdTokenClaims } from './claims';
-import { readAccessTokenCookie, readIdTokenCookie } from './cookies';
-import { LOCAL_USER_CONTEXT, isAdmin, type UserContext } from './identity';
-import { getOidcVerify } from './oidc';
-
-declare module 'hono' {
- interface ContextVariableMap {
- user_context?: UserContext;
- }
-}
-
-const AUTH_HEADER_TYPE = 'Bearer';
-/**
- * Bearer token from `Authorization: Bearer <token>` when present.
- * Case-insensitive scheme; rejects empty credentials. Non-Bearer schemes → undefined
- * so cookie auth can still apply.
- */
-export function readBearerToken(c: Context): string | undefined {
- const header = c.req.header('Authorization')?.trim();
- if (!header) {
- return undefined;
- }
- const prefix = `${AUTH_HEADER_TYPE} `;
- if (!header.toLowerCase().startsWith(prefix.toLowerCase())) {
- return undefined;
- }
- const token = header.slice(prefix.length).trim();
- return token.length > 0 ? token : undefined;
-}
+import type { Authenticator } from './authenticator';
+import { toRequestContext, type IdTokenClaims } from './claims';
+import { hasAdminRole, type RequestContext } from './identity';
+import { getOidcVerify } from './oidc';
+import { extractRequestToken } from './token';
-export function readAccessToken(c: Context): string | undefined {
- return readBearerToken(c) ?? readAccessTokenCookie({ context: c }) ?? readIdTokenCookie({ context: c });
-}
+export { extractRequestToken, readBearerToken } from './token';
-export function requireAccessToken(c: Context): string {
- const token = readAccessToken(c);
- if (!token) {
- throw new HTTPException(401, {
- message: 'Authentication token required to list or call TrueFoundry models and MCP servers',
- });
- }
- return token;
+export function createAuthMiddleware(authenticator: Authenticator): MiddlewareHandler {
+ return async (c, next) => {
+ c.set('request_context', await authenticator.authenticate(c));
+ return next();
+ };
}
-/**
- * Prefer Bearer over the browser cookie when both are sent (explicit API auth wins).
- */
-export function readIdToken(c: Context): string | undefined {
- return readBearerToken(c) ?? readIdTokenCookie({ context: c });
+export function createAdminAuthMiddleware(authenticator: Authenticator): MiddlewareHandler {
+ return async (c, next) => {
+ const requestContext = await authenticator.authenticate(c);
+ if (!hasAdminRole(requestContext)) {
+ throw new HTTPException(403, { message: 'Admin access required' });
+ }
+ c.set('request_context', requestContext);
+ return next();
+ };
}
/**
- * Bearer or cookie ID token → {@link UserContext} when auth is enabled and the JWT is valid.
- * Missing/invalid JWT → `undefined`. Claim mapping failures after a successful verify rethrow.
+ * Soft OIDC probe for login/callback — not request-gate middleware.
+ *
+ * Same JWT → {@link RequestContext} path as {@link OidcAuthenticator}, but missing/invalid
+ * tokens return `undefined` instead of throwing 401 (claim mapping failures after verify still
+ * rethrow so callers can clear a stale cookie). Needed where "no session yet" must not fail
+ * the request, e.g. redirect-if-already-authenticated on `/auth/callback`.
*/
-export async function resolveAuthUser(c: Context): Promise<UserContext | undefined> {
+export async function resolveOidcRequestContext(c: Context): Promise<RequestContext | undefined> {
const oidcVerify = getOidcVerify();
if (!oidcVerify) {
return undefined;
}
- const token = readIdToken(c);
+ const token = extractRequestToken(c);
if (!token) {
return undefined;
}
@@ -79,54 +58,9 @@ export async function resolveAuthUser(c: Context): Promise<UserContext | undefin
}
const claims: IdTokenClaims = { ...payload };
- return toUserContext(claims, oidcVerify.oidcConfig);
+ return toRequestContext({
+ claims,
+ config: oidcVerify.oidcConfig,
+ user_credential: token,
+ });
}
-
-/** Set `c.var.user` and continue, or throw 401. When auth is disabled, sets {@link LOCAL_USER_CONTEXT}. */
-export const authMiddleware: MiddlewareHandler = async (c, next) => {
- if (!getOidcVerify()) {
- c.set('user_context', LOCAL_USER_CONTEXT);
- return next();
- }
-
- try {
- const user = await resolveAuthUser(c);
- if (!user) {
- throw new HTTPException(401, { message: 'Authentication required' });
- }
- c.set('user_context', user);
- } catch (error) {
- if (error instanceof HTTPException) {
- throw error;
- }
- // Valid JWT but claim mapping failed (e.g. missing user reference claim).
- throw new HTTPException(401, { message: 'Authentication required', cause: error });
- }
- return next();
-};
-
-/** Admin gate: local admin when auth is disabled; when auth is enabled requires an authenticated admin. */
-export const adminAuthMiddleware: MiddlewareHandler = async (c, next) => {
- if (!getOidcVerify()) {
- c.set('user_context', LOCAL_USER_CONTEXT);
- return next();
- }
-
- try {
- const user = await resolveAuthUser(c);
- if (!user) {
- throw new HTTPException(401, { message: 'Authentication required' });
- }
- if (!isAdmin(user)) {
- throw new HTTPException(403, { message: 'Admin access required' });
- }
- c.set('user_context', user);
- } catch (error) {
- if (error instanceof HTTPException) {
- throw error;
- }
- throw new HTTPException(401, { message: 'Authentication required', cause: error });
- }
-
- return next();
-};
diff --git a/packages/trueforge/src/auth/oidcAuthenticator.ts b/packages/trueforge/src/auth/oidcAuthenticator.ts
new file mode 100644
index 000000000..01a797f25
--- /dev/null
+++ b/packages/trueforge/src/auth/oidcAuthenticator.ts
@@ -0,0 +1,44 @@
+import type { Context } from 'hono';
+import { HTTPException } from 'hono/http-exception';
+import { jwtVerify } from 'jose';
+
+import type { Authenticator } from './authenticator';
+import { toRequestContext, type IdTokenClaims } from './claims';
+import type { RequestContext } from './identity';
+import { getOidcVerify } from './oidc';
+import { extractRequestToken } from './token';
+
+export class OidcAuthenticator implements Authenticator {
+ async authenticate(c: Context): Promise<RequestContext> {
+ const oidcVerify = getOidcVerify();
+ if (!oidcVerify) {
+ throw new HTTPException(401, { message: 'Authentication required' });
+ }
+
+ const token = extractRequestToken(c);
+ if (!token) {
+ throw new HTTPException(401, { message: 'Authentication required' });
+ }
+
+ let payload: Awaited<ReturnType<typeof jwtVerify>>['payload'];
+ try {
+ ({ payload } = await jwtVerify(token, oidcVerify.jwks, {
+ issuer: oidcVerify.issuer,
+ audience: oidcVerify.audience,
+ }));
+ } catch {
+ throw new HTTPException(401, { message: 'Authentication required' });
+ }
+
+ try {
+ const claims: IdTokenClaims = { ...payload };
+ return toRequestContext({
+ claims,
+ config: oidcVerify.oidcConfig,
+ user_credential: token,
+ });
+ } catch (error) {
+ throw new HTTPException(401, { message: 'Authentication required', cause: error });
+ }
+ }
+}
diff --git a/packages/trueforge/src/auth/standaloneAuthenticator.ts b/packages/trueforge/src/auth/standaloneAuthenticator.ts
new file mode 100644
index 000000000..f4708d819
--- /dev/null
+++ b/packages/trueforge/src/auth/standaloneAuthenticator.ts
@@ -0,0 +1,8 @@
+import type { Authenticator } from './authenticator';
+import { STANDALONE_REQUEST_CONTEXT, type RequestContext } from './identity';
+
+export class StandaloneAuthenticator implements Authenticator {
+ authenticate(): Promise<RequestContext> {
+ return Promise.resolve(STANDALONE_REQUEST_CONTEXT);
+ }
+}
diff --git a/packages/trueforge/src/auth/token.ts b/packages/trueforge/src/auth/token.ts
new file mode 100644
index 000000000..632c241f3
--- /dev/null
+++ b/packages/trueforge/src/auth/token.ts
@@ -0,0 +1,40 @@
+import type { Context } from 'hono';
+
+import { readAccessTokenCookie, readIdTokenCookie } from './cookies';
+
+const AUTH_HEADER_TYPE = 'Bearer';
+const BEARER_PREFIX = `${AUTH_HEADER_TYPE} `;
+
+/**
+ * Parse `Bearer <token>` from an Authorization-style value.
+ * Case-insensitive scheme; empty credentials → undefined.
+ */
+function parseBearerAuthorization(value: string): string | undefined {
+ const trimmed = value.trim();
+ if (!trimmed.toLowerCase().startsWith(BEARER_PREFIX.toLowerCase())) {
+ return undefined;
+ }
+ const token = trimmed.slice(BEARER_PREFIX.length).trim();
+ return token.length > 0 ? token : undefined;
+}
+
+/**
+ * Bearer token from `Authorization: Bearer <token>` when present.
+ * Non-Bearer schemes → undefined so cookie auth can still apply.
+ */
+export function readBearerToken(c: Context): string | undefined {
+ const header = c.req.header('Authorization');
+ if (!header) {
+ return undefined;
+ }
+ return parseBearerAuthorization(header);
+}
+
+/**
+ * Prefer an explicit Bearer over browser cookies.
+ * Cookie order: `accessToken`, then `id_token`.
+ * Never log the returned value.
+ */
+export function extractRequestToken(c: Context): string | undefined {
+ return readBearerToken(c) ?? readAccessTokenCookie({ context: c }) ?? readIdTokenCookie({ context: c });
+}
diff --git a/packages/trueforge/src/auth/trueFoundryAuthenticator.ts b/packages/trueforge/src/auth/trueFoundryAuthenticator.ts
new file mode 100644
index 000000000..5eb674bd1
--- /dev/null
+++ b/packages/trueforge/src/auth/trueFoundryAuthenticator.ts
@@ -0,0 +1,40 @@
+import type { Context } from 'hono';
+import { HTTPException } from 'hono/http-exception';
+
+import type { GetSessionResponse } from '../truefoundry/TrueFoundryServiceFoundryServerClient';
+import type { Authenticator } from './authenticator';
+import type { RequestContext } from './identity';
+import { extractRequestToken } from './token';
+
+/** Narrow port used by the authenticator (avoids depending on the full SFY client). */
+export interface TrueFoundrySessionClient {
+ getSession(accessToken: string): Promise<GetSessionResponse>;
+}
+
+export class TrueFoundryAuthenticator implements Authenticator {
+ readonly #client: TrueFoundrySessionClient;
+
+ constructor(client: TrueFoundrySessionClient) {
+ this.#client = client;
+ }
+
+ async authenticate(c: Context): Promise<RequestContext> {
+ const token = extractRequestToken(c);
+ if (!token) {
+ throw new HTTPException(401, { message: 'Authentication required' });
+ }
+
+ const session = await this.#client.getSession(token);
+ const { subject } = session.user;
+ return {
+ tenant_id: session.user.tenantName,
+ subject: {
+ id: subject.subjectId,
+ type: subject.subjectType,
+ display_name: subject.subjectDisplayName ?? subject.subjectSlug ?? subject.subjectId,
+ },
+ roles: session.user.roles,
+ user_credential: token,
+ };
+ }
+}
diff --git a/packages/trueforge/src/config.ts b/packages/trueforge/src/config.ts
index 619844167..5d7a8f1a7 100644
--- a/packages/trueforge/src/config.ts
+++ b/packages/trueforge/src/config.ts
@@ -40,6 +40,7 @@ const DEFAULT_POSTGRES_PORT = 5432;
const DEFAULT_REDIS_URL = 'redis://localhost:6379';
const DEFAULT_OIDC_USER_REFERENCE_CLAIM = 'sub';
+const DEFAULT_OIDC_USER_DISPLAY_NAME_CLAIM = 'name';
const DEFAULT_OIDC_USER_ROLE_CLAIM = 'groups';
const DEFAULT_OIDC_ADMIN_ROLE_VALUE = 'admin';
const DEFAULT_OIDC_SCOPES = 'openid,profile,email';
@@ -270,6 +271,9 @@ function resolveOIDCConfig(): OIDCConfig | undefined {
OIDC_USER_REFERENCE_CLAIM:
getEnv('OIDC_USER_REFERENCE_CLAIM', { defaultValue: DEFAULT_OIDC_USER_REFERENCE_CLAIM }) ??
DEFAULT_OIDC_USER_REFERENCE_CLAIM,
+ OIDC_USER_DISPLAY_NAME_CLAIM:
+ getEnv('OIDC_USER_DISPLAY_NAME_CLAIM', { defaultValue: DEFAULT_OIDC_USER_DISPLAY_NAME_CLAIM }) ??
+ DEFAULT_OIDC_USER_DISPLAY_NAME_CLAIM,
OIDC_USER_ROLE_CLAIM:
getEnv('OIDC_USER_ROLE_CLAIM', { defaultValue: DEFAULT_OIDC_USER_ROLE_CLAIM }) ?? DEFAULT_OIDC_USER_ROLE_CLAIM,
OIDC_ADMIN_ROLE_VALUE:
@@ -294,6 +298,11 @@ export interface OIDCConfig {
* Optional; defaults to "sub"
*/
OIDC_USER_REFERENCE_CLAIM: string;
+ /** Claim used as the display name; e.g. "name" or "preferred_username".
+ * Optional; defaults to "name". Missing/empty falls back to the user reference.
+ * Env: `OIDC_USER_DISPLAY_NAME_CLAIM`.
+ */
+ OIDC_USER_DISPLAY_NAME_CLAIM: string;
/** Claim to be used as the user role; e.g. "role" or "groups"
* Optional; defaults to "groups"
*/
@@ -676,6 +685,27 @@ export function isTrueFoundryModeEnabled(
return config.TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL !== undefined;
}
+/** Runtime auth/integration mode for this process. */
+export enum TrueForgeMode {
+ Standalone = 'standalone',
+ Oidc = 'oidc',
+ TrueFoundry = 'truefoundry',
+}
+
+/**
+ * Resolve the active {@link TrueForgeMode} from configuration.
+ * TrueFoundry wins over OIDC when both would otherwise be set (startup already rejects that combo).
+ */
+export function getTrueForgeMode(config: ServerConfiguration = configuration): TrueForgeMode {
+ if (isTrueFoundryModeEnabled(config)) {
+ return TrueForgeMode.TrueFoundry;
+ }
+ if (isOidcConfigured(config)) {
+ return TrueForgeMode.Oidc;
+ }
+ return TrueForgeMode.Standalone;
+}
+
// TrueFoundry mode authenticates each caller with their own gateway token, so browser SSO must be
// off — the two auth models are mutually exclusive.
if (isTrueFoundryModeEnabled(configuration) && isOidcConfigured(configuration)) {
diff --git a/packages/trueforge/src/db/postgres/types.ts b/packages/trueforge/src/db/postgres/types.ts
index c3025bb4b..c5638e3f6 100644
--- a/packages/trueforge/src/db/postgres/types.ts
+++ b/packages/trueforge/src/db/postgres/types.ts
@@ -398,7 +398,7 @@ export interface ScheduleTable {
manifest: JSONColumnType<ScheduleManifest, ScheduleManifest, ScheduleManifest>;
/** `paused` stops triggering and drops the pending run; in-flight runs continue */
status: ScheduleStatus;
- /** Identity every run of this schedule executes as (`UserContext.userRef`) */
+ /** Identity every run of this schedule executes as (`RequestContext.subject.id`) */
created_by: string;
created_at: Date;
updated_at: Date;
@@ -419,7 +419,7 @@ export interface ScheduleRunTable {
scheduled_for: Date;
/** `scheduled` | `triggered` | `failed` | `missed` — varchar(16) */
status: ScheduleRunStatus;
- /** `UserContext.userRef` of who triggered the run */
+ /** `RequestContext.subject.id` of who triggered the run */
triggered_by: string;
triggered_at: Date | null;
created_at: Date;
@@ -453,7 +453,7 @@ export interface McpServerTable {
/**
* PRIMARY KEY (oauth_server_id, user_id)
* No `tenant_id` — already scoped to tenant via the FK. Tokens are per harness user
- * (`user_id` = `UserContext.userRef`); any tenant-scoped read resolves `oauth_server_id`
+ * (`user_id` = `RequestContext.subject.id`); any tenant-scoped read resolves `oauth_server_id`
* through mcp_server (by tenant_id + name) first.
*/
export interface OAuthTokenTable {
diff --git a/packages/trueforge/src/db/sqlite/types.ts b/packages/trueforge/src/db/sqlite/types.ts
index 57343d86a..114a8814a 100644
--- a/packages/trueforge/src/db/sqlite/types.ts
+++ b/packages/trueforge/src/db/sqlite/types.ts
@@ -243,7 +243,7 @@ export interface ScheduleTable {
manifest: JsonbColumn<ScheduleManifest>;
/** `paused` stops triggering and drops the pending run; in-flight runs continue */
status: ScheduleStatus;
- /** Identity every run of this schedule executes as (`UserContext.userRef`) */
+ /** Identity every run of this schedule executes as (`RequestContext.subject.id`) */
created_by: string;
created_at: string;
updated_at: string;
@@ -264,7 +264,7 @@ export interface ScheduleRunTable {
scheduled_for: string;
/** `scheduled` | `triggered` | `failed` | `missed` — length ≤ 16 */
status: ScheduleRunStatus;
- /** `UserContext.userRef` of who triggered the run */
+ /** `RequestContext.subject.id` of who triggered the run */
triggered_by: string;
triggered_at: string | null;
created_at: string;
@@ -297,7 +297,7 @@ export interface McpServerTable {
/**
* PRIMARY KEY (oauth_server_id, user_id)
* No `tenant_id` — already scoped to tenant via the FK. Tokens are per harness user
- * (`user_id` = `UserContext.userRef`); any tenant-scoped read resolves `oauth_server_id`
+ * (`user_id` = `RequestContext.subject.id`); any tenant-scoped read resolves `oauth_server_id`
* through mcp_server (by tenant_id + name) first.
*/
export interface OAuthTokenTable {
diff --git a/packages/trueforge/src/main.ts b/packages/trueforge/src/main.ts
index b3874a51c..2c0ae33fb 100644
--- a/packages/trueforge/src/main.ts
+++ b/packages/trueforge/src/main.ts
@@ -11,6 +11,7 @@
*/
import { extractErrorLogFields } from '@truefoundry/trueforge-core/core';
import type { Context } from 'hono';
+import { HTTPException } from 'hono/http-exception';
import { mkdir } from 'node:fs/promises';
import path from 'node:path';
import {
@@ -23,9 +24,17 @@ 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;
try {
- ({ default: configuration, isOidcConfigured, isTrueFoundryModeEnabled } = await import('./config'));
+ ({
+ default: configuration,
+ isOidcConfigured,
+ isTrueFoundryModeEnabled,
+ getTrueForgeMode,
+ TrueForgeMode,
+ } = await import('./config'));
} catch (error) {
console.error(
'Failed to start server: Failed to load configuration:',
@@ -47,7 +56,8 @@ import type { RedisClientType } from 'redis';
import type { Logger } from 'winston';
import { createServerApp } from './app';
-import { requireAccessToken } from './auth/middleware';
+import { createAuthenticator } from './auth/createAuthenticator';
+import { resolveRequestContext } from './auth/identity';
import { initOidc } from './auth/oidc';
import { McpCatalog } from './catalog/McpCatalog';
import { ModelCatalog } from './catalog/ModelCatalog';
@@ -93,6 +103,16 @@ interface ServerPersistence<TTransaction> {
redis: RedisClientType | undefined;
}
+function requireRequestCredentialToken(c: Context): string {
+ const credential = resolveRequestContext(c).user_credential;
+ if (credential === null) {
+ throw new HTTPException(401, {
+ message: 'Authentication token required to list or call TrueFoundry models and MCP servers',
+ });
+ }
+ return credential;
+}
+
/**
* 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.
@@ -113,7 +133,7 @@ function buildResolveModelProviderStore<TTransaction>(options: {
// unavailable there; fall back to the persistence store.
return c =>
c
- ? new TrueFoundryModelProviderStore<TTransaction>({ client, accessToken: requireAccessToken(c) })
+ ? new TrueFoundryModelProviderStore<TTransaction>({ client, accessToken: requireRequestCredentialToken(c) })
: options.persistenceStore;
}
@@ -143,7 +163,7 @@ function buildResolveMcpServerStore<TTransaction>(options: {
});
return c =>
c
- ? new TrueFoundryMcpServerStore<TTransaction>({ client, accessToken: requireAccessToken(c) })
+ ? new TrueFoundryMcpServerStore<TTransaction>({ client, accessToken: requireRequestCredentialToken(c) })
: withAuthPersistence;
}
@@ -316,6 +336,26 @@ async function createServerRuntime<TTransaction>(persistence: ServerPersistence<
}
const oidcClient = await initOidc(oidc);
+ let authenticator;
+ const mode = getTrueForgeMode(configuration);
+ if (mode === TrueForgeMode.TrueFoundry) {
+ if (!isTrueFoundryModeEnabled(configuration)) {
+ throw new Error('TrueFoundry mode requires TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL');
+ }
+ authenticator = createAuthenticator({
+ mode: TrueForgeMode.TrueFoundry,
+ trueFoundryClient: new TrueFoundryServiceFoundryServerClient({
+ serviceFoundryServerUrl: configuration.TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL,
+ logger,
+ tls: { enabled: configuration.TRUEFOUNDRY_MTLS_ENABLED, dir: configuration.TRUEFOUNDRY_MTLS_CERTS_DIR },
+ }),
+ });
+ } else if (mode === TrueForgeMode.Oidc) {
+ authenticator = createAuthenticator({ mode: TrueForgeMode.Oidc });
+ } else {
+ authenticator = createAuthenticator({ mode: TrueForgeMode.Standalone });
+ }
+
// Standalone is one process, so it owns the control loops too.
const controller = configuration.STANDALONE
? createController({
@@ -348,6 +388,7 @@ async function createServerRuntime<TTransaction>(persistence: ServerPersistence<
eventSubscriptions,
logger,
oidcClient,
+ authenticator,
});
return { activeTurns, app, controller, destroyDb, redis, requestReplyRouter };
diff --git a/packages/trueforge/src/mcp/auth/types.ts b/packages/trueforge/src/mcp/auth/types.ts
index 659f35ff4..bc228d338 100644
--- a/packages/trueforge/src/mcp/auth/types.ts
+++ b/packages/trueforge/src/mcp/auth/types.ts
@@ -16,7 +16,7 @@ export interface OAuthToken {
scope: string | null;
}
-/** Composite key: MCP server row id + harness `UserContext.userRef`. */
+/** Composite key: MCP server row id + harness `RequestContext.subject.id`. */
export interface OAuthTokenKey {
id: string;
userRef: string;
diff --git a/packages/trueforge/src/routes/authRoutes.ts b/packages/trueforge/src/routes/authRoutes.ts
index ad6a4ed10..dc1314a02 100644
--- a/packages/trueforge/src/routes/authRoutes.ts
+++ b/packages/trueforge/src/routes/authRoutes.ts
@@ -63,19 +63,20 @@ export const meRoute = createRoute({
tags: [OpenApiTag.AUTH],
summary: 'Current session',
description:
- 'Returns the authenticated caller identity. When auth is enabled this requires a valid ' +
- '`id_token` cookie or `Authorization: Bearer` ID token (401 otherwise). When auth is disabled, ' +
- 'returns the default identity.',
+ 'Returns the authenticated caller identity (`type`, `tenant_id`, `subject`, `roles`) wrapped as `{ data }`. ' +
+ '`type` is `oidc-connected` when browser OIDC is enabled, otherwise `default`. When auth is enabled ' +
+ 'this requires a valid `id_token` cookie or `Authorization: Bearer` token (401 otherwise). When auth is ' +
+ 'disabled, returns the standalone default identity.',
'x-fern-sdk-group-name': ['auth'],
'x-fern-sdk-method-name': 'me',
responses: {
200: {
content: { 'application/json': { schema: GetMeResponseSchema } },
- description: 'Session type and identity for the current request.',
+ description: 'Caller identity for the current request.',
},
401: {
content: { 'application/json': { schema: RequestErrorResponseSchema } },
- description: 'Auth is enabled and the request has no valid cookie or Bearer ID token.',
+ description: 'Auth is enabled and the request has no valid cookie or Bearer token.',
},
},
});
diff --git a/packages/trueforge/src/schemas/auth.ts b/packages/trueforge/src/schemas/auth.ts
index 9574f8ca6..58a4be218 100644
--- a/packages/trueforge/src/schemas/auth.ts
+++ b/packages/trueforge/src/schemas/auth.ts
@@ -28,16 +28,33 @@ export const OAuthCallbackSuccessSchema = z.object({
success: z.literal(true).describe('Present when the OAuth callback completed without a return_to.'),
});
-export const GetMeResponseSchema = z
+export const GetMeSubjectSchema = z
.object({
- type: z
- .enum(['default', 'oidc-connected'])
- .describe(
- 'Session kind: `default` when no valid OIDC session; `oidc-connected` after a successful browser login.',
- ),
- email: z.string().describe('User email from the ID token when connected; `"default"` when anonymous.'),
- role: z.string().describe('Caller role.'),
+ id: z.string().describe('Stable subject identifier for the caller.'),
+ type: z.string().describe('Subject kind as returned by the identity provider (stored as-is).'),
+ display_name: z.string().describe('Human-readable name for the caller.'),
})
- .openapi('GetMeResponse');
+ .openapi('GetMeSubject');
+export const MeSessionTypeSchema = z
+ .enum(['default', 'oidc-connected'])
+ .describe(
+ '`oidc-connected` when the process is running with browser OIDC login; `default` for standalone or TrueFoundry token auth.',
+ )
+ .openapi('MeSessionType');
+
+export const MeSchema = z
+ .object({
+ type: MeSessionTypeSchema,
+ tenant_id: z.string().describe('Tenant scope for the authenticated caller.'),
+ subject: GetMeSubjectSchema,
+ roles: z.array(z.string()).describe('Roles for the authenticated caller.'),
+ })
+ .openapi('Me');
+
+export const GetMeResponseSchema = z.object({ data: MeSchema }).openapi('GetMeResponse');
+
+export type GetMeSubject = z.infer<typeof GetMeSubjectSchema>;
+export type MeSessionType = z.infer<typeof MeSessionTypeSchema>;
+export type Me = z.infer<typeof MeSchema>;
export type GetMeResponse = z.infer<typeof GetMeResponseSchema>;
diff --git a/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts b/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts
index 1f40ca014..047aabed6 100644
--- a/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts
+++ b/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts
@@ -9,9 +9,37 @@ import { createInternalTlsDispatcher, normalizeInternalTlsUrl, type InternalTlsO
const INTEGRATIONS_PATH = 'v1/provider-integrations';
const INSTALLATIONS_PATH = 'v1/llm-gateway/installations';
const MCP_SERVERS_PATH = 'v1/mcp';
+const SESSION_PATH = 'v1/session';
const INTEGRATIONS_PAGE_SIZE = 1000;
const MCP_SERVERS_PAGE_SIZE = 100;
+/**
+ * Fields required to build RequestContext from ServiceFoundry `GET /v1/session`.
+ * Wire shape is camelCase (Nest Session + exposed `subject()`).
+ * Unauthenticated callers get HTTP 200 with `user: null`.
+ */
+const SessionSubjectSchema = z.object({
+ subjectId: z.string().min(1),
+ subjectType: z.string().min(1),
+ subjectDisplayName: z.string().nullable().optional(),
+ subjectSlug: z.string().nullable().optional(),
+});
+
+const GetSessionUserSchema = z.object({
+ tenantName: z.string().min(1),
+ roles: z.array(z.string()),
+ subject: SessionSubjectSchema,
+});
+
+const GetSessionWireSchema = z.object({
+ user: GetSessionUserSchema.nullable(),
+});
+
+/** Authenticated session payload (`user` is non-null after {@link TrueFoundryServiceFoundryServerClient.getSession}). */
+export interface GetSessionResponse {
+ user: z.infer<typeof GetSessionUserSchema>;
+}
+
const ListResponseSchema = z.union([
z.array(z.unknown()),
z.object({
@@ -137,6 +165,36 @@ export class TrueFoundryServiceFoundryServerClient {
return rows[0];
}
+ /**
+ * `GET v1/session` for RequestContext mapping.
+ * `user: null` (invalid/missing auth on a 200) → 401; all other failures → 500.
+ */
+ async getSession(accessToken: string): Promise<GetSessionResponse> {
+ let payload: unknown;
+ try {
+ payload = await this.#getJson(this.#url(SESSION_PATH), accessToken);
+ } catch (error) {
+ if (error instanceof HTTPException && (error.status === 401 || error.status === 403)) {
+ throw error;
+ }
+ throw new HTTPException(500, {
+ message: 'TrueFoundry ServiceFoundry session request failed',
+ cause: error,
+ });
+ }
+ const parsed = GetSessionWireSchema.safeParse(payload);
+ if (!parsed.success) {
+ throw new HTTPException(500, {
+ message: 'TrueFoundry ServiceFoundry session response was malformed',
+ cause: parsed.error,
+ });
+ }
+ if (parsed.data.user === null) {
+ throw new HTTPException(401, { message: 'Authentication required' });
+ }
+ return { user: parsed.data.user };
+ }
+
#parseListResponse(payload: unknown): ListResponse {
const parsed = ListResponseSchema.safeParse(payload);
if (!parsed.success) {
diff --git a/packages/trueforge/tests/unit/apis/agents.test.ts b/packages/trueforge/tests/unit/apis/agents.test.ts
index 14808cdd6..1e3a39463 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 { STANDALONE_REQUEST_CONTEXT } from '../../../src/auth/identity';
import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';
import { SqliteAgentStore } from '../../../src/db/sqlite/agent-store/SqliteAgentStore';
import { createSqliteDb } from '../../../src/db/sqlite/client';
@@ -84,6 +85,7 @@ describe('agents router', () => {
skillStore: new SqliteSkillStore(db),
sandboxProviderStore: new SqliteSandboxProviderStore(db),
withTransaction: callback => db.transaction().execute(callback),
+ resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT,
});
});
diff --git a/packages/trueforge/tests/unit/apis/auth.test.ts b/packages/trueforge/tests/unit/apis/auth.test.ts
index 8768fdd0e..8f607ca21 100644
--- a/packages/trueforge/tests/unit/apis/auth.test.ts
+++ b/packages/trueforge/tests/unit/apis/auth.test.ts
@@ -3,8 +3,11 @@ import { createHash } from 'node:crypto';
import type { Configuration } from 'openid-client';
import winston from 'winston';
import { createAuthRouter } from '../../../src/apis/auth';
-import { LOCAL_USER_CONTEXT } from '../../../src/auth/identity';
+import { STANDALONE_REQUEST_CONTEXT } from '../../../src/auth/identity';
+import { createAuthMiddleware } from '../../../src/auth/middleware';
import { disableOidcAuth, initOidc } from '../../../src/auth/oidc';
+import { OidcAuthenticator } from '../../../src/auth/oidcAuthenticator';
+import { StandaloneAuthenticator } from '../../../src/auth/standaloneAuthenticator';
import configuration from '../../../src/config';
jest.mock('../../../src/config', () => {
@@ -13,6 +16,7 @@ jest.mock('../../../src/config', () => {
OIDC_CLIENT_ID: 'harness-client',
OIDC_CLIENT_SECRET: 'harness-secret',
OIDC_USER_REFERENCE_CLAIM: 'sub',
+ OIDC_USER_DISPLAY_NAME_CLAIM: 'name',
OIDC_USER_ROLE_CLAIM: 'groups',
OIDC_ADMIN_ROLE_VALUE: 'admin',
OIDC_SCOPES: ['openid', 'profile', 'email', 'groups'],
@@ -53,13 +57,22 @@ const logger = winston.createLogger({ silent: true });
const ACCESS_TOKEN = 'access-1';
+function createTestAuthRouter(params: { oidcClient: Configuration | undefined }) {
+ const authenticator = params.oidcClient ? new OidcAuthenticator() : new StandaloneAuthenticator();
+ return createAuthRouter({
+ oidcClient: params.oidcClient,
+ logger,
+ authMiddleware: createAuthMiddleware(authenticator),
+ });
+}
+
describe('auth router (no identity provider configured)', () => {
beforeEach(() => {
disableOidcAuth();
});
it('GET /auth/login redirects home — there is nothing to log into', async () => {
- const router = createAuthRouter({ oidcClient: undefined, logger });
+ const router = createTestAuthRouter({ oidcClient: undefined });
const res = await router.request('/login', { redirect: 'manual' });
@@ -68,7 +81,7 @@ describe('auth router (no identity provider configured)', () => {
});
it('GET /auth/callback redirects home — there is nothing to complete', async () => {
- const router = createAuthRouter({ oidcClient: undefined, logger });
+ const router = createTestAuthRouter({ oidcClient: undefined });
const res = await router.request('/callback?state=abc', { redirect: 'manual' });
@@ -77,23 +90,26 @@ describe('auth router (no identity provider configured)', () => {
});
it('POST /auth/logout is a no-op 204 — there is no real session to clear', async () => {
- const router = createAuthRouter({ oidcClient: undefined, logger });
+ const router = createTestAuthRouter({ oidcClient: undefined });
const res = await router.request('/logout', { method: 'POST' });
expect(res.status).toBe(204);
});
- it('GET /auth/me returns the default identity when auth is disabled', async () => {
- const router = createAuthRouter({ oidcClient: undefined, logger });
+ it('GET /auth/me returns the standalone identity when auth is disabled', async () => {
+ const router = createTestAuthRouter({ oidcClient: undefined });
const res = await router.request('/me');
expect(res.status).toBe(200);
expect(await res.json()).toEqual({
- type: 'default',
- email: LOCAL_USER_CONTEXT.userRef,
- role: LOCAL_USER_CONTEXT.role,
+ data: {
+ type: 'default',
+ tenant_id: STANDALONE_REQUEST_CONTEXT.tenant_id,
+ subject: STANDALONE_REQUEST_CONTEXT.subject,
+ roles: STANDALONE_REQUEST_CONTEXT.roles,
+ },
});
});
});
@@ -202,7 +218,7 @@ describe('auth router (auth enabled)', () => {
}
it('GET /login redirects to the IdP and stores state', async () => {
- const res = await createAuthRouter({ oidcClient, logger }).request('/login?return_to=/sessions/abc123', {
+ const res = await createTestAuthRouter({ oidcClient }).request('/login?return_to=/sessions/abc123', {
redirect: 'manual',
});
@@ -232,7 +248,7 @@ describe('auth router (auth enabled)', () => {
throw new Error('OIDC client was not initialized');
}
- const res = await createAuthRouter({ oidcClient: rolesOidcClient, logger }).request('/login', {
+ const res = await createTestAuthRouter({ oidcClient: rolesOidcClient }).request('/login', {
redirect: 'manual',
});
@@ -249,7 +265,7 @@ describe('auth router (auth enabled)', () => {
// `iss` is forwarded verbatim: IdPs advertising it reject an exchange that drops it.
it('GET /callback exchanges the code and sets id_token', async () => {
- const router = createAuthRouter({ oidcClient, logger });
+ const router = createTestAuthRouter({ oidcClient });
const loginRes = await router.request('/login?return_to=/sessions/abc123', { redirect: 'manual' });
const stateCookieRaw = cookieValue(setCookies(loginRes), STATE_COOKIE) ?? '';
const authorizationUrl = new URL(loginRes.headers.get('location') ?? '');
@@ -275,13 +291,17 @@ describe('auth router (auth enabled)', () => {
throw new Error('OIDC client was not initialized');
}
- const router = createAuthRouter({ oidcClient: restrictedClient, logger });
+ const router = createTestAuthRouter({ oidcClient: restrictedClient });
const loginRes = await router.request('/login', { redirect: 'manual' });
const stateCookieRaw = cookieValue(setCookies(loginRes), STATE_COOKIE) ?? '';
const authorizationUrl = new URL(loginRes.headers.get('location') ?? '');
const state = authorizationUrl.searchParams.get('state') ?? '';
expect(JSON.parse(authorizationUrl.searchParams.get('claims') ?? '{}')).toEqual({
- id_token: { sub: { essential: true }, groups: { essential: true }, email: { essential: true } },
+ id_token: {
+ sub: { essential: true },
+ groups: { essential: true },
+ email: { essential: true },
+ },
});
const callbackRes = await router.request(`/callback?code=abc123&state=${state}&iss=${encodeURIComponent(ISSUER)}`, {
@@ -295,7 +315,7 @@ describe('auth router (auth enabled)', () => {
});
it('GET /callback redirects home with error when the IdP returns an error', async () => {
- const res = await createAuthRouter({ oidcClient, logger }).request(
+ const res = await createTestAuthRouter({ oidcClient }).request(
'/callback?state=any&error=access_denied&error_description=user%20cancelled',
{ redirect: 'manual' },
);
@@ -304,7 +324,7 @@ describe('auth router (auth enabled)', () => {
});
it('GET /callback uses login_failed when the IdP error has no description', async () => {
- const res = await createAuthRouter({ oidcClient, logger }).request('/callback?state=any&error=access_denied', {
+ const res = await createTestAuthRouter({ oidcClient }).request('/callback?state=any&error=access_denied', {
redirect: 'manual',
});
expect(res.status).toBe(302);
@@ -312,7 +332,7 @@ describe('auth router (auth enabled)', () => {
});
it('GET /callback uses login_failed when the IdP error description is blank', async () => {
- const res = await createAuthRouter({ oidcClient, logger }).request(
+ const res = await createTestAuthRouter({ oidcClient }).request(
'/callback?state=any&error=access_denied&error_description=%20%20',
{ redirect: 'manual' },
);
@@ -324,16 +344,15 @@ describe('auth router (auth enabled)', () => {
// No `error` code → this is our own validation failure, so the attacker-supplied
// description must not be reflected; the reason stays generic.
const crafted = 'Your%20account%20is%20compromised%2C%20call%201-800-EVIL';
- const res = await createAuthRouter({ oidcClient, logger }).request(
- `/callback?state=any&error_description=${crafted}`,
- { redirect: 'manual' },
- );
+ const res = await createTestAuthRouter({ oidcClient }).request(`/callback?state=any&error_description=${crafted}`, {
+ redirect: 'manual',
+ });
expect(res.status).toBe(302);
expect(res.headers.get('location')).toBe('/?error=login_failed');
});
it('GET /callback redirects home with error when state mismatches', async () => {
- const res = await createAuthRouter({ oidcClient, logger }).request('/callback?code=abc&state=wrong', {
+ const res = await createTestAuthRouter({ oidcClient }).request('/callback?code=abc&state=wrong', {
redirect: 'manual',
});
expect(res.status).toBe(302);
@@ -342,7 +361,7 @@ describe('auth router (auth enabled)', () => {
it('GET /callback replays home when already authenticated and the state cookie is spent', async () => {
const token = await createIdToken();
- const res = await createAuthRouter({ oidcClient, logger }).request('/callback?code=abc&state=spent', {
+ const res = await createTestAuthRouter({ oidcClient }).request('/callback?code=abc&state=spent', {
redirect: 'manual',
headers: { Cookie: `${ID_TOKEN_COOKIE}=${token}` },
});
@@ -362,13 +381,10 @@ describe('auth router (auth enabled)', () => {
}
const token = await createIdToken();
- const res = await createAuthRouter({ oidcClient: restrictedClient, logger }).request(
- '/callback?code=abc&state=spent',
- {
- redirect: 'manual',
- headers: { Cookie: `${ID_TOKEN_COOKIE}=${token}` },
- },
- );
+ const res = await createTestAuthRouter({ oidcClient: restrictedClient }).request('/callback?code=abc&state=spent', {
+ redirect: 'manual',
+ headers: { Cookie: `${ID_TOKEN_COOKIE}=${token}` },
+ });
expect(res.status).toBe(302);
expect(res.headers.get('location')).toBe('/?error=login_failed');
expect(
@@ -378,7 +394,7 @@ describe('auth router (auth enabled)', () => {
it('GET /callback replays home when already authenticated even if the IdP returned an error', async () => {
const token = await createIdToken();
- const res = await createAuthRouter({ oidcClient, logger }).request(
+ const res = await createTestAuthRouter({ oidcClient }).request(
'/callback?state=any&error=access_denied&error_description=user%20cancelled',
{
redirect: 'manual',
@@ -399,7 +415,7 @@ describe('auth router (auth enabled)', () => {
}
const token = await createIdToken();
- const router = createAuthRouter({ oidcClient: restrictedClient, logger });
+ const router = createTestAuthRouter({ oidcClient: restrictedClient });
const loginRes = await router.request('/login?return_to=/sessions/abc123', { redirect: 'manual' });
const stateCookieRaw = cookieValue(setCookies(loginRes), STATE_COOKIE) ?? '';
const authorizationUrl = new URL(loginRes.headers.get('location') ?? '');
@@ -418,7 +434,7 @@ describe('auth router (auth enabled)', () => {
it('GET /callback keeps the existing session when code exchange fails', async () => {
const token = await createIdToken();
- const router = createAuthRouter({ oidcClient, logger });
+ const router = createTestAuthRouter({ oidcClient });
const loginRes = await router.request('/login?return_to=/sessions/abc123', { redirect: 'manual' });
const stateCookieRaw = cookieValue(setCookies(loginRes), STATE_COOKIE) ?? '';
const authorizationUrl = new URL(loginRes.headers.get('location') ?? '');
@@ -442,7 +458,7 @@ describe('auth router (auth enabled)', () => {
});
it('POST /logout clears id_token even when no cookie is present', async () => {
- const res = await createAuthRouter({ oidcClient, logger }).request('/logout', {
+ const res = await createTestAuthRouter({ oidcClient }).request('/logout', {
method: 'POST',
});
@@ -453,16 +469,23 @@ describe('auth router (auth enabled)', () => {
});
it('GET /me returns 401 when the id_token cookie is missing', async () => {
- const res = await createAuthRouter({ oidcClient, logger }).request('/me');
+ const res = await createTestAuthRouter({ oidcClient }).request('/me');
expect(res.status).toBe(401);
});
- it('GET /me returns oidc-connected identity when authenticated', async () => {
+ it('GET /me returns RequestContext identity when authenticated', async () => {
const token = await createIdToken();
- const res = await createAuthRouter({ oidcClient, logger }).request('/me', {
+ const res = await createTestAuthRouter({ oidcClient }).request('/me', {
headers: { Cookie: `${ID_TOKEN_COOKIE}=${token}` },
});
expect(res.status).toBe(200);
- expect(await res.json()).toEqual({ type: 'oidc-connected', email: 'user-1', role: 'user' });
+ expect(await res.json()).toEqual({
+ data: {
+ type: 'oidc-connected',
+ tenant_id: 'default',
+ subject: { id: 'user-1', type: 'user', display_name: 'user-1' },
+ roles: [],
+ },
+ });
});
});
diff --git a/packages/trueforge/tests/unit/apis/capabilities.test.ts b/packages/trueforge/tests/unit/apis/capabilities.test.ts
index fc9c09047..2406d378d 100644
--- a/packages/trueforge/tests/unit/apis/capabilities.test.ts
+++ b/packages/trueforge/tests/unit/apis/capabilities.test.ts
@@ -6,8 +6,12 @@ import { exportJWK, generateKeyPair, SignJWT } from 'jose';
import type { Configuration } from 'openid-client';
import { createLogger } from 'winston';
import { createCapabilitiesRouter } from '../../../src/apis/capabilities';
-import { authMiddleware } from '../../../src/auth/middleware';
+import type { Authenticator } from '../../../src/auth/authenticator';
+import { resolveRequestContext } from '../../../src/auth/identity';
+import { createAuthMiddleware } from '../../../src/auth/middleware';
import { disableOidcAuth, enableOidcAuth, initOidc } from '../../../src/auth/oidc';
+import { OidcAuthenticator } from '../../../src/auth/oidcAuthenticator';
+import { StandaloneAuthenticator } from '../../../src/auth/standaloneAuthenticator';
import type { OIDCConfig } from '../../../src/config';
import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';
import { createSqliteDb } from '../../../src/db/sqlite/client';
@@ -33,6 +37,7 @@ const OIDC_CONFIG: OIDCConfig = {
OIDC_CLIENT_ID: AUDIENCE,
OIDC_CLIENT_SECRET: 'harness-secret',
OIDC_USER_REFERENCE_CLAIM: 'sub',
+ OIDC_USER_DISPLAY_NAME_CLAIM: 'name',
OIDC_USER_ROLE_CLAIM: 'groups',
OIDC_ADMIN_ROLE_VALUE: 'admin',
OIDC_SCOPES: ['openid', 'profile', 'email', 'groups'],
@@ -46,9 +51,9 @@ function json(body: unknown, status = 200): Response {
});
}
-function withAuth(router: OpenAPIHono): OpenAPIHono {
+function withAuth(router: OpenAPIHono, authenticator: Authenticator): OpenAPIHono {
const shell = new OpenAPIHono();
- shell.use('*', authMiddleware);
+ shell.use('*', createAuthMiddleware(authenticator));
shell.route('/', router);
return shell;
}
@@ -64,14 +69,16 @@ describe('capabilities routers', () => {
setCachedLocalSandboxSupport(undefined);
});
- function makeRouter(): OpenAPIHono {
+ function makeRouter(authenticator: Authenticator = new StandaloneAuthenticator()): OpenAPIHono {
const db = createSqliteDb(':memory:');
return withAuth(
createCapabilitiesRouter({
sandboxProviderStore: new SqliteSandboxProviderStore(db),
withTransaction: callback => db.transaction().execute(callback),
logger: silentLogger,
+ resolveRequestContext,
}),
+ authenticator,
);
}
@@ -242,7 +249,9 @@ describe('capabilities routers', () => {
sandboxProviderStore: new SqliteSandboxProviderStore(db),
withTransaction: callback => db.transaction().execute(callback),
logger: silentLogger,
+ resolveRequestContext,
}),
+ new OidcAuthenticator(),
);
const adminRes = await router.request('/', {
diff --git a/packages/trueforge/tests/unit/apis/deletedSessionCrud.test.ts b/packages/trueforge/tests/unit/apis/deletedSessionCrud.test.ts
index 6212a27ae..66ea90872 100644
--- a/packages/trueforge/tests/unit/apis/deletedSessionCrud.test.ts
+++ b/packages/trueforge/tests/unit/apis/deletedSessionCrud.test.ts
@@ -3,9 +3,9 @@ import { AgentSpecSchema, Sessions } from '@truefoundry/trueforge-core/agent-ses
import { RequestReplyRouter } from '@truefoundry/trueforge-core/request-reply';
import { createClient } from 'redis';
import { createLogger } from 'winston';
-import { createSessionsRouter, TENANT_ID } from '../../../src/apis/sessions';
+import { createSessionsRouter } from '../../../src/apis/sessions';
import { createTurnsRouter } from '../../../src/apis/turns';
-import { LOCAL_USER_CONTEXT } from '../../../src/auth/identity';
+import { STANDALONE_REQUEST_CONTEXT } from '../../../src/auth/identity';
import { McpServerWithAuthStore } from '../../../src/db/McpServerWithAuthStore';
import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';
import { SqliteAgentStore } from '../../../src/db/sqlite/agent-store/SqliteAgentStore';
@@ -52,7 +52,7 @@ describe('public CRUD after session deletion', () => {
sandboxProviderStore,
redis: createClient(),
requestReplyRouter: new RequestReplyRouter(),
- resolveUserContext: () => LOCAL_USER_CONTEXT,
+ resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT,
logger: createLogger({ silent: true }),
}),
);
@@ -70,14 +70,14 @@ describe('public CRUD after session deletion', () => {
eventSubscriptions: new EventSubscriptionRegistry(undefined),
sandboxProviderStore,
logger: createLogger({ silent: true }),
- resolveUserContext: () => LOCAL_USER_CONTEXT,
+ resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT,
}),
);
await sessionStore.createSession({
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
session_id: 's1',
- created_by: LOCAL_USER_CONTEXT.userRef,
+ created_by: STANDALONE_REQUEST_CONTEXT.subject.id,
agent: {
type: 'inline',
spec: AgentSpecSchema.parse({
diff --git a/packages/trueforge/tests/unit/apis/mcpOAuth.test.ts b/packages/trueforge/tests/unit/apis/mcpOAuth.test.ts
index a38a29430..58b09090a 100644
--- a/packages/trueforge/tests/unit/apis/mcpOAuth.test.ts
+++ b/packages/trueforge/tests/unit/apis/mcpOAuth.test.ts
@@ -5,7 +5,7 @@
import winston from 'winston';
import { createMcpOAuthRouter } from '../../../src/apis/mcpOAuth';
import { createMcpServersRouter, createSettingsMcpServersRouter } from '../../../src/apis/mcpServers';
-import { LOCAL_USER_CONTEXT } from '../../../src/auth/identity';
+import { STANDALONE_REQUEST_CONTEXT } from '../../../src/auth/identity';
import configuration from '../../../src/config';
import { McpServerWithAuthStore } from '../../../src/db/McpServerWithAuthStore';
import type { IMcpServerWithAuthStore } from '../../../src/db/mcpServerStore';
@@ -99,14 +99,14 @@ describe('MCP OAuth authorize + callback', () => {
tokenStore,
withTransaction,
logger,
- resolveUserContext: () => LOCAL_USER_CONTEXT,
+ resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT,
});
mcpServersRouter = createMcpServersRouter({
resolveMcpServerStore: () => mcpServerStore,
tokenStore,
withTransaction,
logger,
- resolveUserContext: () => LOCAL_USER_CONTEXT,
+ resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT,
});
oauthRouter = createMcpOAuthRouter({
tokenStore,
@@ -186,7 +186,7 @@ describe('MCP OAuth authorize + callback', () => {
const record = await mcpServerStore.getServer({ tenant_id: 'default', name: 'oauth-mcp' });
expect(record).toBeDefined();
- const token = await tokenStore.getToken({ id: record?.id ?? '', userRef: LOCAL_USER_CONTEXT.userRef });
+ const token = await tokenStore.getToken({ id: record?.id ?? '', userRef: STANDALONE_REQUEST_CONTEXT.subject.id });
expect(token?.accessToken).toBe('access-1');
expect(token?.refreshToken).toBe('refresh-1');
@@ -233,7 +233,12 @@ describe('MCP OAuth authorize + callback', () => {
tokenStore,
withTransaction,
logger,
- resolveUserContext: () => ({ userRef: 'other-user', role: 'user' }),
+ resolveRequestContext: () => ({
+ tenant_id: 'default',
+ subject: { id: 'other-user', type: 'user', display_name: 'other-user' },
+ roles: [],
+ user_credential: null,
+ }),
});
const put = await settingsRouter.request('/', {
diff --git a/packages/trueforge/tests/unit/apis/mcpServers.test.ts b/packages/trueforge/tests/unit/apis/mcpServers.test.ts
index 242b7fdfe..85589316b 100644
--- a/packages/trueforge/tests/unit/apis/mcpServers.test.ts
+++ b/packages/trueforge/tests/unit/apis/mcpServers.test.ts
@@ -1,8 +1,7 @@
import winston from 'winston';
import { createCatalogRouter } from '../../../src/apis/catalog';
import { createMcpServersRouter, createSettingsMcpServersRouter } from '../../../src/apis/mcpServers';
-import { TENANT_ID } from '../../../src/apis/sessions';
-import { LOCAL_USER_CONTEXT } from '../../../src/auth/identity';
+import { STANDALONE_REQUEST_CONTEXT } from '../../../src/auth/identity';
import { McpCatalog } from '../../../src/catalog/McpCatalog';
import { ModelCatalog } from '../../../src/catalog/ModelCatalog';
import { SandboxCatalog } from '../../../src/catalog/SandboxCatalog';
@@ -113,7 +112,7 @@ describe('mcp-servers routers', () => {
tokenStore,
withTransaction,
logger,
- resolveUserContext: () => LOCAL_USER_CONTEXT,
+ resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT,
});
catalogRouter = createCatalogRouter({
modelCatalog: ModelCatalog.load(),
@@ -126,14 +125,14 @@ describe('mcp-servers routers', () => {
tokenStore,
withTransaction,
logger,
- resolveUserContext: () => LOCAL_USER_CONTEXT,
+ resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT,
});
});
/** Persist a DCR server + stub client without calling the authorization server. */
async function seedDcrServerWithClient(body: typeof putBodyWithDcr = putBodyWithDcr) {
const record = await mcpServerStore.upsertServer({
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
name: body.name,
manifest: body,
});
@@ -225,7 +224,7 @@ describe('mcp-servers routers', () => {
message: "Failed to discover OAuth authorization server for MCP server 'linear'",
},
});
- expect(await mcpServerStore.getServer({ tenant_id: TENANT_ID, name: putBodyWithDcr.name })).toBeUndefined();
+ expect(await mcpServerStore.getServer({ tenant_id: 'default', name: putBodyWithDcr.name })).toBeUndefined();
});
it('POST with DCR fails registration without writing a server row', async () => {
@@ -238,7 +237,7 @@ describe('mcp-servers routers', () => {
};
const response = await settingsRouter.request('/', postInit(wrapManifest(createDcr)));
expect(response.status).toBe(422);
- expect(await mcpServerStore.getServer({ tenant_id: TENANT_ID, name: createDcr.name })).toBeUndefined();
+ expect(await mcpServerStore.getServer({ tenant_id: 'default', name: createDcr.name })).toBeUndefined();
});
it('DCR server reads authenticated when a token row exists, auth_required once deleted', async () => {
@@ -246,7 +245,7 @@ describe('mcp-servers routers', () => {
await tokenStore.saveToken({
id: record.id,
- userRef: LOCAL_USER_CONTEXT.userRef,
+ userRef: STANDALONE_REQUEST_CONTEXT.subject.id,
token: {
accessToken: 'access-1',
refreshToken: 'refresh-1',
@@ -264,7 +263,7 @@ describe('mcp-servers routers', () => {
// List auth_status is presence-based; expiry is handled at resolve/refresh time.
await tokenStore.saveToken({
id: record.id,
- userRef: LOCAL_USER_CONTEXT.userRef,
+ userRef: STANDALONE_REQUEST_CONTEXT.subject.id,
token: {
accessToken: 'access-1',
refreshToken: 'refresh-1',
@@ -279,7 +278,7 @@ describe('mcp-servers routers', () => {
status: 'authenticated',
});
- await tokenStore.deleteToken({ id: record.id, userRef: LOCAL_USER_CONTEXT.userRef });
+ await tokenStore.deleteToken({ id: record.id, userRef: STANDALONE_REQUEST_CONTEXT.subject.id });
const cleared = await settingsRouter.request('/');
const clearedBody = (await cleared.json()) as { data: { name: string; auth_status: { status: string } }[] };
@@ -294,7 +293,7 @@ describe('mcp-servers routers', () => {
await tokenStore.saveToken({
id: record.id,
- userRef: LOCAL_USER_CONTEXT.userRef,
+ userRef: STANDALONE_REQUEST_CONTEXT.subject.id,
token: {
accessToken: 'access-1',
refreshToken: 'refresh-1',
@@ -310,14 +309,14 @@ describe('mcp-servers routers', () => {
data: configured(putBodyWithDcr, 'authenticated'),
});
- await tokenStore.deleteToken({ id: record.id, userRef: LOCAL_USER_CONTEXT.userRef });
+ await tokenStore.deleteToken({ id: record.id, userRef: STANDALONE_REQUEST_CONTEXT.subject.id });
});
it('PUT URL change re-registers DCR and clears tokens and pending authorizations', async () => {
const record = await seedDcrServerWithClient();
await tokenStore.saveToken({
id: record.id,
- userRef: LOCAL_USER_CONTEXT.userRef,
+ userRef: STANDALONE_REQUEST_CONTEXT.subject.id,
token: {
accessToken: 'stale-for-old-url',
refreshToken: 'stale-refresh',
@@ -338,7 +337,7 @@ describe('mcp-servers routers', () => {
await tokenStore.savePendingAuthorization({
state: 'stale-pending-state',
id: record.id,
- userRef: LOCAL_USER_CONTEXT.userRef,
+ userRef: STANDALONE_REQUEST_CONTEXT.subject.id,
mcpServerUrl: putBodyWithDcr.url,
codeVerifier: 'stale-verifier',
returnTo: null,
@@ -401,7 +400,9 @@ describe('mcp-servers routers', () => {
expect(await response.json()).toEqual({
data: configured({ ...putBodyWithDcr, url: newUrl }, 'auth_required'),
});
- expect(await tokenStore.getToken({ id: record.id, userRef: LOCAL_USER_CONTEXT.userRef })).toBeUndefined();
+ expect(
+ await tokenStore.getToken({ id: record.id, userRef: STANDALONE_REQUEST_CONTEXT.subject.id }),
+ ).toBeUndefined();
expect(await tokenStore.getToken({ id: record.id, userRef: 'other-user' })).toBeUndefined();
expect(await tokenStore.consumePendingAuthorization({ state: 'stale-pending-state' })).toBeUndefined();
expect(await mcpServerStore.getClient({ id: record.id })).toMatchObject({
@@ -411,7 +412,7 @@ describe('mcp-servers routers', () => {
globalThis.fetch = realFetch;
// Restore baseline for later suite cases that still expect original linear URL / no token.
await mcpServerStore.upsertServer({
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
name: putBodyWithDcr.name,
manifest: putBodyWithDcr,
});
@@ -439,7 +440,7 @@ describe('mcp-servers routers', () => {
data: configured(putBodyWithHeaderAuthWire, 'authenticated'),
});
- const stored = await mcpServerStore.getServer({ tenant_id: TENANT_ID, name: putBodyWithHeaderAuth.name });
+ const stored = await mcpServerStore.getServer({ tenant_id: 'default', name: putBodyWithHeaderAuth.name });
expect(stored?.manifest.auth).toEqual(putBodyWithHeaderAuth.auth);
});
@@ -483,7 +484,7 @@ describe('mcp-servers routers', () => {
),
});
- const stored = await mcpServerStore.getServer({ tenant_id: TENANT_ID, name: putBodyWithHeaderAuth.name });
+ const stored = await mcpServerStore.getServer({ tenant_id: 'default', name: putBodyWithHeaderAuth.name });
expect(stored?.manifest).toEqual({
...putBodyWithHeaderAuth,
url: keep.url,
@@ -518,7 +519,7 @@ describe('mcp-servers routers', () => {
),
});
- const stored = await mcpServerStore.getServer({ tenant_id: TENANT_ID, name: putBodyWithHeaderAuth.name });
+ const stored = await mcpServerStore.getServer({ tenant_id: 'default', name: putBodyWithHeaderAuth.name });
expect(stored?.manifest).toEqual({
...putBodyWithHeaderAuth,
url: keep.url,
@@ -553,7 +554,7 @@ describe('mcp-servers routers', () => {
),
});
- const stored = await mcpServerStore.getServer({ tenant_id: TENANT_ID, name: putBodyWithHeaderAuth.name });
+ const stored = await mcpServerStore.getServer({ tenant_id: 'default', name: putBodyWithHeaderAuth.name });
expect(stored?.manifest.auth).toEqual(rotated.auth);
});
@@ -590,11 +591,11 @@ describe('mcp-servers routers', () => {
});
it('GET / chat list auth_status is scoped to the calling user', async () => {
- const record = await mcpServerStore.getServer({ tenant_id: TENANT_ID, name: putBodyWithDcr.name });
+ const record = await mcpServerStore.getServer({ tenant_id: 'default', name: putBodyWithDcr.name });
if (record === undefined) throw new Error('expected DCR server to exist');
await tokenStore.saveToken({
id: record.id,
- userRef: LOCAL_USER_CONTEXT.userRef,
+ userRef: STANDALONE_REQUEST_CONTEXT.subject.id,
token: {
accessToken: 'access-1',
refreshToken: 'refresh-1',
@@ -616,7 +617,12 @@ describe('mcp-servers routers', () => {
tokenStore,
withTransaction,
logger,
- resolveUserContext: () => ({ userRef: 'other-user', role: 'user' }),
+ resolveRequestContext: () => ({
+ tenant_id: 'default',
+ subject: { id: 'other-user', type: 'user', display_name: 'other-user' },
+ roles: [],
+ user_credential: null,
+ }),
});
const forOther = await otherRouter.request('/');
const otherBody = (await forOther.json()) as {
@@ -626,7 +632,7 @@ describe('mcp-servers routers', () => {
status: 'auth_required',
});
- await tokenStore.deleteToken({ id: record.id, userRef: LOCAL_USER_CONTEXT.userRef });
+ await tokenStore.deleteToken({ id: record.id, userRef: STANDALONE_REQUEST_CONTEXT.subject.id });
});
it('PUT rejects invalid bodies at the Zod layer', async () => {
@@ -731,7 +737,7 @@ describe('mcp-servers routers', () => {
);
// Registration fails before any DB write — no server exists to authorize.
expect(put.status).toBe(422);
- expect(await mcpServerStore.getServer({ tenant_id: TENANT_ID, name: 'failing-oauth-mcp' })).toBeUndefined();
+ expect(await mcpServerStore.getServer({ tenant_id: 'default', name: 'failing-oauth-mcp' })).toBeUndefined();
const authorize = await mcpServersRouter.request('/failing-oauth-mcp/authorize');
expect(authorize.status).toBe(404);
@@ -831,7 +837,7 @@ describe('mcp-servers routers', () => {
});
await tokenStore.saveToken({
id: record.id,
- userRef: LOCAL_USER_CONTEXT.userRef,
+ userRef: STANDALONE_REQUEST_CONTEXT.subject.id,
token: {
accessToken: 'access-1',
refreshToken: 'refresh-1',
@@ -845,7 +851,9 @@ describe('mcp-servers routers', () => {
expect(await response.json()).toEqual({
data: configured(putBodyWithDcr, 'auth_required'),
});
- expect(await tokenStore.getToken({ id: record.id, userRef: LOCAL_USER_CONTEXT.userRef })).toBeUndefined();
+ expect(
+ await tokenStore.getToken({ id: record.id, userRef: STANDALONE_REQUEST_CONTEXT.subject.id }),
+ ).toBeUndefined();
expect(await mcpServerStore.getClient({ id: record.id })).toEqual({
server: {
authorizationEndpoint: 'https://auth.example.com/authorize',
diff --git a/packages/trueforge/tests/unit/apis/modelProviders.test.ts b/packages/trueforge/tests/unit/apis/modelProviders.test.ts
index 9ea68b4b2..053bde6f0 100644
--- a/packages/trueforge/tests/unit/apis/modelProviders.test.ts
+++ b/packages/trueforge/tests/unit/apis/modelProviders.test.ts
@@ -1,9 +1,8 @@
import winston from 'winston';
import { createCatalogRouter } from '../../../src/apis/catalog';
import { createModelsRouter } from '../../../src/apis/models';
-import { TENANT_ID } from '../../../src/apis/sessions';
import { createSettingsRouter } from '../../../src/apis/settings';
-import { LOCAL_USER_CONTEXT } from '../../../src/auth/identity';
+import { STANDALONE_REQUEST_CONTEXT } from '../../../src/auth/identity';
import { McpCatalog } from '../../../src/catalog/McpCatalog';
import { ModelCatalog } from '../../../src/catalog/ModelCatalog';
import { SandboxCatalog } from '../../../src/catalog/SandboxCatalog';
@@ -109,7 +108,7 @@ async function createRouters(): Promise<{
sandboxProviderStore: new SqliteSandboxProviderStore(db),
withTransaction: callback => db.transaction().execute(callback),
logger: winston.createLogger({ silent: true }),
- resolveUserContext: () => LOCAL_USER_CONTEXT,
+ resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT,
}),
catalogRouter: createCatalogRouter({
modelCatalog: ModelCatalog.load(),
@@ -120,6 +119,7 @@ async function createRouters(): Promise<{
modelsRouter: createModelsRouter({
resolveModelProviderStore: () => modelProviderStore,
withTransaction: callback => db.transaction().execute(callback),
+ resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT,
}),
modelProviderStore,
};
@@ -389,7 +389,7 @@ describe('model-provider secret redaction and strict PUT', () => {
expect(updateBody.data.manifest.auth.api_key).toBe(toRedactedSecretValue(anthropicBody.auth.api_key));
expect(updateBody.data.manifest.models).toHaveLength(2);
- const stored = await modelProviderStore.getProvider({ tenant_id: TENANT_ID, name: 'anthropic' });
+ const stored = await modelProviderStore.getProvider({ tenant_id: 'default', name: 'anthropic' });
if (!stored || !('auth' in stored.manifest)) {
throw new Error('expected stored anthropic provider with auth');
}
@@ -408,7 +408,7 @@ describe('model-provider secret redaction and strict PUT', () => {
data: configured('anthropic', withRedactedApiKey({ ...anthropicProvider, auth: { api_key: rotatedKey } })),
});
- const stored = await modelProviderStore.getProvider({ tenant_id: TENANT_ID, name: 'anthropic' });
+ const stored = await modelProviderStore.getProvider({ tenant_id: 'default', name: 'anthropic' });
if (!stored || !('auth' in stored.manifest)) {
throw new Error('expected stored anthropic provider with auth');
}
diff --git a/packages/trueforge/tests/unit/apis/sandboxFileDownload.test.ts b/packages/trueforge/tests/unit/apis/sandboxFileDownload.test.ts
index 1ace8b8ef..635742a92 100644
--- a/packages/trueforge/tests/unit/apis/sandboxFileDownload.test.ts
+++ b/packages/trueforge/tests/unit/apis/sandboxFileDownload.test.ts
@@ -2,9 +2,8 @@ import { OpenAPIHono } from '@hono/zod-openapi';
import type { AgentSpec } from '@truefoundry/trueforge-core/agent-session';
import { AgentSpecSchema, Sessions } from '@truefoundry/trueforge-core/agent-session';
import { createLogger } from 'winston';
-import { TENANT_ID } from '../../../src/apis/sessions';
import { createTurnsRouter, toContentDisposition } from '../../../src/apis/turns';
-import { LOCAL_USER_CONTEXT } from '../../../src/auth/identity';
+import { STANDALONE_REQUEST_CONTEXT } from '../../../src/auth/identity';
import { McpServerWithAuthStore } from '../../../src/db/McpServerWithAuthStore';
import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';
import { SqliteAgentStore } from '../../../src/db/sqlite/agent-store/SqliteAgentStore';
@@ -53,7 +52,7 @@ async function buildApp() {
eventSubscriptions: new EventSubscriptionRegistry(undefined),
sandboxProviderStore: new SqliteSandboxProviderStore(db),
logger: createLogger({ silent: true }),
- resolveUserContext: () => LOCAL_USER_CONTEXT,
+ resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT,
}),
);
@@ -116,9 +115,9 @@ describe('GET /{session_id}/turns/{turn_id}/download-sandbox-file', () => {
it('returns 404 for a turn that does not exist in the session', async () => {
const { app, sessions } = await buildApp();
const session = await sessions.create({
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
session_id: 'no-turn',
- created_by: LOCAL_USER_CONTEXT.userRef,
+ created_by: STANDALONE_REQUEST_CONTEXT.subject.id,
agent: { type: 'inline', spec: agentSpec() },
external_id: null,
});
diff --git a/packages/trueforge/tests/unit/apis/sandboxProviders.test.ts b/packages/trueforge/tests/unit/apis/sandboxProviders.test.ts
index 8f86cd883..6d311f591 100644
--- a/packages/trueforge/tests/unit/apis/sandboxProviders.test.ts
+++ b/packages/trueforge/tests/unit/apis/sandboxProviders.test.ts
@@ -12,7 +12,7 @@ import type { SandboxBuild } from '@truefoundry/trueforge-core/core';
import { createLogger } from 'winston';
import { createCatalogRouter } from '../../../src/apis/catalog';
import { createSandboxProvidersRouter } from '../../../src/apis/sandboxProviders';
-import { TENANT_ID } from '../../../src/apis/sessions';
+import { STANDALONE_REQUEST_CONTEXT } from '../../../src/auth/identity';
import { McpCatalog } from '../../../src/catalog/McpCatalog';
import { ModelCatalog } from '../../../src/catalog/ModelCatalog';
import { SandboxCatalog } from '../../../src/catalog/SandboxCatalog';
@@ -89,6 +89,7 @@ async function createRouters(): Promise<{
sandboxProviderStore,
withTransaction: callback => db.transaction().execute(callback),
logger: silentLogger,
+ resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT,
}),
sandboxProviderStore,
};
@@ -115,6 +116,7 @@ describe('sandboxProviders router', () => {
sandboxProviderStore,
withTransaction: callback => db.transaction().execute(callback),
logger: silentLogger,
+ resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT,
});
catalogRouter = createCatalogRouter({
modelCatalog: ModelCatalog.load(),
@@ -145,7 +147,7 @@ describe('sandboxProviders router', () => {
expect(get.status).toBe(200);
expect(await get.json()).toEqual({ data: putBodyWire });
- const stored = await sandboxProviderStore.getSandboxProvider(TENANT_ID);
+ const stored = await sandboxProviderStore.getSandboxProvider('default');
expect(stored?.manifest).toEqual(putBody);
});
@@ -229,7 +231,7 @@ describe('sandbox-provider secret redaction and strict PUT', () => {
expect(update.status).toBe(200);
expect(await update.json()).toEqual({ data: wireResponse(redactedKeep) });
- const stored = await sandboxProviderStore.getSandboxProvider(TENANT_ID);
+ const stored = await sandboxProviderStore.getSandboxProvider('default');
expect(stored?.manifest).toEqual({ ...putBody, exec_timeout_ms: 120000 });
});
@@ -247,7 +249,7 @@ describe('sandbox-provider secret redaction and strict PUT', () => {
data: wireResponse({ ...keep, auth: { api_key: toRedactedSecretValue(putBody.auth.api_key) } }),
});
- const stored = await sandboxProviderStore.getSandboxProvider(TENANT_ID);
+ const stored = await sandboxProviderStore.getSandboxProvider('default');
expect(stored?.manifest).toEqual(putBody);
});
@@ -263,7 +265,7 @@ describe('sandbox-provider secret redaction and strict PUT', () => {
data: wireResponse({ ...rotated, auth: { api_key: toRedactedSecretValue(rotatedKey) } }),
});
- const stored = await sandboxProviderStore.getSandboxProvider(TENANT_ID);
+ const stored = await sandboxProviderStore.getSandboxProvider('default');
expect(stored?.manifest.auth.api_key).toBe(rotatedKey);
});
diff --git a/packages/trueforge/tests/unit/apis/schedules.test.ts b/packages/trueforge/tests/unit/apis/schedules.test.ts
index b98b088ed..3d44e81ff 100644
--- a/packages/trueforge/tests/unit/apis/schedules.test.ts
+++ b/packages/trueforge/tests/unit/apis/schedules.test.ts
@@ -1,8 +1,7 @@
import { OpenAPIHono } from '@hono/zod-openapi';
import { AgentSpecSchema } from '@truefoundry/trueforge-core/agent-session';
import { createSchedulesRouter } from '../../../src/apis/schedules';
-import { TENANT_ID } from '../../../src/apis/sessions';
-import type { UserContext } from '../../../src/auth/identity';
+import type { RequestContext } from '../../../src/auth/identity';
import { ScheduleAgentNotFoundError, startScheduleRun } from '../../../src/controller/scheduleDispatch';
import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';
import { SqliteAgentStore } from '../../../src/db/sqlite/agent-store/SqliteAgentStore';
@@ -23,9 +22,24 @@ jest.mock('../../../src/controller/scheduleDispatch', () => ({
const mockedStartScheduleRun = jest.mocked(startScheduleRun);
-const ALICE: UserContext = { userRef: 'alice', role: 'user' };
-const BOB: UserContext = { userRef: 'bob', role: 'user' };
-const ADMIN: UserContext = { userRef: 'root', role: 'admin' };
+const ALICE: RequestContext = {
+ tenant_id: 'default',
+ subject: { id: 'alice', type: 'user', display_name: 'alice' },
+ roles: [],
+ user_credential: null,
+};
+const BOB: RequestContext = {
+ tenant_id: 'default',
+ subject: { id: 'bob', type: 'user', display_name: 'bob' },
+ roles: [],
+ user_credential: null,
+};
+const ADMIN: RequestContext = {
+ tenant_id: 'default',
+ subject: { id: 'root', type: 'user', display_name: 'root' },
+ roles: ['admin'],
+ user_credential: null,
+};
const scheduleBody = {
agent_name: 'reporter',
@@ -39,13 +53,13 @@ async function setup() {
const agentStore = new SqliteAgentStore(db);
const scheduleStore = new SqliteScheduleStore(db);
await agentStore.createAgent({
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
name: 'reporter',
manifest: AgentSpecSchema.parse({ model: { name: 'test-provider/test-model' }, instructions: 'test' }),
external_id: null,
});
- let current: UserContext = ALICE;
+ let current: RequestContext = ALICE;
const app = new OpenAPIHono();
app.route(
'/',
@@ -67,11 +81,11 @@ async function setup() {
logger: { error: jest.fn(), warn: jest.fn(), info: jest.fn(), debug: jest.fn() } as never,
},
withTransaction: callback => db.transaction().execute(callback),
- resolveUserContext: () => current,
+ resolveRequestContext: () => current,
}),
);
- const asUser = (user: UserContext) => {
+ const asUser = (user: RequestContext) => {
current = user;
};
const postJson = (path: string, method: string, body: unknown) =>
@@ -153,7 +167,7 @@ describe('schedule RBAC — creator-scoped, admin sees all', () => {
const { app, asUser, agentStore, postJson } = await setup();
// A second agent so both schedules can share the same name without colliding.
await agentStore.createAgent({
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
name: 'reporter-two',
manifest: AgentSpecSchema.parse({ model: { name: 'test-provider/test-model' }, instructions: 'test' }),
external_id: null,
@@ -189,7 +203,7 @@ describe('schedule list agent_names filter', () => {
it('filters by a single agent_names value and by comma-separated agent_names', async () => {
const { app, asUser, agentStore, postJson } = await setup();
await agentStore.createAgent({
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
name: 'reporter-two',
manifest: AgentSpecSchema.parse({ model: { name: 'test-provider/test-model' }, instructions: 'test' }),
external_id: null,
@@ -249,7 +263,7 @@ describe('create schedule run', () => {
const created = await postJson('/', 'POST', scheduleBody);
const { id: scheduleId } = ((await created.json()) as { data: { id: string } }).data;
- const pendingBefore = await scheduleStore.getScheduledRunFor({ tenant_id: TENANT_ID, schedule_id: scheduleId });
+ const pendingBefore = await scheduleStore.getScheduledRunFor({ tenant_id: 'default', schedule_id: scheduleId });
expect(pendingBefore?.status).toBe('scheduled');
const res = await postJson('/runs', 'POST', { schedule_id: scheduleId });
@@ -274,11 +288,11 @@ describe('create schedule run', () => {
}),
);
- const pendingAfter = await scheduleStore.getScheduledRunFor({ tenant_id: TENANT_ID, schedule_id: scheduleId });
+ const pendingAfter = await scheduleStore.getScheduledRunFor({ tenant_id: 'default', schedule_id: scheduleId });
expect(pendingAfter?.id).toBe(pendingBefore?.id);
expect(pendingAfter?.status).toBe('scheduled');
- const runs = await scheduleStore.listRuns({ tenant_id: TENANT_ID, schedule_id: scheduleId });
+ const runs = await scheduleStore.listRuns({ tenant_id: 'default', schedule_id: scheduleId });
expect(runs.map(r => r.status).sort()).toEqual(['scheduled', 'triggered']);
});
@@ -309,7 +323,7 @@ describe('create schedule run', () => {
expect(res.status).toBe(404);
expect(((await res.json()) as { error: { message: string } }).error.message).toBe('Agent not found: reporter');
- const runs = await scheduleStore.listRuns({ tenant_id: TENANT_ID, schedule_id: scheduleId });
+ const runs = await scheduleStore.listRuns({ tenant_id: 'default', schedule_id: scheduleId });
const runNow = runs.find(r => r.name.startsWith('manual-'));
expect(runNow?.status).toBe('failed');
});
diff --git a/packages/trueforge/tests/unit/apis/sessionHttp.test.ts b/packages/trueforge/tests/unit/apis/sessionHttp.test.ts
index 6bebb6c2b..704b9027e 100644
--- a/packages/trueforge/tests/unit/apis/sessionHttp.test.ts
+++ b/packages/trueforge/tests/unit/apis/sessionHttp.test.ts
@@ -7,10 +7,9 @@ import { createInternalMetricsRouter } from '../../../src/apis/sessionMetrics';
import {
createInternalSessionsRouter,
createSessionsRouter,
- TENANT_ID,
type SessionsRouterDeps,
} from '../../../src/apis/sessions';
-import { LOCAL_USER_CONTEXT } from '../../../src/auth/identity';
+import { STANDALONE_REQUEST_CONTEXT } from '../../../src/auth/identity';
import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';
import { SqliteAgentStore } from '../../../src/db/sqlite/agent-store/SqliteAgentStore';
import { createSqliteDb } from '../../../src/db/sqlite/client';
@@ -58,7 +57,7 @@ describe('sessions HTTP agent binding', () => {
agentStore = new SqliteAgentStore(db);
await modelProviderStore.upsertProvider({
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
name: 'anthropic',
manifest: {
type: 'anthropic',
@@ -86,7 +85,7 @@ describe('sessions HTTP agent binding', () => {
sandboxProviderStore,
redis: createClient(),
requestReplyRouter: new RequestReplyRouter(),
- resolveUserContext: () => LOCAL_USER_CONTEXT,
+ resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT,
logger: createLogger({ silent: true }),
};
app.route('/', createSessionsRouter(deps));
@@ -95,7 +94,7 @@ describe('sessions HTTP agent binding', () => {
'/api/internal/metrics',
createInternalMetricsRouter({
sessionMetricsStore,
- resolveUserContext: deps.resolveUserContext,
+ resolveRequestContext: deps.resolveRequestContext,
}),
);
});
@@ -113,7 +112,7 @@ describe('sessions HTTP agent binding', () => {
};
expect(json.data.agent.type).toBe('inline');
expect(json.data.agent.spec.instructions).toBe('inline');
- expect(json.data.created_by).toBe(LOCAL_USER_CONTEXT.userRef);
+ expect(json.data.created_by).toBe(STANDALONE_REQUEST_CONTEXT.subject.id);
expect(json.data.metrics).toEqual({ total_cost_in_usd: 0, total_duration_ms: 0, total_turns: 0 });
});
@@ -124,7 +123,7 @@ describe('sessions HTTP agent binding', () => {
it('creates a named session and filters list by agent_id', async () => {
const agent = await agentStore.createAgent({
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
name: 'named-agent',
manifest: AgentSpecSchema.parse({
model: { name: 'anthropic/claude-sonnet-4-6' },
@@ -151,22 +150,22 @@ describe('sessions HTTP agent binding', () => {
it('returns caller-scoped metrics for a named agent', async () => {
const agent = await agentStore.createAgent({
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
name: 'metrics-agent',
manifest: inlineSpec,
external_id: null,
});
await sessionStore.createSession({
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
session_id: 'my-metrics-session',
- created_by: LOCAL_USER_CONTEXT.userRef,
+ created_by: STANDALONE_REQUEST_CONTEXT.subject.id,
agent: { type: 'reference', id: agent.id, name: agent.name },
custom: null,
metadata: {},
external_id: null,
});
await sessionStore.createSession({
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
session_id: 'other-user-metrics-session',
created_by: 'someone-else',
agent: { type: 'reference', id: agent.id, name: agent.name },
@@ -228,7 +227,7 @@ describe('sessions HTTP agent binding', () => {
it("rejects access to another user's session on get/update/delete/cancel/events and scopes list", async () => {
await sessionStore.createSession({
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
session_id: 'other-user-session',
created_by: 'someone-else',
agent: { type: 'inline', spec: inlineSpec },
@@ -240,13 +239,13 @@ describe('sessions HTTP agent binding', () => {
const created = await app.request('/', jsonInit('POST', { agent: { spec: inlineSpec } }));
expect(created.status).toBe(201);
const json = (await created.json()) as { data: { id: string; created_by: string } };
- expect(json.data.created_by).toBe(LOCAL_USER_CONTEXT.userRef);
+ expect(json.data.created_by).toBe(STANDALONE_REQUEST_CONTEXT.subject.id);
const listed = await app.request('/');
expect(listed.status).toBe(200);
const listedJson = (await listed.json()) as { data: Array<{ id: string; created_by: string }> };
expect(listedJson.data.map(row => row.id)).toEqual([json.data.id]);
- expect(listedJson.data.every(row => row.created_by === LOCAL_USER_CONTEXT.userRef)).toBe(true);
+ expect(listedJson.data.every(row => row.created_by === STANDALONE_REQUEST_CONTEXT.subject.id)).toBe(true);
const forbiddenBody = { error: { message: 'Only the session creator can access this session' } };
@@ -276,7 +275,7 @@ describe('sessions HTTP agent binding', () => {
it('rejects PATCH agent on a named session', async () => {
const agent = await agentStore.createAgent({
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
name: 'named-agent',
manifest: AgentSpecSchema.parse({
model: { name: 'anthropic/claude-sonnet-4-6' },
@@ -396,7 +395,7 @@ describe('sessions HTTP agent binding', () => {
expect(againJson.data.agent.spec.instructions).toBe('inline');
await sessionStore.createSession({
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
session_id: 'someone-elses-session',
created_by: 'someone-else',
agent: { type: 'inline', spec: inlineSpec },
diff --git a/packages/trueforge/tests/unit/apis/skills.test.ts b/packages/trueforge/tests/unit/apis/skills.test.ts
index 2aaecdf41..829372d33 100644
--- a/packages/trueforge/tests/unit/apis/skills.test.ts
+++ b/packages/trueforge/tests/unit/apis/skills.test.ts
@@ -1,5 +1,6 @@
import { createCatalogRouter } from '../../../src/apis/catalog';
import { createAvailableSkillsRouter, createSkillsRouter } from '../../../src/apis/skills';
+import { STANDALONE_REQUEST_CONTEXT } from '../../../src/auth/identity';
import { McpCatalog } from '../../../src/catalog/McpCatalog';
import { ModelCatalog } from '../../../src/catalog/ModelCatalog';
import { SandboxCatalog } from '../../../src/catalog/SandboxCatalog';
@@ -53,6 +54,7 @@ describe('skills routers', () => {
settingsRouter = createSkillsRouter({
skillStore,
withTransaction: callback => db.transaction().execute(callback),
+ resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT,
});
catalogRouter = createCatalogRouter({
modelCatalog: ModelCatalog.load(),
@@ -63,6 +65,7 @@ describe('skills routers', () => {
availableRouter = createAvailableSkillsRouter({
skillStore,
withTransaction: callback => db.transaction().execute(callback),
+ resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT,
});
});
diff --git a/packages/trueforge/tests/unit/apis/turnHarnessErrorStatus.test.ts b/packages/trueforge/tests/unit/apis/turnHarnessErrorStatus.test.ts
index ee5c8a6c8..5f7c6bd6b 100644
--- a/packages/trueforge/tests/unit/apis/turnHarnessErrorStatus.test.ts
+++ b/packages/trueforge/tests/unit/apis/turnHarnessErrorStatus.test.ts
@@ -3,7 +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 { LOCAL_USER_CONTEXT } from '../../../src/auth/identity';
+import { STANDALONE_REQUEST_CONTEXT } from '../../../src/auth/identity';
import { McpServerWithAuthStore } from '../../../src/db/McpServerWithAuthStore';
import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';
import { SqliteAgentStore } from '../../../src/db/sqlite/agent-store/SqliteAgentStore';
@@ -43,8 +43,10 @@ async function postTurnRejectingWith(error: AgentHarnessError): Promise<Response
const sessions = {
get: () =>
Promise.resolve({
+ session_id: 's1',
+ tenant_id: STANDALONE_REQUEST_CONTEXT.tenant_id,
agent_spec: { model: { name: 'test-provider/test-model' } },
- record: { last_turn_id: null, created_by: LOCAL_USER_CONTEXT.userRef },
+ record: { last_turn_id: null, created_by: STANDALONE_REQUEST_CONTEXT.subject.id },
createTurn: () => Promise.reject(error),
}),
} as unknown as Sessions;
@@ -70,7 +72,7 @@ async function postTurnRejectingWith(error: AgentHarnessError): Promise<Response
eventSubscriptions: new EventSubscriptionRegistry(undefined),
sandboxProviderStore: new SqliteSandboxProviderStore(db),
logger: createLogger({ silent: true }),
- resolveUserContext: () => LOCAL_USER_CONTEXT,
+ resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT,
}),
);
diff --git a/packages/trueforge/tests/unit/apis/turns.test.ts b/packages/trueforge/tests/unit/apis/turns.test.ts
index 8128cf964..fc2bfd620 100644
--- a/packages/trueforge/tests/unit/apis/turns.test.ts
+++ b/packages/trueforge/tests/unit/apis/turns.test.ts
@@ -7,9 +7,8 @@ import {
} from '@truefoundry/trueforge-core/agent-session';
import type { Kysely } from 'kysely';
import { createLogger } from 'winston';
-import { TENANT_ID } from '../../../src/apis/sessions';
import { createTurnsRouter, turnStreamId } from '../../../src/apis/turns';
-import { LOCAL_USER_CONTEXT } from '../../../src/auth/identity';
+import { STANDALONE_REQUEST_CONTEXT } from '../../../src/auth/identity';
import { McpServerWithAuthStore } from '../../../src/db/McpServerWithAuthStore';
import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';
import { SqliteAgentStore } from '../../../src/db/sqlite/agent-store/SqliteAgentStore';
@@ -41,7 +40,7 @@ describe('turns', () => {
const sessions = new Sessions({ sessionStore });
await sessionStore.createSession({
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
session_id: 's1',
created_by: 'someone-else',
agent: {
@@ -72,7 +71,7 @@ describe('turns', () => {
eventSubscriptions: new EventSubscriptionRegistry(undefined),
sandboxProviderStore: new SqliteSandboxProviderStore(db),
logger: createLogger({ silent: true }),
- resolveUserContext: () => LOCAL_USER_CONTEXT,
+ resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT,
}),
);
@@ -146,8 +145,9 @@ describe('turns', () => {
get: () =>
Promise.resolve({
session_id: 's1',
+ tenant_id: STANDALONE_REQUEST_CONTEXT.tenant_id,
spec: AgentSpecSchema.parse({ model: { name: 'test-provider/test-model' } }),
- record: { last_turn_id: null, created_by: LOCAL_USER_CONTEXT.userRef },
+ record: { last_turn_id: null, created_by: STANDALONE_REQUEST_CONTEXT.subject.id },
createTurn: () =>
Promise.resolve({
id: 'turn-non-stream',
@@ -192,7 +192,7 @@ describe('turns', () => {
eventSubscriptions,
sandboxProviderStore: new SqliteSandboxProviderStore(db),
logger,
- resolveUserContext: () => LOCAL_USER_CONTEXT,
+ resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT,
}),
);
@@ -218,7 +218,7 @@ describe('turns', () => {
// Resumable stream must exist before the JSON response returns.
await expect(
- eventSubscriptions.get(turnStreamId(TENANT_ID, 's1', 'turn-non-stream')).assertSubscribable(),
+ eventSubscriptions.get(turnStreamId('default', 's1', 'turn-non-stream')).assertSubscribable(),
).resolves.toBeUndefined();
releaseRest?.();
@@ -260,11 +260,13 @@ describe('turns', () => {
const sessions = {
get: () =>
Promise.resolve({
+ session_id: 's1',
+ tenant_id: STANDALONE_REQUEST_CONTEXT.tenant_id,
spec: agentSpec,
record: {
session_id: 's1',
last_turn_id: null,
- created_by: LOCAL_USER_CONTEXT.userRef,
+ created_by: STANDALONE_REQUEST_CONTEXT.subject.id,
agent: { type: 'inline', spec: agentSpec },
},
createTurn: () =>
@@ -293,7 +295,7 @@ describe('turns', () => {
eventSubscriptions: new EventSubscriptionRegistry(undefined),
sandboxProviderStore: new SqliteSandboxProviderStore(db),
logger,
- resolveUserContext: () => LOCAL_USER_CONTEXT,
+ resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT,
}),
);
diff --git a/packages/trueforge/tests/unit/auth/claims.test.ts b/packages/trueforge/tests/unit/auth/claims.test.ts
index 890d84a71..4a50b63ef 100644
--- a/packages/trueforge/tests/unit/auth/claims.test.ts
+++ b/packages/trueforge/tests/unit/auth/claims.test.ts
@@ -3,7 +3,7 @@ import {
claimValues,
resolveRole,
resolveUserRef,
- toUserContext,
+ toRequestContext,
} from '../../../src/auth/claims';
import { EmailNotAllowedError } from '../../../src/auth/emailAllowlist';
import type { OIDCConfig } from '../../../src/config';
@@ -14,6 +14,7 @@ function config(overrides: Partial<OIDCConfig> = {}): OIDCConfig {
OIDC_CLIENT_ID: 'client-id',
OIDC_CLIENT_SECRET: 'client-secret',
OIDC_USER_REFERENCE_CLAIM: 'sub',
+ OIDC_USER_DISPLAY_NAME_CLAIM: 'name',
OIDC_USER_ROLE_CLAIM: 'groups',
OIDC_ADMIN_ROLE_VALUE: 'harness-admins',
OIDC_SCOPES: ['openid', 'profile', 'email', 'groups'],
@@ -22,6 +23,8 @@ function config(overrides: Partial<OIDCConfig> = {}): OIDCConfig {
};
}
+const TEST_TOKEN = 'test';
+
describe('claimValues', () => {
it('passes through an array of strings', () => {
expect(claimValues(['a', 'b'])).toEqual(['a', 'b']);
@@ -92,43 +95,85 @@ describe('resolveRole', () => {
});
});
-describe('toUserContext', () => {
- it('combines userRef and role from the claims', () => {
- expect(toUserContext({ sub: 'user-123', groups: ['harness-admins'] }, config())).toEqual({
- userRef: 'user-123',
- role: 'admin',
+describe('toRequestContext', () => {
+ it('maps claims onto RequestContext with roles from the role claim', () => {
+ expect(
+ toRequestContext({
+ claims: { sub: 'user-123', groups: ['harness-admins'], name: 'User One' },
+ config: config(),
+ user_credential: TEST_TOKEN,
+ }),
+ ).toEqual({
+ tenant_id: 'default',
+ subject: { id: 'user-123', type: 'user', display_name: 'User One' },
+ roles: ['harness-admins'],
+ user_credential: TEST_TOKEN,
+ });
+ });
+
+ it('falls back display_name to subject id when the display-name claim is absent', () => {
+ expect(
+ toRequestContext({
+ claims: { sub: 'user-123', groups: ['harness-admins'] },
+ config: config(),
+ user_credential: TEST_TOKEN,
+ }),
+ ).toEqual({
+ tenant_id: 'default',
+ subject: { id: 'user-123', type: 'user', display_name: 'user-123' },
+ roles: ['harness-admins'],
+ user_credential: TEST_TOKEN,
});
});
it('propagates resolveUserRef throwing when the reference claim is missing', () => {
- expect(() => toUserContext({ groups: ['harness-admins'] }, config())).toThrow();
+ expect(() =>
+ toRequestContext({
+ claims: { groups: ['harness-admins'] },
+ config: config(),
+ user_credential: TEST_TOKEN,
+ }),
+ ).toThrow();
});
it('allows any email when the allowlist is empty', () => {
expect(
- toUserContext(
- { sub: 'user-123', groups: [], email: '[email protected]' },
- config({ OIDC_ALLOWED_EMAILS: [] }),
- ),
- ).toEqual({ userRef: 'user-123', role: 'user' });
+ toRequestContext({
+ claims: { sub: 'user-123', groups: [], email: '[email protected]' },
+ config: config({ OIDC_ALLOWED_EMAILS: [] }),
+ user_credential: TEST_TOKEN,
+ }),
+ ).toEqual({
+ tenant_id: 'default',
+ subject: { id: 'user-123', type: 'user', display_name: 'user-123' },
+ roles: [],
+ user_credential: TEST_TOKEN,
+ });
});
it('throws EmailNotAllowedError when the email is outside the allowlist', () => {
expect(() =>
- toUserContext(
- { sub: 'user-123', groups: [], email: '[email protected]' },
- config({ OIDC_ALLOWED_EMAILS: ['*@company.com'] }),
- ),
+ toRequestContext({
+ claims: { sub: 'user-123', groups: [], email: '[email protected]' },
+ config: config({ OIDC_ALLOWED_EMAILS: ['*@company.com'] }),
+ user_credential: TEST_TOKEN,
+ }),
).toThrow(EmailNotAllowedError);
});
it('allows a matching domain glob', () => {
expect(
- toUserContext(
- { sub: 'user-123', groups: ['harness-admins'], email: '[email protected]' },
- config({ OIDC_ALLOWED_EMAILS: ['*@company.com'] }),
- ),
- ).toEqual({ userRef: 'user-123', role: 'admin' });
+ toRequestContext({
+ claims: { sub: 'user-123', groups: ['harness-admins'], email: '[email protected]' },
+ config: config({ OIDC_ALLOWED_EMAILS: ['*@company.com'] }),
+ user_credential: TEST_TOKEN,
+ }),
+ ).toEqual({
+ tenant_id: 'default',
+ subject: { id: 'user-123', type: 'user', display_name: 'user-123' },
+ roles: ['harness-admins'],
+ user_credential: TEST_TOKEN,
+ });
});
});
@@ -145,16 +190,20 @@ describe('buildAuthorizationRequestParams', () => {
expect(scopes).toEqual(['openid', 'profile', 'email', 'groups']);
});
- it('requests both the role claim and the (default) reference claim as essential in the id_token', () => {
+ it('requests reference and role claims as essential in the id_token', () => {
const { claims } = buildAuthorizationRequestParams(config({ OIDC_USER_ROLE_CLAIM: 'roles' }));
- expect(claims).toEqual({ id_token: { sub: { essential: true }, roles: { essential: true } } });
+ expect(claims).toEqual({
+ id_token: { sub: { essential: true }, roles: { essential: true } },
+ });
});
it('requests a non-default reference claim as essential too', () => {
const { claims } = buildAuthorizationRequestParams(
config({ OIDC_USER_REFERENCE_CLAIM: 'email', OIDC_USER_ROLE_CLAIM: 'roles' }),
);
- expect(claims).toEqual({ id_token: { email: { essential: true }, roles: { essential: true } } });
+ expect(claims).toEqual({
+ id_token: { email: { essential: true }, roles: { essential: true } },
+ });
});
it('collapses to a single essential entry when the reference and role claim names collide', () => {
@@ -167,7 +216,11 @@ describe('buildAuthorizationRequestParams', () => {
it('requests email as essential when an allowlist is configured', () => {
const { claims } = buildAuthorizationRequestParams(config({ OIDC_ALLOWED_EMAILS: ['*@company.com'] }));
expect(claims).toEqual({
- id_token: { sub: { essential: true }, groups: { essential: true }, email: { essential: true } },
+ id_token: {
+ sub: { essential: true },
+ groups: { essential: true },
+ email: { essential: true },
+ },
});
});
});
diff --git a/packages/trueforge/tests/unit/auth/emailAllowlist.test.ts b/packages/trueforge/tests/unit/auth/emailAllowlist.test.ts
index d3ffe5704..3344b418e 100644
--- a/packages/trueforge/tests/unit/auth/emailAllowlist.test.ts
+++ b/packages/trueforge/tests/unit/auth/emailAllowlist.test.ts
@@ -7,6 +7,7 @@ function config(overrides: Partial<OIDCConfig> = {}): OIDCConfig {
OIDC_CLIENT_ID: 'client-id',
OIDC_CLIENT_SECRET: 'client-secret',
OIDC_USER_REFERENCE_CLAIM: 'sub',
+ OIDC_USER_DISPLAY_NAME_CLAIM: 'name',
OIDC_USER_ROLE_CLAIM: 'groups',
OIDC_ADMIN_ROLE_VALUE: 'admin',
OIDC_SCOPES: ['openid', 'profile', 'email'],
diff --git a/packages/trueforge/tests/unit/auth/identity.test.ts b/packages/trueforge/tests/unit/auth/identity.test.ts
index 5eada457d..2152cf21d 100644
--- a/packages/trueforge/tests/unit/auth/identity.test.ts
+++ b/packages/trueforge/tests/unit/auth/identity.test.ts
@@ -1,50 +1,59 @@
-import { isAdmin, LOCAL_USER_CONTEXT, type UserContext } from '../../../src/auth/identity';
-import { disableOidcAuth, enableOidcAuth, initOidc } from '../../../src/auth/oidc';
-import type { OIDCConfig } from '../../../src/config';
+import { Hono } from 'hono';
+import { hasAdminRole, resolveRequestContext, STANDALONE_REQUEST_CONTEXT } from '../../../src/auth/identity';
-const OIDC_CONFIG: OIDCConfig = {
- OIDC_ISSUER_URL: 'https://issuer.example.com/',
- OIDC_CLIENT_ID: 'harness-client',
- OIDC_CLIENT_SECRET: 'harness-secret',
- OIDC_USER_REFERENCE_CLAIM: 'sub',
- OIDC_USER_ROLE_CLAIM: 'groups',
- OIDC_ADMIN_ROLE_VALUE: 'admin',
- OIDC_SCOPES: ['openid', 'profile', 'email', 'groups'],
- OIDC_ALLOWED_EMAILS: [],
-};
-
-function user(role: UserContext['role']): UserContext {
- return { userRef: 'alice', role };
-}
-
-describe('isAdmin', () => {
- afterEach(() => {
- disableOidcAuth();
+describe('STANDALONE_REQUEST_CONTEXT', () => {
+ it('has the fixed standalone identity shape', () => {
+ expect(STANDALONE_REQUEST_CONTEXT).toEqual({
+ tenant_id: 'default',
+ subject: {
+ id: 'trueforge-default',
+ type: 'user',
+ display_name: 'trueforge-default',
+ },
+ roles: ['admin'],
+ user_credential: null,
+ });
});
+});
- it('is always true without OIDC (standalone)', () => {
- disableOidcAuth();
- expect(isAdmin(user('user'))).toBe(true);
- expect(isAdmin(LOCAL_USER_CONTEXT)).toBe(true);
+describe('hasAdminRole', () => {
+ // Unit tests run under STANDALONE=true (.env.test) → mode Standalone.
+ it('treats admin as admin and other roles as non-admin in standalone', () => {
+ expect(hasAdminRole({ roles: ['admin'] })).toBe(true);
+ expect(hasAdminRole({ roles: ['everyone'] })).toBe(false);
+ expect(hasAdminRole(STANDALONE_REQUEST_CONTEXT)).toBe(true);
});
+});
+
+describe('resolveRequestContext', () => {
+ it('returns request_context when set by auth middleware', async () => {
+ const app = new Hono();
+ app.get('/', c => {
+ c.set('request_context', STANDALONE_REQUEST_CONTEXT);
+ return c.json(resolveRequestContext(c));
+ });
- it('checks role when auth is enabled', async () => {
- globalThis.fetch = async () =>
- new Response(
- JSON.stringify({
- issuer: 'https://issuer.example.com',
- jwks_uri: 'https://issuer.example.com/jwks',
- }),
- { headers: { 'Content-Type': 'application/json' } },
- );
+ const res = await app.request('/');
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual(STANDALONE_REQUEST_CONTEXT);
+ });
- const client = await initOidc(OIDC_CONFIG);
- if (!client) {
- throw new Error('OIDC client was not initialized');
- }
- enableOidcAuth({ client, oidcConfig: OIDC_CONFIG });
+ it('throws when request_context is missing', async () => {
+ const app = new Hono();
+ app.get('/', c => {
+ try {
+ resolveRequestContext(c);
+ return c.json({ ok: true });
+ } catch (error) {
+ const message = error instanceof Error ? error.message : 'unknown';
+ return c.json({ error: message }, 500);
+ }
+ });
- expect(isAdmin(user('admin'))).toBe(true);
- expect(isAdmin(user('user'))).toBe(false);
+ const res = await app.request('/');
+ expect(res.status).toBe(500);
+ expect(await res.json()).toEqual({
+ error: 'RequestContext missing; auth middleware did not run',
+ });
});
});
diff --git a/packages/trueforge/tests/unit/auth/middleware.test.ts b/packages/trueforge/tests/unit/auth/middleware.test.ts
index 33211bba6..296dedce4 100644
--- a/packages/trueforge/tests/unit/auth/middleware.test.ts
+++ b/packages/trueforge/tests/unit/auth/middleware.test.ts
@@ -2,8 +2,12 @@ import { OpenAPIHono } from '@hono/zod-openapi';
import { HTTPException } from 'hono/http-exception';
import { exportJWK, generateKeyPair, SignJWT } from 'jose';
import type { Configuration } from 'openid-client';
-import { adminAuthMiddleware, authMiddleware } from '../../../src/auth/middleware';
+import type { Authenticator } from '../../../src/auth/authenticator';
+import { STANDALONE_REQUEST_CONTEXT } from '../../../src/auth/identity';
+import { createAdminAuthMiddleware, createAuthMiddleware } from '../../../src/auth/middleware';
import { disableOidcAuth, enableOidcAuth, initOidc } from '../../../src/auth/oidc';
+import { OidcAuthenticator } from '../../../src/auth/oidcAuthenticator';
+import { StandaloneAuthenticator } from '../../../src/auth/standaloneAuthenticator';
import type { OIDCConfig } from '../../../src/config';
const ISSUER = 'https://issuer.example.com';
@@ -14,6 +18,7 @@ const OIDC_CONFIG: OIDCConfig = {
OIDC_CLIENT_ID: AUDIENCE,
OIDC_CLIENT_SECRET: 'harness-secret',
OIDC_USER_REFERENCE_CLAIM: 'sub',
+ OIDC_USER_DISPLAY_NAME_CLAIM: 'name',
OIDC_USER_ROLE_CLAIM: 'groups',
OIDC_ADMIN_ROLE_VALUE: 'admin',
OIDC_SCOPES: ['openid', 'profile', 'email', 'groups'],
@@ -27,7 +32,7 @@ function json(body: unknown, status = 200): Response {
});
}
-function createApp() {
+function createApp(authenticator: Authenticator) {
const app = new OpenAPIHono();
app.onError((error, c) => {
if (error instanceof HTTPException) {
@@ -44,40 +49,38 @@ function createApp() {
app.get('/api/v1/openapi', c => c.json({ public: true }));
const models = new OpenAPIHono();
- models.use('*', authMiddleware);
- models.get('/', c => c.json({ ok: true, user: c.get('user_context') }));
+ models.use('*', createAuthMiddleware(authenticator));
+ models.get('/', c => c.json({ ok: true, user: c.get('request_context') }));
app.route('/api/v1/models', models);
const settings = new OpenAPIHono();
- settings.use('*', adminAuthMiddleware);
- settings.get('/', c => c.json({ ok: true, user: c.get('user_context') }));
+ settings.use('*', createAdminAuthMiddleware(authenticator));
+ settings.get('/', c => c.json({ ok: true, user: c.get('request_context') }));
app.route('/api/v1/settings', settings);
return app;
}
-describe('authMiddleware', () => {
- it('allows settings without admin role when auth is disabled', async () => {
- disableOidcAuth();
- const res = await createApp().request('/api/v1/settings');
+describe('createAuthMiddleware / createAdminAuthMiddleware', () => {
+ it('allows settings for standalone authenticator (always admin)', async () => {
+ const res = await createApp(new StandaloneAuthenticator()).request('/api/v1/settings');
expect(res.status).toBe(200);
expect(await res.json()).toEqual({
ok: true,
- user: { userRef: 'trueforge-default', role: 'admin' },
+ user: STANDALONE_REQUEST_CONTEXT,
});
});
- it('sets default user when auth is disabled', async () => {
- disableOidcAuth();
- const res = await createApp().request('/api/v1/models');
+ it('sets standalone request context when using StandaloneAuthenticator', async () => {
+ const res = await createApp(new StandaloneAuthenticator()).request('/api/v1/models');
expect(res.status).toBe(200);
expect(await res.json()).toEqual({
ok: true,
- user: { userRef: 'trueforge-default', role: 'admin' },
+ user: STANDALONE_REQUEST_CONTEXT,
});
});
- describe('when auth is enabled', () => {
+ describe('with OidcAuthenticator', () => {
const realFetch = globalThis.fetch;
let privateKey: Awaited<ReturnType<typeof generateKeyPair>>['privateKey'];
let oidcClient: Configuration;
@@ -131,12 +134,16 @@ describe('authMiddleware', () => {
sub?: string;
groups?: string[];
email?: string;
+ name?: string;
exp?: string | number;
}): Promise<string> {
const claims: Record<string, unknown> = { groups: params?.groups ?? [] };
if (params?.email !== undefined) {
claims['email'] = params.email;
}
+ if (params?.name !== undefined) {
+ claims['name'] = params.name;
+ }
return new SignJWT(claims)
.setProtectedHeader({ alg: 'RS256', kid: 'test-kid' })
.setIssuer(params?.issuer ?? ISSUER)
@@ -147,14 +154,32 @@ describe('authMiddleware', () => {
.sign(privateKey);
}
+ function oidcRequestContext(params: {
+ subjectId: string;
+ roles: string[];
+ userCredential: string;
+ displayName?: string;
+ }) {
+ return {
+ tenant_id: 'default',
+ subject: {
+ id: params.subjectId,
+ type: 'user' as const,
+ display_name: params.displayName ?? params.subjectId,
+ },
+ roles: params.roles,
+ user_credential: params.userCredential,
+ };
+ }
+
it('returns 401 when the id_token cookie and Bearer token are missing', async () => {
- const res = await createApp().request('/api/v1/models');
+ const res = await createApp(new OidcAuthenticator()).request('/api/v1/models');
expect(res.status).toBe(401);
expect(await res.json()).toEqual({ error: { message: 'Authentication required' } });
});
it('returns 401 when the token is invalid', async () => {
- const res = await createApp().request('/api/v1/models', {
+ const res = await createApp(new OidcAuthenticator()).request('/api/v1/models', {
headers: { Cookie: 'id_token=not-a-jwt' },
});
expect(res.status).toBe(401);
@@ -162,7 +187,7 @@ describe('authMiddleware', () => {
});
it('returns 401 when the Bearer token is invalid', async () => {
- const res = await createApp().request('/api/v1/models', {
+ const res = await createApp(new OidcAuthenticator()).request('/api/v1/models', {
headers: { Authorization: 'Bearer not-a-jwt' },
});
expect(res.status).toBe(401);
@@ -171,7 +196,7 @@ describe('authMiddleware', () => {
it('returns 401 when the token has the wrong issuer', async () => {
const token = await createIdToken({ issuer: 'https://other.example.com' });
- const res = await createApp().request('/api/v1/models', {
+ const res = await createApp(new OidcAuthenticator()).request('/api/v1/models', {
headers: { Cookie: `id_token=${token}` },
});
expect(res.status).toBe(401);
@@ -180,7 +205,7 @@ describe('authMiddleware', () => {
it('returns 401 when the token has the wrong audience', async () => {
const token = await createIdToken({ audience: 'other-client' });
- const res = await createApp().request('/api/v1/models', {
+ const res = await createApp(new OidcAuthenticator()).request('/api/v1/models', {
headers: { Cookie: `id_token=${token}` },
});
expect(res.status).toBe(401);
@@ -189,41 +214,49 @@ describe('authMiddleware', () => {
it('returns 401 when the token is expired', async () => {
const token = await createIdToken({ exp: Math.floor(Date.now() / 1000) - 60 });
- const res = await createApp().request('/api/v1/models', {
+ const res = await createApp(new OidcAuthenticator()).request('/api/v1/models', {
headers: { Cookie: `id_token=${token}` },
});
expect(res.status).toBe(401);
expect(await res.json()).toEqual({ error: { message: 'Authentication required' } });
});
- it('sets user context from claims (reference claim + role)', async () => {
+ it('sets request context from claims (reference claim + role)', async () => {
const token = await createIdToken({ sub: 'alice', groups: ['admin'] });
- const res = await createApp().request('/api/v1/models', {
+ const res = await createApp(new OidcAuthenticator()).request('/api/v1/models', {
headers: { Cookie: `id_token=${token}` },
});
expect(res.status).toBe(200);
expect(await res.json()).toEqual({
ok: true,
- user: { userRef: 'alice', role: 'admin' },
+ user: oidcRequestContext({
+ subjectId: 'alice',
+ roles: ['admin'],
+ userCredential: token,
+ }),
});
});
- it('sets user context from Authorization Bearer ID token', async () => {
+ it('sets request context from Authorization Bearer ID token', async () => {
const token = await createIdToken({ sub: 'alice', groups: ['admin'] });
- const res = await createApp().request('/api/v1/models', {
+ const res = await createApp(new OidcAuthenticator()).request('/api/v1/models', {
headers: { Authorization: `Bearer ${token}` },
});
expect(res.status).toBe(200);
expect(await res.json()).toEqual({
ok: true,
- user: { userRef: 'alice', role: 'admin' },
+ user: oidcRequestContext({
+ subjectId: 'alice',
+ roles: ['admin'],
+ userCredential: token,
+ }),
});
});
it('prefers Bearer over cookie when both are present', async () => {
const cookieToken = await createIdToken({ sub: 'cookie-user', groups: [] });
const bearerToken = await createIdToken({ sub: 'bearer-user', groups: ['admin'] });
- const res = await createApp().request('/api/v1/models', {
+ const res = await createApp(new OidcAuthenticator()).request('/api/v1/models', {
headers: {
Cookie: `id_token=${cookieToken}`,
Authorization: `Bearer ${bearerToken}`,
@@ -232,13 +265,17 @@ describe('authMiddleware', () => {
expect(res.status).toBe(200);
expect(await res.json()).toEqual({
ok: true,
- user: { userRef: 'bearer-user', role: 'admin' },
+ user: oidcRequestContext({
+ subjectId: 'bearer-user',
+ roles: ['admin'],
+ userCredential: bearerToken,
+ }),
});
});
it('ignores non-Bearer Authorization and falls back to cookie', async () => {
const token = await createIdToken({ sub: 'alice', groups: ['admin'] });
- const res = await createApp().request('/api/v1/models', {
+ const res = await createApp(new OidcAuthenticator()).request('/api/v1/models', {
headers: {
Authorization: `Basic ${token}`,
Cookie: `id_token=${token}`,
@@ -247,37 +284,49 @@ describe('authMiddleware', () => {
expect(res.status).toBe(200);
expect(await res.json()).toEqual({
ok: true,
- user: { userRef: 'alice', role: 'admin' },
+ user: oidcRequestContext({
+ subjectId: 'alice',
+ roles: ['admin'],
+ userCredential: token,
+ }),
});
});
it('allows settings when the caller has admin role', async () => {
const token = await createIdToken({ sub: 'alice', groups: ['admin'] });
- const res = await createApp().request('/api/v1/settings', {
+ const res = await createApp(new OidcAuthenticator()).request('/api/v1/settings', {
headers: { Cookie: `id_token=${token}` },
});
expect(res.status).toBe(200);
expect(await res.json()).toEqual({
ok: true,
- user: { userRef: 'alice', role: 'admin' },
+ user: oidcRequestContext({
+ subjectId: 'alice',
+ roles: ['admin'],
+ userCredential: token,
+ }),
});
});
it('allows settings with Bearer when the caller has admin role', async () => {
const token = await createIdToken({ sub: 'alice', groups: ['admin'] });
- const res = await createApp().request('/api/v1/settings', {
+ const res = await createApp(new OidcAuthenticator()).request('/api/v1/settings', {
headers: { Authorization: `Bearer ${token}` },
});
expect(res.status).toBe(200);
expect(await res.json()).toEqual({
ok: true,
- user: { userRef: 'alice', role: 'admin' },
+ user: oidcRequestContext({
+ subjectId: 'alice',
+ roles: ['admin'],
+ userCredential: token,
+ }),
});
});
it('returns 403 on settings when the caller is not admin', async () => {
const token = await createIdToken({ sub: 'bob', groups: ['everyone'] });
- const res = await createApp().request('/api/v1/settings', {
+ const res = await createApp(new OidcAuthenticator()).request('/api/v1/settings', {
headers: { Cookie: `id_token=${token}` },
});
expect(res.status).toBe(403);
@@ -290,7 +339,7 @@ describe('authMiddleware', () => {
oidcConfig: { ...OIDC_CONFIG, OIDC_ALLOWED_EMAILS: ['*@company.com'] },
});
const token = await createIdToken({ sub: 'alice', groups: ['admin'], email: '[email protected]' });
- const res = await createApp().request('/api/v1/models', {
+ const res = await createApp(new OidcAuthenticator()).request('/api/v1/models', {
headers: { Cookie: `id_token=${token}` },
});
expect(res.status).toBe(401);
@@ -303,13 +352,17 @@ describe('authMiddleware', () => {
oidcConfig: { ...OIDC_CONFIG, OIDC_ALLOWED_EMAILS: ['*@company.com'] },
});
const token = await createIdToken({ sub: 'alice', groups: ['admin'], email: '[email protected]' });
- const res = await createApp().request('/api/v1/models', {
+ const res = await createApp(new OidcAuthenticator()).request('/api/v1/models', {
headers: { Cookie: `id_token=${token}` },
});
expect(res.status).toBe(200);
expect(await res.json()).toEqual({
ok: true,
- user: { userRef: 'alice', role: 'admin' },
+ user: oidcRequestContext({
+ subjectId: 'alice',
+ roles: ['admin'],
+ userCredential: token,
+ }),
});
});
@@ -320,7 +373,7 @@ describe('authMiddleware', () => {
'/api/v1/mcp-servers/oauth/callback',
'/api/v1/openapi',
])('does not gate public mount %s', async path => {
- const res = await createApp().request(path);
+ const res = await createApp(new OidcAuthenticator()).request(path);
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ public: true });
});
diff --git a/packages/trueforge/tests/unit/runtime/getMcpConnection.test.ts b/packages/trueforge/tests/unit/runtime/getMcpConnection.test.ts
index cf14c7205..f9065ad8f 100644
--- a/packages/trueforge/tests/unit/runtime/getMcpConnection.test.ts
+++ b/packages/trueforge/tests/unit/runtime/getMcpConnection.test.ts
@@ -1,5 +1,4 @@
-import { TENANT_ID } from '../../../src/apis/sessions';
-import { LOCAL_USER_CONTEXT } from '../../../src/auth/identity';
+import { STANDALONE_REQUEST_CONTEXT } from '../../../src/auth/identity';
import { McpServerWithAuthStore } from '../../../src/db/McpServerWithAuthStore';
import type { IMcpServerWithAuthStore } from '../../../src/db/mcpServerStore';
import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';
@@ -70,7 +69,7 @@ describe('getMcpConnection', () => {
try {
const record = await mcpServerStore.upsertServer({
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
name: 'oauth-mcp',
manifest: {
type: 'remote',
@@ -82,12 +81,12 @@ describe('getMcpConnection', () => {
});
const connection = await getMcpConnection({
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
name: 'oauth-mcp',
store: mcpServerStore,
tokenStore,
clientName: 'test-client',
- userRef: LOCAL_USER_CONTEXT.userRef,
+ userRef: STANDALONE_REQUEST_CONTEXT.subject.id,
});
expect(connection).toBeDefined();
if (connection === undefined) {
@@ -120,7 +119,7 @@ describe('getMcpConnection', () => {
it('returns Bearer headers when a usable token is already stored', async () => {
const record = await mcpServerStore.upsertServer({
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
name: 'tokened-mcp',
manifest: {
type: 'remote',
@@ -132,7 +131,7 @@ describe('getMcpConnection', () => {
});
await tokenStore.saveToken({
id: record.id,
- userRef: LOCAL_USER_CONTEXT.userRef,
+ userRef: STANDALONE_REQUEST_CONTEXT.subject.id,
token: {
accessToken: 'live-access',
refreshToken: null,
@@ -142,12 +141,12 @@ describe('getMcpConnection', () => {
});
const connection = await getMcpConnection({
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
name: 'tokened-mcp',
store: mcpServerStore,
tokenStore,
clientName: 'test-client',
- userRef: LOCAL_USER_CONTEXT.userRef,
+ userRef: STANDALONE_REQUEST_CONTEXT.subject.id,
});
expect(connection).toBeDefined();
if (connection === undefined || typeof connection.headers !== 'function') {
@@ -160,7 +159,7 @@ describe('getMcpConnection', () => {
it('returns empty static headers when the server has no auth', async () => {
await mcpServerStore.upsertServer({
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
name: 'open-mcp',
manifest: {
type: 'remote',
@@ -171,12 +170,12 @@ describe('getMcpConnection', () => {
});
const connection = await getMcpConnection({
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
name: 'open-mcp',
store: mcpServerStore,
tokenStore,
clientName: 'test-client',
- userRef: LOCAL_USER_CONTEXT.userRef,
+ userRef: STANDALONE_REQUEST_CONTEXT.subject.id,
});
expect(connection).toBeDefined();
if (connection === undefined) {
@@ -189,7 +188,7 @@ describe('getMcpConnection', () => {
it('returns configured static headers for header-auth servers', async () => {
await mcpServerStore.upsertServer({
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
name: 'header-mcp',
manifest: {
type: 'remote',
@@ -201,12 +200,12 @@ describe('getMcpConnection', () => {
});
const connection = await getMcpConnection({
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
name: 'header-mcp',
store: mcpServerStore,
tokenStore,
clientName: 'test-client',
- userRef: LOCAL_USER_CONTEXT.userRef,
+ userRef: STANDALONE_REQUEST_CONTEXT.subject.id,
});
expect(connection).toBeDefined();
if (connection === undefined) {
@@ -219,7 +218,7 @@ describe('getMcpConnection', () => {
it('skips local DCR for truefoundry servers even when wire auth is dcr', async () => {
await mcpServerStore.upsertServer({
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
name: 'tfy-mcp',
manifest: {
type: 'truefoundry',
@@ -231,12 +230,12 @@ describe('getMcpConnection', () => {
});
const connection = await getMcpConnection({
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
name: 'tfy-mcp',
store: mcpServerStore,
tokenStore,
clientName: 'test-client',
- userRef: LOCAL_USER_CONTEXT.userRef,
+ userRef: STANDALONE_REQUEST_CONTEXT.subject.id,
});
expect(connection).toEqual({
url: 'https://gateway.example/mcp-server/tfy-mcp',
@@ -247,12 +246,12 @@ describe('getMcpConnection', () => {
it('returns undefined when the server is not registered', async () => {
await expect(
getMcpConnection({
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
name: 'missing-mcp',
store: mcpServerStore,
tokenStore,
clientName: 'test-client',
- userRef: LOCAL_USER_CONTEXT.userRef,
+ userRef: STANDALONE_REQUEST_CONTEXT.subject.id,
}),
).resolves.toBeUndefined();
});
diff --git a/packages/trueforge/tests/unit/runtime/sessionResources.test.ts b/packages/trueforge/tests/unit/runtime/sessionResources.test.ts
index b3d763f79..72391f11f 100644
--- a/packages/trueforge/tests/unit/runtime/sessionResources.test.ts
+++ b/packages/trueforge/tests/unit/runtime/sessionResources.test.ts
@@ -1,6 +1,5 @@
import { AgentSpecSchema } from '@truefoundry/trueforge-core/agent-session';
import { HTTPException } from 'hono/http-exception';
-import { TENANT_ID } from '../../../src/apis/sessions';
import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';
import { createSqliteDb } from '../../../src/db/sqlite/client';
import { SqliteMcpServerStore } from '../../../src/db/sqlite/mcp-server-store/SqliteMcpServerStore';
@@ -32,7 +31,7 @@ describe('validateAgentSpec', () => {
await migrateSqliteToLatest(db);
const modelProviderStore = new SqliteModelProviderStore(db);
await modelProviderStore.upsertProvider({
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
name: 'test-provider',
manifest: {
// Caller-named, so `custom` is the only type it can be.
@@ -66,7 +65,7 @@ describe('validateAgentSpec', () => {
await expect(
getModelDetails({
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
name: 'test-provider/test-model',
store: stores.modelProviderStore,
}),
@@ -89,7 +88,7 @@ describe('validateAgentSpec', () => {
model: { name: 'not-a-fqn' },
instructions: 'test',
}),
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
...stores,
}),
).rejects.toMatchObject({
@@ -106,7 +105,7 @@ describe('validateAgentSpec', () => {
model: { name: 'missing-provider/test-model' },
instructions: 'test',
}),
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
...stores,
}),
).rejects.toMatchObject({
@@ -123,7 +122,7 @@ describe('validateAgentSpec', () => {
model: { name: 'test-provider/missing-model' },
instructions: 'test',
}),
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
...stores,
}),
).rejects.toMatchObject({
@@ -140,7 +139,7 @@ describe('validateAgentSpec', () => {
model: { name: 'test-provider/test-model', params: { reasoning_effort: 'medium' } },
instructions: 'test',
}),
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
...stores,
}),
).rejects.toMatchObject({
@@ -158,7 +157,7 @@ describe('validateAgentSpec', () => {
instructions: 'test',
mcp_servers: [{ name: 'missing-mcp' }],
}),
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
...stores,
}),
).rejects.toMatchObject({
@@ -176,7 +175,7 @@ describe('validateAgentSpec', () => {
instructions: 'test',
skills: [{ name: 'missing-skill' }],
}),
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
...stores,
}),
).rejects.toMatchObject({
@@ -194,7 +193,7 @@ describe('validateAgentSpec', () => {
instructions: 'test',
config: { sandbox: { enabled: true } },
}),
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
...stores,
}),
).rejects.toMatchObject({
@@ -206,7 +205,7 @@ describe('validateAgentSpec', () => {
it('rejects skills when no sandbox provider is configured', async () => {
const stores = await setup();
await stores.skillStore.upsertSkill({
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
name: 'demo',
manifest: {
type: 'git',
@@ -224,7 +223,7 @@ describe('validateAgentSpec', () => {
instructions: 'test',
skills: [{ name: 'demo' }],
}),
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
...stores,
}),
).rejects.toMatchObject({
@@ -236,7 +235,7 @@ describe('validateAgentSpec', () => {
it('admits sandbox.enabled when a sandbox provider row exists', async () => {
const stores = await setup();
await stores.sandboxProviderStore.upsertSandboxProvider({
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
manifest: {
type: 'daytona',
auth: { api_key: 'dtn-test' },
@@ -257,7 +256,7 @@ describe('validateAgentSpec', () => {
instructions: 'test',
config: { sandbox: { enabled: true } },
}),
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
...stores,
}),
).resolves.toBeUndefined();
@@ -278,10 +277,10 @@ describe('validateAgentSpec', () => {
instructions: 'test',
config: { sandbox: { enabled: true } },
}),
- tenant_id: TENANT_ID,
+ tenant_id: 'default',
...stores,
}),
).resolves.toBeUndefined();
- expect(await stores.sandboxProviderStore.getSandboxProvider(TENANT_ID)).toBeUndefined();
+ expect(await stores.sandboxProviderStore.getSandboxProvider('default')).toBeUndefined();
});
});