80 lines
3.5 KiB
TypeScript
80 lines
3.5 KiB
TypeScript
/**
|
|
* CL0UD workload-identity JWT verification for explicit machine routes.
|
|
* Config-driven; fail-closed when a workload token is presented but invalid.
|
|
* Tenant/capabilities come from verified claims only.
|
|
*/
|
|
import { createRemoteJWKSet, decodeJwt, jwtVerify, type JWTPayload } from 'jose';
|
|
|
|
export type WorkloadPrincipal = {
|
|
sub: string;
|
|
tenantId: string;
|
|
capabilities: string[];
|
|
claims: JWTPayload;
|
|
};
|
|
|
|
export class WorkloadVerificationError extends Error {
|
|
constructor(message: string) { super(message); this.name = 'WorkloadVerificationError'; }
|
|
}
|
|
|
|
const jwksCache = new Map<string, ReturnType<typeof createRemoteJWKSet>>();
|
|
let resolverOverride: ((protectedHeader: unknown, token: unknown) => Promise<CryptoKey | Uint8Array>) | null = null;
|
|
|
|
export function __setWorkloadKeyResolverForTests(fn: typeof resolverOverride) { resolverOverride = fn; }
|
|
export function __resetWorkloadJwksCache() { jwksCache.clear(); resolverOverride = null; }
|
|
|
|
function readEnv(name: string): string | undefined {
|
|
const v = process.env[name];
|
|
return v && v.trim() ? v.trim() : undefined;
|
|
}
|
|
|
|
export function cl0udWorkloadConfig() {
|
|
const issuer = readEnv('CL0UD_WORKLOAD_ISSUER') ?? readEnv('CL0UD_ISSUER');
|
|
const jwksUrl = readEnv('CL0UD_WORKLOAD_JWKS_URL');
|
|
const audience = readEnv('CL0UD_WORKLOAD_AUDIENCE') ?? '0pt';
|
|
const tenantClaim = readEnv('CL0UD_WORKLOAD_TENANT_CLAIM') ?? 'tenant_id';
|
|
const capabilitiesClaim = readEnv('CL0UD_WORKLOAD_CAPABILITIES_CLAIM') ?? 'capabilities';
|
|
return { issuer, jwksUrl, audience, tenantClaim, capabilitiesClaim };
|
|
}
|
|
|
|
export function isCl0udWorkloadConfigured(): boolean {
|
|
const c = cl0udWorkloadConfig();
|
|
return Boolean(c.issuer || c.jwksUrl);
|
|
}
|
|
|
|
async function getJwks(c: ReturnType<typeof cl0udWorkloadConfig>) {
|
|
if (resolverOverride) return resolverOverride;
|
|
const url = c.jwksUrl ?? (c.issuer ? `${c.issuer.replace(/\/$/, '')}/.well-known/jwks.json` : undefined);
|
|
if (!url) throw new WorkloadVerificationError('CL0UD workload JWKS URL/issuer not configured');
|
|
let jwks = jwksCache.get(url);
|
|
if (!jwks) { jwks = createRemoteJWKSet(new URL(url)); jwksCache.set(url, jwks); }
|
|
return jwks;
|
|
}
|
|
|
|
function stringArray(v: unknown): string[] {
|
|
if (Array.isArray(v)) return v.filter((x): x is string => typeof x === 'string' && x.length > 0);
|
|
if (typeof v === 'string' && v.trim()) return v.split(/[\s,]+/).filter(Boolean);
|
|
return [];
|
|
}
|
|
|
|
export async function verifyCl0udWorkloadToken(token: string): Promise<WorkloadPrincipal> {
|
|
const c = cl0udWorkloadConfig();
|
|
if (!isCl0udWorkloadConfigured()) throw new WorkloadVerificationError('CL0UD workload identity not configured');
|
|
const jwks = await getJwks(c);
|
|
const { payload } = await jwtVerify(token, jwks as any, {
|
|
...(c.issuer ? { issuer: c.issuer } : {}),
|
|
audience: c.audience,
|
|
});
|
|
const tenantId = payload[c.tenantClaim];
|
|
if (typeof tenantId !== 'string' || !tenantId) throw new WorkloadVerificationError(`missing ${c.tenantClaim} claim`);
|
|
const sub = typeof payload.sub === 'string' && payload.sub ? payload.sub : `workload:${tenantId}`;
|
|
const capabilities = stringArray(payload[c.capabilitiesClaim] ?? payload.scope);
|
|
return { sub, tenantId, capabilities, claims: payload };
|
|
}
|
|
|
|
/** Best-effort check: does this bearer look like a configured CL0UD workload token? */
|
|
export function looksLikeCl0udWorkloadToken(token: string): boolean {
|
|
const c = cl0udWorkloadConfig();
|
|
if (!c.issuer) return false;
|
|
try { return decodeJwt(token).iss === c.issuer; } catch { return false; }
|
|
}
|