diff --git a/.changeset/provider-token-claims.md b/.changeset/provider-token-claims.md new file mode 100644 index 00000000..7cc00762 --- /dev/null +++ b/.changeset/provider-token-claims.md @@ -0,0 +1,10 @@ +--- +'seamless-auth-api': minor +--- + +Let OpenID Provider tokens carry roles, permissions and custom claims (seamless-auth-oidc-provider#47). + +- `GET /oidc/accounts/:id` now returns the ADR 0004 permission claims (`permissions`, `org_roles`, `org_permissions`, or `permissions_omitted`) and `customClaims`, computed for the session and client the lookup names, with the same shared 1 KiB budget as a first-party token. An omission writes `custom_claims_omitted` with the client id. +- Custom claims for a provider token add the client's `oidc_client` set after the instance and organization role sets and before the session's `pre_token` hook claims. +- `org_id` for a provider token is now the session's active organization, while the user is still a member, instead of the user's oldest membership. This is a behavior change for provider clients that read `org_id`. +- `/oidc/sign` signs these claims only with the values it computes again for that session and client. A different value, a custom claim name it did not compute, or a permission or custom claim set carried in part is refused with the new code `claims_mismatch` (403), which the provider answers by reading the account again and retrying once. A reserved or unlisted name is still `malformed_signing_input`. Client credentials tokens still carry none of them. diff --git a/docs/adr/0005-extensibility-callouts.md b/docs/adr/0005-extensibility-callouts.md index f5a7d9ce..5489c5b4 100644 --- a/docs/adr/0005-extensibility-callouts.md +++ b/docs/adr/0005-extensibility-callouts.md @@ -136,6 +136,12 @@ They must be read back to sign, so they cannot be hashed. They are AES-256-GCM e - Separate 1 KiB budgets for permissions and custom claims did not fit the server adapter's session cookie: 5670 bytes against 4096 at both, with only about 136 bytes of custom claims fitting beside a full permission set. Brandon chose the shared budget and the order in E6 on 2026-11-07. At the shared budget the worst-case cookie measures 3868 bytes. - A set can only be written for a role or client that exists, and retiring the role or deleting the client deletes its set. - `z.json()` in the shared claim schemas overflowed the OpenAPI generator. `@seamless-auth/types` 0.40.0 describes a claim value as a union bounded at the claim depth, so the route schemas use the shared ones directly. +- Provider tokens (seamless-auth-oidc-provider#47): + - Brandon chose the scope names on 2026-11-07: `permissions` releases `roles`, `permissions`, `org_id`, `org_roles` and `org_permissions` (or `permissions_omitted`), and `custom_claims` releases every custom claim the API resolves for the user and the client. They apply to ID tokens, userinfo, and a user's access token for a resource when the grant holds the scope. `seamless` still releases `roles` and `org_id` alone. + - The API computes the claims for the session and client (`GET /oidc/accounts/:id`), with the client's set after the role sets and before the session's hook claims and the shared budget applied, and `/oidc/sign` computes them again and signs only an exact match. The edge never reads custom claim tables. + - `org_id` in a provider token is now the session's active organization, as in a first-party token, rather than the user's oldest membership. + - A role or membership can change between the edge's read and its sign. `/oidc/sign` answers that, and any other account claim that does not match, with `claims_mismatch`, a new refusal code, and the edge reads the account again and retries once. A second mismatch fails the token request with `server_error`. Brandon chose this on 2026-11-07. + - The budget is applied to everything the account has, whatever the scopes, so a client that asks only for `permissions` can see `permissions_omitted` because of custom claims it did not ask for. ## Consequences diff --git a/src/controllers/oidcEdge.ts b/src/controllers/oidcEdge.ts index 04bdc7b2..28ed64b2 100644 --- a/src/controllers/oidcEdge.ts +++ b/src/controllers/oidcEdge.ts @@ -30,11 +30,11 @@ import { OidcPayload } from '../models/oidcPayloads.js'; import { Session } from '../models/sessions.js'; import type { AuthEventType } from '../schemas/authEvent.types.js'; import { AuthEventService } from '../services/authEventService.js'; +import { getOidcAccountClaims } from '../services/oidcAccountClaims.js'; import { getOidcAuthContext, isUuid } from '../services/oidcAuthContext.js'; import { sendBackchannelLogout } from '../services/oidcBackchannelLogout.js'; import { findActiveOidcClient, - getOidcAccountClaims, getOidcClientMetadata, getOidcClientResources, verifyOidcClientSecret, @@ -200,7 +200,7 @@ export async function getOidcAccount(req: Req, res: Respons // read the claims of anyone who is not signing in through it. if (!session || session.userId !== req.params.id) return res.status(404).json(NOT_FOUND); - const claims = await getOidcAccountClaims(req.params.id); + const claims = await getOidcAccountClaims(session, clientId, { recordOmission: true }); return claims ? res.status(200).json(claims) : res.status(404).json(NOT_FOUND); } diff --git a/src/services/customClaimService.ts b/src/services/customClaimService.ts index 89cf4d2e..c15b595d 100644 --- a/src/services/customClaimService.ts +++ b/src/services/customClaimService.ts @@ -118,18 +118,21 @@ function setsFor(rows: CustomClaim[], kind: CustomClaimSourceKind, names: string /** * Instance role sets, then organization role sets (only while the membership exists), then the - * session's hook claims. A later source wins per name, and roles of one kind apply in name order, + * OpenID Provider client's set (provider tokens only), then the session's hook claims. A later + * source wins per name, and roles of one kind apply in name order, * so the result does not depend on the order roles were granted in. Reserved names are filtered * again here, whatever was stored. The token budget is applied by `authorizationClaims`. */ export async function resolveCustomClaims({ roles, organizationRoles, + clientId, hookClaims, transaction, }: { roles: string[]; organizationRoles: string[]; + clientId?: string | null; hookClaims: ClaimSet | null | undefined; transaction?: Transaction; }): Promise { @@ -138,6 +141,7 @@ export async function resolveCustomClaims({ ...(organizationRoles.length ? [{ sourceKind: 'organization_role', sourceName: { [Op.in]: organizationRoles } }] : []), + ...(clientId ? [{ sourceKind: 'oidc_client', sourceName: clientId }] : []), ]; const rows = wanted.length ? await CustomClaim.findAll({ where: { [Op.or]: wanted }, transaction }) @@ -147,6 +151,7 @@ export async function resolveCustomClaims({ for (const set of [ ...setsFor(rows, 'instance_role', roles), ...setsFor(rows, 'organization_role', organizationRoles), + ...(clientId ? setsFor(rows, 'oidc_client', [clientId]) : []), hookClaims ?? {}, ]) { for (const [name, value] of Object.entries(set)) { diff --git a/src/services/oidcAccountClaims.ts b/src/services/oidcAccountClaims.ts new file mode 100644 index 00000000..1dcb8185 --- /dev/null +++ b/src/services/oidcAccountClaims.ts @@ -0,0 +1,104 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +import type { CustomClaimSet, OidcAccountClaims } from '@seamless-auth/types'; + +import { User } from '../models/users.js'; +import { + AUTHORIZATION_CLAIMS_BUDGET_BYTES, + authorizationClaims, + resolveAuthorization, +} from './accessTokenService.js'; +import { AuthEventService } from './authEventService.js'; +import { resolveCustomClaims } from './customClaimService.js'; +import { isUuid } from './oidcAuthContext.js'; + +type ProviderSession = { + id: string; + userId: string; + organizationId?: string | null; + recovery?: boolean | null; + hookClaims?: Record | null; +}; + +/** The permission claims a provider token carries together or not at all. */ +export const PERMISSION_CLAIMS = [ + 'permissions', + 'permissions_omitted', + 'org_roles', + 'org_permissions', +] as const; + +/** + * Computed the way `mintAccessToken` computes a first-party token, plus the client's own set, + * so `/oidc/accounts/:id` and `/oidc/sign` arrive at the same values. `org_id` is the session's + * active organization, as in a first-party token. + */ +export async function getOidcAccountClaims( + session: ProviderSession, + clientId: string, + { recordOmission = false }: { recordOmission?: boolean } = {}, +): Promise { + if (!isUuid(session.userId)) return null; + + const user = await User.findOne({ where: { id: session.userId } }); + + if (!user || user.revoked) return null; + + const recovery = session.recovery === true; + const authorization = await resolveAuthorization({ + userId: user.id, + roles: user.roles, + organizationId: session.organizationId, + recovery, + }); + // The hook decided its claims for the session's organization, so they go with it. + const leftOrganization = Boolean(session.organizationId && !authorization.organizationId); + + const budgeted = authorizationClaims( + authorization, + recovery + ? {} + : await resolveCustomClaims({ + roles: user.roles ?? [], + organizationRoles: authorization.organizationRoles, + clientId, + hookClaims: leftOrganization ? null : session.hookClaims, + }), + ); + + if (recordOmission && budgeted.customClaimsOmitted) { + await AuthEventService.logContext({ + userId: user.id, + sessionId: session.id, + type: 'custom_claims_omitted', + metadata: { + bytes: budgeted.customClaimsOmitted.bytes, + budgetBytes: AUTHORIZATION_CLAIMS_BUDGET_BYTES, + clientId, + }, + }); + } + + return { + sub: user.id, + email: user.email, + email_verified: user.emailVerified === true, + ...(user.phone + ? { phone_number: user.phone, phone_number_verified: user.phoneVerified === true } + : {}), + roles: user.roles ?? [], + org_id: authorization.organizationId, + ...(recovery ? {} : budgeted.authorization), + // Every source is held to CustomClaimSetSchema when written, so the merged set is one. + customClaims: budgeted.customClaims as CustomClaimSet, + }; +} + +/** Every claim a provider token for this account may carry, by the name it is signed under. */ +export function providerTokenClaims({ customClaims, ...claims }: OidcAccountClaims) { + return { ...customClaims, ...claims } as Record; +} diff --git a/src/services/oidcClientRegistry.ts b/src/services/oidcClientRegistry.ts index adfe14ff..b137e00b 100644 --- a/src/services/oidcClientRegistry.ts +++ b/src/services/oidcClientRegistry.ts @@ -6,7 +6,6 @@ import { APPLICATION_NOTICE_SCOPE, - type OidcAccountClaims, type OidcClientMetadata, type OidcPublicJwk, oidcRedirectUriKind, @@ -21,9 +20,6 @@ import { getSystemConfig } from '../config/getSystemConfig.js'; import { OidcClientResource } from '../models/oidcClientResources.js'; import { OidcClient } from '../models/oidcClients.js'; import { OidcResource } from '../models/oidcResources.js'; -import { User } from '../models/users.js'; -import { isUuid } from './oidcAuthContext.js'; -import { getDefaultOrganizationIdForUser } from './organizationService.js'; const SHARED_SECRET_METHODS = new Set(['client_secret_basic', 'client_secret_post']); const DEVICE_CODE_GRANT = 'urn:ietf:params:oauth:grant-type:device_code'; @@ -203,23 +199,3 @@ export async function getOidcClientResourceScopes(clientId: string) { const resources = await getOidcClientResources(clientId); return new Map(resources.map((resource) => [resource.identifier, new Set(resource.scopes)])); } - -export async function getOidcAccountClaims(userId: string): Promise { - if (!isUuid(userId)) return null; - - const user = await User.findOne({ where: { id: userId } }); - - if (!user || user.revoked) return null; - - return { - sub: user.id, - email: user.email, - email_verified: user.emailVerified === true, - ...(user.phone - ? { phone_number: user.phone, phone_number_verified: user.phoneVerified === true } - : {}), - roles: user.roles ?? [], - org_id: await getDefaultOrganizationIdForUser(user.id), - customClaims: {}, - }; -} diff --git a/src/services/oidcSigning.ts b/src/services/oidcSigning.ts index 3bf6989d..d0861289 100644 --- a/src/services/oidcSigning.ts +++ b/src/services/oidcSigning.ts @@ -5,6 +5,8 @@ */ import { + CUSTOM_CLAIM_NAME_PATTERN, + isReservedClaimName, type OidcSignRefusalCode, type OidcSignRequest, seamlessBuiltInResource, @@ -15,12 +17,13 @@ import { constants, sign } from 'crypto'; import { getSystemConfig } from '../config/getSystemConfig.js'; import { Session } from '../models/sessions.js'; import { parseDurationToSeconds } from '../utils/utils.js'; -import { deriveAcrAmr, resolveCurrentSession, sessionAuthTime } from './oidcAuthContext.js'; import { - findActiveOidcClient, getOidcAccountClaims, - getOidcClientResourceScopes, -} from './oidcClientRegistry.js'; + PERMISSION_CLAIMS, + providerTokenClaims, +} from './oidcAccountClaims.js'; +import { deriveAcrAmr, resolveCurrentSession, sessionAuthTime } from './oidcAuthContext.js'; +import { findActiveOidcClient, getOidcClientResourceScopes } from './oidcClientRegistry.js'; import { hasOidcGrantForSession, recordSessionExchangeToken } from './oidcPayloadStore.js'; import { getActiveOidcSigningKey, OidcProviderKeysError } from './oidcProviderKeys.js'; @@ -79,15 +82,41 @@ const ALLOWED_CLAIMS: Record> = { ]), }; -// Released by scope, so they may be present, but only with the account's own values. -const IDENTITY_CLAIMS = [ +// Released by scope, so they may be present, but only with the values the API computes for the +// account and client. Custom claims (ADR 0005 E6) are any other name a custom claim may have. +const ACCOUNT_CLAIMS = new Set([ 'email', 'email_verified', 'phone_number', 'phone_number_verified', 'roles', 'org_id', -] as const; + ...PERMISSION_CLAIMS, +]); + +function isAccountClaimName(claim: string) { + return ( + ACCOUNT_CLAIMS.has(claim) || + (CUSTOM_CLAIM_NAME_PATTERN.test(claim) && !isReservedClaimName(claim)) + ); +} + +/** JSON equality that ignores object key order, which a JSONB round trip does not keep. */ +function canonical(value: unknown): unknown { + if (Array.isArray(value)) return value.map(canonical); + if (value && typeof value === 'object') { + return Object.fromEntries( + Object.keys(value) + .sort() + .map((key) => [key, canonical((value as JsonObject)[key])]), + ); + } + return value; +} + +function sameJson(a: unknown, b: unknown) { + return JSON.stringify(canonical(a ?? null)) === JSON.stringify(canonical(b ?? null)); +} function isSessionExchangeToken(request: OidcSignRequest, claims: JsonObject) { return request.kind === 'access_token' && scopesOf(claims).includes(SESSION_EXCHANGE_SCOPE); @@ -186,9 +215,7 @@ export async function signForOidcEdge(request: OidcSignRequest): Promise - !allowed.has(claim) && - !(allowsIdentity && (IDENTITY_CLAIMS as readonly string[]).includes(claim)), + (claim) => !allowed.has(claim) && !(allowsIdentity && isAccountClaimName(claim)), ) ) { return refuse('malformed_signing_input'); @@ -323,14 +350,10 @@ async function checkUserToken( return refuse('auth_context_mismatch', session.userId); } - if (IDENTITY_CLAIMS.some((claim) => claim in claims)) { - const account = await getOidcAccountClaims(session.userId); - const mismatch = IDENTITY_CLAIMS.some( - (claim) => - claim in claims && - JSON.stringify(claims[claim]) !== JSON.stringify(account?.[claim] ?? null), - ); - if (!account || mismatch) return refuse('subject_mismatch', session.userId); + const released = Object.keys(claims).filter((claim) => !ALLOWED_CLAIMS[request.kind].has(claim)); + if (released.length > 0) { + const refusal = await checkAccountClaims(session, client.id, claims, released); + if (refusal) return refusal; } if (request.kind === 'id_token') { @@ -351,6 +374,46 @@ async function checkUserToken( : null; } +/** + * The edge releases account claims by scope, but every value is the API's: it computes them + * again here for this session and client, the same way `/oidc/accounts/:id` did, and signs + * only what matches. A custom claim name it did not compute is one it never checked. The + * permission claims and the custom claims are each carried whole or not at all (ADR 0005 E6), + * since a partial list looks complete. Each is `claims_mismatch`: a change since the edge's + * read looks the same as a forgery, so the edge reads the account again and retries once. + */ +async function checkAccountClaims( + session: NonNullable>>, + clientId: string, + claims: JsonObject, + released: string[], +): Promise { + const account = await getOidcAccountClaims(session, clientId); + if (!account) return refuse('subject_mismatch', session.userId); + + const expected = providerTokenClaims(account); + if ( + released.some( + (claim) => + (!ACCOUNT_CLAIMS.has(claim) && !(claim in expected)) || + !sameJson(claims[claim], expected[claim]), + ) + ) { + return refuse('claims_mismatch', session.userId); + } + + const sets = [ + PERMISSION_CLAIMS.filter((claim) => claim in expected), + Object.keys(account.customClaims), + ]; + for (const set of sets) { + const carried = set.filter((claim) => claim in claims).length; + if (carried > 0 && carried < set.length) return refuse('claims_mismatch', session.userId); + } + + return null; +} + /** ADR 0003, X2: a token useful nowhere else, that lives briefly and can be told apart. */ function checkSessionExchangeToken( request: OidcSignRequest, diff --git a/tests/integration/oidc/oidcEdge.spec.ts b/tests/integration/oidc/oidcEdge.spec.ts index d47cf6aa..b48b8d54 100644 --- a/tests/integration/oidc/oidcEdge.spec.ts +++ b/tests/integration/oidc/oidcEdge.spec.ts @@ -38,6 +38,9 @@ vi.mock('../../../src/services/oidcClientRegistry.js', () => ({ getOidcClientResources: vi.fn(), getOidcClientMetadata: vi.fn(), verifyOidcClientSecret: vi.fn(), +})); + +vi.mock('../../../src/services/oidcAccountClaims.js', () => ({ getOidcAccountClaims: vi.fn(), })); @@ -53,9 +56,9 @@ import { Session } from '../../../src/models/sessions.js'; import { AuthEventService } from '../../../src/services/authEventService.js'; import { getOidcAuthContext } from '../../../src/services/oidcAuthContext.js'; import { sendBackchannelLogout } from '../../../src/services/oidcBackchannelLogout.js'; +import { getOidcAccountClaims } from '../../../src/services/oidcAccountClaims.js'; import { findActiveOidcClient, - getOidcAccountClaims, getOidcClientMetadata, getOidcClientResources, verifyOidcClientSecret, @@ -330,6 +333,19 @@ describe('POST /oidc/sign', () => { ); }); + it('answers 403 claims_mismatch, which the edge retries once', async () => { + vi.mocked(signForOidcEdge).mockResolvedValue({ + ok: false, + code: 'claims_mismatch', + userId: 'user-1', + }); + + const res = await edge('post', '/oidc/sign').send(body); + + expect(res.status).toBe(403); + expect(res.body).toEqual({ error: 'claims_mismatch' }); + }); + it('answers 400 for a malformed signing input', async () => { vi.mocked(signForOidcEdge).mockResolvedValue({ ok: false, code: 'malformed_signing_input' }); @@ -406,13 +422,24 @@ describe('keys, clients and accounts', () => { }); it('returns account claims only for the user behind a grant-bound session', async () => { - const claims = { sub: USER, roles: [], org_id: null, customClaims: {} }; + const claims = { + sub: USER, + roles: [], + org_id: 'org-1', + permissions: ['orders:read'], + org_roles: ['member'], + org_permissions: [], + customClaims: { tier: 'gold' }, + }; const path = `/oidc/accounts/${USER}?clientId=app&sessionId=${SESSION}`; - vi.mocked(findGrantBoundSession).mockResolvedValue({ id: SESSION, userId: USER } as never); + const session = { id: SESSION, userId: USER }; + vi.mocked(findGrantBoundSession).mockResolvedValue(session as never); vi.mocked(getOidcAccountClaims).mockResolvedValueOnce(claims); expect((await edge('get', path)).body).toEqual(claims); expect(findGrantBoundSession).toHaveBeenCalledWith(SESSION, 'app'); + // Computed for the session and client the lookup names, not just the user. + expect(getOidcAccountClaims).toHaveBeenCalledWith(session, 'app', { recordOmission: true }); vi.mocked(getOidcAccountClaims).mockResolvedValueOnce(null); expect((await edge('get', path)).status).toBe(404); diff --git a/tests/postgres/providerClaims.spec.ts b/tests/postgres/providerClaims.spec.ts new file mode 100644 index 00000000..091f02b5 --- /dev/null +++ b/tests/postgres/providerClaims.spec.ts @@ -0,0 +1,273 @@ +import { generateKeyPairSync, randomUUID } from 'crypto'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +import { invalidateSystemConfigCache } from '../../src/config/getSystemConfig.js'; +import { getSequelize, initializeModels } from '../../src/models/index.js'; +import { buildSystemConfig } from '../factories/systemConfigFactory.js'; + +const PROVIDER_ISSUER = 'https://login.provider-claims.test'; +const RESOURCE = 'https://orders.provider-claims.test'; +const KID = 'provider-claims-key'; +const role = `pc-role-${randomUUID().slice(0, 8)}`; +const orgRole = `pc-org-${randomUUID().slice(0, 8)}`; +const permission = `pc:${randomUUID().slice(0, 8)}`; + +const providerKey = generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey; +const savedEnv: Record = {}; + +type Models = Awaited>; +type Signing = typeof import('../../src/services/oidcSigning.js'); +type AccountClaims = typeof import('../../src/services/oidcAccountClaims.js'); +type Store = typeof import('../../src/services/oidcPayloadStore.js'); +type Claims = typeof import('../../src/services/customClaimService.js'); +type Permissions = typeof import('../../src/services/permissionService.js'); + +let models: Models; +let signing: Signing; +let accountClaims: AccountClaims; +let store: Store; +let claims: Claims; +let permissions: Permissions; + +async function setConfig(key: string, value: unknown) { + await getSequelize().query( + `INSERT INTO system_config (key, value, "createdAt", "updatedAt") + VALUES (:key, CAST(:value AS jsonb), now(), now()) + ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value`, + { replacements: { key, value: JSON.stringify(value) } }, + ); +} + +beforeAll(async () => { + for (const [key, value] of Object.entries({ + OIDC_JWKS_ACTIVE_KID: KID, + OIDC_JWKS_KEYS: JSON.stringify({ + keys: [{ ...providerKey.export({ format: 'jwk' }), kid: KID }], + }), + })) { + savedEnv[key] = process.env[key]; + process.env[key] = value; + } + + models = await initializeModels(); + for (const [key, value] of Object.entries( + buildSystemConfig({ available_roles: ['user', role] }), + )) { + await setConfig(key, value); + } + await setConfig('oidc_issuer', PROVIDER_ISSUER); + invalidateSystemConfigCache(); + + signing = await import('../../src/services/oidcSigning.js'); + accountClaims = await import('../../src/services/oidcAccountClaims.js'); + store = await import('../../src/services/oidcPayloadStore.js'); + claims = await import('../../src/services/customClaimService.js'); + permissions = await import('../../src/services/permissionService.js'); + + await permissions.createPermission(permission); + await permissions.setRolePermissions({ + kind: 'instance', + name: role, + permissions: [permission], + actorUserId: null, + }); + await permissions.createOrganizationRole({ + name: orgRole, + permissions: [permission], + actorUserId: null, + }); +}); + +afterAll(async () => { + await getSequelize().query('DELETE FROM custom_claims;'); + await setConfig('available_roles', ['user']); + await getSequelize().query(`DELETE FROM system_config WHERE key = 'oidc_issuer'`); + invalidateSystemConfigCache(); + for (const [key, value] of Object.entries(savedEnv)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + await getSequelize().close(); +}); + +/** A member signed in through the provider for a client that has its own custom claims. */ +async function providerMember() { + const { OidcClient, OidcClientResource, OidcResource, Organization, OrganizationMembership } = + models; + const userId = randomUUID(); + const user = await models.User.create({ + id: userId, + email: `${userId}@provider-claims.test`, + phone: null, + roles: [role], + }); + const organization = await Organization.create({ + name: `Acme ${userId.slice(0, 8)}`, + slug: `acme-${userId.slice(0, 8)}`, + }); + await OrganizationMembership.create({ + organizationId: organization.id, + userId, + roles: [orgRole], + }); + const client = await OidcClient.create({ + id: `pc-${randomUUID()}`, + name: 'Orders', + firstParty: true, + clientType: 'public', + tokenEndpointAuthMethod: 'none', + redirectUris: ['https://app.provider-claims.test/cb'], + grantTypes: ['authorization_code', 'refresh_token'], + }); + const resource = await OidcResource.findOne({ where: { identifier: RESOURCE } }); + const linked = + resource ?? + (await OidcResource.create({ + identifier: RESOURCE, + name: 'Orders', + scopes: ['read'], + } as never)); + await OidcClientResource.create({ + clientId: client.id, + resourceId: linked.id, + scopes: ['read'], + } as never); + + const now = Date.now(); + const session = await models.Session.create({ + userId, + organizationId: organization.id, + mode: 'server', + refreshTokenLookup: randomUUID().replaceAll('-', ''), + expiresAt: new Date(now + 3_600_000), + idleExpiresAt: new Date(now + 3_600_000), + lastUsedAt: new Date(now), + chainStartedAt: new Date(now), + hookClaims: { seats: 10 }, + }); + await store.bindOidcSession(session.id, userId, client.id); + await store.upsertOidcPayload('Grant', randomUUID(), { + payload: { accountId: userId, clientId: client.id }, + expiresIn: 3600, + sessionId: session.id, + }); + + await claims.setCustomClaimSource('instance_role', role, { plan: 'free', region: 'us' }); + await claims.setCustomClaimSource('organization_role', orgRole, { plan: 'team' }); + await claims.setCustomClaimSource('oidc_client', client.id, { + plan: 'client', + tenant: { name: 'acme', tier: 2 }, + }); + + return { user, organization, client, session }; +} + +function signingInput(header: Record, body: Record) { + const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString('base64url'); + return `${encode(header)}.${encode(body)}`; +} + +function sign( + kind: 'id_token' | 'access_token', + member: Awaited>, + extra: Record, +) { + const now = Math.floor(Date.now() / 1000); + const base = + kind === 'id_token' + ? { aud: member.client.id } + : { aud: RESOURCE, client_id: member.client.id, scope: 'read' }; + return signing.signForOidcEdge({ + kind, + kid: KID, + clientId: member.client.id, + sessionId: member.session.id, + grantType: 'authorization_code', + signingInput: signingInput( + { alg: 'RS256', kid: KID, ...(kind === 'access_token' ? { typ: 'at+jwt' } : {}) }, + JSON.parse( + JSON.stringify({ + iss: PROVIDER_ISSUER, + sub: member.user.id, + exp: now + 300, + iat: now, + ...base, + ...extra, + }), + ), + ), + }); +} + +describe('provider token claims on the deployed schema', () => { + it('computes permissions, the active organization and every custom claim source in order', async () => { + const member = await providerMember(); + + const account = await accountClaims.getOidcAccountClaims(member.session, member.client.id); + + expect(account).toMatchObject({ + sub: member.user.id, + roles: [role], + org_id: member.organization.id, + permissions: [permission], + org_roles: [orgRole], + org_permissions: [permission], + // Instance role, organization role, client, then hook. + customClaims: { plan: 'client', region: 'us', tenant: { name: 'acme', tier: 2 }, seats: 10 }, + }); + }); + + it('signs those values into ID and access tokens, and refuses forged or unlisted ones', async () => { + const member = await providerMember(); + const account = await accountClaims.getOidcAccountClaims(member.session, member.client.id); + const carried = accountClaims.providerTokenClaims(account!); + delete carried.sub; + delete carried.email; + delete carried.email_verified; + + expect((await sign('id_token', member, carried)).ok).toBe(true); + expect((await sign('access_token', member, carried)).ok).toBe(true); + + expect(await sign('id_token', member, { ...carried, plan: 'enterprise' })).toMatchObject({ + code: 'claims_mismatch', + }); + expect( + await sign('access_token', member, { ...carried, permissions: [permission, 'admin:write'] }), + ).toMatchObject({ code: 'claims_mismatch' }); + expect(await sign('id_token', member, { ...carried, is_admin: true })).toMatchObject({ + code: 'claims_mismatch', + }); + expect(await sign('id_token', member, { ...carried, act: { sub: 'x' } })).toMatchObject({ + code: 'malformed_signing_input', + }); + }); + + it('stops signing a client set that was removed, and org claims once the member leaves', async () => { + const member = await providerMember(); + const before = accountClaims.providerTokenClaims( + (await accountClaims.getOidcAccountClaims(member.session, member.client.id))!, + ); + + await claims.deleteCustomClaimSource('oidc_client', member.client.id); + // What a role or client change between the edge's read and its sign looks like. + expect(await sign('access_token', member, { tenant: before.tenant })).toMatchObject({ + code: 'claims_mismatch', + }); + + await models.OrganizationMembership.destroy({ where: { userId: member.user.id } }); + expect( + await sign('access_token', member, { + org_id: before.org_id, + permissions: before.permissions, + org_roles: before.org_roles, + org_permissions: before.org_permissions, + }), + ).toMatchObject({ code: 'claims_mismatch' }); + + const after = await accountClaims.getOidcAccountClaims(member.session, member.client.id); + expect(after).toMatchObject({ org_id: null, customClaims: { plan: 'free', region: 'us' } }); + expect(after).not.toHaveProperty('org_roles'); + // The hook's claims were decided for that organization. + expect(after?.customClaims).not.toHaveProperty('seats'); + }); +}); diff --git a/tests/unit/services/customClaimService.spec.ts b/tests/unit/services/customClaimService.spec.ts index b70211b5..f4e29a21 100644 --- a/tests/unit/services/customClaimService.spec.ts +++ b/tests/unit/services/customClaimService.spec.ts @@ -1,3 +1,4 @@ +import { Op } from 'sequelize'; import { beforeEach, describe, expect, it, vi } from 'vitest'; vi.mock('../../../src/models/oidcClients.js', () => ({ @@ -59,6 +60,39 @@ describe('resolveCustomClaims', () => { expect(resolved).toEqual({ plan: 'enterprise', region: 'us', tier: 1, seats: 5 }); }); + it('applies the OpenID Provider client after roles and before the hook', async () => { + stored( + row('instance_role', 'user', { plan: 'free', region: 'us' }), + row('organization_role', 'admin', { plan: 'team', seats: 5 }), + row('oidc_client', 'other-app', { tenant: 'other' }), + row('oidc_client', 'app', { plan: 'client', tenant: 'acme', seats: 9 }), + ); + + const resolved = await resolveCustomClaims({ + roles: ['user'], + organizationRoles: ['admin'], + clientId: 'app', + hookClaims: { seats: 10 }, + }); + + expect(resolved).toEqual({ plan: 'client', region: 'us', seats: 10, tenant: 'acme' }); + expect(CustomClaim.findAll).toHaveBeenCalledWith( + expect.objectContaining({ + where: expect.objectContaining({ + [Op.or]: expect.arrayContaining([{ sourceKind: 'oidc_client', sourceName: 'app' }]), + }), + }), + ); + }); + + it('never applies a client set to a token for no client', async () => { + stored(row('oidc_client', 'app', { tenant: 'acme' })); + + expect( + await resolveCustomClaims({ roles: ['user'], organizationRoles: [], hookClaims: null }), + ).toEqual({}); + }); + it('applies instance roles in name order, whatever order they were granted in', async () => { stored( row('instance_role', 'zeta', { plan: 'z' }), diff --git a/tests/unit/services/oidcAccountClaims.spec.ts b/tests/unit/services/oidcAccountClaims.spec.ts new file mode 100644 index 00000000..79df2694 --- /dev/null +++ b/tests/unit/services/oidcAccountClaims.spec.ts @@ -0,0 +1,167 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('../../../src/services/accessTokenService', async (importOriginal) => ({ + ...(await importOriginal()), + resolveAuthorization: vi.fn(), +})); + +vi.mock('../../../src/services/customClaimService', () => ({ + resolveCustomClaims: vi.fn(), +})); + +import { User } from '../../../src/models/users'; +import { resolveAuthorization } from '../../../src/services/accessTokenService'; +import { AuthEventService } from '../../../src/services/authEventService'; +import { resolveCustomClaims } from '../../../src/services/customClaimService'; +import { getOidcAccountClaims, providerTokenClaims } from '../../../src/services/oidcAccountClaims'; + +const USER = '11111111-1111-4111-8111-111111111111'; +const SESSION = '22222222-2222-4222-8222-222222222222'; + +const session = { + id: SESSION, + userId: USER, + organizationId: 'org-1', + recovery: false, + hookClaims: { seats: 10 }, +}; + +const member = { + roles: ['user'], + permissions: ['orders:read'], + organizationId: 'org-1', + organizationRoles: ['member'], + organizationPermissions: ['projects:read'], +}; + +function user(overrides: Record = {}) { + return { + id: USER, + email: 'a@example.com', + emailVerified: true, + phone: '+14155552671', + phoneVerified: false, + roles: ['user'], + revoked: false, + ...overrides, + }; +} + +beforeEach(() => { + vi.mocked(User.findOne).mockResolvedValue(user() as never); + vi.mocked(resolveAuthorization).mockResolvedValue(member); + vi.mocked(resolveCustomClaims).mockResolvedValue({ tier: 'gold', seats: 10 }); +}); + +describe('getOidcAccountClaims', () => { + it('returns the identity, permission and custom claims for the session and client', async () => { + expect(await getOidcAccountClaims(session, 'app')).toEqual({ + sub: USER, + email: 'a@example.com', + email_verified: true, + phone_number: '+14155552671', + phone_number_verified: false, + roles: ['user'], + org_id: 'org-1', + permissions: ['orders:read'], + org_roles: ['member'], + org_permissions: ['projects:read'], + customClaims: { tier: 'gold', seats: 10 }, + }); + expect(resolveAuthorization).toHaveBeenCalledWith({ + userId: USER, + roles: ['user'], + organizationId: 'org-1', + recovery: false, + }); + expect(resolveCustomClaims).toHaveBeenCalledWith({ + roles: ['user'], + organizationRoles: ['member'], + clientId: 'app', + hookClaims: { seats: 10 }, + }); + }); + + it("names the session's organization only while the user is still a member", async () => { + vi.mocked(resolveAuthorization).mockResolvedValue({ + ...member, + organizationId: null, + organizationRoles: [], + organizationPermissions: [], + }); + + const claims = await getOidcAccountClaims(session, 'app'); + + expect(claims).toMatchObject({ org_id: null, permissions: ['orders:read'] }); + expect(claims).not.toHaveProperty('org_roles'); + // The hook decided its claims for that organization. + expect(vi.mocked(resolveCustomClaims).mock.calls[0][0].hookClaims).toBeNull(); + }); + + it('leaves the phone out when there is none, and defaults roles', async () => { + vi.mocked(User.findOne).mockResolvedValue(user({ phone: null, roles: null }) as never); + + const claims = await getOidcAccountClaims({ ...session, organizationId: null }, 'app'); + + expect(claims).not.toHaveProperty('phone_number'); + expect(claims?.roles).toEqual([]); + }); + + it('carries no permission or custom claims for a recovery session', async () => { + vi.mocked(resolveAuthorization).mockResolvedValue({ + ...member, + permissions: [], + organizationId: null, + organizationRoles: [], + organizationPermissions: [], + }); + + const claims = await getOidcAccountClaims({ ...session, recovery: true }, 'app'); + + expect(claims).not.toHaveProperty('permissions'); + expect(claims?.customClaims).toEqual({}); + expect(resolveCustomClaims).not.toHaveBeenCalled(); + }); + + it('applies the shared budget, permissions first, and records an omission only when asked', async () => { + vi.mocked(resolveCustomClaims).mockResolvedValue({ blob: 'x'.repeat(1100) }); + + const claims = await getOidcAccountClaims(session, 'app'); + expect(claims).toMatchObject({ permissions_omitted: true, customClaims: {} }); + expect(claims).not.toHaveProperty('permissions'); + expect(AuthEventService.logContext).not.toHaveBeenCalled(); + + await getOidcAccountClaims(session, 'app', { recordOmission: true }); + expect(AuthEventService.logContext).toHaveBeenCalledWith( + expect.objectContaining({ + userId: USER, + sessionId: SESSION, + type: 'custom_claims_omitted', + metadata: expect.objectContaining({ budgetBytes: 1024, clientId: 'app' }), + }), + ); + }); + + it('returns null for a malformed id, an unknown user or a revoked one', async () => { + expect(await getOidcAccountClaims({ ...session, userId: 'nope' }, 'app')).toBeNull(); + + vi.mocked(User.findOne).mockResolvedValue(null); + expect(await getOidcAccountClaims(session, 'app')).toBeNull(); + + vi.mocked(User.findOne).mockResolvedValue(user({ revoked: true }) as never); + expect(await getOidcAccountClaims(session, 'app')).toBeNull(); + }); +}); + +describe('providerTokenClaims', () => { + it('flattens the custom claims, never over a Seamless claim', () => { + expect( + providerTokenClaims({ + sub: USER, + roles: ['user'], + org_id: null, + customClaims: { tier: 'gold', roles: ['admin'] }, + }), + ).toEqual({ sub: USER, roles: ['user'], org_id: null, tier: 'gold' }); + }); +}); diff --git a/tests/unit/services/oidcClientRegistry.spec.ts b/tests/unit/services/oidcClientRegistry.spec.ts index 0fd3462e..7e7b64b7 100644 --- a/tests/unit/services/oidcClientRegistry.spec.ts +++ b/tests/unit/services/oidcClientRegistry.spec.ts @@ -12,19 +12,13 @@ vi.mock('../../../src/models/oidcResources', () => ({ OidcResource: { findAll: vi.fn() }, })); -vi.mock('../../../src/services/organizationService', () => ({ - getDefaultOrganizationIdForUser: vi.fn(async () => 'org-1'), -})); - import { getSystemConfig } from '../../../src/config/getSystemConfig'; import { OidcClient } from '../../../src/models/oidcClients'; import { OidcClientResource } from '../../../src/models/oidcClientResources'; import { OidcResource } from '../../../src/models/oidcResources'; -import { User } from '../../../src/models/users'; import { createOidcClientSecretLookup, findActiveOidcClient, - getOidcAccountClaims, getOidcClientMetadata, getOidcClientResources, getOidcClientResourceScopes, @@ -352,52 +346,3 @@ describe('getOidcClientResources', () => { ]); }); }); - -describe('getOidcAccountClaims', () => { - it('returns the standard and Seamless claims', async () => { - vi.mocked(User.findOne).mockResolvedValue({ - id: USER, - email: 'a@example.com', - emailVerified: true, - phone: '+14155552671', - phoneVerified: false, - roles: ['user'], - revoked: false, - } as never); - - expect(await getOidcAccountClaims(USER)).toEqual({ - sub: USER, - email: 'a@example.com', - email_verified: true, - phone_number: '+14155552671', - phone_number_verified: false, - roles: ['user'], - org_id: 'org-1', - customClaims: {}, - }); - }); - - it('leaves the phone out when there is none, and defaults roles', async () => { - vi.mocked(User.findOne).mockResolvedValue({ - id: USER, - email: 'a@example.com', - emailVerified: false, - phone: null, - revoked: false, - } as never); - - const claims = await getOidcAccountClaims(USER); - expect(claims).not.toHaveProperty('phone_number'); - expect(claims?.roles).toEqual([]); - }); - - it('returns null for a malformed id, an unknown user or a revoked one', async () => { - expect(await getOidcAccountClaims('nope')).toBeNull(); - - vi.mocked(User.findOne).mockResolvedValue(null); - expect(await getOidcAccountClaims(USER)).toBeNull(); - - vi.mocked(User.findOne).mockResolvedValue({ id: USER, revoked: true } as never); - expect(await getOidcAccountClaims(USER)).toBeNull(); - }); -}); diff --git a/tests/unit/services/oidcSigning.spec.ts b/tests/unit/services/oidcSigning.spec.ts index 1bf3a7ba..6015ea64 100644 --- a/tests/unit/services/oidcSigning.spec.ts +++ b/tests/unit/services/oidcSigning.spec.ts @@ -4,10 +4,14 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; vi.mock('../../../src/services/oidcClientRegistry', () => ({ findActiveOidcClient: vi.fn(), - getOidcAccountClaims: vi.fn(), getOidcClientResourceScopes: vi.fn(), })); +vi.mock('../../../src/services/oidcAccountClaims', async (importOriginal) => ({ + ...(await importOriginal()), + getOidcAccountClaims: vi.fn(), +})); + vi.mock('../../../src/services/oidcPayloadStore', () => ({ hasOidcGrantForSession: vi.fn(), recordSessionExchangeToken: vi.fn(), @@ -25,10 +29,10 @@ vi.mock('../../../src/services/oidcProviderKeys', async (importOriginal) => ({ import { getSystemConfig } from '../../../src/config/getSystemConfig'; import { Session } from '../../../src/models/sessions'; +import { getOidcAccountClaims } from '../../../src/services/oidcAccountClaims'; import { resolveCurrentSession } from '../../../src/services/oidcAuthContext'; import { findActiveOidcClient, - getOidcAccountClaims, getOidcClientResourceScopes, } from '../../../src/services/oidcClientRegistry'; import { @@ -161,6 +165,8 @@ describe('signForOidcEdge', () => { email_verified: true, roles: ['user'], org_id: null, + permissions: [], + customClaims: {}, }); }); @@ -382,7 +388,7 @@ describe('signForOidcEdge', () => { ['other roles', { roles: ['admin'] }], ])('refuses identity claims with %s', async (_label, identity) => { expect(await signForOidcEdge(idTokenRequest(idTokenClaims(identity)))).toMatchObject({ - code: 'subject_mismatch', + code: 'claims_mismatch', }); }); @@ -394,7 +400,7 @@ describe('signForOidcEdge', () => { }); it('refuses a claim the library does not put in that token', async () => { - expect(await signForOidcEdge(idTokenRequest(idTokenClaims({ is_admin: true })))).toEqual({ + expect(await signForOidcEdge(idTokenRequest(idTokenClaims({ 'is-admin': true })))).toEqual({ ok: false, code: 'malformed_signing_input', }); @@ -404,6 +410,137 @@ describe('signForOidcEdge', () => { }); }); + describe('authorization and custom claims (seamless-auth-oidc-provider#47)', () => { + const account = { + sub: 'user-1', + email: 'a@example.com', + email_verified: true, + roles: ['user'], + org_id: 'org-1', + permissions: ['orders:read'], + org_roles: ['member'], + org_permissions: ['projects:read'], + customClaims: { tier: 'gold', limits: { seats: 5, regions: ['us', 'eu'] } }, + }; + const carried = { + roles: ['user'], + org_id: 'org-1', + permissions: ['orders:read'], + org_roles: ['member'], + org_permissions: ['projects:read'], + tier: 'gold', + limits: { seats: 5, regions: ['us', 'eu'] }, + }; + + beforeEach(() => { + vi.mocked(getOidcAccountClaims).mockResolvedValue(account); + }); + + it('signs the values the API computes for the session and client', async () => { + expect((await signForOidcEdge(idTokenRequest(idTokenClaims(carried)))).ok).toBe(true); + expect((await signForOidcEdge(accessTokenRequest(carried))).ok).toBe(true); + expect(getOidcAccountClaims).toHaveBeenCalledWith( + expect.objectContaining({ id: SESSION, userId: 'user-1' }), + 'app', + ); + }); + + it('compares custom values whatever their key order', async () => { + const reordered = { ...carried, limits: { regions: ['us', 'eu'], seats: 5 } }; + expect((await signForOidcEdge(idTokenRequest(idTokenClaims(reordered)))).ok).toBe(true); + }); + + it('signs either set alone, and neither', async () => { + const { tier: _tier, limits: _limits, ...permissionsOnly } = carried; + expect((await signForOidcEdge(idTokenRequest(idTokenClaims(permissionsOnly)))).ok).toBe(true); + const customOnly = { tier: 'gold', limits: carried.limits }; + expect((await signForOidcEdge(accessTokenRequest(customOnly))).ok).toBe(true); + expect((await signForOidcEdge(idTokenRequest())).ok).toBe(true); + }); + + it.each([ + ['a forged custom value', { tier: 'platinum' }], + ['a forged nested custom value', { limits: { seats: 500, regions: ['us', 'eu'] } }], + ['an extra permission', { permissions: ['orders:read', 'orders:write'] }], + ['another organization', { org_id: 'org-2' }], + ['raised organization roles', { org_roles: ['owner'] }], + ['the omission marker the API did not set', { permissions_omitted: true }], + ])('refuses %s', async (_label, forged) => { + expect( + await signForOidcEdge(idTokenRequest(idTokenClaims({ ...carried, ...forged }))), + ).toEqual({ ok: false, code: 'claims_mismatch', userId: 'user-1' }); + expect(await signForOidcEdge(accessTokenRequest({ ...carried, ...forged }))).toEqual({ + ok: false, + code: 'claims_mismatch', + userId: 'user-1', + }); + }); + + it('refuses a custom claim name the API did not compute', async () => { + expect( + await signForOidcEdge(idTokenRequest(idTokenClaims({ ...carried, is_admin: true }))), + ).toEqual({ ok: false, code: 'claims_mismatch', userId: 'user-1' }); + }); + + it('refuses a null value under a name the API did not compute', async () => { + expect( + await signForOidcEdge(idTokenRequest(idTokenClaims({ ...carried, is_admin: null }))), + ).toEqual({ ok: false, code: 'claims_mismatch', userId: 'user-1' }); + }); + + it.each(['act', 'may_act', 'name', 'recovery', 'seamless_admin', 'org_tier', 'Tier'])( + 'refuses the reserved or unlisted name %s before reading the account', + async (name) => { + vi.mocked(getOidcAccountClaims).mockResolvedValue({ + ...account, + customClaims: { ...account.customClaims, [name]: true }, + }); + expect(await signForOidcEdge(idTokenRequest(idTokenClaims({ [name]: true })))).toEqual({ + ok: false, + code: 'malformed_signing_input', + }); + expect(getOidcAccountClaims).not.toHaveBeenCalled(); + }, + ); + + it.each([ + ['permissions without the organization claims', { org_roles: undefined }], + ['part of the custom claims', { limits: undefined }], + ])('refuses %s, since a partial set looks complete', async (_label, dropped) => { + const claims = { ...carried, ...dropped }; + expect(await signForOidcEdge(accessTokenRequest(JSON.parse(JSON.stringify(claims))))).toEqual( + { ok: false, code: 'claims_mismatch', userId: 'user-1' }, + ); + }); + + it('signs the omission marker when the API omitted permissions, and refuses the lists', async () => { + vi.mocked(getOidcAccountClaims).mockResolvedValue({ + sub: 'user-1', + roles: ['user'], + org_id: 'org-1', + permissions_omitted: true, + customClaims: { tier: 'gold' }, + }); + expect( + (await signForOidcEdge(accessTokenRequest({ permissions_omitted: true, tier: 'gold' }))).ok, + ).toBe(true); + expect( + await signForOidcEdge(accessTokenRequest({ permissions: ['orders:read'], tier: 'gold' })), + ).toMatchObject({ code: 'claims_mismatch' }); + }); + + it('refuses custom claims on a client credentials token', async () => { + expect(await signForOidcEdge(clientCredentialsRequest({ tier: 'gold' }))).toEqual({ + ok: false, + code: 'malformed_signing_input', + }); + expect(await signForOidcEdge(clientCredentialsRequest({ permissions: [] }))).toEqual({ + ok: false, + code: 'malformed_signing_input', + }); + }); + }); + it('accepts an ID token typed JWT and refuses any other typ', async () => { expect((await signForOidcEdge(idTokenRequest(idTokenClaims(), { typ: 'JWT' }))).ok).toBe(true); expect(await signForOidcEdge(idTokenRequest(idTokenClaims(), { typ: 'logout+jwt' }))).toEqual({