Something went wrong. Try again.
Tangled Spindle built on Cloudflare Workers
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160import { 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<Response> { 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" }); });});