feat(auth): dual-accept CL0UD workload identity on the machine routes
CI (SIAX Cloud) / sonar (pull_request) Skipped
masterplan-lock / check (pull_request) Successful in 7s
masterplan-lock / check (push) Successful in 7s
CI (SIAX Cloud) / Component conformance (blocking) (pull_request) Successful in 13s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 17s
CI (SIAX Cloud) / security (pull_request) Successful in 18s
CI (SIAX Cloud) / integration (pull_request) Successful in 27s
CI (SIAX Cloud) / quality (pull_request) Successful in 10m5s
CI (SIAX Cloud) / sonar (pull_request) Skipped
masterplan-lock / check (pull_request) Successful in 7s
masterplan-lock / check (push) Successful in 7s
CI (SIAX Cloud) / Component conformance (blocking) (pull_request) Successful in 13s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 17s
CI (SIAX Cloud) / security (pull_request) Successful in 18s
CI (SIAX Cloud) / integration (pull_request) Successful in 27s
CI (SIAX Cloud) / quality (pull_request) Successful in 10m5s
The internal machine routes (`quality/bridge-run`, `canonical/facts`, `internal/evidence-outbox/dispatch`, `internal/er/candidates`, `search/definitions`) trusted a shared `X-Internal-Token` with NO tenant authority: middleware let it through without setting any verified tenant, so `assertTenantMatchesVerified` was a no-op and a caller-chosen `tenant_id` in the body was authoritative. This closes that gap while keeping the engine working during the transition to CL0UD workload tokens: - `src/auth/internal-service-tenant.ts` — the server-configured `INTERNAL_SERVICE_TENANTS` scope, a scope header that only middleware may set, and a parser that strips/ignores client values. - `src/auth/cl0ud-workload.ts` — a real `jose`/JWKS verifier for CL0UD workload JWTs (`iss`/`aud`/`exp`), deriving `tenant_id` and `capabilities` from verified claims only. Fail-closed when a token is presented but the issuer/JWKS/audience/tenant claim does not verify. - `middleware.ts` — strips every `x-0pt-verified-*` header on all forwarded paths. Legacy internal tokens get the single configured tenant as scope (an ambiguous multi-tenant list is refused with 401 instead of widened); a Bearer CL0UD workload token is verified and its claims become the verified tenant/subject/capabilities. - `src/http/tenant-guard.ts` — enforces the service scope on tenant-scoped writes (deny when the tenant is outside the scope) and adds `assertWorkloadCapabilities` for capability-scoped principals. - `quality/bridge-run` now calls `assertTenantMatchesVerified` like `canonical/facts` already did. Tests: `tests/auth/workload-identity-dual-accept.test.ts` (10 cases) covers forged-header stripping, ambiguous-scope refusal, wrong audience, missing tenant claim, cross-tenant denial and missing-capability denial. Real CL0UD provisioning (service accounts + published JWKS) is still required before a workload token exists in production; until then the legacy token path is the only one that authenticates, now tenant-scoped.
This commit is contained in:
@@ -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();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user