Files
mtusi2026lab7/student-tests/pki.test.ts

53 lines
1.9 KiB
TypeScript

import { test, expect } from "bun:test";
import { mkdtemp, readFile, rm } from "node:fs/promises";
import { resolve } from "node:path";
import { createCA, issue } from "../scripts/pki";
import { validateLeaf } from "../scripts/security-guards";
import { local } from "../scripts/runtime";
test("issued leaf verifies exact SAN, issuer, validity and matching key", async () => {
const scratch = await mkdtemp(resolve(local, "pki-case-"));
const password = "pki-test-process-only-strong-passphrase";
try {
await createCA(resolve(scratch, "ca"), password);
await issue(
resolve(scratch, "ca"),
resolve(scratch, "worker"),
"worker",
password,
);
await issue(
resolve(scratch, "ca"),
resolve(scratch, "api"),
"api",
password,
);
const read = (f: string) => readFile(resolve(scratch, f), "utf8");
const cert = await read("worker/cert.pem"),
key = await read("worker/key.pem"),
ca = await read("ca/ca.crt");
expect(validateLeaf(cert, key, ca, "worker").serial).toBeTruthy();
expect(() => validateLeaf(cert, key, ca, "api")).toThrow(
"CERTIFICATE_SAN_INVALID",
);
expect(() => validateLeaf(cert, key, ca, "worker", 0)).toThrow(
"CERTIFICATE_LIFETIME_INVALID",
);
expect(() =>
validateLeaf(cert, key, ca, "worker", Date.now() + 31 * 86400_000),
).toThrow("CERTIFICATE_LIFETIME_INVALID");
expect(() => validateLeaf(cert, awaitKey, ca, "worker")).toThrow();
const otherKey = await read("api/key.pem");
expect(() => validateLeaf(cert, otherKey, ca, "worker")).toThrow(
"CERTIFICATE_KEY_MISMATCH",
);
await createCA(resolve(scratch, "foreign"), password);
const foreign = await read("foreign/ca.crt");
expect(() => validateLeaf(cert, key, foreign, "worker")).toThrow(
"CERTIFICATE_CA_INVALID",
);
} finally {
await rm(scratch, { recursive: true, force: true });
}
}, 30_000);
const awaitKey = "malformed";