feat(auth,foundation): Wave 2 flag-gated Zitadel JWT verify + validation + eslint + tests
CI (SIAX Cloud) / security (push) Failing after 28s
CI (SIAX Cloud) / quality (push) Failing after 44s
CI (SIAX Cloud) / security (pull_request) Failing after 26s
CI (SIAX Cloud) / quality (pull_request) Failing after 33s

Co-Authored-By: Claude Opus 4.8 <[email protected]>
This commit is contained in:
SIAX Foundation Bot
2026-07-25 14:32:34 +02:00
co-authored by Claude Opus 4.8
parent 844220d9f5
commit 1d76d50f3d
18 changed files with 1074 additions and 36 deletions
+118
View File
@@ -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');
}
});
});
+124
View File
@@ -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',
});
});
});
+142
View File
@@ -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: '[email protected]',
},
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);
});
});