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
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:
@@ -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; }
|
||||
}
|
||||
@@ -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 [];
|
||||
|
||||
+19
-49
@@ -1,53 +1,8 @@
|
||||
/**
|
||||
* src/http/tenant-guard.ts
|
||||
* ==========================
|
||||
* P014 fix: every route under `app/api/0pt/**` sits behind `middleware.ts`,
|
||||
* which performs real Zitadel Bearer verification and — only when a
|
||||
* principal was actually verified — forwards the result as the
|
||||
* `x-0pt-verified-tenant` request header (see middleware.ts, src/auth/context.ts).
|
||||
*
|
||||
* Independently of that, every one of these route handlers reads `tenant_id`
|
||||
* from CLIENT-CONTROLLED input (a `?tenant_id=` query param or a JSON body
|
||||
* field) to decide which tenant's rows to read or write. Until this pass,
|
||||
* NONE of them cross-checked that client-supplied value against the verified
|
||||
* header — so a caller holding a valid token for tenant A could read or
|
||||
* write tenant B's sources, rights, provenance, health, quality rules/runs,
|
||||
* documents, or lakehouse mappings simply by naming `tenant_id=t_b` in the
|
||||
* request. `SourceRegistryService.assertSourceTenant` (and friends) only
|
||||
* checks that the object being read *belongs* to the tenant_id it was asked
|
||||
* to check against — it has no way to know whether the CALLER is actually
|
||||
* entitled to assert that tenant_id in the first place. That entitlement
|
||||
* check belongs at the HTTP boundary, once, here.
|
||||
*
|
||||
* This mirrors the exact decision `src/auth/context.ts`'s `resolveAuthContext`
|
||||
* already makes for the enforced-Bearer path ("a disagreeing X-Tenant-Id
|
||||
* header is a 403"), applied uniformly to every 0pt capability route that
|
||||
* takes tenant_id as a body/query parameter rather than relying on
|
||||
* middleware to inject ctx.tenantId directly (most of these routes predate
|
||||
* that plumbing and read tenant_id straight from the request; fixing that
|
||||
* more deeply is a larger refactor than this pass — this closes the actual
|
||||
* authz hole without changing every route's request contract).
|
||||
*/
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { readServiceTenantScope } from "@/src/auth/internal-service-tenant";
|
||||
|
||||
export const VERIFIED_TENANT_HEADER = "x-0pt-verified-tenant";
|
||||
|
||||
/**
|
||||
* Returns a 403 NextResponse when `tenantId` (whatever the route read it
|
||||
* from — query string or body) disagrees with the tenant middleware.ts
|
||||
* already verified for this request. Returns `null` when the caller may
|
||||
* proceed — either because the tenant matches, or because no verified
|
||||
* tenant is present on the request at all.
|
||||
*
|
||||
* The header is absent only in the explicit local-development escape hatch
|
||||
* (`AUTH_ENFORCE=false` with no bearer token presented) — `assertAuthConfigSafe()`
|
||||
* refuses to boot that way in production, so an absent header here can only
|
||||
* happen in a mode that already accepts fully unauthenticated requests.
|
||||
* Rejecting in that mode would be strictly more restrictive than the
|
||||
* existing dev escape hatch intends, so this deliberately no-ops rather than
|
||||
* invents a tenant to compare against.
|
||||
*/
|
||||
export function assertTenantMatchesVerified(
|
||||
request: NextRequest,
|
||||
tenantId: string | null | undefined,
|
||||
@@ -74,7 +29,7 @@ export function assertTenantMatchesVerified(
|
||||
return null;
|
||||
}
|
||||
if (!verified) return null;
|
||||
if (!tenantId) return null; // handlers already 400 on a missing tenant_id separately
|
||||
if (!tenantId) return null;
|
||||
if (tenantId !== verified) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
@@ -88,7 +43,6 @@ export function assertTenantMatchesVerified(
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Bind document operations to middleware's verified subject; never accept a conflicting body actor. */
|
||||
export function resolveDocumentActor(
|
||||
request: NextRequest,
|
||||
requestedActor: string | undefined,
|
||||
@@ -102,7 +56,23 @@ export function resolveDocumentActor(
|
||||
),
|
||||
};
|
||||
}
|
||||
// Absence is the existing unauthenticated development path. In enforced
|
||||
// mode middleware always installs the verified subject before this route.
|
||||
return { actorId: verified || requestedActor };
|
||||
}
|
||||
|
||||
export function assertWorkloadCapabilities(
|
||||
request: NextRequest,
|
||||
required: readonly string[],
|
||||
): NextResponse | null {
|
||||
if (!required.length) return null;
|
||||
const raw = request.headers.get('x-0pt-verified-capabilities');
|
||||
if (raw === null) return null; // not a workload-capability-scoped principal
|
||||
const caps = raw ? raw.split(',').map((s) => s.trim()).filter(Boolean) : [];
|
||||
const missing = required.filter((r) => !caps.includes(r) && !caps.includes('*'));
|
||||
if (missing.length) {
|
||||
return NextResponse.json(
|
||||
{ error: 'OPT_ACCESS_DENIED', message: 'missing required workload capability', details: { missing } },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user