The open-source agent harness - the runtime layer that turns an LLM into a working agent.
Add admin middleware (#104)
Sujai Kumar Guptae9ca6a60c88a
diff --git a/packages/server/.env.example b/packages/server/.env.exampleindex 0cf56af29..0e47efb7d 100644--- a/packages/server/.env.example+++ b/packages/server/.env.example@@ -133,3 +133,5 @@ POSTGRES_PORT=5432# OIDC_USER_ROLE_CLAIM=groups## Case-sensitive role value granting admin access. Optional; defaults to "admin".# OIDC_ADMIN_ROLE_VALUE=admin+## Comma-separated OAuth scopes for login. Optional; defaults to "openid,profile,email,groups".+# OIDC_SCOPES=openid,profile,emaildiff --git a/packages/server/src/apis/capabilities.ts b/packages/server/src/apis/capabilities.tsindex a2dc2cafd..7ff3cff67 100644--- a/packages/server/src/apis/capabilities.ts+++ b/packages/server/src/apis/capabilities.ts@@ -1,4 +1,5 @@import { OpenAPIHono } from '@hono/zod-openapi';+import { isAdmin, resolveUserContext } from '../auth/identity';import type { ISandboxProviderStore } from '../db/sandboxProviderStore';import type { WithTransaction } from '../db/transaction';import { getCapabilitiesRoute } from '../routes/capabilityRoutes';@@ -12,6 +13,7 @@ export function createCapabilitiesRouter<TTransaction>(deps: {router.openapi(getCapabilitiesRoute, async c => {const record = await deps.sandboxProviderStore.getSandboxProvider(TENANT_ID);const sandboxEnabled = record !== undefined;+ const settingsEnabled = isAdmin(resolveUserContext(c));return c.json({data: {@@ -22,7 +24,7 @@ export function createCapabilitiesRouter<TTransaction>(deps: {enabled: false,reason: 'Skills run in a sandbox, which is not configured.',},- settings: { enabled: true },+ settings: { enabled: settingsEnabled },},},200,diff --git a/packages/server/src/apis/settings.ts b/packages/server/src/apis/settings.tsindex 51782357e..19f520cfc 100644--- a/packages/server/src/apis/settings.ts+++ b/packages/server/src/apis/settings.ts@@ -1,7 +1,7 @@/*** Admin/settings API surface under /api/v1/settings.* Sub-routers (model-providers, mcp-servers, skills, sandbox-providers) mount here.- * Auth is applied at the /api/v1/settings mount boundary in app.ts.+ * Auth is applied at the /api/v1/settings mount boundary in app.ts (admin when OIDC is on).*/import { OpenAPIHono } from '@hono/zod-openapi';import type { Logger } from 'winston';diff --git a/packages/server/src/app.ts b/packages/server/src/app.tsindex 27b869b7b..f8172cac4 100644--- a/packages/server/src/app.ts+++ b/packages/server/src/app.ts@@ -19,7 +19,7 @@ import { createSettingsRouter } from './apis/settings';import { createAvailableSkillsRouter } from './apis/skills';import { createTurnsRouter } from './apis/turns';import { resolveUserContext } from './auth/identity';-import { authMiddleware } from './auth/middleware';+import { adminAuthMiddleware, authMiddleware } from './auth/middleware';import type { McpCatalog } from './catalog/McpCatalog';import type { ModelCatalog } from './catalog/ModelCatalog';import type { SandboxCatalog } from './catalog/SandboxCatalog';@@ -62,6 +62,14 @@ function withAuth(router: OpenAPIHono): OpenAPIHono {return shell;}+/** Admin-only routes: standalone passes through; 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;@@ -158,7 +166,7 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {);app.route('/api/v1/settings',- withAuth(+ withAdminAuth(createSettingsRouter({modelCatalog: deps.modelCatalog,modelProviderStore: deps.modelProviderStore,diff --git a/packages/server/src/auth/claims.ts b/packages/server/src/auth/claims.tsindex 440a4fad1..1791d2007 100644--- a/packages/server/src/auth/claims.ts+++ b/packages/server/src/auth/claims.ts@@ -60,24 +60,15 @@ export interface AuthorizationRequestParams {/*** 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.+ * 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.*/export function buildAuthorizationRequestParams(config: OIDCConfig): AuthorizationRequestParams {- const scopes = ['openid', 'profile', 'email'];- if (config.OIDC_USER_ROLE_CLAIM === 'groups') {- scopes.push('groups');- }-return {- scopes,+ scopes: config.OIDC_SCOPES,claims: {id_token: {[config.OIDC_USER_REFERENCE_CLAIM]: { essential: true },diff --git a/packages/server/src/auth/identity.ts b/packages/server/src/auth/identity.tsindex d1bace889..1aa98eed1 100644--- a/packages/server/src/auth/identity.ts+++ b/packages/server/src/auth/identity.ts@@ -1,4 +1,5 @@import type { Context } from 'hono';+import { getOidcVerify } from './oidc';export type Role = 'admin' | 'user';@@ -16,6 +17,14 @@ export const LOCAL_USER_CONTEXT: UserContext = {role: 'admin',};+/** Standalone/no IdP: always true. With OIDC: admin role only. */+export function isAdmin(user: UserContext): boolean {+ if (!getOidcVerify()) {+ return true;+ }+ return user.role === 'admin';+}+/** Resolves the caller identity from the request context. Injected on session/turn routers. */export type ResolveUserContext = (c: Context) => UserContext;diff --git a/packages/server/src/auth/middleware.ts b/packages/server/src/auth/middleware.tsindex 10fbd4563..e6f6f3485 100644--- a/packages/server/src/auth/middleware.ts+++ b/packages/server/src/auth/middleware.ts@@ -3,7 +3,7 @@ import { HTTPException } from 'hono/http-exception';import { jwtVerify } from 'jose';import { toUserContext, type IdTokenClaims } from './claims';import { readIdTokenCookie } from './cookies';-import { LOCAL_USER_CONTEXT, type UserContext } from './identity';+import { LOCAL_USER_CONTEXT, isAdmin, type UserContext } from './identity';import { getOidcVerify } from './oidc';declare module 'hono' {@@ -63,3 +63,28 @@ export const authMiddleware: MiddlewareHandler = async (c, next) => {}return next();};++/** Standalone admin gate: no-op without OIDC; with OIDC requires an authenticated admin. */+export const adminAuthMiddleware: MiddlewareHandler = async (c, next) => {+ if (!getOidcVerify()) {+ 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/server/src/auth/oidc.ts b/packages/server/src/auth/oidc.tsindex 0fc688ffe..1b2f4433a 100644--- a/packages/server/src/auth/oidc.ts+++ b/packages/server/src/auth/oidc.ts@@ -10,13 +10,12 @@ import {randomState,} from 'openid-client';import configuration, { type OIDCConfig } from '../config';+import { buildAuthorizationRequestParams } from './claims';import { ID_TOKEN_COOKIE, OAUTH_STATE_COOKIE, setAuthCookie } from './cookies';const CALLBACK_PATH = '/api/v1/auth/callback';const OAUTH_STATE_MAX_AGE_SECONDS = 10 * 60;const ID_TOKEN_COOKIE_MAX_AGE_SECONDS = 24 * 60 * 60;-// TODO: use dynamic claims/scopes when we add RBAC-const OIDC_SCOPES = 'openid email profile';/** JWKS + claim config used by cookie JWT verification when browser OIDC is on. */export interface OidcVerify {@@ -90,12 +89,21 @@ export async function buildLoginAuthorization(params: {client: Configuration;returnTo: string | undefined;}): Promise<string> {+ const oidcConfig = getOidcVerify()?.oidcConfig;+ if (!oidcConfig) {+ throw new Error(+ 'OIDC claim configuration is unavailable; call initOidc before building a login authorization URL.',+ );+ }++ const { scopes, claims } = buildAuthorizationRequestParams(oidcConfig);const returnTo = safeReturnTo(params.returnTo);const codeVerifier = randomPKCECodeVerifier();const state = randomState();const authorizationUrl = buildAuthorizationUrl(params.client, {redirect_uri: authCallbackUrl(),- scope: OIDC_SCOPES,+ scope: scopes.join(' '),+ claims: JSON.stringify(claims),code_challenge: await calculatePKCECodeChallenge(codeVerifier),code_challenge_method: 'S256',state,diff --git a/packages/server/src/config.ts b/packages/server/src/config.tsindex a5a396070..1542521ba 100644--- a/packages/server/src/config.ts+++ b/packages/server/src/config.ts@@ -39,6 +39,7 @@ 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';+const DEFAULT_OIDC_SCOPES = 'openid,profile,email';// ============================================================================// HELPER FUNCTIONS@@ -82,6 +83,17 @@ function parsePort(raw: string | undefined): number {return port;}+export function parseOidcScopes(raw: string): string[] {+ const scopes = raw+ .split(',')+ .map(part => part.trim())+ .filter(part => part.length > 0);+ if (scopes.length === 0) {+ throw new Error('OIDC_SCOPES must contain at least one scope.');+ }+ return scopes;+}+/** 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;@@ -234,6 +246,7 @@ function resolveOIDCConfig(): OIDCConfig | undefined {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,+ OIDC_SCOPES: parseOidcScopes(getEnv('OIDC_SCOPES', { defaultValue: DEFAULT_OIDC_SCOPES }) ?? DEFAULT_OIDC_SCOPES),};}@@ -260,6 +273,11 @@ export interface OIDCConfig {* Case sensitive. Optional; defaults to "admin"*/OIDC_ADMIN_ROLE_VALUE: string;+ /** Comma-separated OAuth scopes for the authorization request. Env: `OIDC_SCOPES`.+ * Optional; defaults to "openid,profile,email,groups". Whitespace around entries is stripped.+ * Okta `groups` claims require the `groups` scope; Azure AD app roles typically omit it.+ */+ OIDC_SCOPES: string[];}export interface SharedServerConfiguration {diff --git a/packages/server/tests/unit/apis/auth.test.ts b/packages/server/tests/unit/apis/auth.test.tsindex 26f35349b..422d60257 100644--- a/packages/server/tests/unit/apis/auth.test.ts+++ b/packages/server/tests/unit/apis/auth.test.ts@@ -15,6 +15,7 @@ jest.mock('../../../src/config', () => {OIDC_USER_REFERENCE_CLAIM: 'sub',OIDC_USER_ROLE_CLAIM: 'groups',OIDC_ADMIN_ROLE_VALUE: 'admin',+ OIDC_SCOPES: ['openid', 'profile', 'email', 'groups'],};return {__esModule: true,@@ -200,9 +201,40 @@ describe('auth router (OIDC configured)', () => {expect(authUrl.searchParams.get('client_id')).toBe(CLIENT_ID);expect(authUrl.searchParams.get('redirect_uri')).toBe('https://harness.example.com/api/v1/auth/callback');expect(authUrl.searchParams.get('code_challenge_method')).toBe('S256');+ expect(authUrl.searchParams.get('scope')?.split(' ')).toEqual(+ expect.arrayContaining(['openid', 'profile', 'email', 'groups']),+ );+ expect(JSON.parse(authUrl.searchParams.get('claims') ?? '{}')).toEqual({+ id_token: { sub: { essential: true }, groups: { essential: true } },+ });expect(cookieValue(setCookies(res), STATE_COOKIE)).toBeTruthy();});+ it('GET /login requests roles claim without groups scope when OIDC_USER_ROLE_CLAIM=roles', async () => {+ const rolesOidcClient = await initOidc({+ ...configuredOidc,+ OIDC_USER_ROLE_CLAIM: 'roles',+ OIDC_SCOPES: ['openid', 'profile', 'email'],+ });+ if (!rolesOidcClient) {+ throw new Error('OIDC client was not initialized');+ }++ const res = await createAuthRouter({ oidcClient: rolesOidcClient, logger }).request('/login', {+ redirect: 'manual',+ });++ expect(res.status).toBe(302);+ const authUrl = new URL(res.headers.get('location') ?? '');+ expect(authUrl.searchParams.get('scope')?.split(' ')).toEqual(+ expect.arrayContaining(['openid', 'profile', 'email']),+ );+ expect(authUrl.searchParams.get('scope')?.split(' ')).not.toContain('groups');+ expect(JSON.parse(authUrl.searchParams.get('claims') ?? '{}')).toEqual({+ id_token: { sub: { essential: true }, roles: { essential: true } },+ });+ });+// `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 });diff --git a/packages/server/tests/unit/apis/capabilities.test.ts b/packages/server/tests/unit/apis/capabilities.test.tsindex b1f4907af..5c4a067df 100644--- a/packages/server/tests/unit/apis/capabilities.test.ts+++ b/packages/server/tests/unit/apis/capabilities.test.ts@@ -1,17 +1,53 @@+import { OpenAPIHono } from '@hono/zod-openapi';+import { exportJWK, generateKeyPair, SignJWT } from 'jose';+import type { Configuration } from 'openid-client';import { createCapabilitiesRouter } from '../../../src/apis/capabilities';+import { authMiddleware } from '../../../src/auth/middleware';+import { disableOidcAuth, enableOidcAuth, initOidc } from '../../../src/auth/oidc';+import type { OIDCConfig } from '../../../src/config';import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';import { createSqliteDb } from '../../../src/db/sqlite/client';import { SqliteSandboxProviderStore } from '../../../src/db/sqlite/sandbox-provider-store/SqliteSandboxProviderStore';+const ISSUER = 'https://issuer.example.com';+const AUDIENCE = 'harness-client';++const OIDC_CONFIG: OIDCConfig = {+ OIDC_ISSUER_URL: `${ISSUER}/`,+ OIDC_CLIENT_ID: AUDIENCE,+ 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'],+};++function json(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { 'Content-Type': 'application/json' },+ });+}++function withAuth(router: OpenAPIHono): OpenAPIHono {+ const shell = new OpenAPIHono();+ shell.use('*', authMiddleware);+ shell.route('/', router);+ return shell;+}+describe('capabilities routers', () => {it('capabilities derive sandbox and skill from the store', async () => {+ disableOidcAuth();const db = createSqliteDb(':memory:');await migrateSqliteToLatest(db);const store = new SqliteSandboxProviderStore(db);- const router = createCapabilitiesRouter({- sandboxProviderStore: store,- withTransaction: callback => db.transaction().execute(callback),- });+ const router = withAuth(+ createCapabilitiesRouter({+ sandboxProviderStore: store,+ withTransaction: callback => db.transaction().execute(callback),+ }),+ );const empty = await router.request('/');expect(empty.status).toBe(200);@@ -49,4 +85,87 @@ describe('capabilities routers', () => {},});});++ describe('when OIDC is configured', () => {+ const realFetch = globalThis.fetch;+ let privateKey: Awaited<ReturnType<typeof generateKeyPair>>['privateKey'];+ let oidcClient: Configuration;++ beforeAll(async () => {+ const keyPair = await generateKeyPair('RS256');+ privateKey = keyPair.privateKey;+ const publicJwk = await exportJWK(keyPair.publicKey);+ publicJwk.kid = 'test-kid';+ publicJwk.alg = 'RS256';+ publicJwk.use = 'sig';++ globalThis.fetch = async input => {+ const url = String(input);+ if (url === `${ISSUER}/.well-known/openid-configuration`) {+ return json({+ issuer: ISSUER,+ authorization_endpoint: `${ISSUER}/authorize`,+ token_endpoint: `${ISSUER}/token`,+ jwks_uri: `${ISSUER}/jwks`,+ response_types_supported: ['code'],+ id_token_signing_alg_values_supported: ['RS256'],+ subject_types_supported: ['public'],+ });+ }+ if (url === `${ISSUER}/jwks`) {+ return json({ keys: [publicJwk] });+ }+ return new Response(`unexpected url: ${url}`, { status: 404 });+ };++ const client = await initOidc(OIDC_CONFIG);+ if (!client) {+ throw new Error('OIDC client was not initialized');+ }+ oidcClient = client;+ });++ afterAll(() => {+ globalThis.fetch = realFetch;+ disableOidcAuth();+ });++ beforeEach(() => {+ enableOidcAuth({ client: oidcClient, oidcConfig: OIDC_CONFIG });+ });++ async function createIdToken(groups: string[]): Promise<string> {+ return new SignJWT({ groups })+ .setProtectedHeader({ alg: 'RS256', kid: 'test-kid' })+ .setIssuer(ISSUER)+ .setAudience(AUDIENCE)+ .setSubject('user-1')+ .setIssuedAt()+ .setExpirationTime('1h')+ .sign(privateKey);+ }++ it('marks settings enabled for admin callers and disabled for non-admin callers', async () => {+ const db = createSqliteDb(':memory:');+ await migrateSqliteToLatest(db);+ const router = withAuth(+ createCapabilitiesRouter({+ sandboxProviderStore: new SqliteSandboxProviderStore(db),+ withTransaction: callback => db.transaction().execute(callback),+ }),+ );++ const adminRes = await router.request('/', {+ headers: { Cookie: `id_token=${await createIdToken(['admin'])}` },+ });+ expect(adminRes.status).toBe(200);+ expect((await adminRes.json()).data.settings).toEqual({ enabled: true });++ const userRes = await router.request('/', {+ headers: { Cookie: `id_token=${await createIdToken(['everyone'])}` },+ });+ expect(userRes.status).toBe(200);+ expect((await userRes.json()).data.settings).toEqual({ enabled: false });+ });+ });});diff --git a/packages/server/tests/unit/auth/claims.test.ts b/packages/server/tests/unit/auth/claims.test.tsindex 0ab83b824..edf8d7bce 100644--- a/packages/server/tests/unit/auth/claims.test.ts+++ b/packages/server/tests/unit/auth/claims.test.ts@@ -15,6 +15,7 @@ function config(overrides: Partial<OIDCConfig> = {}): OIDCConfig {OIDC_USER_REFERENCE_CLAIM: 'sub',OIDC_USER_ROLE_CLAIM: 'groups',OIDC_ADMIN_ROLE_VALUE: 'harness-admins',+ OIDC_SCOPES: ['openid', 'profile', 'email', 'groups'],...overrides,};}@@ -103,19 +104,16 @@ describe('toUserContext', () => {});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('requests configured scopes', () => {+ const { scopes } = buildAuthorizationRequestParams(+ config({ OIDC_SCOPES: ['openid', 'profile', 'email', 'offline_access'] }),+ );+ expect(scopes).toEqual(['openid', 'profile', 'email', 'offline_access']);});- 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('defaults to openid, profile, email, and groups', () => {+ const { scopes } = buildAuthorizationRequestParams(config());+ expect(scopes).toEqual(['openid', 'profile', 'email', 'groups']);});it('requests both the role claim and the (default) reference claim as essential in the id_token', () => {diff --git a/packages/server/tests/unit/auth/identity.test.ts b/packages/server/tests/unit/auth/identity.test.tsindex 2f6422bc3..98c56452f 100644--- a/packages/server/tests/unit/auth/identity.test.ts+++ b/packages/server/tests/unit/auth/identity.test.ts@@ -1,18 +1,49 @@-import type { Context } from 'hono';-import { LOCAL_USER_CONTEXT, resolveUserContext } from '../../../src/auth/identity';+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';-describe('resolveUserContext', () => {- it('returns the user set on the request context', () => {- const c = {- get: (key: string) => (key === 'user_context' ? LOCAL_USER_CONTEXT : undefined),- } as unknown as Context;- expect(resolveUserContext(c)).toEqual(LOCAL_USER_CONTEXT);+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'],+};++function user(role: UserContext['role']): UserContext {+ return { userRef: 'alice', role };+}++describe('isAdmin', () => {+ afterEach(() => {+ disableOidcAuth();+ });++ it('is always true without OIDC (standalone)', () => {+ disableOidcAuth();+ expect(isAdmin(user('user'))).toBe(true);+ expect(isAdmin(LOCAL_USER_CONTEXT)).toBe(true);});- it('throws when auth middleware did not set user', () => {- const c = {- get: () => undefined,- } as unknown as Context;- expect(() => resolveUserContext(c)).toThrow('UserContext missing; auth middleware did not run');+ it('checks role when OIDC is configured', 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 client = await initOidc(OIDC_CONFIG);+ if (!client) {+ throw new Error('OIDC client was not initialized');+ }+ enableOidcAuth({ client, oidcConfig: OIDC_CONFIG });++ expect(isAdmin(user('admin'))).toBe(true);+ expect(isAdmin(user('user'))).toBe(false);});});diff --git a/packages/server/tests/unit/auth/middleware.test.ts b/packages/server/tests/unit/auth/middleware.test.tsindex 61abb57f3..0884a636b 100644--- a/packages/server/tests/unit/auth/middleware.test.ts+++ b/packages/server/tests/unit/auth/middleware.test.ts@@ -2,7 +2,7 @@ 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 { authMiddleware } from '../../../src/auth/middleware';+import { adminAuthMiddleware, authMiddleware } from '../../../src/auth/middleware';import { disableOidcAuth, enableOidcAuth, initOidc } from '../../../src/auth/oidc';import type { OIDCConfig } from '../../../src/config';@@ -16,6 +16,7 @@ const OIDC_CONFIG: OIDCConfig = {OIDC_USER_REFERENCE_CLAIM: 'sub',OIDC_USER_ROLE_CLAIM: 'groups',OIDC_ADMIN_ROLE_VALUE: 'admin',+ OIDC_SCOPES: ['openid', 'profile', 'email', 'groups'],};function json(body: unknown, status = 200): Response {@@ -46,10 +47,25 @@ function createApp() {models.get('/', c => c.json({ ok: true, user: c.get('user_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') }));+ app.route('/api/v1/settings', settings);+return app;}describe('authMiddleware', () => {+ it('allows settings without admin role when OIDC is not configured', async () => {+ disableOidcAuth();+ const res = await createApp().request('/api/v1/settings');+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({+ ok: true,+ user: undefined,+ });+ });+it('sets default user when OIDC is not configured', async () => {disableOidcAuth();const res = await createApp().request('/api/v1/models');@@ -178,6 +194,27 @@ describe('authMiddleware', () => {});});+ 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', {+ headers: { Cookie: `id_token=${token}` },+ });+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({+ ok: true,+ user: { userRef: 'alice', role: 'admin' },+ });+ });++ 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', {+ headers: { Cookie: `id_token=${token}` },+ });+ expect(res.status).toBe(403);+ expect(await res.json()).toEqual({ error: { message: 'Admin access required' } });+ });+it.each(['/healthz','/api/v1/auth/login',diff --git a/packages/server/tests/unit/config/parseOidcScopes.test.ts b/packages/server/tests/unit/config/parseOidcScopes.test.tsnew file mode 100644index 000000000..aad24fa4b--- /dev/null+++ b/packages/server/tests/unit/config/parseOidcScopes.test.ts@@ -0,0 +1,11 @@+import { parseOidcScopes } from '../../../src/config';++describe('parseOidcScopes', () => {+ it('splits on commas and trims whitespace', () => {+ expect(parseOidcScopes('openid, profile , email,groups')).toEqual(['openid', 'profile', 'email', 'groups']);+ });++ it('throws when no scopes remain after parsing', () => {+ expect(() => parseOidcScopes(' , , ')).toThrow(/OIDC_SCOPES must contain at least one scope/);+ });+});