import { exports } from "cloudflare:workers"; import { describe, expect, it } from "vitest"; import { checkClaims, decodeMultikey, parseJwt, verifySignature } from "../src/auth"; import { XrpcError } from "../src/xrpc"; import fixtures from "./fixtures/signature-fixtures.json"; import { base64url, didDoc, keypair, multikey, offline, routeFetch, signJwt } from "./helpers"; const claims = { iss: "did:web:knot.example.com", aud: "did:web:treadle.example.com", exp: 1000, lxm: "org.tangled.event.notifyEvent", jti: "abc", act: undefined, }; function expectInvalid(fn: () => unknown): void { expect(fn).toThrow(XrpcError); try { fn(); } catch (error) { expect(error).toMatchObject({ status: 401, error: "InvalidToken" }); } } describe("decodeMultikey", () => { it.each([ ["another multibase", "uAAAA"], ["an ed25519 key", "z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK"], ["a character outside base58", "z0OIl"], ])("rejects %s", (_, key) => { expectInvalid(() => decodeMultikey(key)); }); }); describe("parseJwt", () => { it("reads header and claims", () => { const jwt = parseJwt(signJwt(keypair(), claims)); expect(jwt.alg).toBe("ES256K"); expect(jwt.claims).toEqual(claims); }); it.each([ ["not a JWT", "abc"], ["too many parts", `${signJwt(keypair(), claims)}.x`], ["no exp", signJwt(keypair(), { ...claims, exp: undefined })], ["no iss", signJwt(keypair(), { ...claims, iss: 1 })], ["bad base64", "a.b.c"], ])("rejects a token with %s", (_, token) => { expectInvalid(() => parseJwt(token)); }); }); describe("verifySignature", () => { // The fixtures call high-S signatures invalid; verification is lenient on purpose. it.each( fixtures.map((fixture) => { const accepted = !fixture.tags.includes("der-encoded"); return [ `${fixture.comment}: ${accepted ? "accepted" : "rejected"}`, fixture, accepted, ] as const; }), )("%s", (_, fixture, accepted) => { const key = decodeMultikey(fixture.publicKeyDid.slice("did:key:".length)); const valid = verifySignature(key, { alg: fixture.algorithm, signingInput: Uint8Array.fromBase64(fixture.messageBase64), signature: Uint8Array.fromBase64(fixture.signatureBase64), }); expect(valid).toBe(accepted); }); it("accepts a P-256 token signed with WebCrypto", async () => { const pair = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, [ "sign", "verify", ]); if (!("privateKey" in pair)) { throw new Error("expected a key pair"); } const exported = await crypto.subtle.exportKey("raw", pair.publicKey); if (!(exported instanceof ArrayBuffer)) { throw new Error("expected raw key bytes"); } const raw = new Uint8Array(exported); const compressed = Uint8Array.of(2 + ((raw[64] ?? 0) & 1), ...raw.subarray(1, 33)); const input = `${base64url(JSON.stringify({ alg: "ES256", typ: "JWT" }))}.${base64url(JSON.stringify(claims))}`; const signature = await crypto.subtle.sign( { name: "ECDSA", hash: "SHA-256" }, pair.privateKey, new TextEncoder().encode(input), ); const jwt = parseJwt(`${input}.${base64url(new Uint8Array(signature))}`); expect(verifySignature(decodeMultikey(multikey("p256", compressed)), jwt)).toBe(true); }); it("rejects a signature from another key", () => { const jwt = parseJwt(signJwt(keypair(), claims)); expect(verifySignature(decodeMultikey(keypair().multikey), jwt)).toBe(false); }); it("rejects a tampered payload", () => { const key = keypair(); const [header, , signature] = signJwt(key, claims).split("."); const token = `${header}.${base64url(JSON.stringify({ ...claims, iss: "did:web:evil.example.com" }))}.${signature}`; expect(verifySignature(decodeMultikey(key.multikey), parseJwt(token))).toBe(false); }); it("rejects an alg that does not match the key", () => { const key = keypair("p256"); const jwt = parseJwt(signJwt(key, claims, "ES256K")); expect(verifySignature(decodeMultikey(key.multikey), jwt)).toBe(false); }); }); describe("checkClaims", () => { const expected = { audience: claims.aud, method: claims.lxm, now: 990 }; it("accepts matching claims", () => { expect(() => checkClaims(claims, expected)).not.toThrow(); expect(() => checkClaims(claims, { ...expected, now: 1004 })).not.toThrow(); }); it.each([ ["expired", claims, { ...expected, now: 1006 }], ["for another audience", { ...claims, aud: "did:web:other.example.com" }, expected], ["for another method", { ...claims, lxm: "org.tangled.ci.retryPipeline" }, expected], ["without a method", { ...claims, lxm: undefined }, expected], ])("rejects a token %s", (_, tokenClaims, options) => { expectInvalid(() => checkClaims(tokenClaims, options)); }); }); describe("Did", () => { const did = "did:plc:dddddddddddddddddddddddd"; const route = `GET https://plc.directory/${did}`; function resolve(): Promise { return exports.Did({ props: { did } }).fetch("https://did/"); } it("caches a DID document for 5 minutes", async () => { routeFetch({ [route]: () => Response.json(didDoc(did)) }); const res = await resolve(); expect(res.status).toBe(200); expect(res.headers.get("cache-control")).toBe("max-age=300, must-revalidate"); expect(await res.json()).toEqual(didDoc(did)); }); it("does not cache a failed lookup", async () => { routeFetch({ [route]: offline }); const res = await resolve(); expect(res.status).toBe(503); expect(res.headers.get("cache-control")).toBe("no-store"); expect(await res.json()).toMatchObject({ error: "UpstreamUnavailable" }); }); });