fix(auth): make the AUTH_ENFORCE default fail-closed on /api/0pt/*
The auth seam read `process.env.AUTH_ENFORCE === 'true'`, so an absent env var meant NO authentication: any fresh container, local run, DR restore or redeploy that dropped the variable served /api/0pt/* anonymously, taking the tenant from the caller-supplied X-Tenant-Id header. 0pt.app is deployed and was answering anonymously (verified: an invalid Bearer token plus an arbitrary X-Tenant-Id returned 200), so this was a live hole, not latent. * authEnforced() now returns true unless AUTH_ENFORCE is explicitly "false" (trimmed, case-insensitive). Unset/empty/misspelled => ENFORCED. * assertAuthConfigSafe() throws AuthMisconfigurationError when NODE_ENV=production and enforcement resolved off, naming AUTH_ENFORCE. It runs at middleware module load (startup) and on the env-driven request path, so a production instance can neither boot nor serve a single unauthenticated request with auth switched off. * .env.example no longer teaches AUTH_ENFORCE=false; README's Deploy section states the fail-closed posture (no DEPLOY.md in this repo). * 7 new tests, incl. the regression case: with AUTH_ENFORCE unset and no `enforce` option, an unauthenticated request is rejected with 401. No test was inverted or deleted -- none asserted the open default; the three enforce:false cases now describe the explicit local-dev escape hatch. Tests: 121 passed / 1 skipped before, 128 passed / 1 skipped after. Typecheck and build clean; advisory lint unchanged (16 pre-existing problems). Scope: auth default only. The matcher still covers /api/0pt/* alone, and the handlers still take tenant_id from the query/body rather than the verified principal -- both described in the PR body, neither fixed here.
This commit is contained in:
+92
-26
@@ -3,26 +3,31 @@
|
||||
* seam the framework layer (Next.js middleware.ts) calls.
|
||||
*
|
||||
* ==========================================================================
|
||||
* WAVE 2 HARDENING STATUS
|
||||
* AUTH DEFAULT: FAIL-CLOSED
|
||||
*
|
||||
* 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:
|
||||
* 0pt performs REAL, cryptographic Zitadel (OIDC) Bearer-token verification
|
||||
* (src/auth/zitadel.ts). Enforcement is controlled by AUTH_ENFORCE, and the
|
||||
* DEFAULT IS ENFORCED -- an absent, empty, or misspelled value authenticates:
|
||||
*
|
||||
* 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):
|
||||
* AUTH_ENFORCE unset, or any value except "false" (DEFAULT, 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).
|
||||
*
|
||||
* AUTH_ENFORCE == "false" (explicit local-development escape hatch):
|
||||
* No token is required; the tenant comes from the X-Tenant-Id header /
|
||||
* request body. A present, JWT-shaped Bearer token is still best-effort
|
||||
* verified and attached, but never rejected. This mode is REFUSED in
|
||||
* production: {@link assertAuthConfigSafe} throws when NODE_ENV=production,
|
||||
* so an instance that loses (or mis-sets) the variable cannot serve
|
||||
* openly -- it fails to start, and fails the request, instead.
|
||||
*
|
||||
* WHY THE INVERSION: the predicate previously read `AUTH_ENFORCE === 'true'`,
|
||||
* so every fresh container, local run, DR restore, or redeploy that dropped
|
||||
* the variable ran with NO authentication at all, and `.env.example` shipped
|
||||
* `AUTH_ENFORCE=false`. Absence now means enforced.
|
||||
*
|
||||
* 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
|
||||
@@ -38,7 +43,7 @@ export interface HeaderLookup {
|
||||
}
|
||||
|
||||
export interface OptRequestContext {
|
||||
/** Tenant id: from the token in enforce mode, else from X-Tenant-Id header. */
|
||||
/** Tenant id: from the token when enforced, else from the X-Tenant-Id header. */
|
||||
tenantId: string;
|
||||
/** Actor id: from X-Actor-Id header, falling back to the token subject. */
|
||||
actorId: string;
|
||||
@@ -61,9 +66,57 @@ export type AuthDecision =
|
||||
ctx: OptRequestContext;
|
||||
};
|
||||
|
||||
/** True when hard auth enforcement is switched on (AUTH_ENFORCE=="true"). */
|
||||
export function authEnforced(): boolean {
|
||||
return process.env.AUTH_ENFORCE === 'true';
|
||||
/** Name of the environment variable that can switch enforcement off. */
|
||||
export const AUTH_ENFORCE_VAR = 'AUTH_ENFORCE';
|
||||
|
||||
/** The only two environment values this module reads; injectable for tests. */
|
||||
export interface AuthEnvView {
|
||||
AUTH_ENFORCE?: string;
|
||||
NODE_ENV?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Snapshot the auth-relevant environment. `process.env.NODE_ENV` is written
|
||||
* literally so bundlers (Next's edge compiler) inline it.
|
||||
*/
|
||||
function currentEnv(): AuthEnvView {
|
||||
return { AUTH_ENFORCE: process.env.AUTH_ENFORCE, NODE_ENV: process.env.NODE_ENV };
|
||||
}
|
||||
|
||||
/**
|
||||
* True unless enforcement was EXPLICITLY disabled with AUTH_ENFORCE="false".
|
||||
*
|
||||
* FAIL-CLOSED: unset, empty, "flase", "0", or any other value => ENFORCED.
|
||||
*/
|
||||
export function authEnforced(env: AuthEnvView = currentEnv()): boolean {
|
||||
return env.AUTH_ENFORCE?.trim().toLowerCase() !== 'false';
|
||||
}
|
||||
|
||||
/** Thrown when the process is configured to run without auth in production. */
|
||||
export class AuthMisconfigurationError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'AuthMisconfigurationError';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuse to run open in production. Throws {@link AuthMisconfigurationError}
|
||||
* when NODE_ENV=production and enforcement resolved to OFF.
|
||||
*
|
||||
* Called at module scope by middleware.ts (startup) AND on the env-driven
|
||||
* request path below, so a misconfigured production instance can neither boot
|
||||
* nor serve a single unauthenticated request.
|
||||
*/
|
||||
export function assertAuthConfigSafe(env: AuthEnvView = currentEnv()): void {
|
||||
if (env.NODE_ENV === 'production' && !authEnforced(env)) {
|
||||
throw new AuthMisconfigurationError(
|
||||
`0pt refuses to run with authentication disabled in production: ` +
|
||||
`${AUTH_ENFORCE_VAR} is explicitly set to "${env.AUTH_ENFORCE}" while NODE_ENV=production. ` +
|
||||
`Unset ${AUTH_ENFORCE_VAR} (absent = enforced) or set ${AUTH_ENFORCE_VAR}=true. ` +
|
||||
`${AUTH_ENFORCE_VAR}=false is a local-development escape hatch only.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function firstHeader(headers: HeaderLookup, name: string): string | undefined {
|
||||
@@ -111,23 +164,34 @@ export interface ResolveAuthOptions {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Resolve and (when enforced -- the default) 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.
|
||||
*
|
||||
* Throws {@link AuthMisconfigurationError} when the enforcement decision comes
|
||||
* from the environment and that environment is "production with auth off".
|
||||
*/
|
||||
export async function resolveAuthContext(
|
||||
headers: HeaderLookup,
|
||||
opts: ResolveAuthOptions = {},
|
||||
): Promise<AuthDecision> {
|
||||
const verify = opts.verify ?? verifyBearer;
|
||||
const enforce = opts.enforce ?? authEnforced();
|
||||
let enforce: boolean;
|
||||
if (opts.enforce !== undefined) {
|
||||
enforce = opts.enforce;
|
||||
} else {
|
||||
// Never serve openly in production, even if the startup check was bypassed.
|
||||
assertAuthConfigSafe();
|
||||
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 ----------------------
|
||||
// --- ENFORCED (DEFAULT): a valid verified token is mandatory ------------
|
||||
if (!ctx.bearerToken) {
|
||||
return {
|
||||
ok: false,
|
||||
@@ -168,19 +232,21 @@ export async function resolveAuthContext(
|
||||
return { ok: true, ctx };
|
||||
}
|
||||
|
||||
// --- NON-ENFORCE (default): never reject, best-effort verify --------------
|
||||
// --- EXPLICIT OPT-OUT (AUTH_ENFORCE=false, non-production only) -----------
|
||||
// Never rejects; a present token is best-effort verified so tokens can start
|
||||
// flowing in local development.
|
||||
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.
|
||||
// Do NOT overwrite the header/body tenant in this mode; only fill it in
|
||||
// when the caller supplied none.
|
||||
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)',
|
||||
`0pt: bearer verification failed (${AUTH_ENFORCE_VAR}=false, ignoring)`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user