fix(recovery): restore source removed by production documentation merge

This commit is contained in:
2026-11-10 03:42:10 +01:00
parent 585bdd4b44
commit 3d2fc6f913
957 changed files with 115754 additions and 0 deletions
+214
View File
@@ -0,0 +1,214 @@
/**
* Unit tests for src/auth/context.ts -- the auth seam. Verification is
* injected (opts.verify) so these tests are pure and network-free.
*
* Three groups:
* 1. the ENV DEFAULT (the fail-closed contract: absent AUTH_ENFORCE means
* an unauthenticated request is REJECTED, and production refuses to run
* with auth switched off),
* 2. enforced-mode decision logic,
* 3. the explicit `AUTH_ENFORCE=false` local-development escape hatch.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import {
resolveAuthContext,
authEnforced,
assertAuthConfigSafe,
AuthMisconfigurationError,
AUTH_ENFORCE_VAR,
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('auth default -- fail-closed (no AUTH_ENFORCE in the environment)', () => {
const saved = { auth: process.env.AUTH_ENFORCE, node: process.env.NODE_ENV };
beforeEach(() => {
delete process.env.AUTH_ENFORCE;
});
afterEach(() => {
if (saved.auth === undefined) delete process.env.AUTH_ENFORCE;
else process.env.AUTH_ENFORCE = saved.auth;
if (saved.node === undefined) delete process.env.NODE_ENV;
else process.env.NODE_ENV = saved.node;
});
it('REGRESSION: with the variable unset, an unauthenticated request is REJECTED (401)', async () => {
// No `enforce` option -> the decision comes from the environment, which is
// exactly the fresh-container / DR-restore / dropped-env-var case.
const d = await resolveAuthContext(h({ 'x-tenant-id': 'tenant_attacker' }), { verify: okVerify });
expect(d.ok).toBe(false);
if (!d.ok) {
expect(d.status).toBe(401);
expect(d.code).toBe('OPT_UNAUTHENTICATED');
}
});
it('with the variable unset, an invalid token is REJECTED (401) rather than ignored', async () => {
const d = await resolveAuthContext(h({ authorization: 'Bearer bad.tok.en' }), { verify: failVerify });
expect(d.ok).toBe(false);
if (!d.ok) expect(d.status).toBe(401);
});
it('authEnforced() is true when the variable is absent, empty, or misspelled', () => {
expect(authEnforced({})).toBe(true);
expect(authEnforced({ AUTH_ENFORCE: '' })).toBe(true);
expect(authEnforced({ AUTH_ENFORCE: 'flase' })).toBe(true);
expect(authEnforced({ AUTH_ENFORCE: '0' })).toBe(true);
expect(authEnforced({ AUTH_ENFORCE: 'no' })).toBe(true);
expect(authEnforced({ AUTH_ENFORCE: 'true' })).toBe(true);
});
it('only the literal string "false" opts out', () => {
expect(authEnforced({ AUTH_ENFORCE: 'false' })).toBe(false);
expect(authEnforced({ AUTH_ENFORCE: 'FALSE' })).toBe(false);
expect(authEnforced({ AUTH_ENFORCE: ' false ' })).toBe(false);
});
it('assertAuthConfigSafe throws in production when enforcement is off, naming the variable', () => {
expect(() => assertAuthConfigSafe({ NODE_ENV: 'production', AUTH_ENFORCE: 'false' })).toThrow(
AuthMisconfigurationError,
);
expect(() => assertAuthConfigSafe({ NODE_ENV: 'production', AUTH_ENFORCE: 'false' })).toThrow(
new RegExp(AUTH_ENFORCE_VAR),
);
});
it('assertAuthConfigSafe is silent when production enforces, or when off outside production', () => {
expect(() => assertAuthConfigSafe({ NODE_ENV: 'production' })).not.toThrow();
expect(() => assertAuthConfigSafe({ NODE_ENV: 'production', AUTH_ENFORCE: 'true' })).not.toThrow();
expect(() => assertAuthConfigSafe({ NODE_ENV: 'development', AUTH_ENFORCE: 'false' })).not.toThrow();
});
it('a production process with AUTH_ENFORCE=false cannot serve a request at all (throws)', async () => {
process.env.NODE_ENV = 'production';
process.env.AUTH_ENFORCE = 'false';
await expect(
resolveAuthContext(h({ 'x-tenant-id': 'tenant_attacker' }), { verify: okVerify }),
).rejects.toBeInstanceOf(AuthMisconfigurationError);
});
});
describe('resolveAuthContext -- enforced mode (the default)', () => {
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('rejects a forged actor header and accepts only the verified subject', async () => {
const forged = await resolveAuthContext(
h({ authorization: 'Bearer good.tok.en', 'x-actor-id': 'user_other' }),
{ enforce: true, verify: okVerify },
);
expect(forged).toMatchObject({ ok: false, status: 403, code: 'OPT_ACCESS_DENIED' });
const matching = await resolveAuthContext(
h({ authorization: 'Bearer good.tok.en', 'x-actor-id': 'user_1' }),
{ enforce: true, verify: okVerify },
);
expect(matching.ok).toBe(true);
if (matching.ok) expect(matching.ctx.actorId).toBe('user_1');
});
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 -- explicit AUTH_ENFORCE=false escape hatch (local dev only)', () => {
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);
// the caller-supplied header tenant is preserved in this mode
expect(d.ctx.tenantId).toBe('tenant_header');
}
});
});
@@ -0,0 +1,262 @@
/**
* P0 regression (2026-11-07): tenant authority for the machine-to-machine
* (`X-Internal-Token`) principal is SERVER CONFIGURATION, never a client
* header.
*
* The first attempt at this fix read `X-0pt-Internal-Tenant` (or a single
* `INTERNAL_TENANT_ID`) and copied it into `x-0pt-verified-tenant`. Any holder
* of the shared internal token could then still name any tenant, so the
* original cross-tenant write (tenant_id 999999999999999999 -> 201) remained
* possible through a different header. These tests pin the corrected model:
*
* - `INTERNAL_SERVICE_TENANTS` (server env) is the only source of tenant
* authority for the service principal.
* - No configured scope => tenant-scoped writes are denied (fail closed).
* - Client-supplied `x-0pt-internal-tenant`, `x-0pt-verified-tenant` and
* `x-0pt-verified-service-tenants` are ignored and stripped.
* - Bearer/session principals are unchanged.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { NextRequest } from 'next/server';
import { middleware } from '../../middleware';
import {
parseServiceTenants,
resolveInternalServiceTenants,
SERVICE_TENANT_SCOPE_HEADER,
} from '@/src/auth/internal-service-tenant';
import { assertTenantMatchesVerified } from '@/src/http/tenant-guard';
import { POST as canonicalPOST } from '@/app/api/0pt/canonical/facts/route';
import { POST as bridgePOST } from '@/app/api/0pt/quality/bridge-run/route';
import { POST as evidenceDispatchPOST } from '@/app/api/0pt/internal/evidence-outbox/dispatch/route';
const INTERNAL_TOKEN = 'engine-shared-secret';
const SCOPED_ROUTE = '/api/0pt/canonical/facts';
function req(path: string, headers: Record<string, string> = {}): NextRequest {
return new NextRequest(new URL(path, 'http://localhost'), { headers });
}
/** Headers middleware forwarded to the route handler (Next stores them here). */
function forwarded(res: { headers: { get(name: string): string | null } }, name: string): string | null {
return res.headers.get(`x-middleware-request-${name.toLowerCase()}`);
}
function guardRequest(headers: Record<string, string>): NextRequest {
return new NextRequest(new URL(SCOPED_ROUTE, 'http://localhost'), {
method: 'POST',
headers: { 'content-type': 'application/json', ...headers },
});
}
describe('parseServiceTenants / resolveInternalServiceTenants', () => {
it('splits, trims and de-duplicates the allowlist', () => {
expect(parseServiceTenants(' t_a , t_b ,, t_a ')).toEqual(['t_a', 't_b']);
});
it('an unset/empty allowlist means no tenant authority', () => {
expect(parseServiceTenants(undefined)).toEqual([]);
expect(parseServiceTenants('')).toEqual([]);
expect(resolveInternalServiceTenants({})).toEqual([]);
});
});
describe('middleware: internal-token tenant authority comes from server config', () => {
const saved = {
auth: process.env.AUTH_ENFORCE,
token: process.env.INTERNAL_TOKEN,
tenants: process.env.INTERNAL_SERVICE_TENANTS,
node: process.env.NODE_ENV,
};
beforeEach(() => {
delete process.env.AUTH_ENFORCE; // default posture: enforced
process.env.INTERNAL_TOKEN = INTERNAL_TOKEN;
delete process.env.INTERNAL_SERVICE_TENANTS;
});
afterEach(() => {
const values: Record<string, string | undefined> = {
AUTH_ENFORCE: saved.auth,
INTERNAL_TOKEN: saved.token,
INTERNAL_SERVICE_TENANTS: saved.tenants,
NODE_ENV: saved.node,
};
for (const [key, value] of Object.entries(values)) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
});
it('single allowlisted tenant is installed as the verified tenant', async () => {
process.env.INTERNAL_SERVICE_TENANTS = 't_a';
const res = await middleware(req(SCOPED_ROUTE, { 'x-internal-token': INTERNAL_TOKEN }));
expect(res.status).toBe(200);
expect(forwarded(res, 'x-0pt-verified-tenant')).toBe('t_a');
expect(forwarded(res, SERVICE_TENANT_SCOPE_HEADER)).toBe('t_a');
});
it('REFUSES an ambiguous multi-tenant allowlist (no workload-identity binding yet)', async () => {
process.env.INTERNAL_SERVICE_TENANTS = 't_a,t_b';
const res = await middleware(req(SCOPED_ROUTE, { 'x-internal-token': INTERNAL_TOKEN }));
expect(res.status).toBe(401);
const body = await res.json();
expect(body.message).toContain('ambiguous');
expect(forwarded(res, 'x-0pt-verified-tenant')).toBeNull();
expect(forwarded(res, SERVICE_TENANT_SCOPE_HEADER)).toBeNull();
});
it('a single allowlist entry is still forwarded as the service scope', async () => {
process.env.INTERNAL_SERVICE_TENANTS = 't_a';
const res = await middleware(req(SCOPED_ROUTE, { 'x-internal-token': INTERNAL_TOKEN }));
expect(res.status).toBe(200);
expect(forwarded(res, SERVICE_TENANT_SCOPE_HEADER)).toBe('t_a');
});
it('with no configured scope the service principal has no tenant authority (empty scope header)', async () => {
const res = await middleware(req(SCOPED_ROUTE, { 'x-internal-token': INTERNAL_TOKEN }));
expect(res.status).toBe(200);
expect(forwarded(res, 'x-0pt-verified-tenant')).toBeNull();
expect(forwarded(res, SERVICE_TENANT_SCOPE_HEADER)).toBe('');
});
it('IGNORES a client-supplied X-0pt-Internal-Tenant (not an authority source)', async () => {
process.env.INTERNAL_SERVICE_TENANTS = 't_a';
const res = await middleware(
req(SCOPED_ROUTE, {
'x-internal-token': INTERNAL_TOKEN,
'x-0pt-internal-tenant': 't_victim',
}),
);
expect(forwarded(res, 'x-0pt-verified-tenant')).toBe('t_a');
});
it('STRIPS a forged x-0pt-verified-tenant and forged scope header', async () => {
process.env.INTERNAL_SERVICE_TENANTS = 't_a';
const res = await middleware(
req(SCOPED_ROUTE, {
'x-internal-token': INTERNAL_TOKEN,
'x-0pt-verified-tenant': 't_victim',
'x-0pt-verified-sub': 'user_victim',
'x-0pt-verified-service-tenants': 't_victim',
}),
);
expect(forwarded(res, 'x-0pt-verified-tenant')).toBe('t_a');
expect(forwarded(res, 'x-0pt-verified-sub')).toBeNull();
expect(forwarded(res, SERVICE_TENANT_SCOPE_HEADER)).toBe('t_a');
});
it('strips forged verified headers on the unauthenticated development path too', async () => {
process.env.AUTH_ENFORCE = 'false';
const res = await middleware(req('/api/0pt/documents/capture', { 'x-0pt-verified-tenant': 't_victim' }));
expect(forwarded(res, 'x-0pt-verified-tenant')).toBeNull();
});
it('an invalid internal token still falls through to 401', async () => {
const res = await middleware(req(SCOPED_ROUTE, { 'x-internal-token': 'wrong' }));
expect(res.status).toBe(401);
});
});
describe('assertTenantMatchesVerified: service scope is enforced fail-closed', () => {
it('no service scope header behaves exactly as before (Bearer verified tenant)', () => {
const same = assertTenantMatchesVerified(
guardRequest({ 'x-0pt-verified-tenant': 't_a' }),
't_a',
);
expect(same).toBeNull();
const cross = assertTenantMatchesVerified(
guardRequest({ 'x-0pt-verified-tenant': 't_a' }),
't_victim',
);
expect(cross?.status).toBe(403);
});
it('allows a tenant inside the configured service scope', () => {
const res = assertTenantMatchesVerified(
guardRequest({ [SERVICE_TENANT_SCOPE_HEADER]: 't_a,t_b' }),
't_b',
);
expect(res).toBeNull();
});
it('DENIES a tenant outside the configured service scope (403)', async () => {
const res = assertTenantMatchesVerified(
guardRequest({ [SERVICE_TENANT_SCOPE_HEADER]: 't_a' }),
't_victim',
);
expect(res?.status).toBe(403);
const body = await res!.json();
expect(body.error).toBe('OPT_ACCESS_DENIED');
expect(body.details.service_tenant_scope).toEqual(['t_a']);
});
it('DENIES every tenant when the configured scope is empty (fail closed, even if a verified tenant was also set)', () => {
const res = assertTenantMatchesVerified(
guardRequest({
[SERVICE_TENANT_SCOPE_HEADER]: '',
'x-0pt-verified-tenant': '999999999999999999',
}),
'999999999999999999',
);
expect(res?.status).toBe(403);
});
});
describe('route handlers: internal service cannot write a foreign tenant', () => {
it('canonical facts: cross-tenant write is 403 before the service runs', async () => {
const res = await canonicalPOST(
new NextRequest(new URL(SCOPED_ROUTE, 'http://localhost'), {
method: 'POST',
headers: { 'content-type': 'application/json', [SERVICE_TENANT_SCOPE_HEADER]: 't_a' },
body: JSON.stringify({
tenant_id: 't_victim',
entities: [],
facts: [],
relations: [],
}),
}),
);
expect(res.status).toBe(403);
});
it('quality bridge-run: cross-tenant run is 403 before rules are provisioned', async () => {
const res = await bridgePOST(
new NextRequest(new URL('/api/0pt/quality/bridge-run', 'http://localhost'), {
method: 'POST',
headers: { 'content-type': 'application/json', [SERVICE_TENANT_SCOPE_HEADER]: 't_a' },
body: JSON.stringify({
tenant_id: 't_victim',
project_id: 'p1',
dataset_id: 'ds_1',
rows: [],
}),
}),
);
expect(res.status).toBe(403);
});
it('evidence-outbox dispatch needs no tenant and is unchanged by the scope', async () => {
// No DB in this test env: the route authenticates first, then reports a
// dependency error -- anything except 401/403 proves the scope did not
// turn a tenant-less machine route into a denial.
const previous = process.env.INTERNAL_TOKEN;
process.env.INTERNAL_TOKEN = INTERNAL_TOKEN;
try {
const res = await evidenceDispatchPOST(
new NextRequest(new URL('/api/0pt/internal/evidence-outbox/dispatch', 'http://localhost'), {
method: 'POST',
headers: {
'content-type': 'application/json',
'x-internal-token': INTERNAL_TOKEN,
[SERVICE_TENANT_SCOPE_HEADER]: '',
},
body: JSON.stringify({ limit: 1 }),
}),
);
expect([401, 403]).not.toContain(res.status);
} finally {
if (previous === undefined) delete process.env.INTERNAL_TOKEN;
else process.env.INTERNAL_TOKEN = previous;
}
});
});
+53
View File
@@ -0,0 +1,53 @@
import { describe, it, expect } from "vitest";
import { verifyInternalServiceToken, INTERNAL_TOKEN_HEADER } from "@/src/auth/internal-token";
function headers(map: Record<string, string> = {}): { get(name: string): string | null } {
const lower = new Map(Object.entries(map).map(([k, v]) => [k.toLowerCase(), v]));
return { get: (name: string) => lower.get(name.toLowerCase()) ?? null };
}
describe("verifyInternalServiceToken", () => {
it("accepts a header that matches the configured INTERNAL_TOKEN exactly", () => {
const ok = verifyInternalServiceToken(headers({ [INTERNAL_TOKEN_HEADER]: "s3cr3t" }), {
INTERNAL_TOKEN: "s3cr3t",
});
expect(ok).toBe(true);
});
it("rejects a mismatched token", () => {
const ok = verifyInternalServiceToken(headers({ [INTERNAL_TOKEN_HEADER]: "wrong" }), {
INTERNAL_TOKEN: "s3cr3t",
});
expect(ok).toBe(false);
});
it("rejects a missing header even when INTERNAL_TOKEN is configured", () => {
const ok = verifyInternalServiceToken(headers({}), { INTERNAL_TOKEN: "s3cr3t" });
expect(ok).toBe(false);
});
it("FAILS CLOSED: an unset INTERNAL_TOKEN never authenticates, even against an empty header value", () => {
// Regression guard: quality_bridge.py sends `os.getenv("INTERNAL_TOKEN", "")`
// -- if the edge's own INTERNAL_TOKEN were also unset, a naive `provided
// === expected` comparison of two empty strings would wrongly authenticate.
const ok = verifyInternalServiceToken(headers({ [INTERNAL_TOKEN_HEADER]: "" }), { INTERNAL_TOKEN: undefined });
expect(ok).toBe(false);
});
it("FAILS CLOSED: an unset INTERNAL_TOKEN never authenticates even a non-empty header", () => {
const ok = verifyInternalServiceToken(headers({ [INTERNAL_TOKEN_HEADER]: "anything" }), {
INTERNAL_TOKEN: undefined,
});
expect(ok).toBe(false);
});
it("rejects a whitespace-only configured token (trimmed to empty)", () => {
const ok = verifyInternalServiceToken(headers({ [INTERNAL_TOKEN_HEADER]: " " }), { INTERNAL_TOKEN: " " });
expect(ok).toBe(false);
});
it("is case-sensitive on the header name lookup contract but tolerant of header-name casing via the HeaderLookup adapter", () => {
const ok = verifyInternalServiceToken(headers({ "X-Internal-Token": "s3cr3t" }), { INTERNAL_TOKEN: "s3cr3t" });
expect(ok).toBe(true);
});
});
@@ -0,0 +1,82 @@
/**
* P014 regression test: before this pass, POST /api/0pt/quality/bridge-run
* -- the ONE route the Python engine's quality_bridge.py actually calls,
* using X-Internal-Token, never a Bearer token -- was rejected 401 by
* middleware.ts in any environment enforcing auth (the default), because
* middleware required a verified Zitadel Bearer token unconditionally on
* every /api/0pt/* path. See src/auth/internal-token.ts's doc comment for
* the full story. Neither existing test suite caught it: the TS bridge test
* calls the route's POST function directly (bypassing middleware.ts
* entirely) and the Python test mocks the HTTP layer.
*
* This test exercises the actual `middleware` function, not the route
* handler, so it proves the fix at the layer where the bug lived.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { NextRequest } from 'next/server';
import { middleware } from '../../middleware';
function req(path: string, headers: Record<string, string> = {}): NextRequest {
return new NextRequest(new URL(path, 'http://localhost'), { headers });
}
describe('middleware.ts: internal-token path for /api/0pt/quality/bridge-run', () => {
const saved = { auth: process.env.AUTH_ENFORCE, internal: process.env.INTERNAL_TOKEN, node: process.env.NODE_ENV };
beforeEach(() => {
delete process.env.AUTH_ENFORCE; // default posture: enforced
process.env.INTERNAL_TOKEN = 'engine-shared-secret';
});
afterEach(() => {
for (const [k, v] of Object.entries(saved)) {
const envKey = k === 'auth' ? 'AUTH_ENFORCE' : k === 'internal' ? 'INTERNAL_TOKEN' : 'NODE_ENV';
if (v === undefined) delete process.env[envKey];
else process.env[envKey] = v;
}
});
it('REGRESSION: a valid X-Internal-Token lets the engine through with NO Bearer token (was: 401)', async () => {
const res = await middleware(
req('/api/0pt/quality/bridge-run', { 'x-internal-token': 'engine-shared-secret' }),
);
// NextResponse.next() carries no body/status override -- it is not an
// error JSON response the way a rejection is.
expect(res.status).toBe(200);
});
it('a valid X-Internal-Token lets the acquisition engine write canonical facts', async () => {
const res = await middleware(
req('/api/0pt/canonical/facts', { 'x-internal-token': 'engine-shared-secret' }),
);
expect(res.status).toBe(200);
});
it('an invalid X-Internal-Token still falls through to the ordinary Bearer requirement (401, not a bypass)', async () => {
const res = await middleware(req('/api/0pt/quality/bridge-run', { 'x-internal-token': 'wrong-secret' }));
expect(res.status).toBe(401);
const body = await res.json();
expect(body.error).toBe('OPT_UNAUTHENTICATED');
});
it('a valid X-Internal-Token on a DIFFERENT /api/0pt/* route does NOT bypass auth (not a blanket exemption)', async () => {
const res = await middleware(req('/api/0pt/sources', { 'x-internal-token': 'engine-shared-secret' }));
expect(res.status).toBe(401);
});
it('no INTERNAL_TOKEN configured on the edge -- the internal-token path never activates, even with the right-looking header', async () => {
delete process.env.INTERNAL_TOKEN;
const res = await middleware(
req('/api/0pt/quality/bridge-run', { 'x-internal-token': 'engine-shared-secret' }),
);
expect(res.status).toBe(401);
});
it('a real Bearer-authenticated caller can still reach bridge-run directly (not internal-token-only)', async () => {
// No X-Internal-Token at all, no Authorization header either -> falls to
// the normal Bearer requirement -> 401, proving this path is additive,
// not a replacement for the existing Zitadel flow.
const res = await middleware(req('/api/0pt/quality/bridge-run'));
expect(res.status).toBe(401);
});
});
+29
View File
@@ -0,0 +1,29 @@
import { beforeEach, expect, it, vi } from "vitest";
import { NextRequest, NextResponse } from "next/server";
const mocks = vi.hoisted(() => ({ routeAuth: vi.fn() }));
vi.mock("@/src/auth/require-route-auth", () => ({ requireRouteAuth: mocks.routeAuth }));
import { requireOrderOwner } from "@/src/auth/require-order-owner";
beforeEach(() => mocks.routeAuth.mockReset());
const request = () => new NextRequest("https://0pt.app/api/orders", { method: "POST" });
it("passes through a failed Zitadel route-auth decision", async () => {
mocks.routeAuth.mockResolvedValue({ response: NextResponse.json({ error: "unauthenticated" }, { status: 401 }) });
expect((await requireOrderOwner(request())).response?.status).toBe(401);
});
it("rejects the local-dev auth bypass when no verified principal exists", async () => {
mocks.routeAuth.mockResolvedValue({ ctx: { tenantId: "spoofable-header" } });
expect((await requireOrderOwner(request())).response?.status).toBe(401);
});
it("uses only the verified JWT principal, not a request-supplied tenant", async () => {
mocks.routeAuth.mockResolvedValue({
ctx: { tenantId: "header-tenant", principal: { tenantId: "signed-tenant", sub: "signed-subject" } },
});
const result = await requireOrderOwner(request());
expect(result.owner).toEqual({ tenantId: "signed-tenant", subject: "signed-subject" });
});
@@ -0,0 +1,151 @@
/**
* Dual-accept workload identity: the machine routes accept EITHER the legacy
* shared `X-Internal-Token` (server-configured single-tenant scope) OR a
* verified CL0UD workload JWT (tenant + capabilities from verified claims
* only). These tests pin the security properties that make that safe:
*
* - a client-supplied `x-0pt-verified-*` header can never authorize
* anything (it is stripped before the handler sees it);
* - an ambiguous legacy scope is refused instead of silently widening;
* - a workload token for tenant A cannot write tenant B's facts;
* - a workload token without the required capability is denied.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { NextRequest } from 'next/server';
import { SignJWT, generateKeyPair } from 'jose';
import { middleware } from '../../middleware';
import { assertTenantMatchesVerified, assertWorkloadCapabilities } from '../../src/http/tenant-guard';
import { __resetWorkloadJwksCache, __setWorkloadKeyResolverForTests } from '../../src/auth/cl0ud-workload';
import { SERVICE_CAPABILITIES_HEADER, SERVICE_TENANT_SCOPE_HEADER } from '../../src/auth/internal-service-tenant';
const ISSUER = 'https://cl0ud.siax.io';
const TENANT_A = '379976258701823235';
const TENANT_B = '999999999999999999';
function req(path: string, headers: Record<string, string> = {}): NextRequest {
return new NextRequest(new URL(path, 'http://localhost'), { headers });
}
let privateKey: CryptoKey;
let publicKey: CryptoKey;
beforeEach(async () => {
const pair = await generateKeyPair('RS256');
privateKey = pair.privateKey as CryptoKey;
publicKey = pair.publicKey as CryptoKey;
__setWorkloadKeyResolverForTests(async () => publicKey);
});
afterEach(() => {
__resetWorkloadJwksCache();
for (const key of ['INTERNAL_TOKEN', 'INTERNAL_SERVICE_TENANTS', 'CL0UD_WORKLOAD_ISSUER', 'CL0UD_WORKLOAD_AUDIENCE', 'AUTH_ENFORCE']) {
delete process.env[key];
}
});
async function workloadToken(claims: Record<string, unknown>, audience = '0pt'): Promise<string> {
return await new SignJWT(claims)
.setProtectedHeader({ alg: 'RS256' })
.setIssuer(ISSUER)
.setAudience(audience)
.setSubject('svc-0pt-worker')
.setIssuedAt()
.setExpirationTime('5m')
.sign(privateKey);
}
describe('middleware: legacy internal token scope', () => {
beforeEach(() => {
process.env.INTERNAL_TOKEN = 'engine-shared-secret';
delete process.env.CL0UD_WORKLOAD_ISSUER;
});
it('single configured tenant becomes the verified tenant and the service scope', async () => {
process.env.INTERNAL_SERVICE_TENANTS = TENANT_A;
const res = await middleware(req('/api/0pt/canonical/facts', { 'x-internal-token': 'engine-shared-secret' }));
expect(res.status).toBe(200);
expect(res.headers.get('x-middleware-request-x-0pt-verified-tenant')).toBe(TENANT_A);
expect(res.headers.get(`x-middleware-request-${SERVICE_TENANT_SCOPE_HEADER}`)).toBe(TENANT_A);
});
it('an ambiguous multi-tenant scope is refused, not widened', async () => {
process.env.INTERNAL_SERVICE_TENANTS = `${TENANT_A},${TENANT_B}`;
const res = await middleware(req('/api/0pt/canonical/facts', { 'x-internal-token': 'engine-shared-secret' }));
expect(res.status).toBe(401);
expect((await res.json()).error).toBe('OPT_UNAUTHENTICATED');
});
it('forged client-supplied verified headers are stripped', async () => {
process.env.INTERNAL_SERVICE_TENANTS = TENANT_A;
const res = await middleware(
req('/api/0pt/canonical/facts', {
'x-internal-token': 'engine-shared-secret',
'x-0pt-verified-tenant': TENANT_B,
[SERVICE_TENANT_SCOPE_HEADER]: TENANT_B,
}),
);
expect(res.status).toBe(200);
expect(res.headers.get('x-middleware-request-x-0pt-verified-tenant')).toBe(TENANT_A);
expect(res.headers.get(`x-middleware-request-${SERVICE_TENANT_SCOPE_HEADER}`)).toBe(TENANT_A);
});
});
describe('middleware: CL0UD workload token (dual-accept)', () => {
beforeEach(() => {
process.env.CL0UD_WORKLOAD_ISSUER = ISSUER;
process.env.CL0UD_WORKLOAD_AUDIENCE = '0pt';
delete process.env.INTERNAL_TOKEN;
});
it('derives tenant and capabilities from verified claims', async () => {
const token = await workloadToken({ tenant_id: TENANT_A, capabilities: ['0pt.canonical.write'] });
const res = await middleware(req('/api/0pt/canonical/facts', { authorization: `Bearer ${token}` }));
expect(res.status).toBe(200);
expect(res.headers.get('x-middleware-request-x-0pt-verified-tenant')).toBe(TENANT_A);
expect(res.headers.get(`x-middleware-request-${SERVICE_CAPABILITIES_HEADER}`)).toBe('0pt.canonical.write');
});
it('rejects a token with the wrong audience', async () => {
const token = await workloadToken({ tenant_id: TENANT_A, capabilities: ['0pt.canonical.write'] }, 'n0d');
const res = await middleware(req('/api/0pt/canonical/facts', { authorization: `Bearer ${token}` }));
expect(res.status).toBe(401);
});
it('rejects a token that carries no tenant claim', async () => {
const token = await workloadToken({ capabilities: ['0pt.canonical.write'] });
const res = await middleware(req('/api/0pt/canonical/facts', { authorization: `Bearer ${token}` }));
expect(res.status).toBe(401);
});
it('ignores forged verified headers on the workload path too', async () => {
const token = await workloadToken({ tenant_id: TENANT_A, capabilities: ['0pt.canonical.write'] });
const res = await middleware(
req('/api/0pt/canonical/facts', {
authorization: `Bearer ${token}`,
'x-0pt-verified-tenant': TENANT_B,
}),
);
expect(res.headers.get('x-middleware-request-x-0pt-verified-tenant')).toBe(TENANT_A);
});
});
describe('tenant guard: scope and capability enforcement', () => {
it('denies a write for a tenant outside the service scope', () => {
const request = req('/api/0pt/canonical/facts', { [SERVICE_TENANT_SCOPE_HEADER]: TENANT_A });
expect(assertTenantMatchesVerified(request, TENANT_A)).toBeNull();
const denied = assertTenantMatchesVerified(request, TENANT_B);
expect(denied?.status).toBe(403);
});
it('denies a tenant that disagrees with a verified workload tenant', () => {
const request = req('/api/0pt/canonical/facts', { 'x-0pt-verified-tenant': TENANT_A });
expect(assertTenantMatchesVerified(request, TENANT_A)).toBeNull();
expect(assertTenantMatchesVerified(request, TENANT_B)?.status).toBe(403);
});
it('denies a missing capability on a capability-scoped principal', () => {
const request = req('/api/0pt/canonical/facts', { [SERVICE_CAPABILITIES_HEADER]: '0pt.canonical.read' });
expect(assertWorkloadCapabilities(request, ['0pt.canonical.write'])?.status).toBe(403);
expect(assertWorkloadCapabilities(request, ['0pt.canonical.read'])).toBeNull();
});
});
+125
View File
@@ -0,0 +1,125 @@
/**
* 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)
.setAudience('siax-test')
.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',
});
});
});