/** * 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 = {}): 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): 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 = { 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; } }); });