The open-source agent harness - the runtime layer that turns an LLM into a working agent.
AGE-1622: add admin and user claim config (#69)
Heer Ambavi38f97f9906e0
diff --git a/packages/server/.env.example b/packages/server/.env.exampleindex a7e49cb9a..f5613958e 100644--- a/packages/server/.env.example+++ b/packages/server/.env.example@@ -79,7 +79,7 @@ REDIS_URL=redis://localhost:6379# PUBLIC_BASE_URL=http://localhost:8790# ----------------------------------------------------------------------------MCP knobs.+# MCP knobs.# ---------------------------------------------------------------------------# Client name used for Dynamic Client Registration (DCR) of MCP servers.# This is the client name shown on authorization-server consent screens.@@ -127,3 +127,9 @@ POSTGRES_PORT=5432# OIDC_ISSUER_URL=https://your-tenant.example.com/oauth2/default# OIDC_CLIENT_ID=# OIDC_CLIENT_SECRET=+# Claim used as the user reference. Optional; defaults to "sub".+# OIDC_USER_REFERENCE_CLAIM=sub+# Claim used as the user role. Optional; defaults to "groups".+# OIDC_USER_ROLE_CLAIM=groups+# Case-sensitive role value granting admin access. Optional; defaults to "admin".+# OIDC_ADMIN_ROLE_VALUE=admindiff --git a/packages/server/src/auth/claims.ts b/packages/server/src/auth/claims.tsnew file mode 100644index 000000000..eb28c6ce7--- /dev/null+++ b/packages/server/src/auth/claims.ts@@ -0,0 +1,94 @@+import type { OIDCConfig } from '../config';++/** Raw claims from a decoded ID token; values are untyped until read here. */+export type IdTokenClaims = Record<string, unknown>;++export type Role = 'admin' | 'user';++export interface UserContext {+ userRef: string;+ role: Role;+}++/**+ * Normalizes a claim value into a string list to check membership against.+ * OIDC doesn't fix the shape of claims like `groups`/`roles`: most IdPs+ * return an array, some collapse a single membership down to a bare string,+ * and a missing/misconfigured claim mapping can omit it entirely. Anything+ * else (number, object, null) is treated as "no values" rather than thrown -+ * a malformed claim should fail a user out of admin, not crash the request.+ */+export function claimValues(claim: unknown): string[] {+ if (Array.isArray(claim)) {+ return claim.filter((value): value is string => typeof value === 'string');+ }+ if (typeof claim === 'string') {+ return [claim];+ }+ return [];+}++/**+ * 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 === '') {+ throw new Error(+ `ID token is missing a non-empty "${config.OIDC_USER_REFERENCE_CLAIM}" claim (OIDC_USER_REFERENCE_CLAIM).`,+ );+ }+ return value;+}++/**+ * 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 {+ 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 {+ return {+ userRef: resolveUserRef(claims, config),+ role: resolveRole(claims, config),+ };+}++export interface AuthorizationRequestParams {+ scopes: string[];+ /** OIDC `claims` request parameter; pass through as-is. */+ claims: { id_token: Record<string, { essential: true }> };+}++/**+ * Scopes + `claims` parameter for the authorization request, derived+ * from the configured claim names. Okta's `groups` claim additionally+ * requires the `groups` scope to be requested (Okta won't return it otherwise,+ * even once mapped on the custom authorization server); Azure AD returns+ * `roles`/`groups` without a matching scope, so requesting a `groups` scope+ * there is harmless but never required.+ * `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.+ */+export function buildAuthorizationRequestParams(config: OIDCConfig): AuthorizationRequestParams {+ const scopes = ['openid', 'profile', 'email'];+ if (config.OIDC_USER_ROLE_CLAIM === 'groups') {+ scopes.push('groups');+ }++ return {+ scopes,+ claims: {+ id_token: {+ [config.OIDC_USER_REFERENCE_CLAIM]: { essential: true },+ [config.OIDC_USER_ROLE_CLAIM]: { essential: true },+ },+ },+ };+}diff --git a/packages/server/src/config.ts b/packages/server/src/config.tsindex 836cbf14b..da273474c 100644--- a/packages/server/src/config.ts+++ b/packages/server/src/config.ts@@ -36,6 +36,10 @@ const DEFAULT_POSTGRES_HOST = 'localhost';const DEFAULT_POSTGRES_PORT = 5432;const DEFAULT_REDIS_URL = 'redis://localhost:6379';+const DEFAULT_OIDC_USER_REFERENCE_CLAIM = 'sub';+const DEFAULT_OIDC_USER_ROLE_CLAIM = 'groups';+const DEFAULT_OIDC_ADMIN_ROLE_VALUE = 'admin';+// ============================================================================// HELPER FUNCTIONS// ============================================================================@@ -219,7 +223,18 @@ function resolveOIDCConfig(): OIDCConfig | undefined {'(unset = fixed local admin identity, no IdP).',);}- return { OIDC_ISSUER_URL: issuerUrl, OIDC_CLIENT_ID: clientId, OIDC_CLIENT_SECRET: clientSecret };+ return {+ OIDC_ISSUER_URL: issuerUrl,+ OIDC_CLIENT_ID: clientId,+ OIDC_CLIENT_SECRET: clientSecret,+ OIDC_USER_REFERENCE_CLAIM:+ getEnv('OIDC_USER_REFERENCE_CLAIM', { defaultValue: DEFAULT_OIDC_USER_REFERENCE_CLAIM }) ??+ DEFAULT_OIDC_USER_REFERENCE_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:+ getEnv('OIDC_ADMIN_ROLE_VALUE', { defaultValue: DEFAULT_OIDC_ADMIN_ROLE_VALUE }) ?? DEFAULT_OIDC_ADMIN_ROLE_VALUE,+ };}// ============================================================================@@ -229,10 +244,22 @@ function resolveOIDCConfig(): OIDCConfig | undefined {export interface OIDCConfig {/** e.g. an Okta custom authorization server, or an Azure AD tenant's v2.0 endpoint. Env: `OIDC_ISSUER_URL`. */OIDC_ISSUER_URL: string;- /** Env: `OIDC_CLIENT_ID`. */+ /** Client ID for the OIDC client;*/OIDC_CLIENT_ID: string;- /** Env: `OIDC_CLIENT_SECRET`. */+ /** Client secret for the OIDC client*/OIDC_CLIENT_SECRET: string;+ /** Claim to be used as the user reference; e.g. "sub" or "email"+ * Optional; defaults to "sub"+ */+ OIDC_USER_REFERENCE_CLAIM: string;+ /** Claim to be used as the user role; e.g. "role" or "groups"+ * Optional; defaults to "groups"+ */+ OIDC_USER_ROLE_CLAIM: string;+ /** Value of the user role claim that will be used to grant admin access to the server+ * Case sensitive. Optional; defaults to "admin"+ */+ OIDC_ADMIN_ROLE_VALUE: string;}export interface SharedServerConfiguration {diff --git a/packages/server/tests/unit/auth/claims.test.ts b/packages/server/tests/unit/auth/claims.test.tsnew file mode 100644index 000000000..0ab83b824--- /dev/null+++ b/packages/server/tests/unit/auth/claims.test.ts@@ -0,0 +1,139 @@+import {+ buildAuthorizationRequestParams,+ claimValues,+ resolveRole,+ resolveUserRef,+ toUserContext,+} from '../../../src/auth/claims';+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: 'harness-admins',+ ...overrides,+ };+}++describe('claimValues', () => {+ it('passes through an array of strings', () => {+ expect(claimValues(['a', 'b'])).toEqual(['a', 'b']);+ });++ it('drops non-string entries from an array', () => {+ expect(claimValues(['a', 1, null, 'b'])).toEqual(['a', 'b']);+ });++ it('wraps a bare string in a single-element array', () => {+ expect(claimValues('harness-admins')).toEqual(['harness-admins']);+ });++ it.each([undefined, null, 42, {}, true])('treats %p as no values', value => {+ expect(claimValues(value)).toEqual([]);+ });+});++describe('resolveUserRef', () => {+ it('reads the configured reference claim', () => {+ expect(resolveUserRef({ sub: 'user-123' }, config())).toBe('user-123');+ });++ it('reads a non-default reference claim when configured', () => {+ expect(resolveUserRef({ sub: 'user-123', email: '[email protected]' }, config({ OIDC_USER_REFERENCE_CLAIM: 'email' }))).toBe(+ '[email protected]',+ );+ });++ it('throws when the claim is missing', () => {+ expect(() => resolveUserRef({}, config())).toThrow(/sub/);+ });++ it('throws when the claim is an empty string', () => {+ expect(() => resolveUserRef({ sub: '' }, config())).toThrow();+ });++ it('throws when the claim is not a string', () => {+ expect(() => resolveUserRef({ sub: 12345 }, config())).toThrow();+ });+});++describe('resolveRole', () => {+ it('is admin when the role claim array includes the admin value', () => {+ expect(resolveRole({ groups: ['everyone', 'harness-admins'] }, config())).toBe('admin');+ });++ it('is user when the role claim array does not include the admin value', () => {+ expect(resolveRole({ groups: ['everyone'] }, config())).toBe('user');+ });++ it('is user when the role claim is missing entirely', () => {+ expect(resolveRole({}, config())).toBe('user');+ });++ it('is admin when the role claim is a bare string matching the admin value', () => {+ expect(resolveRole({ groups: 'harness-admins' }, config())).toBe('admin');+ });++ it('is a case-sensitive match', () => {+ expect(resolveRole({ groups: ['Harness-Admins'] }, config())).toBe('user');+ });++ it('reads a non-default role claim (e.g. Azure App Roles) when configured', () => {+ expect(+ resolveRole({ roles: ['Admin'] }, config({ OIDC_USER_ROLE_CLAIM: 'roles', OIDC_ADMIN_ROLE_VALUE: 'Admin' })),+ ).toBe('admin');+ });+});++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',+ });+ });++ it('propagates resolveUserRef throwing when the reference claim is missing', () => {+ expect(() => toUserContext({ groups: ['harness-admins'] }, config())).toThrow();+ });+});++describe('buildAuthorizationRequestParams', () => {+ it('always requests openid, profile, and email', () => {+ const { scopes } = buildAuthorizationRequestParams(config({ OIDC_USER_ROLE_CLAIM: 'roles' }));+ expect(scopes).toEqual(expect.arrayContaining(['openid', 'profile', 'email']));+ });++ it('adds the groups scope when the role claim is "groups"', () => {+ const { scopes } = buildAuthorizationRequestParams(config({ OIDC_USER_ROLE_CLAIM: 'groups' }));+ expect(scopes).toContain('groups');+ });++ it('does not add a groups scope for a non-"groups" role claim', () => {+ const { scopes } = buildAuthorizationRequestParams(config({ OIDC_USER_ROLE_CLAIM: 'roles' }));+ expect(scopes).not.toContain('groups');+ });++ it('requests both the role claim and the (default) reference claim 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 } } });+ });++ 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 } } });+ });++ it('collapses to a single essential entry when the reference and role claim names collide', () => {+ const { claims } = buildAuthorizationRequestParams(+ config({ OIDC_USER_REFERENCE_CLAIM: 'groups', OIDC_USER_ROLE_CLAIM: 'groups' }),+ );+ expect(claims).toEqual({ id_token: { groups: { essential: true } } });+ });+});