feat(auth,foundation): Wave 2 flag-gated Zitadel JWT verify + validation + eslint + tests
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
844220d9f5
commit
1d76d50f3d
@@ -32,6 +32,23 @@ GRANT_ENC_KEY=change-me-32-byte-key
|
||||
# Shared token for internal/service-to-service calls.
|
||||
INTERNAL_TOKEN=change-me-internal-token
|
||||
|
||||
# ---- Zitadel / OIDC Bearer verification (Wave 2 hardening) ------------------
|
||||
# 0pt verifies inbound Bearer tokens against the fleet Zitadel IdP
|
||||
# (src/auth/zitadel.ts, wired via middleware.ts). JWKS are discovered from
|
||||
# <issuer>/.well-known/openid-configuration, falling back to <issuer>/oauth/v2/keys.
|
||||
#
|
||||
# Fleet Zitadel issuer (OIDC). Default when unset: https://id-customers.siax.io
|
||||
ZITADEL_ISSUER=https://id-customers.siax.io
|
||||
# Flag-gated enforcement. When != "true" (DEFAULT) auth is non-breaking:
|
||||
# a present Bearer token is best-effort verified and attached, but never
|
||||
# rejected. Set to "true" to REQUIRE a valid token on /api/0pt/* (401 on
|
||||
# missing/invalid, 403 when X-Tenant-Id disagrees with the token tenant).
|
||||
AUTH_ENFORCE=false
|
||||
# Optional override for the claim key that carries the SIAX tenant id. When
|
||||
# unset, tenant derivation uses the documented precedence:
|
||||
# urn:zitadel:iam:org:id -> urn:zitadel:iam:user:resourceowner:id -> tenant_id -> tenant.
|
||||
ZITADEL_TENANT_CLAIM=
|
||||
|
||||
# ---- Payments (Stripe) ------------------------------------------------------
|
||||
STRIPE_SECRET_KEY=sk_test_xxx
|
||||
STRIPE_WEBHOOK_SECRET=whsec_xxx
|
||||
|
||||
+23
-29
@@ -3,25 +3,19 @@ name: CI (SIAX Cloud)
|
||||
# Self-hosted CI on SIAX Cloud (Gitea Actions, runners siax-runner-1/2),
|
||||
# following the fleet-wide pattern (quality gate -> advisory security scan).
|
||||
#
|
||||
# WHAT THIS REPO ACTUALLY SHIPS (0pt web console): a Next.js 16 app. Its
|
||||
# package.json exposes exactly four scripts -- build / dev / lint / start --
|
||||
# so the BLOCKING quality gate below runs the one real, installed, functional
|
||||
# build script (`pnpm run build` == `next build`), which type-checks and
|
||||
# compiles the whole app.
|
||||
#
|
||||
# Deliberately NOT run here (honest gaps, additive Wave-1 scope only):
|
||||
# * lint -> the "lint" script is `eslint .` but eslint is NOT in the
|
||||
# dependency tree (zero eslint entries in pnpm-lock.yaml), so a
|
||||
# blocking lint step would fail on "eslint: not found" for a
|
||||
# missing-devDependency reason, not a code reason. Adding eslint
|
||||
# is a source/package.json change (Wave 2/3), not Wave-1
|
||||
# scaffolding. Re-enable once eslint is a real devDependency.
|
||||
# * typecheck-> no `typecheck` script exists, and next.config.mjs sets
|
||||
# `typescript.ignoreBuildErrors: true` on purpose; `next build`
|
||||
# already runs the TS compiler.
|
||||
# * test -> tests/p0/*.test.ts exist but there is NO test runner installed
|
||||
# (no vitest/jest in pnpm-lock.yaml) and no `test` script, so
|
||||
# there is nothing to invoke. Wiring a runner is Wave 2/3.
|
||||
# WHAT THIS REPO SHIPS: a Next.js 16 web console PLUS the 0pt capability layer
|
||||
# (src/, tests/). Wave 2/3 hardening added a real test runner (vitest), a
|
||||
# scoped strict type-check (tsconfig.check.json), and a flat ESLint config, so
|
||||
# the quality gate now runs them:
|
||||
# * typecheck (BLOCKING) -> `tsc -p tsconfig.check.json` over src/ + tests/.
|
||||
# * test (BLOCKING) -> `vitest run` (the src/ capability + auth + validation suites).
|
||||
# * lint (ADVISORY, continue-on-error) -> `eslint src tests`. The v0-generated
|
||||
# legacy adapter/test tree carries pre-existing lint noise
|
||||
# (explicit-any / require-style imports), so lint is advisory to
|
||||
# avoid blocking merges on inherited debt; the Wave 2 auth/validation
|
||||
# additions themselves are lint-clean. Flip to blocking once the
|
||||
# legacy noise is cleared.
|
||||
# * build (BLOCKING) -> `next build` compiles the whole app.
|
||||
#
|
||||
# The security job is intentionally advisory (separate job, `--exit-code 0`) so
|
||||
# it never blocks merges, matching the fleet convention.
|
||||
@@ -45,17 +39,17 @@ jobs:
|
||||
run: |
|
||||
corepack enable
|
||||
corepack prepare pnpm@9 --activate
|
||||
# --ignore-workspace: the repo's pnpm-workspace.yaml is a v0-export artifact
|
||||
# that carries only an `allowBuilds:` block and NO `packages:` field, which
|
||||
# makes pnpm abort with "packages field missing or empty". There are no real
|
||||
# workspace members (only the root package.json), so ignoring the workspace
|
||||
# file is a semantic no-op and lets the frozen install resolve cleanly.
|
||||
- name: Install (frozen lockfile)
|
||||
run: pnpm install --frozen-lockfile --ignore-workspace
|
||||
- name: Build (next build -- blocking quality gate, no `|| true`)
|
||||
# --ignore-workspace: `pnpm run` also re-parses pnpm-workspace.yaml and aborts
|
||||
# on the missing `packages:` field unless the workspace is ignored (see above).
|
||||
run: pnpm --ignore-workspace run build
|
||||
run: pnpm install --frozen-lockfile
|
||||
- name: Typecheck (tsc over src/ + tests/ -- blocking)
|
||||
run: pnpm run typecheck
|
||||
- name: Test (vitest -- blocking)
|
||||
run: pnpm run test
|
||||
- name: Lint (eslint -- advisory; legacy tree has pre-existing noise)
|
||||
continue-on-error: true
|
||||
run: pnpm run lint
|
||||
- name: Build (next build -- blocking quality gate)
|
||||
run: pnpm run build
|
||||
|
||||
security:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"semi": true,
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all",
|
||||
"printWidth": 110
|
||||
}
|
||||
@@ -1,10 +1,16 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { parseBody, documentExtractionSchema } from "@/src/validation/0pt-schemas";
|
||||
import { documentExtractionService } from "@/src/services/document-extraction-service";
|
||||
|
||||
export async function POST(request: NextRequest, { params }: { params: Promise<{ documentId: string }> }) {
|
||||
try {
|
||||
const { documentId } = await params;
|
||||
const body = await request.json();
|
||||
const __raw = await request.json();
|
||||
const __parsed = parseBody(documentExtractionSchema, __raw);
|
||||
if (!__parsed.ok) {
|
||||
return NextResponse.json(__parsed.body, { status: __parsed.status });
|
||||
}
|
||||
const body = __parsed.data;
|
||||
const result = await documentExtractionService.extractDocument(documentId, {
|
||||
tenant_id: body.tenant_id,
|
||||
project_id: body.project_id,
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { parseBody, documentCaptureSchema } from "@/src/validation/0pt-schemas";
|
||||
import { documentCaptureService } from "@/src/services/document-capture-service";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const __raw = await request.json();
|
||||
const __parsed = parseBody(documentCaptureSchema, __raw);
|
||||
if (!__parsed.ok) {
|
||||
return NextResponse.json(__parsed.body, { status: __parsed.status });
|
||||
}
|
||||
const body = __parsed.data;
|
||||
const result = await documentCaptureService.captureFromMailbox(
|
||||
{
|
||||
mailbox: {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { parseBody, requestIcebergWriteSchema } from "@/src/validation/0pt-schemas";
|
||||
import { IcebergWriteService } from "@/src/services/iceberg-write-service";
|
||||
|
||||
const writeService = new IcebergWriteService();
|
||||
@@ -8,7 +9,12 @@ const writeService = new IcebergWriteService();
|
||||
export async function POST(request: NextRequest, { params }: { params: Promise<{ mappingId: string }> }) {
|
||||
try {
|
||||
const { mappingId } = await params;
|
||||
const body = await request.json();
|
||||
const __raw = await request.json();
|
||||
const __parsed = parseBody(requestIcebergWriteSchema, __raw);
|
||||
if (!__parsed.ok) {
|
||||
return NextResponse.json(__parsed.body, { status: __parsed.status });
|
||||
}
|
||||
const body = __parsed.data;
|
||||
const result = await writeService.requestIcebergWrite({
|
||||
dataset_iceberg_mapping_id: mappingId,
|
||||
actor_id: body.actor_id,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { parseBody, mapDatasetToIcebergTableSchema } from "@/src/validation/0pt-schemas";
|
||||
import { IcebergWriteService } from "@/src/services/iceberg-write-service";
|
||||
import { DatasetIcebergMappingService } from "@/src/services/dataset-iceberg-mapping-service";
|
||||
|
||||
@@ -16,7 +17,12 @@ const writeService = new IcebergWriteService({ mappingService });
|
||||
// entrypoint, see docs/ICEBERG_WRITE_BOUNDARY.md.
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const __raw = await request.json();
|
||||
const __parsed = parseBody(mapDatasetToIcebergTableSchema, __raw);
|
||||
if (!__parsed.ok) {
|
||||
return NextResponse.json(__parsed.body, { status: __parsed.status });
|
||||
}
|
||||
const body = __parsed.data;
|
||||
const result = await writeService.mapDatasetToIcebergTable({
|
||||
tenant_id: body.tenant_id,
|
||||
project_id: body.project_id,
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
* Details: docs/P0_QUERY_SOURCE_FLOW.md.
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { parseBody, sourceQuerySchema } from "@/src/validation/0pt-schemas";
|
||||
import { SourceService } from "@/src/services/source-service";
|
||||
import { SourceQueryService, SourceQueryTimeoutError, SourceQueryUnsupportedError } from "@/src/services/source-query-service";
|
||||
|
||||
@@ -24,7 +25,12 @@ const queryService = new SourceQueryService({ sourceService });
|
||||
export async function POST(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
|
||||
try {
|
||||
const { sourceId } = await params;
|
||||
const body = await request.json();
|
||||
const __raw = await request.json();
|
||||
const __parsed = parseBody(sourceQuerySchema, __raw);
|
||||
if (!__parsed.ok) {
|
||||
return NextResponse.json(__parsed.body, { status: __parsed.status });
|
||||
}
|
||||
const body = __parsed.data;
|
||||
|
||||
if (typeof body.query !== "string" || body.query.trim().length === 0) {
|
||||
return NextResponse.json({ error: "query (string) is required" }, { status: 400 });
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { parseBody, createSourceRatePolicySchema } from "@/src/validation/0pt-schemas";
|
||||
import { SourceRatePolicyService } from "@/src/services/source-rate-policy-service";
|
||||
|
||||
const service = new SourceRatePolicyService();
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const __raw = await request.json();
|
||||
const __parsed = parseBody(createSourceRatePolicySchema, __raw);
|
||||
if (!__parsed.ok) {
|
||||
return NextResponse.json(__parsed.body, { status: __parsed.status });
|
||||
}
|
||||
const body = __parsed.data;
|
||||
const policy = await service.createSourceRatePolicy(body);
|
||||
return NextResponse.json(policy, { status: 201 });
|
||||
} catch (error: unknown) {
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* `middleware.ts` -- Next.js request middleware = 0pt's framework-level auth
|
||||
* seam (the Next analog of a Fastify `onRequest` hook).
|
||||
*
|
||||
* Wave 2 hardening: this runs the flag-gated Zitadel verification
|
||||
* (src/auth/context.ts -> src/auth/zitadel.ts) in front of every 0pt
|
||||
* capability route (/api/0pt/*). It does NOT touch the v0-generated UI routes
|
||||
* or the unrelated payment/order APIs.
|
||||
*
|
||||
* AUTH_ENFORCE != "true" (default): never rejects; if a verified token is
|
||||
* present the verified principal is forwarded to the handler as
|
||||
* `x-0pt-verified-sub` / `x-0pt-verified-tenant` request headers.
|
||||
* AUTH_ENFORCE == "true": a valid verified token is required; 401 on
|
||||
* missing/invalid, 403 when X-Tenant-Id disagrees with the token tenant.
|
||||
*
|
||||
* Health/metrics are exempt (they are also outside the matcher below, but the
|
||||
* exemption is kept explicit for robustness).
|
||||
*/
|
||||
|
||||
import { NextResponse, type NextRequest } from 'next/server';
|
||||
import { resolveAuthContext } from '@/src/auth/context';
|
||||
|
||||
// Only guard the 0pt capability surface. The matcher keeps this middleware off
|
||||
// the UI, auth, and payment routes entirely.
|
||||
export const config = {
|
||||
matcher: ['/api/0pt/:path*'],
|
||||
};
|
||||
|
||||
const EXEMPT_PATTERNS: RegExp[] = [/^\/api\/health(\/|$)/, /^\/api\/admin\/metrics(\/|$)/];
|
||||
|
||||
export async function middleware(req: NextRequest): Promise<NextResponse> {
|
||||
const path = req.nextUrl.pathname;
|
||||
if (EXEMPT_PATTERNS.some((re) => re.test(path))) {
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
const decision = await resolveAuthContext(req.headers);
|
||||
|
||||
if (!decision.ok) {
|
||||
return NextResponse.json(
|
||||
{ error: decision.code, message: decision.message, ...(decision.details ? { details: decision.details } : {}) },
|
||||
{ status: decision.status },
|
||||
);
|
||||
}
|
||||
|
||||
const principal = decision.ctx.principal;
|
||||
if (principal) {
|
||||
const forwarded = new Headers(req.headers);
|
||||
forwarded.set('x-0pt-verified-sub', principal.sub);
|
||||
forwarded.set('x-0pt-verified-tenant', principal.tenantId);
|
||||
return NextResponse.next({ request: { headers: forwarded } });
|
||||
}
|
||||
|
||||
return NextResponse.next();
|
||||
}
|
||||
+5
-1
@@ -10,7 +10,9 @@
|
||||
"start": "next start",
|
||||
"typecheck": "tsc -p tsconfig.check.json",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest"
|
||||
"test:watch": "vitest",
|
||||
"format": "prettier --check .",
|
||||
"format:write": "prettier --write ."
|
||||
},
|
||||
"dependencies": {
|
||||
"@hookform/resolvers": "^3.10.0",
|
||||
@@ -49,6 +51,7 @@
|
||||
"date-fns": "4.1.0",
|
||||
"embla-carousel-react": "8.5.1",
|
||||
"input-otp": "1.4.1",
|
||||
"jose": "^5.9.6",
|
||||
"lucide-react": "^0.454.0",
|
||||
"next": "16.0.10",
|
||||
"next-themes": "^0.4.6",
|
||||
@@ -74,6 +77,7 @@
|
||||
"@types/react-dom": "^19",
|
||||
"eslint": "^9.15.0",
|
||||
"postcss": "^8.5",
|
||||
"prettier": "^3.9.6",
|
||||
"tailwindcss": "^4.1.9",
|
||||
"tw-animate-css": "1.3.3",
|
||||
"typescript": "^5",
|
||||
|
||||
Generated
+18
@@ -116,6 +116,9 @@ importers:
|
||||
input-otp:
|
||||
specifier: 1.4.1
|
||||
version: 1.4.1(react-dom@19.2.0(react@19.2.0))(react@19.2.0)
|
||||
jose:
|
||||
specifier: ^5.9.6
|
||||
version: 5.10.0
|
||||
lucide-react:
|
||||
specifier: ^0.454.0
|
||||
version: 0.454.0(react@19.2.0)
|
||||
@@ -186,6 +189,9 @@ importers:
|
||||
postcss:
|
||||
specifier: ^8.5
|
||||
version: 8.5.15
|
||||
prettier:
|
||||
specifier: ^3.9.6
|
||||
version: 3.9.6
|
||||
tailwindcss:
|
||||
specifier: ^4.1.9
|
||||
version: 4.3.1
|
||||
@@ -2068,6 +2074,9 @@ packages:
|
||||
resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==}
|
||||
hasBin: true
|
||||
|
||||
jose@5.10.0:
|
||||
resolution: {integrity: sha512-s+3Al/p9g32Iq+oqXxkW//7jk2Vig6FF1CFqzVXoTUXt2qz89YWbL+OwS17NFYEvxC35n0FKeGO2LGYSxeM2Gg==}
|
||||
|
||||
js-tokens@4.0.0:
|
||||
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
|
||||
|
||||
@@ -2299,6 +2308,11 @@ packages:
|
||||
resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==}
|
||||
engines: {node: '>= 0.8.0'}
|
||||
|
||||
prettier@3.9.6:
|
||||
resolution: {integrity: sha512-OpN0zzVdiaiAhxpuuj5efpIS4sY9j7bY6uR5mnj5yPzGkdkjNKSJeUThPb60Jw29QuAZgA4o+/iB49kFiaBX6g==}
|
||||
engines: {node: '>=14'}
|
||||
hasBin: true
|
||||
|
||||
prop-types@15.8.1:
|
||||
resolution: {integrity: sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==}
|
||||
|
||||
@@ -4407,6 +4421,8 @@ snapshots:
|
||||
|
||||
jiti@2.7.0: {}
|
||||
|
||||
jose@5.10.0: {}
|
||||
|
||||
js-tokens@4.0.0: {}
|
||||
|
||||
js-tokens@9.0.1: {}
|
||||
@@ -4598,6 +4614,8 @@ snapshots:
|
||||
|
||||
prelude-ls@1.2.1: {}
|
||||
|
||||
prettier@3.9.6: {}
|
||||
|
||||
prop-types@15.8.1:
|
||||
dependencies:
|
||||
loose-envify: 1.4.0
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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(),
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* Unit tests for src/auth/context.ts `resolveAuthContext` -- the flag-gated
|
||||
* auth seam. Verification is injected (opts.verify) so these tests are pure
|
||||
* and network-free; they exercise the decision logic in both AUTH_ENFORCE
|
||||
* modes.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { resolveAuthContext, type OptRequestContext } from '@/src/auth/context';
|
||||
import type { VerifiedPrincipal } from '@/src/auth/zitadel';
|
||||
|
||||
const principal: VerifiedPrincipal = {
|
||||
sub: 'user_1',
|
||||
tenantId: 'tenant_x',
|
||||
claims: { sub: 'user_1', iss: 'https://id-customers.siax.io' },
|
||||
};
|
||||
|
||||
const okVerify = vi.fn(async () => principal);
|
||||
const failVerify = vi.fn(async () => {
|
||||
throw new Error('token_verification_failed');
|
||||
});
|
||||
|
||||
function h(init: Record<string, string>): Headers {
|
||||
return new Headers(init);
|
||||
}
|
||||
|
||||
describe('resolveAuthContext -- enforce mode', () => {
|
||||
it('401s when no bearer token is present', async () => {
|
||||
const d = await resolveAuthContext(h({ 'x-tenant-id': 'tenant_x' }), { enforce: true, verify: okVerify });
|
||||
expect(d.ok).toBe(false);
|
||||
if (!d.ok) {
|
||||
expect(d.status).toBe(401);
|
||||
expect(d.code).toBe('OPT_UNAUTHENTICATED');
|
||||
}
|
||||
});
|
||||
|
||||
it('401s when the token fails verification', async () => {
|
||||
const d = await resolveAuthContext(h({ authorization: 'Bearer bad.tok.en' }), {
|
||||
enforce: true,
|
||||
verify: failVerify,
|
||||
});
|
||||
expect(d.ok).toBe(false);
|
||||
if (!d.ok) expect(d.status).toBe(401);
|
||||
});
|
||||
|
||||
it('attaches the verified principal and derives tenant from the TOKEN', async () => {
|
||||
const d = await resolveAuthContext(h({ authorization: 'Bearer good.tok.en' }), {
|
||||
enforce: true,
|
||||
verify: okVerify,
|
||||
});
|
||||
expect(d.ok).toBe(true);
|
||||
if (d.ok) {
|
||||
expect(d.ctx.principal).toEqual(principal);
|
||||
expect(d.ctx.tenantId).toBe('tenant_x');
|
||||
expect(d.ctx.actorId).toBe('user_1');
|
||||
}
|
||||
});
|
||||
|
||||
it('403s when X-Tenant-Id disagrees with the token tenant', async () => {
|
||||
const d = await resolveAuthContext(
|
||||
h({ authorization: 'Bearer good.tok.en', 'x-tenant-id': 'tenant_evil' }),
|
||||
{ enforce: true, verify: okVerify },
|
||||
);
|
||||
expect(d.ok).toBe(false);
|
||||
if (!d.ok) {
|
||||
expect(d.status).toBe(403);
|
||||
expect(d.code).toBe('OPT_ACCESS_DENIED');
|
||||
expect(d.details).toMatchObject({ header_tenant: 'tenant_evil', token_tenant: 'tenant_x' });
|
||||
}
|
||||
});
|
||||
|
||||
it('allows a matching X-Tenant-Id', async () => {
|
||||
const d = await resolveAuthContext(
|
||||
h({ authorization: 'Bearer good.tok.en', 'x-tenant-id': 'tenant_x' }),
|
||||
{ enforce: true, verify: okVerify },
|
||||
);
|
||||
expect(d.ok).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveAuthContext -- non-enforce (default) mode', () => {
|
||||
it('never rejects when no token is present', async () => {
|
||||
const d = await resolveAuthContext(h({ 'x-tenant-id': 'tenant_header' }), {
|
||||
enforce: false,
|
||||
verify: okVerify,
|
||||
});
|
||||
expect(d.ok).toBe(true);
|
||||
if (d.ok) {
|
||||
expect((d.ctx as OptRequestContext).principal).toBeUndefined();
|
||||
expect(d.ctx.tenantId).toBe('tenant_header');
|
||||
}
|
||||
});
|
||||
|
||||
it('never rejects even when a present token fails verification (logs a warning)', async () => {
|
||||
const logger = { warn: vi.fn() };
|
||||
const d = await resolveAuthContext(h({ authorization: 'Bearer bad.tok.en' }), {
|
||||
enforce: false,
|
||||
verify: failVerify,
|
||||
logger,
|
||||
});
|
||||
expect(d.ok).toBe(true);
|
||||
if (d.ok) expect(d.ctx.principal).toBeUndefined();
|
||||
expect(logger.warn).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('attaches the principal when a present token verifies, without overriding a supplied tenant', async () => {
|
||||
const d = await resolveAuthContext(
|
||||
h({ authorization: 'Bearer good.tok.en', 'x-tenant-id': 'tenant_header' }),
|
||||
{ enforce: false, verify: okVerify },
|
||||
);
|
||||
expect(d.ok).toBe(true);
|
||||
if (d.ok) {
|
||||
expect(d.ctx.principal).toEqual(principal);
|
||||
// non-breaking: caller-supplied header tenant is preserved
|
||||
expect(d.ctx.tenantId).toBe('tenant_header');
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* Unit tests for src/auth/zitadel.ts `verifyBearer`, using a locally-generated
|
||||
* RSA keypair + `createLocalJWKSet` so there is ZERO network access: we sign
|
||||
* our own tokens and inject the matching JWKS resolver.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeAll } from 'vitest';
|
||||
import {
|
||||
SignJWT,
|
||||
generateKeyPair,
|
||||
exportJWK,
|
||||
createLocalJWKSet,
|
||||
type JWTVerifyGetKey,
|
||||
type KeyLike,
|
||||
} from 'jose';
|
||||
import { verifyBearer, deriveTenantId, BearerVerificationError } from '@/src/auth/zitadel';
|
||||
|
||||
const ISSUER = 'https://test-issuer.siax.io';
|
||||
const KID = 'test-key-1';
|
||||
|
||||
let privateKey: KeyLike;
|
||||
let jwks: JWTVerifyGetKey;
|
||||
|
||||
beforeAll(async () => {
|
||||
const { publicKey, privateKey: pk } = await generateKeyPair('RS256');
|
||||
privateKey = pk;
|
||||
const jwk = await exportJWK(publicKey);
|
||||
jwk.kid = KID;
|
||||
jwk.alg = 'RS256';
|
||||
jwks = createLocalJWKSet({ keys: [jwk] });
|
||||
});
|
||||
|
||||
interface SignOpts {
|
||||
issuer?: string;
|
||||
expirationTime?: string | number;
|
||||
}
|
||||
|
||||
async function sign(claims: Record<string, unknown>, opts: SignOpts = {}): Promise<string> {
|
||||
return new SignJWT(claims)
|
||||
.setProtectedHeader({ alg: 'RS256', kid: KID })
|
||||
.setIssuedAt()
|
||||
.setIssuer(opts.issuer ?? ISSUER)
|
||||
.setExpirationTime(opts.expirationTime ?? '2h')
|
||||
.sign(privateKey);
|
||||
}
|
||||
|
||||
describe('deriveTenantId', () => {
|
||||
it('prefers the Zitadel org id claim', () => {
|
||||
expect(
|
||||
deriveTenantId({ 'urn:zitadel:iam:org:id': 'org_1', tenant_id: 't_custom' }),
|
||||
).toBe('org_1');
|
||||
});
|
||||
|
||||
it('falls back to the resourceowner id, then tenant_id, then tenant', () => {
|
||||
expect(deriveTenantId({ 'urn:zitadel:iam:user:resourceowner:id': 'org_ro' })).toBe('org_ro');
|
||||
expect(deriveTenantId({ tenant_id: 't_x' })).toBe('t_x');
|
||||
expect(deriveTenantId({ tenant: 't_y' })).toBe('t_y');
|
||||
});
|
||||
|
||||
it('honors an explicit override claim key when present', () => {
|
||||
expect(deriveTenantId({ custom_tid: 't_over', 'urn:zitadel:iam:org:id': 'org_1' }, 'custom_tid')).toBe(
|
||||
't_over',
|
||||
);
|
||||
});
|
||||
|
||||
it('returns undefined when no tenant claim is present', () => {
|
||||
expect(deriveTenantId({ sub: 'u1' })).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('verifyBearer', () => {
|
||||
it('verifies a valid token and derives the principal (sub + tenant)', async () => {
|
||||
const token = await sign({ sub: 'user_1', 'urn:zitadel:iam:org:id': 'tenant_x' });
|
||||
const principal = await verifyBearer(token, { issuer: ISSUER, keyResolver: jwks });
|
||||
expect(principal.sub).toBe('user_1');
|
||||
expect(principal.tenantId).toBe('tenant_x');
|
||||
expect(principal.claims.iss).toBe(ISSUER);
|
||||
});
|
||||
|
||||
it('honors the custom tenant_id claim', async () => {
|
||||
const token = await sign({ sub: 'user_2', tenant_id: 't_protosell' });
|
||||
const principal = await verifyBearer(token, { issuer: ISSUER, keyResolver: jwks });
|
||||
expect(principal.tenantId).toBe('t_protosell');
|
||||
});
|
||||
|
||||
it('rejects a tampered token (bad signature)', async () => {
|
||||
const token = await sign({ sub: 'user_1', 'urn:zitadel:iam:org:id': 'tenant_x' });
|
||||
const firstDot = token.indexOf('.');
|
||||
const secondDot = token.indexOf('.', firstDot + 1);
|
||||
const mid = Math.floor((firstDot + secondDot) / 2);
|
||||
const ch = token.charAt(mid);
|
||||
const tampered = token.slice(0, mid) + (ch === 'a' ? 'b' : 'a') + token.slice(mid + 1);
|
||||
await expect(verifyBearer(tampered, { issuer: ISSUER, keyResolver: jwks })).rejects.toBeInstanceOf(
|
||||
BearerVerificationError,
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects an expired token', async () => {
|
||||
const token = await sign(
|
||||
{ sub: 'user_1', 'urn:zitadel:iam:org:id': 'tenant_x' },
|
||||
{ expirationTime: '-1h' },
|
||||
);
|
||||
await expect(verifyBearer(token, { issuer: ISSUER, keyResolver: jwks })).rejects.toBeInstanceOf(
|
||||
BearerVerificationError,
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects a token from the wrong issuer', async () => {
|
||||
const token = await sign(
|
||||
{ sub: 'user_1', 'urn:zitadel:iam:org:id': 'tenant_x' },
|
||||
{ issuer: 'https://evil-issuer.example' },
|
||||
);
|
||||
await expect(verifyBearer(token, { issuer: ISSUER, keyResolver: jwks })).rejects.toBeInstanceOf(
|
||||
BearerVerificationError,
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects a validly-signed token that carries no tenant claim', async () => {
|
||||
const token = await sign({ sub: 'user_1' });
|
||||
await expect(verifyBearer(token, { issuer: ISSUER, keyResolver: jwks })).rejects.toMatchObject({
|
||||
reason: 'token_missing_tenant_claim',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,142 @@
|
||||
/**
|
||||
* Unit tests for src/validation/0pt-schemas.ts -- the Wave 2 request-body
|
||||
* validation for 0pt's mutating capability routes. Confirms a valid body
|
||||
* passes and a malformed body produces a structured 400.
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
parseBody,
|
||||
documentCaptureSchema,
|
||||
documentExtractionSchema,
|
||||
sourceQuerySchema,
|
||||
createSourceRatePolicySchema,
|
||||
mapDatasetToIcebergTableSchema,
|
||||
requestIcebergWriteSchema,
|
||||
} from '@/src/validation/0pt-schemas';
|
||||
|
||||
describe('parseBody + documentCaptureSchema', () => {
|
||||
const valid = {
|
||||
mailbox: {
|
||||
tenant_id: 't1',
|
||||
client_id: 'c1',
|
||||
client_secret: 's1',
|
||||
mailbox_address: 'ap@x.io',
|
||||
},
|
||||
tenant_id: 't1',
|
||||
project_id: 'p1',
|
||||
};
|
||||
|
||||
it('accepts a valid capture body', () => {
|
||||
const r = parseBody(documentCaptureSchema, valid);
|
||||
expect(r.ok).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects a body missing tenant_id with a 400 + issues', () => {
|
||||
const { tenant_id: _omit, ...bad } = valid;
|
||||
const r = parseBody(documentCaptureSchema, bad);
|
||||
expect(r.ok).toBe(false);
|
||||
if (!r.ok) {
|
||||
expect(r.status).toBe(400);
|
||||
expect(r.body.error).toBe('validation_error');
|
||||
expect(r.body.issues.some((i) => i.path === 'tenant_id')).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects a wrong-typed top field', () => {
|
||||
const r = parseBody(documentCaptureSchema, { ...valid, top: 'ten' });
|
||||
expect(r.ok).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('documentExtractionSchema', () => {
|
||||
it('accepts minimal valid input', () => {
|
||||
expect(parseBody(documentExtractionSchema, { tenant_id: 't', project_id: 'p' }).ok).toBe(true);
|
||||
});
|
||||
it('rejects empty body', () => {
|
||||
expect(parseBody(documentExtractionSchema, {}).ok).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('sourceQuerySchema', () => {
|
||||
it('accepts a valid query', () => {
|
||||
const r = parseBody(sourceQuerySchema, {
|
||||
query: 'SELECT 1',
|
||||
tenant_id: 't',
|
||||
project_id: 'p',
|
||||
connection_config: { host: 'db' },
|
||||
});
|
||||
expect(r.ok).toBe(true);
|
||||
});
|
||||
it('rejects a blank query', () => {
|
||||
const r = parseBody(sourceQuerySchema, {
|
||||
query: ' ',
|
||||
tenant_id: 't',
|
||||
project_id: 'p',
|
||||
connection_config: {},
|
||||
});
|
||||
expect(r.ok).toBe(false);
|
||||
});
|
||||
it('rejects a missing connection_config', () => {
|
||||
const r = parseBody(sourceQuerySchema, { query: 'SELECT 1', tenant_id: 't', project_id: 'p' });
|
||||
expect(r.ok).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createSourceRatePolicySchema', () => {
|
||||
const valid = {
|
||||
source_rate_policy_id: 'rp1',
|
||||
tenant_id: 't',
|
||||
project_id: 'p',
|
||||
source_id: 's',
|
||||
rate_limit_per_minute: 60,
|
||||
crawl_budget: 1000,
|
||||
};
|
||||
it('accepts a valid policy', () => {
|
||||
expect(parseBody(createSourceRatePolicySchema, valid).ok).toBe(true);
|
||||
});
|
||||
it('rejects a bad access enum', () => {
|
||||
expect(parseBody(createSourceRatePolicySchema, { ...valid, access: 'ftp' }).ok).toBe(false);
|
||||
});
|
||||
it('rejects a non-numeric rate_limit_per_minute', () => {
|
||||
expect(parseBody(createSourceRatePolicySchema, { ...valid, rate_limit_per_minute: 'fast' }).ok).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('mapDatasetToIcebergTableSchema', () => {
|
||||
const valid = {
|
||||
tenant_id: 't',
|
||||
project_id: 'p',
|
||||
dataset_id: 'd',
|
||||
dataset_iceberg_mapping_id: 'm',
|
||||
namespace: 'ns',
|
||||
table_name: 'tbl',
|
||||
storage_uri: 's3://x',
|
||||
catalog_ref: 'cat',
|
||||
actor_id: 'a',
|
||||
correlation_id: 'corr',
|
||||
};
|
||||
it('accepts a valid mapping', () => {
|
||||
expect(parseBody(mapDatasetToIcebergTableSchema, valid).ok).toBe(true);
|
||||
});
|
||||
it('rejects a mapping missing storage_uri', () => {
|
||||
const { storage_uri: _omit, ...bad } = valid;
|
||||
expect(parseBody(mapDatasetToIcebergTableSchema, bad).ok).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('requestIcebergWriteSchema', () => {
|
||||
const valid = {
|
||||
actor_id: 'a',
|
||||
correlation_id: 'corr',
|
||||
schema_version: 'v1',
|
||||
manifest_uri: 's3://m',
|
||||
};
|
||||
it('accepts a valid write request', () => {
|
||||
expect(parseBody(requestIcebergWriteSchema, valid).ok).toBe(true);
|
||||
});
|
||||
it('rejects a write request missing manifest_uri', () => {
|
||||
const { manifest_uri: _omit, ...bad } = valid;
|
||||
expect(parseBody(requestIcebergWriteSchema, bad).ok).toBe(false);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user