feat(auth,foundation): Wave 2 flag-gated Zitadel JWT verify + validation + eslint + tests
Co-Authored-By: Claude Opus 4.8 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
844220d9f5
commit
1d76d50f3d
@@ -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 };
|
||||
}
|
||||
Reference in New Issue
Block a user