Skip to content

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

feat(auth): allowlist OIDC logins by email or domain glob (#512)

Abhishek Choudharyef316d284944
diff --git a/.changeset/oidc-allowed-emails.md b/.changeset/oidc-allowed-emails.md
new file mode 100644
index 000000000..b33abd7ba
--- /dev/null
+++ b/.changeset/oidc-allowed-emails.md
@@ -0,0 +1,5 @@
+---
+"@truefoundry/trueforge": minor
+---
+
+Add optional `OIDC_ALLOWED_EMAILS` allowlist (exact addresses and `*` globs) so OIDC logins can be limited to approved emails or domains.
diff --git a/charts/trueforge/README.md b/charts/trueforge/README.md
index 9d9a6fc6b..a264a60b3 100644
--- a/charts/trueforge/README.md
+++ b/charts/trueforge/README.md
@@ -141,6 +141,8 @@ configs:
# userRoleClaim: groups
# adminRoleValue: admin
# scopes: "openid,profile,email,groups"
+ # Optional email allowlist (exact + * globs). Empty = unrestricted.
+ # allowedEmails: "[email protected],*@partner.com"
```
## Using Secrets
diff --git a/charts/trueforge/templates/_helpers.tpl b/charts/trueforge/templates/_helpers.tpl
index c1f85800f..a8e398b8b 100644
--- a/charts/trueforge/templates/_helpers.tpl
+++ b/charts/trueforge/templates/_helpers.tpl
@@ -183,6 +183,9 @@ fields, wires bundled Postgres/Redis, optional OIDC, then server.extraEnv.
{{- $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) -}}
+{{- if .Values.configs.oidc.allowedEmails -}}
+{{- $env = append $env (dict "name" "OIDC_ALLOWED_EMAILS" "value" .Values.configs.oidc.allowedEmails) -}}
+{{- end -}}
{{- end -}}
{{- range .Values.server.extraEnv -}}
diff --git a/charts/trueforge/values.yaml b/charts/trueforge/values.yaml
index 33e3aafa8..f5f3cb379 100644
--- a/charts/trueforge/values.yaml
+++ b/charts/trueforge/values.yaml
@@ -83,6 +83,9 @@ configs:
userRoleClaim: groups
adminRoleValue: admin
scopes: "openid,profile,email"
+ # Optional comma-separated exact emails and/or * globs (e.g. "*@company.com").
+ # Empty = unrestricted. Matched against the ID token `email` claim.
+ allowedEmails: ""
# Bitnami relocated its versioned container images to docker.io/bitnamilegacy and
# left only rolling `latest` tags under docker.io/bitnami, so the subchart image
# defaults no longer pull. We source pinned legacy images from the TrueFoundry
diff --git a/docs/authentication/overview.mdx b/docs/authentication/overview.mdx
index a74792ce2..284ba4f39 100644
--- a/docs/authentication/overview.mdx
+++ b/docs/authentication/overview.mdx
@@ -127,6 +127,7 @@ The default. Do **not** set any `OIDC_*` variables, run TrueForge as usual ([Qui
| `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 |
+ | `OIDC_ALLOWED_EMAILS` | No | Comma-separated allowlist of exact emails and/or `*` globs (e.g. `[email protected],*@partner.com`). When set, only ID tokens whose `email` claim matches an entry may sign in. Empty / unset = unrestricted. Matching is case-insensitive. |
How you pass these depends on how you run TrueForge:
@@ -143,6 +144,8 @@ The default. Do **not** set any `OIDC_*` variables, run TrueForge as usual ([Qui
OIDC_USER_ROLE_CLAIM=groups
OIDC_ADMIN_ROLE_VALUE=harness-admin
OIDC_SCOPES=openid,profile,email,groups
+ # Optional: restrict who can sign in (exact emails and/or * globs)
+ # [email protected],*@partner.com
```
</Tab>
<Tab title="Helm">
@@ -167,6 +170,8 @@ The default. Do **not** set any `OIDC_*` variables, run TrueForge as usual ([Qui
userRoleClaim: groups
adminRoleValue: harness-admin
scopes: "openid,profile,email,groups"
+ # Optional: restrict who can sign in
+ # allowedEmails: "[email protected],*@partner.com"
extraObjects:
- apiVersion: v1
kind: Secret
@@ -220,6 +225,7 @@ To call the HTTP API or SDK against a server with login enabled, pass an ID toke
| Blank authorize screen when requesting `groups` | Custom Authorization Server is missing the `groups` scope and/or ID-token groups claim (Okta) |
| Login works but everyone is `role: "user"` | Groups/roles claim missing from the ID token, wrong claim name, or admin value mismatch (case-sensitive) |
| SDK returns `401` | OIDC is on and the request has no [ID token](/api/quickstart#get-a-token-and-connect) or session cookie |
+| Sign-in fails with `login_failed` / APIs return `401` after allowlist rollout | Caller’s `email` claim is outside `OIDC_ALLOWED_EMAILS`, or the ID token has no `email` claim while an allowlist is set. Failures stay generic so the allowlist is not disclosed. |
## Security checklist
diff --git a/packages/trueforge/.env.example b/packages/trueforge/.env.example
index a0375be89..56c23b01e 100644
--- a/packages/trueforge/.env.example
+++ b/packages/trueforge/.env.example
@@ -155,3 +155,7 @@ POSTGRES_PORT=5432
# OIDC_ADMIN_ROLE_VALUE=admin
## Comma-separated OAuth scopes for login. Optional; defaults to "openid,profile,email".
# OIDC_SCOPES=openid,profile,email
+## Optional comma-separated email allowlist (exact addresses and/or * globs).
+## When set, only ID tokens whose `email` claim matches an entry may sign in.
+## Example: [email protected],*@partner.com Empty / unset = unrestricted.
+# OIDC_ALLOWED_EMAILS=
\ No newline at end of file
diff --git a/packages/trueforge/src/apis/auth.ts b/packages/trueforge/src/apis/auth.ts
index d90a1e3f6..0a224aaa3 100644
--- a/packages/trueforge/src/apis/auth.ts
+++ b/packages/trueforge/src/apis/auth.ts
@@ -1,5 +1,6 @@
import { OpenAPIHono } from '@hono/zod-openapi';
import { extractErrorLogFields } from '@truefoundry/trueforge-core/core';
+import type { Context } 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';
@@ -15,6 +16,26 @@ function oauthErrorRedirect(reason: string): string {
return `/?error=${encodeURIComponent(reason)}`;
}
+/**
+ * Soft-success probe for callback: a usable session → redirect; a leftover cookie
+ * with unusable claims (allowlist, missing user ref, etc.) → clear it and continue
+ * so the caller can show a generic login failure without leaking why.
+ */
+async function redirectIfAlreadyAuthenticated(params: {
+ context: Context;
+ whenAuthenticated: string;
+}): Promise<Response | undefined> {
+ try {
+ if (await resolveAuthUser(params.context)) {
+ return params.context.redirect(params.whenAuthenticated, 302);
+ }
+ } catch {
+ // Valid JWT but unusable claims — drop the stale cookie; treat as unauthenticated.
+ clearAuthCookie({ context: params.context, name: ID_TOKEN_COOKIE });
+ }
+ return undefined;
+}
+
/**
* Auth surfaces mounted at /api/v1/auth: login, callback, logout, me.
* Login, callback, and logout stay public; me requires {@link authMiddleware}.
@@ -52,8 +73,9 @@ export function createAuthRouter(params: { oidcClient: Configuration | undefined
if (pending?.state !== query.state || query.error || !query.code) {
// If already authenticated, redirect home instead of showing an error.
- if (await resolveAuthUser(c)) {
- return c.redirect('/', 302);
+ const soft = await redirectIfAlreadyAuthenticated({ context: c, whenAuthenticated: '/' });
+ if (soft) {
+ return soft;
}
// Only reflect a non-empty IdP `error_description` when the IdP returned an error.
// No fallback to the `error` code — blank/missing descriptions use the default.
@@ -74,8 +96,12 @@ export function createAuthRouter(params: { oidcClient: Configuration | undefined
return c.redirect(safeReturnTo(pending.return_to), 302);
} catch (error) {
params.logger.error('Failed to exchange authorization code', extractErrorLogFields(error));
- if (await resolveAuthUser(c)) {
- return c.redirect(safeReturnTo(pending.return_to), 302);
+ const soft = await redirectIfAlreadyAuthenticated({
+ context: c,
+ whenAuthenticated: safeReturnTo(pending.return_to),
+ });
+ if (soft) {
+ return soft;
}
const reason = error instanceof Error ? error.message : 'login_failed';
return c.redirect(oauthErrorRedirect(reason), 302);
diff --git a/packages/trueforge/src/auth/claims.ts b/packages/trueforge/src/auth/claims.ts
index 1791d2007..1978183c9 100644
--- a/packages/trueforge/src/auth/claims.ts
+++ b/packages/trueforge/src/auth/claims.ts
@@ -1,4 +1,5 @@
import type { OIDCConfig } from '../config';
+import { assertEmailAllowed } from './emailAllowlist';
import type { Role, UserContext } from './identity';
/** Raw claims from a decoded ID token; values are untyped until read here. */
@@ -46,6 +47,7 @@ export function resolveRole(claims: IdTokenClaims, config: OIDCConfig): Role {
/** Everything `/callback` (and later `/me`, once sessions are real) needs from a set of claims. */
export function toUserContext(claims: IdTokenClaims, config: OIDCConfig): UserContext {
+ assertEmailAllowed(claims, config);
return {
userRef: resolveUserRef(claims, config),
role: resolveRole(claims, config),
@@ -65,15 +67,21 @@ export interface AuthorizationRequestParams {
* 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.
+ * When an email allowlist is configured, `email` is also marked essential so
+ * the IdP cannot complete login without a usable address to check.
*/
export function buildAuthorizationRequestParams(config: OIDCConfig): AuthorizationRequestParams {
+ const idTokenClaims: Record<string, { essential: true }> = {
+ [config.OIDC_USER_REFERENCE_CLAIM]: { essential: true },
+ [config.OIDC_USER_ROLE_CLAIM]: { essential: true },
+ };
+ if (config.OIDC_ALLOWED_EMAILS.length > 0) {
+ idTokenClaims['email'] = { essential: true };
+ }
return {
scopes: config.OIDC_SCOPES,
claims: {
- id_token: {
- [config.OIDC_USER_REFERENCE_CLAIM]: { essential: true },
- [config.OIDC_USER_ROLE_CLAIM]: { essential: true },
- },
+ id_token: idTokenClaims,
},
};
}
diff --git a/packages/trueforge/src/auth/emailAllowlist.ts b/packages/trueforge/src/auth/emailAllowlist.ts
new file mode 100644
index 000000000..0a39bdf87
--- /dev/null
+++ b/packages/trueforge/src/auth/emailAllowlist.ts
@@ -0,0 +1,57 @@
+import type { OIDCConfig } from '../config';
+
+/**
+ * Thrown when OIDC_ALLOWED_EMAILS is set and the caller's email does not match.
+ * Message is intentionally the generic `login_failed` so OAuth redirects never
+ * reveal allowlist membership to the client.
+ */
+export class EmailNotAllowedError extends Error {
+ constructor() {
+ super('login_failed');
+ this.name = 'EmailNotAllowedError';
+ }
+}
+
+/**
+ * Converts an allowlist entry to a anchored regex. `*` is a wildcard; other
+ * regex metacharacters are matched literally. Case is handled by the caller.
+ */
+export function emailAllowlistPatternToRegExp(pattern: string): RegExp {
+ const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*');
+ return new RegExp(`^${escaped}$`, 'u');
+}
+
+/** True when `email` matches any allowlist entry (exact or glob). Empty allowlist → true. */
+export function emailMatchesAllowlist(email: string, patterns: string[]): boolean {
+ if (patterns.length === 0) {
+ return true;
+ }
+ const normalized = email.trim().toLowerCase();
+ if (normalized === '') {
+ return false;
+ }
+ return patterns.some(pattern => {
+ const trimmed = pattern.trim().toLowerCase();
+ if (trimmed === '') {
+ return false;
+ }
+ return emailAllowlistPatternToRegExp(trimmed).test(normalized);
+ });
+}
+
+/**
+ * When {@link OIDCConfig.OIDC_ALLOWED_EMAILS} is non-empty, requires a non-empty
+ * ID-token `email` claim that matches at least one entry. No-op when unrestricted.
+ */
+export function assertEmailAllowed(claims: Record<string, unknown>, config: OIDCConfig): void {
+ if (config.OIDC_ALLOWED_EMAILS.length === 0) {
+ return;
+ }
+ const email = claims['email'];
+ if (typeof email !== 'string' || email.trim() === '') {
+ throw new EmailNotAllowedError();
+ }
+ if (!emailMatchesAllowlist(email, config.OIDC_ALLOWED_EMAILS)) {
+ throw new EmailNotAllowedError();
+ }
+}
diff --git a/packages/trueforge/src/auth/oidc.ts b/packages/trueforge/src/auth/oidc.ts
index 5d17c4308..0c7ad6c92 100644
--- a/packages/trueforge/src/auth/oidc.ts
+++ b/packages/trueforge/src/auth/oidc.ts
@@ -10,8 +10,9 @@ import {
randomState,
} from 'openid-client';
import { getPublicBaseUrl, type OIDCConfig } from '../config';
-import { buildAuthorizationRequestParams } from './claims';
+import { buildAuthorizationRequestParams, type IdTokenClaims } from './claims';
import { ID_TOKEN_COOKIE, OAUTH_STATE_COOKIE, setAuthCookie } from './cookies';
+import { assertEmailAllowed } from './emailAllowlist';
import { safeReturnTo } from './safeReturnTo';
const CALLBACK_PATH = '/api/v1/auth/callback';
@@ -119,6 +120,11 @@ export async function exchangeAuthorizationCode(params: {
// Origin and path come from config so redirect_uri matches the one registered with the IdP.
const callbackUrl = new URL(authCallbackUrl());
callbackUrl.search = params.callbackParams.toString();
+ const oidcConfig = getOidcVerify()?.oidcConfig;
+ if (!oidcConfig) {
+ throw new Error('OIDC claim configuration is unavailable; call initOidc before exchanging an authorization code.');
+ }
+
const tokens = await authorizationCodeGrant(params.client, callbackUrl, {
pkceCodeVerifier: params.codeVerifier,
expectedState: params.state,
@@ -127,6 +133,12 @@ export async function exchangeAuthorizationCode(params: {
if (!idToken) {
throw new Error('Token response missing id_token');
}
+
+ // Reject before stamping the cookie so disallowed users never get a session.
+ const tokenClaims = tokens.claims();
+ const claims: IdTokenClaims = tokenClaims ? { ...tokenClaims } : {};
+ assertEmailAllowed(claims, oidcConfig);
+
setAuthCookie({
context: params.context,
name: ID_TOKEN_COOKIE,
diff --git a/packages/trueforge/src/config.ts b/packages/trueforge/src/config.ts
index 68727bd4d..6bf3f0a73 100644
--- a/packages/trueforge/src/config.ts
+++ b/packages/trueforge/src/config.ts
@@ -97,6 +97,20 @@ export function parseOidcScopes(raw: string): string[] {
return scopes;
}
+/**
+ * Parses `OIDC_ALLOWED_EMAILS`: comma-separated exact addresses and/or globs
+ * (`*@company.com`). Empty / unset → no allowlist (any authenticated user may sign in).
+ */
+export function parseOidcAllowedEmails(raw: string | undefined): string[] {
+ if (raw === undefined || raw.trim() === '') {
+ return [];
+ }
+ return raw
+ .split(',')
+ .map(part => part.trim())
+ .filter(part => part.length > 0);
+}
+
/** Parses a positive-integer env var, falling back to `defaultValue` when unset/blank. */
function parsePositiveInt(options: { envKey: string; raw: string | undefined; defaultValue: number }): number {
const { envKey, raw, defaultValue } = options;
@@ -261,6 +275,7 @@ function resolveOIDCConfig(): OIDCConfig | undefined {
OIDC_ADMIN_ROLE_VALUE:
getEnv('OIDC_ADMIN_ROLE_VALUE', { defaultValue: DEFAULT_OIDC_ADMIN_ROLE_VALUE }) ?? DEFAULT_OIDC_ADMIN_ROLE_VALUE,
OIDC_SCOPES: parseOidcScopes(getEnv('OIDC_SCOPES', { defaultValue: DEFAULT_OIDC_SCOPES }) ?? DEFAULT_OIDC_SCOPES),
+ OIDC_ALLOWED_EMAILS: parseOidcAllowedEmails(getEnv('OIDC_ALLOWED_EMAILS')),
};
}
@@ -292,6 +307,12 @@ export interface OIDCConfig {
* Okta `groups` claims require the `groups` scope; Azure AD app roles typically omit it.
*/
OIDC_SCOPES: string[];
+ /**
+ * Optional allowlist of emails that may sign in. Env: `OIDC_ALLOWED_EMAILS`.
+ * Comma-separated exact addresses and/or `*` globs (e.g. `[email protected],*@partner.com`).
+ * Matching is case-insensitive against the ID token `email` claim. Empty = unrestricted.
+ */
+ OIDC_ALLOWED_EMAILS: string[];
}
export interface SharedServerConfiguration {
diff --git a/packages/trueforge/tests/unit/apis/auth.test.ts b/packages/trueforge/tests/unit/apis/auth.test.ts
index 1e1c75314..8768fdd0e 100644
--- a/packages/trueforge/tests/unit/apis/auth.test.ts
+++ b/packages/trueforge/tests/unit/apis/auth.test.ts
@@ -16,6 +16,7 @@ jest.mock('../../../src/config', () => {
OIDC_USER_ROLE_CLAIM: 'groups',
OIDC_ADMIN_ROLE_VALUE: 'admin',
OIDC_SCOPES: ['openid', 'profile', 'email', 'groups'],
+ OIDC_ALLOWED_EMAILS: [] as string[],
};
const config = {
STANDALONE: false as const,
@@ -265,6 +266,34 @@ describe('auth router (auth enabled)', () => {
expect(idTokenCookie).toContain('Max-Age=86400');
});
+ it('GET /callback rejects emails outside OIDC_ALLOWED_EMAILS without setting a session', async () => {
+ const restrictedClient = await initOidc({
+ ...configuredOidc,
+ OIDC_ALLOWED_EMAILS: ['*@company.com'],
+ });
+ if (!restrictedClient) {
+ throw new Error('OIDC client was not initialized');
+ }
+
+ const router = createAuthRouter({ oidcClient: restrictedClient, logger });
+ 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 } },
+ });
+
+ const callbackRes = await router.request(`/callback?code=abc123&state=${state}&iss=${encodeURIComponent(ISSUER)}`, {
+ redirect: 'manual',
+ headers: { Cookie: `${STATE_COOKIE}=${stateCookieRaw}` },
+ });
+
+ expect(callbackRes.status).toBe(302);
+ expect(callbackRes.headers.get('location')).toBe('/?error=login_failed');
+ expect(setCookies(callbackRes).some(cookie => cookie.startsWith(`${ID_TOKEN_COOKIE}=`))).toBe(false);
+ });
+
it('GET /callback redirects home with error when the IdP returns an error', async () => {
const res = await createAuthRouter({ oidcClient, logger }).request(
'/callback?state=any&error=access_denied&error_description=user%20cancelled',
@@ -321,6 +350,32 @@ describe('auth router (auth enabled)', () => {
expect(res.headers.get('location')).toBe('/');
});
+ it('GET /callback clears a leftover cookie outside the allowlist without revealing why', async () => {
+ // Rollout case: allowlist enabled while browsers still hold pre-allowlist id_tokens.
+ // Failure stays generic (`login_failed`) so allowlist membership is not disclosed.
+ const restrictedClient = await initOidc({
+ ...configuredOidc,
+ OIDC_ALLOWED_EMAILS: ['*@company.com'],
+ });
+ if (!restrictedClient) {
+ throw new Error('OIDC client was not initialized');
+ }
+
+ 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}` },
+ },
+ );
+ expect(res.status).toBe(302);
+ expect(res.headers.get('location')).toBe('/?error=login_failed');
+ expect(
+ setCookies(res).some(cookie => cookie.startsWith(`${ID_TOKEN_COOKIE}=`) && cookie.includes('Max-Age=0')),
+ ).toBe(true);
+ });
+
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(
@@ -334,6 +389,33 @@ describe('auth router (auth enabled)', () => {
expect(res.headers.get('location')).toBe('/');
});
+ it('GET /callback keeps login_failed when exchange fails and the leftover cookie is blocked', async () => {
+ const restrictedClient = await initOidc({
+ ...configuredOidc,
+ OIDC_ALLOWED_EMAILS: ['*@company.com'],
+ });
+ if (!restrictedClient) {
+ throw new Error('OIDC client was not initialized');
+ }
+
+ const token = await createIdToken();
+ const router = createAuthRouter({ oidcClient: restrictedClient, logger });
+ 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') ?? '');
+ const state = authorizationUrl.searchParams.get('state') ?? '';
+
+ const res = await router.request(`/callback?code=abc&state=${state}&iss=${encodeURIComponent(ISSUER)}`, {
+ redirect: 'manual',
+ headers: { Cookie: `${STATE_COOKIE}=${stateCookieRaw}; ${ID_TOKEN_COOKIE}=${token}` },
+ });
+ expect(res.status).toBe(302);
+ expect(res.headers.get('location')).toBe('/?error=login_failed');
+ expect(
+ setCookies(res).some(cookie => cookie.startsWith(`${ID_TOKEN_COOKIE}=`) && cookie.includes('Max-Age=0')),
+ ).toBe(true);
+ });
+
it('GET /callback keeps the existing session when code exchange fails', async () => {
const token = await createIdToken();
const router = createAuthRouter({ oidcClient, logger });
diff --git a/packages/trueforge/tests/unit/apis/capabilities.test.ts b/packages/trueforge/tests/unit/apis/capabilities.test.ts
index 78856454f..fc9c09047 100644
--- a/packages/trueforge/tests/unit/apis/capabilities.test.ts
+++ b/packages/trueforge/tests/unit/apis/capabilities.test.ts
@@ -36,6 +36,7 @@ const OIDC_CONFIG: OIDCConfig = {
OIDC_USER_ROLE_CLAIM: 'groups',
OIDC_ADMIN_ROLE_VALUE: 'admin',
OIDC_SCOPES: ['openid', 'profile', 'email', 'groups'],
+ OIDC_ALLOWED_EMAILS: [],
};
function json(body: unknown, status = 200): Response {
diff --git a/packages/trueforge/tests/unit/auth/claims.test.ts b/packages/trueforge/tests/unit/auth/claims.test.ts
index edf8d7bce..890d84a71 100644
--- a/packages/trueforge/tests/unit/auth/claims.test.ts
+++ b/packages/trueforge/tests/unit/auth/claims.test.ts
@@ -5,6 +5,7 @@ import {
resolveUserRef,
toUserContext,
} from '../../../src/auth/claims';
+import { EmailNotAllowedError } from '../../../src/auth/emailAllowlist';
import type { OIDCConfig } from '../../../src/config';
function config(overrides: Partial<OIDCConfig> = {}): OIDCConfig {
@@ -16,6 +17,7 @@ function config(overrides: Partial<OIDCConfig> = {}): OIDCConfig {
OIDC_USER_ROLE_CLAIM: 'groups',
OIDC_ADMIN_ROLE_VALUE: 'harness-admins',
OIDC_SCOPES: ['openid', 'profile', 'email', 'groups'],
+ OIDC_ALLOWED_EMAILS: [],
...overrides,
};
}
@@ -101,6 +103,33 @@ describe('toUserContext', () => {
it('propagates resolveUserRef throwing when the reference claim is missing', () => {
expect(() => toUserContext({ groups: ['harness-admins'] }, config())).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' });
+ });
+
+ 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'] }),
+ ),
+ ).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' });
+ });
});
describe('buildAuthorizationRequestParams', () => {
@@ -134,4 +163,11 @@ describe('buildAuthorizationRequestParams', () => {
);
expect(claims).toEqual({ id_token: { groups: { essential: true } } });
});
+
+ 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 } },
+ });
+ });
});
diff --git a/packages/trueforge/tests/unit/auth/emailAllowlist.test.ts b/packages/trueforge/tests/unit/auth/emailAllowlist.test.ts
new file mode 100644
index 000000000..d3ffe5704
--- /dev/null
+++ b/packages/trueforge/tests/unit/auth/emailAllowlist.test.ts
@@ -0,0 +1,70 @@
+import { assertEmailAllowed, emailMatchesAllowlist, EmailNotAllowedError } from '../../../src/auth/emailAllowlist';
+import type { OIDCConfig } from '../../../src/config';
+
+function config(overrides: Partial<OIDCConfig> = {}): OIDCConfig {
+ return {
+ OIDC_ISSUER_URL: 'https://example.okta.com/oauth2/default',
+ OIDC_CLIENT_ID: 'client-id',
+ OIDC_CLIENT_SECRET: 'client-secret',
+ OIDC_USER_REFERENCE_CLAIM: 'sub',
+ OIDC_USER_ROLE_CLAIM: 'groups',
+ OIDC_ADMIN_ROLE_VALUE: 'admin',
+ OIDC_SCOPES: ['openid', 'profile', 'email'],
+ OIDC_ALLOWED_EMAILS: [],
+ ...overrides,
+ };
+}
+
+describe('emailMatchesAllowlist', () => {
+ it('allows any email when the pattern list is empty', () => {
+ expect(emailMatchesAllowlist('[email protected]', [])).toBe(true);
+ });
+
+ it('matches an exact address case-insensitively', () => {
+ expect(emailMatchesAllowlist('[email protected]', ['[email protected]'])).toBe(true);
+ expect(emailMatchesAllowlist('[email protected]', ['[email protected]'])).toBe(false);
+ });
+
+ it('matches a domain glob', () => {
+ expect(emailMatchesAllowlist('[email protected]', ['*@company.com'])).toBe(true);
+ expect(emailMatchesAllowlist('[email protected]', ['*@company.com'])).toBe(false);
+ });
+
+ it('matches when any of several patterns hits', () => {
+ expect(emailMatchesAllowlist('[email protected]', ['[email protected]', '*@partner.com'])).toBe(true);
+ });
+
+ it('treats dots in the pattern as literals, not wildcards', () => {
+ expect(emailMatchesAllowlist('alice@companyXcom', ['*@company.com'])).toBe(false);
+ });
+});
+
+describe('assertEmailAllowed', () => {
+ it('is a no-op when the allowlist is empty', () => {
+ expect(() => assertEmailAllowed({}, config())).not.toThrow();
+ });
+
+ it('throws when the email claim is missing', () => {
+ expect(() => assertEmailAllowed({ sub: 'u1' }, config({ OIDC_ALLOWED_EMAILS: ['*@company.com'] }))).toThrow(
+ EmailNotAllowedError,
+ );
+ });
+
+ it('throws when the email does not match', () => {
+ expect(() =>
+ assertEmailAllowed({ email: '[email protected]' }, config({ OIDC_ALLOWED_EMAILS: ['*@company.com'] })),
+ ).toThrow(EmailNotAllowedError);
+ });
+
+ it('uses a generic login_failed message so redirects do not reveal allowlist membership', () => {
+ expect(() =>
+ assertEmailAllowed({ email: '[email protected]' }, config({ OIDC_ALLOWED_EMAILS: ['*@company.com'] })),
+ ).toThrow('login_failed');
+ });
+
+ it('allows a matching email', () => {
+ expect(() =>
+ assertEmailAllowed({ email: '[email protected]' }, config({ OIDC_ALLOWED_EMAILS: ['*@company.com'] })),
+ ).not.toThrow();
+ });
+});
diff --git a/packages/trueforge/tests/unit/auth/identity.test.ts b/packages/trueforge/tests/unit/auth/identity.test.ts
index 5234adf5e..5eada457d 100644
--- a/packages/trueforge/tests/unit/auth/identity.test.ts
+++ b/packages/trueforge/tests/unit/auth/identity.test.ts
@@ -10,6 +10,7 @@ const OIDC_CONFIG: OIDCConfig = {
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 {
diff --git a/packages/trueforge/tests/unit/auth/middleware.test.ts b/packages/trueforge/tests/unit/auth/middleware.test.ts
index 6e2e257a0..33211bba6 100644
--- a/packages/trueforge/tests/unit/auth/middleware.test.ts
+++ b/packages/trueforge/tests/unit/auth/middleware.test.ts
@@ -17,6 +17,7 @@ const OIDC_CONFIG: OIDCConfig = {
OIDC_USER_ROLE_CLAIM: 'groups',
OIDC_ADMIN_ROLE_VALUE: 'admin',
OIDC_SCOPES: ['openid', 'profile', 'email', 'groups'],
+ OIDC_ALLOWED_EMAILS: [],
};
function json(body: unknown, status = 200): Response {
@@ -129,9 +130,14 @@ describe('authMiddleware', () => {
audience?: string;
sub?: string;
groups?: string[];
+ email?: string;
exp?: string | number;
}): Promise<string> {
- return new SignJWT({ groups: params?.groups ?? [] })
+ const claims: Record<string, unknown> = { groups: params?.groups ?? [] };
+ if (params?.email !== undefined) {
+ claims['email'] = params.email;
+ }
+ return new SignJWT(claims)
.setProtectedHeader({ alg: 'RS256', kid: 'test-kid' })
.setIssuer(params?.issuer ?? ISSUER)
.setAudience(params?.audience ?? AUDIENCE)
@@ -278,6 +284,35 @@ describe('authMiddleware', () => {
expect(await res.json()).toEqual({ error: { message: 'Admin access required' } });
});
+ it('returns 401 when the email is outside OIDC_ALLOWED_EMAILS', async () => {
+ enableOidcAuth({
+ client: oidcClient,
+ 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', {
+ headers: { Cookie: `id_token=${token}` },
+ });
+ expect(res.status).toBe(401);
+ expect(await res.json()).toEqual({ error: { message: 'Authentication required' } });
+ });
+
+ it('allows a caller whose email matches OIDC_ALLOWED_EMAILS', async () => {
+ enableOidcAuth({
+ client: oidcClient,
+ 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', {
+ headers: { Cookie: `id_token=${token}` },
+ });
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({
+ ok: true,
+ user: { userRef: 'alice', role: 'admin' },
+ });
+ });
+
it.each([
'/healthz',
'/api/v1/auth/login',
diff --git a/packages/trueforge/tests/unit/config/parseOidcAllowedEmails.test.ts b/packages/trueforge/tests/unit/config/parseOidcAllowedEmails.test.ts
new file mode 100644
index 000000000..e25678850
--- /dev/null
+++ b/packages/trueforge/tests/unit/config/parseOidcAllowedEmails.test.ts
@@ -0,0 +1,17 @@
+import { parseOidcAllowedEmails } from '../../../src/config';
+
+describe('parseOidcAllowedEmails', () => {
+ it('returns an empty list when unset or blank', () => {
+ expect(parseOidcAllowedEmails(undefined)).toEqual([]);
+ expect(parseOidcAllowedEmails('')).toEqual([]);
+ expect(parseOidcAllowedEmails(' ')).toEqual([]);
+ });
+
+ it('splits on commas and trims whitespace', () => {
+ expect(parseOidcAllowedEmails(' [email protected] , *@partner.com ')).toEqual(['[email protected]', '*@partner.com']);
+ });
+
+ it('drops empty entries between commas', () => {
+ expect(parseOidcAllowedEmails('[email protected],, *@c.com,')).toEqual(['[email protected]', '*@c.com']);
+ });
+});