About: how pages are checked

tests/sims/jwt.test.ts

The automated tests for the /simulators/jwt-lifecycle simulator. They run the model on its own, outside the browser, and compare it with a reference that doesn't depend on the model being right. They run on every change to the simulator's code.

  1. The signature is the HMAC-SHA256 of header.payload, base64url-encoded without padding, as Node's crypto computes it.
  2. PyJWT decodes the tokens with the same secret, issuer and audience, and rejects them with the wrong secret.
  3. The API rejects a changed payload, a different key, alg "none", an expired token and the wrong issuer or audience, and accepts a good one.
// /simulators/jwt-lifecycle: HS256 JSON Web Tokens and the checks an API makes on them.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createHmac } from 'node:crypto';
import { execFileSync } from 'node:child_process';
import { signHS256, verify, b64url, b64urlToBytes, START, ISS, AUD } from '../../src/lib/sims/jwt.ts';

const SECRET = 'a-test-secret-that-is-long-enough-for-hs256';
const claims = (over: object = {}) => ({ iss: ISS, aud: AUD, sub: 'user-42', iat: START, exp: START + 900, ...over });
const header = { alg: 'HS256', typ: 'JWT' };

test("the signature is the HMAC-SHA256 of header.payload, base64url-encoded without padding, as Node's crypto computes it", async () => {
	for (let i = 0; i < 50; i++) {
		const tok = await signHS256(header, claims({ n: i, note: 'x'.repeat(i) }), SECRET);
		const [h, p, s] = tok.split('.');
		assert.equal(s, createHmac('sha256', SECRET).update(`${h}.${p}`).digest('base64url'));
		assert.ok(!/[=+/]/.test(tok), 'a token must be base64url without padding');
	}
	for (let n = 0; n < 40; n++) {
		const bytes = Uint8Array.from({ length: n }, (_, i) => (i * 97 + n) & 255);
		assert.deepEqual([...b64urlToBytes(b64url(bytes))], [...bytes]);
		assert.equal(b64url(bytes), Buffer.from(bytes).toString('base64url'));
	}
});

let pyjwt = true;
try { execFileSync('python3', ['-c', 'import jwt'], { stdio: 'ignore' }); } catch { pyjwt = false; }

test('PyJWT decodes the tokens with the same secret, issuer and audience, and rejects them with the wrong secret', { skip: !pyjwt && 'PyJWT is not installed' }, async () => {
	const toks = await Promise.all([1, 2, 3].map((n) => signHS256(header, claims({ n, exp: 4102444800 }), SECRET)));
	const out = JSON.parse(execFileSync('python3', ['-c', `
import jwt, json, sys
toks, secret, iss, aud = json.loads(sys.stdin.read())
res = []
for t in toks:
    good = jwt.decode(t, secret, algorithms=['HS256'], issuer=iss, audience=aud)
    try: jwt.decode(t, secret + 'x', algorithms=['HS256'], issuer=iss, audience=aud); bad = True
    except jwt.InvalidSignatureError: bad = False
    res.append([good['n'], bad])
print(json.dumps(res))
`], { input: JSON.stringify([toks, SECRET, ISS, AUD]) }).toString());
	assert.deepEqual(out, [[1, false], [2, false], [3, false]]);
});

test('the API rejects a changed payload, a different key, alg "none", an expired token and the wrong issuer or audience, and accepts a good one', async () => {
	const now = START + 60, expect = { iss: ISS, aud: AUD };
	const good = await signHS256(header, claims(), SECRET);
	assert.equal((await verify(good, SECRET, now, expect)).status, 200);
	const [h, p, s] = good.split('.');
	const forged = `${h}.${b64url(new TextEncoder().encode(JSON.stringify(claims({ sub: 'admin' }))))}.${s}`;
	assert.match((await verify(forged, SECRET, now, expect)).reason, /Invalid signature/);
	assert.match((await verify(good, SECRET + 'x', now, expect)).reason, /Invalid signature/);
	const none = `${b64url(new TextEncoder().encode('{"alg":"none"}'))}.${p}.`;
	assert.match((await verify(none, SECRET, now, expect)).reason, /accepts only HS256/);
	assert.match((await verify(good, SECRET, START + 900, expect)).reason, /Expired/, 'exp equal to now must already count as expired');
	assert.match((await verify(await signHS256(header, claims({ iss: 'https://evil.example' }), SECRET), SECRET, now, expect)).reason, /Wrong issuer/);
	assert.match((await verify(await signHS256(header, claims({ aud: 'other-api' }), SECRET), SECRET, now, expect)).reason, /Wrong audience/);
	assert.match((await verify('a.b', SECRET, now, expect)).reason, /three parts/);
});

Shared helpers: tests/sims/check.ts. The model under test is imported from src/lib/sims/.

Published