feat(auth,foundation): Wave 2 flag-gated Zitadel JWT verify + validation + eslint + tests
CI (SIAX Cloud) / security (push) Failing after 28s
CI (SIAX Cloud) / quality (push) Failing after 44s
CI (SIAX Cloud) / security (pull_request) Failing after 26s
CI (SIAX Cloud) / quality (pull_request) Failing after 33s

Co-Authored-By: Claude Opus 4.8 <[email protected]>
This commit is contained in:
SIAX Foundation Bot
2026-07-25 14:32:34 +02:00
co-authored by Claude Opus 4.8
parent 844220d9f5
commit 1d76d50f3d
18 changed files with 1074 additions and 36 deletions
+188
View File
@@ -0,0 +1,188 @@
/**
* `0pt/auth/context.ts` -- request-context extraction AND auth, the single
* seam the framework layer (Next.js middleware.ts) calls.
*
* ==========================================================================
* WAVE 2 HARDENING STATUS
*
* 0pt now performs REAL, cryptographic Zitadel (OIDC) Bearer-token
* verification (src/auth/zitadel.ts), gated behind the AUTH_ENFORCE env flag
* so it can ship to the deployed console WITHOUT breaking existing callers:
*
* AUTH_ENFORCE != "true" (DEFAULT, non-breaking):
* Preserves the historical behavior (no token was ever required; tenant
* came from the X-Tenant-Id header / request body). ADDITIONALLY, if a
* Bearer token is present and JWT-shaped, we ATTEMPT `verifyBearer` and
* attach the verified principal to the resolved context -- but we NEVER
* reject on failure in this mode (a warning is logged). This lets tokens
* start flowing and being verified with zero caller migration.
*
* AUTH_ENFORCE == "true" (enforced):
* REQUIRES a valid, verified token on every non-exempt route. The tenant
* is derived from the TOKEN (not the X-Tenant-Id header). Missing/invalid
* token -> 401 (OPT_UNAUTHENTICATED). If an X-Tenant-Id header is present
* and disagrees with the token's tenant -> 403 (OPT_ACCESS_DENIED).
*
* This module is framework-neutral: it takes a minimal header-lookup (the Web
* `Headers` interface satisfies it, as does Next's `NextRequest.headers`) and
* returns a decision object. It does NOT import next/*, so it is fully
* unit-testable in isolation.
* ==========================================================================
*/
import { verifyBearer, type VerifiedPrincipal } from './zitadel';
/** Minimal header accessor -- Web `Headers` and `NextRequest.headers` satisfy this. */
export interface HeaderLookup {
get(name: string): string | null | undefined;
}
export interface OptRequestContext {
/** Tenant id: from the token in enforce mode, else from X-Tenant-Id header. */
tenantId: string;
/** Actor id: from X-Actor-Id header, falling back to the token subject. */
actorId: string;
/** Correlation/request id (X-Request-Id header, else a fresh uuid). */
requestId: string;
/** The raw bearer token, if an Authorization: Bearer header was present. */
bearerToken?: string;
/** Present when a Bearer token was successfully verified (either mode). */
principal?: VerifiedPrincipal;
}
export type AuthDecision =
| { ok: true; ctx: OptRequestContext }
| {
ok: false;
status: 401 | 403;
code: 'OPT_UNAUTHENTICATED' | 'OPT_ACCESS_DENIED';
message: string;
details?: Record<string, unknown>;
ctx: OptRequestContext;
};
/** True when hard auth enforcement is switched on (AUTH_ENFORCE=="true"). */
export function authEnforced(): boolean {
return process.env.AUTH_ENFORCE === 'true';
}
function firstHeader(headers: HeaderLookup, name: string): string | undefined {
const v = headers.get(name);
if (v === null || v === undefined) return undefined;
return v;
}
/** A raw token that structurally looks like a compact JWS (three segments). */
function looksLikeJwt(token: string): boolean {
return token.split('.').length === 3;
}
function newRequestId(): string {
try {
return globalThis.crypto.randomUUID();
} catch {
return `req_${Date.now()}_${Math.random().toString(36).slice(2)}`;
}
}
/** Read whatever context headers are present, without enforcing required-ness. */
export function readRequestContext(headers: HeaderLookup): OptRequestContext {
const auth = firstHeader(headers, 'authorization');
const bearerToken = auth?.startsWith('Bearer ') ? auth.slice('Bearer '.length).trim() : undefined;
return {
tenantId: firstHeader(headers, 'x-tenant-id') ?? '',
actorId: firstHeader(headers, 'x-actor-id') ?? '',
requestId: firstHeader(headers, 'x-request-id') ?? newRequestId(),
bearerToken: bearerToken && bearerToken.length > 0 ? bearerToken : undefined,
};
}
/** Minimal logger seam so middleware can pass the platform logger; defaults to console. */
export interface AuthLogger {
warn(obj: unknown, msg?: string): void;
}
export interface ResolveAuthOptions {
/** Injectable verifier (test seam); defaults to the real {@link verifyBearer}. */
verify?: typeof verifyBearer;
/** Force enforcement on/off (test seam); defaults to {@link authEnforced}. */
enforce?: boolean;
logger?: AuthLogger;
}
/**
* Resolve and (in enforce mode) enforce the request auth context. Returns an
* {@link AuthDecision}; the caller (middleware) turns a `!ok` decision into an
* HTTP response and an `ok` decision into forwarded principal headers.
*/
export async function resolveAuthContext(
headers: HeaderLookup,
opts: ResolveAuthOptions = {},
): Promise<AuthDecision> {
const verify = opts.verify ?? verifyBearer;
const enforce = opts.enforce ?? authEnforced();
const logger: AuthLogger = opts.logger ?? {
warn: (o, m) => console.warn(m ?? 'auth warning', o),
};
const ctx = readRequestContext(headers);
if (enforce) {
// --- ENFORCED: a valid verified token is mandatory ----------------------
if (!ctx.bearerToken) {
return {
ok: false,
status: 401,
code: 'OPT_UNAUTHENTICATED',
message: 'Authentication required: missing Authorization: Bearer <token>',
ctx,
};
}
let principal: VerifiedPrincipal;
try {
principal = await verify(ctx.bearerToken);
} catch (err) {
return {
ok: false,
status: 401,
code: 'OPT_UNAUTHENTICATED',
message: 'Authentication required: invalid or unverifiable Bearer token',
details: { reason: err instanceof Error ? err.message : 'verification_failed' },
ctx,
};
}
// Tenant is derived from the TOKEN. A disagreeing X-Tenant-Id is a 403.
const headerTenant = firstHeader(headers, 'x-tenant-id');
if (headerTenant && headerTenant !== principal.tenantId) {
return {
ok: false,
status: 403,
code: 'OPT_ACCESS_DENIED',
message: 'X-Tenant-Id header disagrees with authenticated token tenant',
details: { header_tenant: headerTenant, token_tenant: principal.tenantId },
ctx,
};
}
ctx.tenantId = principal.tenantId;
ctx.actorId = ctx.actorId || principal.sub;
ctx.principal = principal;
return { ok: true, ctx };
}
// --- NON-ENFORCE (default): never reject, best-effort verify --------------
if (ctx.bearerToken && looksLikeJwt(ctx.bearerToken)) {
try {
const principal = await verify(ctx.bearerToken);
ctx.principal = principal;
// Do NOT overwrite the header/body tenant in non-enforce mode; only
// fill it in when the caller supplied none, to stay non-breaking.
if (!ctx.tenantId) ctx.tenantId = principal.tenantId;
if (!ctx.actorId) ctx.actorId = principal.sub;
} catch (err) {
logger.warn(
{ err: err instanceof Error ? err.message : String(err) },
'0pt: bearer verification failed (AUTH_ENFORCE off, ignoring)',
);
}
}
return { ok: true, ctx };
}
+213
View File
@@ -0,0 +1,213 @@
/**
* `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 `<issuer>/.well-known/openid-configuration` and reading its
* `jwks_uri` (the spec-correct OIDC discovery path).
* 2. Falling back to `<issuer>/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,
jwtVerify,
type JWTPayload,
type JWTVerifyGetKey,
} from 'jose';
/** Default fleet Zitadel issuer (OIDC). Overridable via ZITADEL_ISSUER. */
export const DEFAULT_ZITADEL_ISSUER = 'https://id-customers.siax.io';
/** 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<string, JWTVerifyGetKey>();
// 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<string> {
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<JWTVerifyGetKey> {
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<VerifiedPrincipal> {
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);
}
const sub = typeof payload.sub === 'string' ? payload.sub : undefined;
if (!sub || sub.length === 0) {
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 };
}
+123
View File
@@ -0,0 +1,123 @@
/**
* `0pt/validation/0pt-schemas.ts` -- Wave 2 input validation for the 0pt
* capability API's MUTATING routes.
*
* Before Wave 2 every POST/PUT handler did `const body = await request.json()`
* and read fields straight off `body` (an implicit `any`), so a malformed
* payload reached the service layer untyped and surfaced as an opaque 500/400.
* These Zod schemas validate the request body at the edge and produce a typed,
* structured 400. This is VALIDATION ONLY -- it re-encodes the shape each
* handler already destructures; it does not add or change business logic.
*/
import { z } from 'zod';
/** A structured 400 parse result. */
export type ParseResult<T> =
| { ok: true; data: T }
| { ok: false; status: 400; body: { error: 'validation_error'; issues: { path: string; message: string }[] } };
/** Validate `body` against `schema`, returning parsed data or a 400 payload. */
export function parseBody<S extends z.ZodTypeAny>(schema: S, body: unknown): ParseResult<z.infer<S>> {
const result = schema.safeParse(body);
if (result.success) return { ok: true, data: result.data };
return {
ok: false,
status: 400,
body: {
error: 'validation_error',
issues: result.error.issues.map((i) => ({
path: i.path.join('.'),
message: i.message,
})),
},
};
}
// A permissive JSON object (used for opaque config blobs whose inner shape is
// owned by a downstream adapter, not this validation layer).
const jsonObject = z.record(z.string(), z.unknown());
/** POST /api/0pt/documents/capture */
export const documentCaptureSchema = z.object({
mailbox: z.object({
tenant_id: z.string().min(1),
client_id: z.string().min(1),
client_secret: z.string().min(1),
mailbox_address: z.string().min(1),
folder: z.string().min(1).optional(),
}),
since_iso: z.string().min(1).optional(),
top: z.number().int().positive().optional(),
max_pages: z.number().int().positive().optional(),
tenant_id: z.string().min(1),
project_id: z.string().min(1),
actor_id: z.string().min(1).optional(),
correlation_id: z.string().min(1).optional(),
});
/** POST /api/0pt/documents/[documentId]/extraction */
export const documentExtractionSchema = z.object({
tenant_id: z.string().min(1),
project_id: z.string().min(1),
actor_id: z.string().min(1).optional(),
correlation_id: z.string().min(1).optional(),
model_id: z.string().min(1).optional(),
});
/** POST /api/0pt/sources/[sourceId]/query */
export const sourceQuerySchema = z.object({
query: z.string().trim().min(1),
params: z.unknown().optional(),
tenant_id: z.string().min(1),
project_id: z.string().min(1),
actor_id: z.string().min(1).optional(),
correlation_id: z.string().min(1).optional(),
max_rows: z.number().int().positive().optional(),
timeout_ms: z.number().int().positive().optional(),
connection_config: jsonObject,
});
/** POST /api/0pt/sources/rate-policies -- mirrors CreateSourceRatePolicyInput. */
export const createSourceRatePolicySchema = z.object({
source_rate_policy_id: z.string().min(1),
tenant_id: z.string().min(1),
project_id: z.string().min(1),
source_id: z.string().min(1),
rate_limit_per_minute: z.number().int().nonnegative(),
crawl_budget: z.number().int().nonnegative(),
compliance_notes: z.string().optional(),
domain: z.string().min(1).optional(),
robots_ok: z.boolean().optional(),
access: z.enum(['api', 'bulk', 'authorized_web', 'licensed']).optional(),
status: z.enum(['active', 'paused', 'deprecated']).optional(),
correlation_id: z.string().min(1).optional(),
created_by: z.string().min(1).optional(),
});
/** POST /api/0pt/lakehouse/mappings -- mirrors MapDatasetToIcebergTableInput. */
export const mapDatasetToIcebergTableSchema = z.object({
tenant_id: z.string().min(1),
project_id: z.string().min(1),
dataset_id: z.string().min(1),
dataset_iceberg_mapping_id: z.string().min(1),
namespace: z.string().min(1),
table_name: z.string().min(1),
storage_uri: z.string().min(1),
catalog_ref: z.string().min(1),
table_format: z.string().min(1).optional(),
actor_id: z.string().min(1),
correlation_id: z.string().min(1),
});
/** POST /api/0pt/lakehouse/mappings/[mappingId]/writes -- RequestIcebergWriteInput. */
export const requestIcebergWriteSchema = z.object({
actor_id: z.string().min(1),
correlation_id: z.string().min(1),
snapshot_type: z.string().min(1).optional(),
schema_version: z.string().min(1),
manifest_uri: z.string().min(1),
record_count: z.number().int().nonnegative().optional(),
size_bytes: z.number().int().nonnegative().optional(),
heavy: z.boolean().optional(),
});