Files
leadboard/tests/external-api.test.mjs
2026-11-23 06:40:52 +00:00

49 lines
2.9 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import { generateKeyPairSync, sign } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import { computeModel } from '../calc-engine.js';
import { createAnchorStore } from '../anchor-store.js';
import { ApiError, buildExternal, verifyApiToken } from '../external-api.js';
const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
const jwk = { ...publicKey.export({ format: 'jwk' }), kid: 'k1' };
const issuer = 'https://auth.example.test/application/o/leadboard';
const token = (claims, kid = 'k1') => {
const enc = (v) => Buffer.from(JSON.stringify(v)).toString('base64url');
const head = enc({ alg: 'RS256', kid });
const body = enc({ iss: `${issuer}/`, aud: 'leadboard-api', exp: Math.floor(Date.now() / 1000) + 300, scope: 'openid leadboard:read', sub: 's1', actor_type: 'service', ...claims });
return `Bearer ${head}.${body}.${sign('RSA-SHA256', Buffer.from(`${head}.${body}`), privateKey).toString('base64url')}`;
};
const getKeys = async () => ({ keys: [jwk] });
test('bearer tokens: valid passes; wrong audience, expired, missing scope and no token are refused', async () => {
const ok = await verifyApiToken(token({}), { issuer, getKeys });
assert.equal(ok.actorType, 'service');
const status = async (auth) => { try { await verifyApiToken(auth, { issuer, getKeys }); return 200; } catch (e) { assert.ok(e instanceof ApiError); return e.status; } };
assert.equal(await status(undefined), 401);
assert.equal(await status(token({ aud: 'other' })), 401);
assert.equal(await status(token({ exp: 1 })), 401);
assert.equal(await status(token({ iss: 'https://evil.test/' })), 401);
assert.equal(await status(token({ scope: 'openid' })), 403);
assert.equal(await status(token({}, 'unknown')), 401);
});
test('external data: 503 before the first anchor; afterwards totals add up and no personal data is included', async () => {
const data = JSON.parse(await readFile(new URL('../seed/demo.json', import.meta.url), 'utf8'));
const model = computeModel(data);
const store = createAnchorStore(null);
assert.throws(() => buildExternal(model, { active: null }), e => e.status === 503 && e.code === 'not_anchored');
await store.anchor(model, { year: 2027, half: 'H1', note: 'test', by: 't' });
const anchors = await store.evaluate(model, 2027);
const { invoice, coda } = buildExternal(model, anchors);
assert.equal(invoice.dataVersion, 'v1');
assert.equal(invoice.calcVersion, 3);
assert.equal(invoice.invoiceTotal, invoice.departments.reduce((s, d) => s + d.annual, 0));
for (const d of invoice.departments) assert.equal(d.h1.target + d.h2.target, d.annual);
const text = JSON.stringify({ invoice, coda });
for (const p of model.people) if (p.name) assert.ok(!text.includes(`"${p.name}"`), p.name);
assert.ok(!text.includes('salary'));
assert.equal(coda.companies[0].company, '夢想創造');
});