feat(auth): dual-accept CL0UD workload identity on the machine routes
CI (SIAX Cloud) / sonar (pull_request) Skipped
masterplan-lock / check (pull_request) Successful in 7s
masterplan-lock / check (push) Successful in 7s
CI (SIAX Cloud) / Component conformance (blocking) (pull_request) Successful in 13s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 17s
CI (SIAX Cloud) / security (pull_request) Successful in 18s
CI (SIAX Cloud) / integration (pull_request) Successful in 27s
CI (SIAX Cloud) / quality (pull_request) Successful in 10m5s

The internal machine routes (`quality/bridge-run`, `canonical/facts`,
`internal/evidence-outbox/dispatch`, `internal/er/candidates`,
`search/definitions`) trusted a shared `X-Internal-Token` with NO tenant
authority: middleware let it through without setting any verified tenant, so
`assertTenantMatchesVerified` was a no-op and a caller-chosen `tenant_id` in
the body was authoritative.

This closes that gap while keeping the engine working during the transition
to CL0UD workload tokens:

- `src/auth/internal-service-tenant.ts` — the server-configured
  `INTERNAL_SERVICE_TENANTS` scope, a scope header that only middleware may
  set, and a parser that strips/ignores client values.
- `src/auth/cl0ud-workload.ts` — a real `jose`/JWKS verifier for CL0UD
  workload JWTs (`iss`/`aud`/`exp`), deriving `tenant_id` and `capabilities`
  from verified claims only. Fail-closed when a token is presented but the
  issuer/JWKS/audience/tenant claim does not verify.
- `middleware.ts` — strips every `x-0pt-verified-*` header on all forwarded
  paths. Legacy internal tokens get the single configured tenant as scope
  (an ambiguous multi-tenant list is refused with 401 instead of widened);
  a Bearer CL0UD workload token is verified and its claims become the
  verified tenant/subject/capabilities.
- `src/http/tenant-guard.ts` — enforces the service scope on tenant-scoped
  writes (deny when the tenant is outside the scope) and adds
  `assertWorkloadCapabilities` for capability-scoped principals.
- `quality/bridge-run` now calls `assertTenantMatchesVerified` like
  `canonical/facts` already did.

Tests: `tests/auth/workload-identity-dual-accept.test.ts` (10 cases) covers
forged-header stripping, ambiguous-scope refusal, wrong audience, missing
tenant claim, cross-tenant denial and missing-capability denial.

Real CL0UD provisioning (service accounts + published JWKS) is still
required before a workload token exists in production; until then the
legacy token path is the only one that authenticates, now tenant-scoped.
This commit is contained in:
2026-11-09 18:34:34 +01:00
parent 62517aca49
commit d40360aabc
5 changed files with 330 additions and 121 deletions
+79
View File
@@ -0,0 +1,79 @@
/**
* 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; }
}
+7
View File
@@ -50,6 +50,13 @@ export const INTERNAL_SERVICE_TENANTS_VAR = 'INTERNAL_SERVICE_TENANTS';
*/
export const SERVICE_TENANT_SCOPE_HEADER = 'x-0pt-verified-service-tenants';
/**
* Request header installed by middleware.ts ONLY: the CL0UD workload token's
* verified capability list, comma-separated. Stripped from every inbound
* request like the tenant scope.
*/
export const SERVICE_CAPABILITIES_HEADER = 'x-0pt-verified-capabilities';
/** Parse a comma-separated tenant allowlist (trimmed, de-duplicated, ordered). */
export function parseServiceTenants(value: string | undefined | null): string[] {
if (!value) return [];