/** * `0pt/auth/zitadel.ts` -- self-contained Zitadel (OIDC) Bearer JWT * verification for 0pt. * * ========================================================================== * Wave 2 foundational hardening: REAL cryptographic verification that closes * the "no signature verification at all" hole (0pt's API layer historically * trusted an X-Tenant-Id header and NEVER verified the Bearer token). This * mirrors the canonical implementation already shipped on the n0d/aud0/api0/ * inf0 hardening branches. It is intentionally self-contained (no dependency * on @siax/capability-registry, which is not consumable cross-repo) and * depends only on `jose` + the platform's global `fetch`. * * ISSUER / JWKS DISCOVERY * ---------------------- * The fleet IdP is Zitadel at ZITADEL_ISSUER (default * https://id-customers.siax.io). Signing keys are resolved by: * 1. Fetching `/.well-known/openid-configuration` and reading its * `jwks_uri` (the spec-correct OIDC discovery path). * 2. Falling back to `/oauth/v2/keys` (Zitadel's well-known JWKS * endpoint) if discovery is unavailable. * The resolved JWKS is wrapped in jose's `createRemoteJWKSet`, which caches * keys and refreshes on an unknown `kid`; the resolver is additionally cached * per-issuer for the process lifetime. * * TENANT CLAIM DERIVATION (documented precedence) * ----------------------------------------------- * `deriveTenantId` maps a verified token to a SIAX tenant id with this * precedence (overridable via ZITADEL_TENANT_CLAIM, which -- when set and * present on the token -- wins outright): * 1. `urn:zitadel:iam:org:id` -- Zitadel's standard * organization-id claim; * 0pt's tenant boundary * maps 1:1 to a Zitadel org. * 2. `urn:zitadel:iam:user:resourceowner:id` -- the user's resource-owner * org id (present on some * token profiles). * 3. `tenant_id` -- an explicit custom claim, * if a Zitadel action/mapper * injects the SIAX tenant * slug directly. * 4. `tenant` -- a looser custom fallback. * A signed-but-tenantless token is not usable here and fails verification. */ import { createRemoteJWKSet, decodeJwt, jwtVerify, type JWTPayload, type JWTVerifyGetKey, } from 'jose'; import { normalizeZitadelClaims, ZitadelClaimError } from '@siax/auth-zitadel'; /** Default fleet Zitadel issuer (OIDC). Overridable via ZITADEL_ISSUER. */ export const DEFAULT_ZITADEL_ISSUER = 'https://id-customers.siax.io'; /** Central Keycloak (SIAX Portal) trust; additive, unset keeps legacy behaviour. */ export function keycloakIssuer(): string | undefined { const raw = process.env.KEYCLOAK_ISSUER?.trim().replace(/\/+$/, ''); return raw && raw.length > 0 ? raw : undefined; } export function keycloakAudiences(): string[] { const raw = process.env.KEYCLOAK_EXPECTED_AUDIENCE?.trim(); if (!raw) return ['account']; const list = raw.split(',').map((s) => s.trim()).filter((s) => s.length > 0); return list.length > 0 ? list : ['account']; } export function keycloakAuthorizedParty(): string | undefined { const raw = process.env.KEYCLOAK_AUTHORIZED_PARTY?.trim(); return raw && raw.length > 0 ? raw : undefined; } function tokenIssuerUnsafe(token: string): string | undefined { try { const iss = decodeJwt(token).iss; return typeof iss === 'string' ? iss : undefined; } catch { return undefined; } } /** Standard + custom claim paths tenant derivation reads, in precedence order. */ export const ZITADEL_ORG_ID_CLAIM = 'urn:zitadel:iam:org:id'; export const ZITADEL_RESOURCEOWNER_CLAIM = 'urn:zitadel:iam:user:resourceowner:id'; export const TENANT_ID_CLAIM = 'tenant_id'; export const TENANT_CLAIM = 'tenant'; /** Ordered claim keys checked by {@link deriveTenantId} (after any override). */ export const TENANT_CLAIM_PRECEDENCE = [ ZITADEL_ORG_ID_CLAIM, ZITADEL_RESOURCEOWNER_CLAIM, TENANT_ID_CLAIM, TENANT_CLAIM, ] as const; /** Resolve the configured issuer, trimming and falling back to the default. */ export function zitadelIssuer(): string { const fromEnv = process.env.ZITADEL_ISSUER?.trim(); return fromEnv && fromEnv.length > 0 ? fromEnv : DEFAULT_ZITADEL_ISSUER; } /** The env-configured tenant-claim override, if any (ZITADEL_TENANT_CLAIM). */ export function tenantClaimOverride(): string | undefined { const v = process.env.ZITADEL_TENANT_CLAIM?.trim(); return v && v.length > 0 ? v : undefined; } /** A verified caller principal derived from a valid Zitadel access/ID token. */ export interface VerifiedPrincipal { /** The token subject (`sub`) -- the authenticated actor id. */ sub: string; /** The SIAX tenant id derived from the token (see deriveTenantId). */ tenantId: string; /** The full verified JWT payload, for any additional downstream claims. */ claims: JWTPayload; } /** Thrown by {@link verifyBearer} on any verification/derivation failure. */ export class BearerVerificationError extends Error { readonly reason: string; readonly cause?: unknown; constructor(reason: string, cause?: unknown) { super(reason); this.name = 'BearerVerificationError'; this.reason = reason; this.cause = cause; } } function claimAsString(claims: JWTPayload, key: string): string | undefined { const v = claims[key]; return typeof v === 'string' && v.length > 0 ? v : undefined; } /** * Map a verified JWT payload to a SIAX tenant id (documented precedence above). * @param override an explicit claim key to try first (ZITADEL_TENANT_CLAIM). */ export function deriveTenantId(claims: JWTPayload, override = tenantClaimOverride()): string | undefined { if (override) { const fromOverride = claimAsString(claims, override); if (fromOverride) return fromOverride; } for (const key of TENANT_CLAIM_PRECEDENCE) { const v = claimAsString(claims, key); if (v) return v; } return undefined; } // --- JWKS resolution -------------------------------------------------------- const jwksCache = new Map(); // Test seam: an injected resolver bypasses remote discovery entirely. let keyResolverOverride: JWTVerifyGetKey | undefined; /** * TEST SEAM: inject a JWKS resolver (e.g. jose `createLocalJWKSet`) so unit * tests can verify locally-signed tokens without any network access. Pass * `undefined` to clear. */ export function __setKeyResolverForTests(resolver: JWTVerifyGetKey | undefined): void { keyResolverOverride = resolver; } /** TEST SEAM: clear the per-issuer remote-JWKS cache. */ export function __resetJwksCache(): void { jwksCache.clear(); } function stripTrailingSlash(url: string): string { return url.replace(/\/+$/, ''); } async function resolveJwksUri(issuer: string): Promise { const base = stripTrailingSlash(issuer); const wellKnown = `${base}/.well-known/openid-configuration`; try { const res = await fetch(wellKnown); if (res.ok) { const cfg = (await res.json()) as { jwks_uri?: unknown }; if (typeof cfg.jwks_uri === 'string' && cfg.jwks_uri.length > 0) { return cfg.jwks_uri; } } } catch { // fall through to the Zitadel default keys endpoint } return `${base}/oauth/v2/keys`; } async function getRemoteJwks(issuer: string): Promise { const cached = jwksCache.get(issuer); if (cached) return cached; const uri = await resolveJwksUri(issuer); const resolver = createRemoteJWKSet(new URL(uri)); jwksCache.set(issuer, resolver); return resolver; } export interface VerifyBearerOptions { /** Override the issuer (default: {@link zitadelIssuer}). */ issuer?: string; /** Override the key resolver (test seam; default: remote JWKS for issuer). */ keyResolver?: JWTVerifyGetKey; /** Override the tenant-claim key (default: {@link tenantClaimOverride}). */ tenantClaim?: string; } /** * Verify a raw Bearer token string against Zitadel: checks the RS/ES * signature (via JWKS), the `iss` claim, and `exp`/`nbf` (jose enforces * expiry automatically), then derives the tenant id. Returns a * {@link VerifiedPrincipal} or throws {@link BearerVerificationError}. */ export async function verifyBearer( token: string, opts: VerifyBearerOptions = {}, ): Promise { // Central Keycloak (SIAX Portal) user tokens, routed by issuer. const kcIssuer = keycloakIssuer(); if (kcIssuer !== undefined && tokenIssuerUnsafe(token) === kcIssuer) { const resolver = opts.keyResolver ?? keyResolverOverride ?? (await getRemoteJwks(kcIssuer)); let payload: JWTPayload; try { ({ payload } = await jwtVerify(token, resolver, { issuer: kcIssuer, audience: keycloakAudiences(), })); } catch (err) { throw new BearerVerificationError('keycloak_token_verification_failed', err); } const azp = typeof payload.azp === 'string' ? payload.azp : ''; const expectedAzp = keycloakAuthorizedParty(); if (expectedAzp !== undefined && azp !== expectedAzp) { throw new BearerVerificationError('keycloak_azp_mismatch'); } const sub = typeof payload.sub === 'string' ? payload.sub : undefined; if (!sub) throw new BearerVerificationError('token_missing_sub'); const tenantId = deriveTenantId(payload, opts.tenantClaim ?? tenantClaimOverride()); if (!tenantId) throw new BearerVerificationError('token_missing_tenant_claim'); return { sub, tenantId, claims: payload }; } const issuer = opts.issuer ?? zitadelIssuer(); const resolver = opts.keyResolver ?? keyResolverOverride ?? (await getRemoteJwks(issuer)); let payload: JWTPayload; try { const result = await jwtVerify(token, resolver, { issuer }); payload = result.payload; } catch (err) { throw new BearerVerificationError('token_verification_failed', err); } try { const identity = normalizeZitadelClaims(payload, { source: 'jwt', tenantClaim: opts.tenantClaim ?? tenantClaimOverride(), }); return { sub: identity.principal.subject, tenantId: identity.tenant.tenantId, claims: payload, }; } catch (err) { if (err instanceof ZitadelClaimError) { if (/sub/i.test(err.reason)) { throw new BearerVerificationError('token_missing_sub'); } if (/tenant/i.test(err.reason)) { throw new BearerVerificationError('token_missing_tenant_claim'); } if (/aud/i.test(err.reason)) { throw new BearerVerificationError('token_invalid_audience'); } throw new BearerVerificationError('token_verification_failed', err); } throw err; } }