| 1 | import { createHash, createHmac } from "node:crypto"; |
| 2 | import { afterEach, describe, expect, it, vi } from "vitest"; |
| 3 | import { decryptAndReseal, decryptSecret, encryptSecret, keyId, masterKeys, matchesAnyKey, openSecret, resealSecret } from "../../src/lib/crypto.js"; |
| 4 | import { signBlobUrl, signRuntimeToken, verifyBlobUrl, verifyRuntimeToken } from "../../src/lib/runtime-auth.js"; |
| 5 | import { inviteProof, validInviteProof } from "../../src/auth/invite-proof.js"; |
| 6 | import { readUnsubToken, unsubToken } from "../../src/mail/unsubscribe.js"; |
| 7 | import { readVerifyToken, verifyToken } from "../../src/mail/suppression.js"; |
| 8 | import { codeHash, codeMatches } from "../../src/auth/signup.js"; |
| 9 | import { ImportService } from "../../src/imports/service.js"; |
| 10 | import type { Env } from "../../src/env.js"; |
| 11 | |
| 12 | const OLD = Buffer.alloc(32, 1).toString("base64"); |
| 13 | const NEW = Buffer.alloc(32, 2).toString("base64"); |
| 14 | const OTHER = Buffer.alloc(32, 3).toString("base64"); |
| 15 | const PUB = "https://diffinery.example"; |
| 16 | /** Before the rotation, during it (old key kept as MASTER_KEY_PREV), after it, and an unrelated instance. */ |
| 17 | const before = { MASTER_KEY: OLD, PUBLIC_URL: PUB } as unknown as Env; |
| 18 | const during = { MASTER_KEY: NEW, MASTER_KEY_PREV: OLD, PUBLIC_URL: PUB } as unknown as Env; |
| 19 | const after = { MASTER_KEY: NEW, PUBLIC_URL: PUB } as unknown as Env; |
| 20 | const other = { MASTER_KEY: OTHER, PUBLIC_URL: PUB } as unknown as Env; |
| 21 | |
| 22 | const kidOf = (k: string) => createHash("sha256").update(Buffer.from(k, "base64")).digest("hex").slice(0, 8); |
| 23 | const hmacB64url = (key: string, data: string) => createHmac("sha256", key).update(data).digest("base64url"); |
| 24 | |
| 25 | describe("master keys", () => { |
| 26 | it("are the current key first, then the previous one while rotating", () => { |
| 27 | expect(masterKeys(before)).toEqual([OLD]); |
| 28 | expect(masterKeys(during)).toEqual([NEW, OLD]); |
| 29 | // The same value twice, or an empty one, counts once; MASTER_KEY_PREV alone is no key at all. |
| 30 | expect(masterKeys({ MASTER_KEY: OLD, MASTER_KEY_PREV: OLD })).toEqual([OLD]); |
| 31 | expect(masterKeys({ MASTER_KEY: OLD, MASTER_KEY_PREV: "" })).toEqual([OLD]); |
| 32 | expect(masterKeys({ MASTER_KEY_PREV: OLD })).toEqual([]); |
| 33 | }); |
| 34 | |
| 35 | it("are named in envelopes by the first 8 hex characters of SHA-256 over their bytes", async () => { |
| 36 | expect(await keyId(OLD)).toBe(kidOf(OLD)); |
| 37 | expect(await keyId(NEW)).not.toBe(await keyId(OLD)); |
| 38 | }); |
| 39 | |
| 40 | it("a malformed previous key never breaks a check under the current one", async () => { |
| 41 | const mac = async (k: string) => Buffer.from(k, "base64").toString("hex"); |
| 42 | expect(await matchesAnyKey([NEW, "!!"], await mac(NEW), mac)).toBe(true); |
| 43 | await expect(matchesAnyKey(["!!", NEW], "x", async () => Promise.reject(new Error("bad key")))).rejects.toThrow("bad key"); |
| 44 | }); |
| 45 | }); |
| 46 | |
| 47 | describe("secret envelopes", () => { |
| 48 | // Written by the v1 code (before keys could be rotated) with OLD, scope repo:r1. |
| 49 | const V1 = "v1.u9iC/IUkKT+24mVm.pCaoBWOPvxHGC6vK6GkimNm7zhfgouc="; |
| 50 | |
| 51 | it("written before rotation existed still decrypt, before and during a rotation", async () => { |
| 52 | expect(await decryptSecret(before, "repo:r1", V1)).toBe("hunter2"); |
| 53 | expect(await openSecret(during, "repo:r1", V1)).toEqual({ plaintext: "hunter2", current: false }); |
| 54 | expect(await openSecret(before, "repo:r1", V1)).toEqual({ plaintext: "hunter2", current: false }); |
| 55 | }); |
| 56 | |
| 57 | it("are v2 with the key id now, and round-trip", async () => { |
| 58 | const e = await encryptSecret(before, "repo:r1", "hunter2"); |
| 59 | expect(e).toMatch(new RegExp(`^v2\\.${kidOf(OLD)}\\.[A-Za-z0-9+/=]+\\.[A-Za-z0-9+/=]+$`)); |
| 60 | expect(e).not.toContain("hunter2"); |
| 61 | expect(await openSecret(before, "repo:r1", e)).toEqual({ plaintext: "hunter2", current: true }); |
| 62 | // The same AES-GCM ciphertext as v1 would carry: dropping the key id gives a valid v1 envelope. |
| 63 | const [, , iv, ct] = e.split("."); |
| 64 | expect(await decryptSecret(before, "repo:r1", `v1.${iv}.${ct}`)).toBe("hunter2"); |
| 65 | }); |
| 66 | |
| 67 | it("sealed with the old key decrypt with MASTER_KEY_PREV, and new ones use the new key", async () => { |
| 68 | const old = await encryptSecret(before, "org:o1", "s3cret"); |
| 69 | expect(await openSecret(during, "org:o1", old)).toEqual({ plaintext: "s3cret", current: false }); |
| 70 | const fresh = await encryptSecret(during, "org:o1", "s3cret"); |
| 71 | expect(fresh.split(".")[1]).toBe(kidOf(NEW)); |
| 72 | expect(await openSecret(during, "org:o1", fresh)).toEqual({ plaintext: "s3cret", current: true }); |
| 73 | expect(await decryptSecret(after, "org:o1", fresh)).toBe("s3cret"); |
| 74 | // Once MASTER_KEY_PREV is gone, what only the old key opens doesn't decrypt. |
| 75 | await expect(decryptSecret(after, "org:o1", old)).rejects.toThrow(/doesn't decrypt with MASTER_KEY$/); |
| 76 | await expect(decryptSecret(after, "repo:r1", V1)).rejects.toThrow(); |
| 77 | }); |
| 78 | |
| 79 | it("are tried with every key when the key id names none of them", async () => { |
| 80 | const e = await encryptSecret(before, "repo:r1", "x"); |
| 81 | const [v, , iv, ct] = e.split("."); |
| 82 | expect(await openSecret(during, "repo:r1", `${v}.00000000.${iv}.${ct}`)).toEqual({ plaintext: "x", current: false }); |
| 83 | }); |
| 84 | |
| 85 | it("don't decrypt with a wrong key, in another scope, or when damaged", async () => { |
| 86 | const e = await encryptSecret(before, "repo:r1", "hunter2"); |
| 87 | await expect(decryptSecret(other, "repo:r1", e)).rejects.toThrow(/doesn't decrypt/); |
| 88 | await expect(decryptSecret({ MASTER_KEY: OTHER, MASTER_KEY_PREV: NEW }, "repo:r1", e)).rejects.toThrow(/MASTER_KEY or MASTER_KEY_PREV/); |
| 89 | await expect(decryptSecret(before, "repo:r2", e)).rejects.toThrow(/doesn't decrypt/); |
| 90 | await expect(decryptSecret(before, "repo:r1", V1.replace("pCa", "pCb"))).rejects.toThrow(/doesn't decrypt/); |
| 91 | for (const bad of ["v3.a.b", "v1.a", "v2.zzzzzzzz.a.b", "v2.a.b", "plain"]) await expect(decryptSecret(before, "repo:r1", bad), bad).rejects.toThrow(/bad secret envelope/); |
| 92 | await expect(encryptSecret({ MASTER_KEY_PREV: OLD }, "repo:r1", "x")).rejects.toThrow(/MASTER_KEY is not configured/); |
| 93 | await expect(decryptSecret({}, "repo:r1", V1)).rejects.toThrow(/MASTER_KEY is not configured/); |
| 94 | }); |
| 95 | |
| 96 | it("are sealed again only when that is worth it, and never lost", async () => { |
| 97 | const current = await encryptSecret(during, "repo:r1", "hunter2"); |
| 98 | expect(await resealSecret(during, "repo:r1", current)).toBe(current); |
| 99 | for (const stale of [V1, await encryptSecret(before, "repo:r1", "hunter2")]) { |
| 100 | const resealed = await resealSecret(during, "repo:r1", stale); |
| 101 | expect(resealed.split(".").slice(0, 2)).toEqual(["v2", kidOf(NEW)]); |
| 102 | expect(await decryptSecret(after, "repo:r1", resealed)).toBe("hunter2"); |
| 103 | } |
| 104 | // One that doesn't decrypt is kept as it was. |
| 105 | expect(await resealSecret(other, "repo:r1", V1)).toBe(V1); |
| 106 | }); |
| 107 | |
| 108 | it("in use are stored again under the current key, and using them never depends on that", async () => { |
| 109 | const current = await encryptSecret(during, "repo:r1", "hunter2"); |
| 110 | const stored: string[] = []; |
| 111 | expect(await decryptAndReseal(during, "repo:r1", current, (s) => stored.push(s))).toBe("hunter2"); |
| 112 | expect(stored).toEqual([]); |
| 113 | for (const stale of [V1, await encryptSecret(before, "repo:r1", "hunter2")]) { |
| 114 | stored.length = 0; |
| 115 | expect(await decryptAndReseal(during, "repo:r1", stale, (s) => stored.push(s))).toBe("hunter2"); |
| 116 | expect(stored).toHaveLength(1); |
| 117 | expect(stored[0]!.split(".").slice(0, 2)).toEqual(["v2", kidOf(NEW)]); |
| 118 | expect(await decryptSecret(after, "repo:r1", stored[0]!)).toBe("hunter2"); |
| 119 | } |
| 120 | // A store that fails (or rejects) is logged, and the secret is still returned. |
| 121 | const err = vi.spyOn(console, "error").mockImplementation(() => {}); |
| 122 | expect(await decryptAndReseal(during, "repo:r1", V1, () => Promise.reject(new Error("D1 down")))).toBe("hunter2"); |
| 123 | expect(await decryptAndReseal(during, "repo:r1", V1, () => { throw new Error("sql busy"); })).toBe("hunter2"); |
| 124 | expect(err).toHaveBeenCalledTimes(2); |
| 125 | err.mockRestore(); |
| 126 | // One that doesn't decrypt still throws, as decryptSecret does, and stores nothing. |
| 127 | await expect(decryptAndReseal(other, "repo:r1", V1, (s) => stored.push(s))).rejects.toThrow(/decrypt/); |
| 128 | }); |
| 129 | }); |
| 130 | |
| 131 | describe("signatures made with MASTER_KEY", () => { |
| 132 | it("runtime tokens: old ones verify while rotating, new ones use the new key", async () => { |
| 133 | const exp = Math.floor(Date.now() / 1000) + 600; |
| 134 | const claims = { repo: "r1", run: "run1", job: "job1", exp }; |
| 135 | const old = await signRuntimeToken(before, "x", claims, ["refs/heads/main"]); |
| 136 | expect(await verifyRuntimeToken(during, old)).toMatchObject({ repo: "r1", job: "job1" }); |
| 137 | expect(await verifyRuntimeToken(after, old)).toBeNull(); |
| 138 | const fresh = await signRuntimeToken(during, "x", claims, ["refs/heads/main"]); |
| 139 | expect(await verifyRuntimeToken(after, fresh)).toMatchObject({ repo: "r1" }); |
| 140 | expect(await verifyRuntimeToken(before, fresh)).toBeNull(); |
| 141 | expect(await verifyRuntimeToken(other, old)).toBeNull(); |
| 142 | expect(await verifyRuntimeToken({}, old)).toBeNull(); |
| 143 | }); |
| 144 | |
| 145 | it("blob URLs: signed exactly as before, accepted with MASTER_KEY_PREV, new ones under the new key", async () => { |
| 146 | const ref = { repo: "r1", kind: "artifact" as const, id: 42 }; |
| 147 | const old = new URL(await signBlobUrl(before, "https://d.example", ref, "r", 4102444800)); |
| 148 | // Signed by the code before rotation existed, with OLD. |
| 149 | expect(old.searchParams.get("sig")).toBe("1I0_HL80HFt73S7qB9xv13q82j8Y8OvdubCBDKmlufM"); |
| 150 | expect(await verifyBlobUrl(during, ref, "r", old.searchParams)).toBe(true); |
| 151 | expect(await verifyBlobUrl(after, ref, "r", old.searchParams)).toBe(false); |
| 152 | const fresh = new URL(await signBlobUrl(during, "https://d.example", ref, "r", 4102444800)); |
| 153 | expect(fresh.searchParams.get("sig")).not.toBe(old.searchParams.get("sig")); |
| 154 | expect(await verifyBlobUrl(after, ref, "r", fresh.searchParams)).toBe(true); |
| 155 | expect(await verifyBlobUrl(other, ref, "r", old.searchParams)).toBe(false); |
| 156 | }); |
| 157 | |
| 158 | it("invitation proofs", async () => { |
| 159 | const old = await inviteProof(before, "hash1"); |
| 160 | expect(old).toBe(hmacB64url(`diffinery-invite-proof-v1:${OLD}`, "hash1")); |
| 161 | expect(await validInviteProof(during, "hash1", old)).toBe(true); |
| 162 | expect(await validInviteProof(during, "hash2", old)).toBe(false); |
| 163 | expect(await validInviteProof(after, "hash1", old)).toBe(false); |
| 164 | const fresh = await inviteProof(during, "hash1"); |
| 165 | expect(fresh).toBe(hmacB64url(`diffinery-invite-proof-v1:${NEW}`, "hash1")); |
| 166 | expect(await validInviteProof(after, "hash1", fresh)).toBe(true); |
| 167 | expect(await validInviteProof(other, "hash1", old)).toBe(false); |
| 168 | }); |
| 169 | |
| 170 | it("unsubscribe links", async () => { |
| 171 | const t = { accountId: "acc1", scope: { t: "category" as const, category: "watching" as const } }; |
| 172 | const old = await unsubToken(before, t); |
| 173 | const [payload, sig] = old.split("."); |
| 174 | expect(sig).toBe(hmacB64url(`diffinery-unsubscribe-v1:${OLD}`, payload!)); |
| 175 | expect(await readUnsubToken(during, old)).toEqual(t); |
| 176 | expect(await readUnsubToken(after, old)).toBeNull(); |
| 177 | const fresh = await unsubToken(during, t); |
| 178 | expect(fresh.split(".")[1]).toBe(hmacB64url(`diffinery-unsubscribe-v1:${NEW}`, fresh.split(".")[0]!)); |
| 179 | expect(await readUnsubToken(after, fresh)).toEqual(t); |
| 180 | expect(await readUnsubToken(other, old)).toBeNull(); |
| 181 | }); |
| 182 | |
| 183 | it("email verification links", async () => { |
| 184 | const t = { accountId: "ann", email: "[email protected]", expiresAt: Date.now() + 60_000 }; |
| 185 | const old = await verifyToken(before, t); |
| 186 | expect(old.split(".")[1]).toBe(hmacB64url(`diffinery-verify-email-v1:${OLD}`, old.split(".")[0]!)); |
| 187 | expect(await readVerifyToken(during, old)).toMatchObject({ accountId: "ann" }); |
| 188 | expect(await readVerifyToken(after, old)).toBeNull(); |
| 189 | const fresh = await verifyToken(during, t); |
| 190 | expect(await readVerifyToken(after, fresh)).toMatchObject({ accountId: "ann" }); |
| 191 | expect(await readVerifyToken(other, old)).toBeNull(); |
| 192 | }); |
| 193 | |
| 194 | it("sign-up code hashes", async () => { |
| 195 | const stored = await codeHash(before, "row1", "123456"); |
| 196 | expect(stored).toBe(hmacB64url(`diffinery-signup-code-v1:${OLD}`, "row1:123456")); |
| 197 | expect(await codeMatches(before, "row1", "123456", stored)).toBe(true); |
| 198 | expect(await codeMatches(during, "row1", "123456", stored)).toBe(true); |
| 199 | expect(await codeMatches(during, "row1", "654321", stored)).toBe(false); |
| 200 | expect(await codeMatches(after, "row1", "123456", stored)).toBe(false); |
| 201 | expect(await codeHash(during, "row1", "123456")).toBe(hmacB64url(`diffinery-signup-code-v1:${NEW}`, "row1:123456")); |
| 202 | expect(await codeMatches(other, "row1", "123456", stored)).toBe(false); |
| 203 | }); |
| 204 | |
| 205 | describe("GitHub account links", () => { |
| 206 | afterEach(() => vi.unstubAllGlobals()); |
| 207 | const hex16 = (key: string, data: string) => createHmac("sha256", key).update(data).digest("hex").slice(0, 32); |
| 208 | const svc = (env: Env) => new ImportService({ ...env, DB: {}, GITHUB_OAUTH_CLIENT_ID: "id", GITHUB_OAUTH_CLIENT_SECRET: "s" } as unknown as Env); |
| 209 | const person = { id: "u1", kind: "user", login: "ann" } as never; |
| 210 | |
| 211 | it("show the gist nonce under MASTER_KEY, and also take the one under MASTER_KEY_PREV", async () => { |
| 212 | const api = "https://api.github.com"; |
| 213 | const { nonce } = await svc(before).linkChallenge(person, null); |
| 214 | expect(nonce).toBe(`diffinery-link-${hex16(OLD, `github-link:u1:${api}`)}`); |
| 215 | const nonces = await (svc(during) as unknown as { linkNonces(a: string, b: string): Promise<string[]> }).linkNonces("u1", api); |
| 216 | expect(nonces).toEqual([`diffinery-link-${hex16(NEW, `github-link:u1:${api}`)}`, nonce]); |
| 217 | expect((await svc(during).linkChallenge(person, null)).nonce).toBe(nonces[0]); |
| 218 | }); |
| 219 | |
| 220 | it("accept an OAuth state made with MASTER_KEY_PREV", async () => { |
| 221 | const state = new URL(await svc(before).oauthStart(person)).searchParams.get("state")!; |
| 222 | expect(state).toBe(`u1.${hex16(OLD, "github-oauth:u1")}`); |
| 223 | // Past the state check, GitHub is asked for a token (and here returns none). |
| 224 | vi.stubGlobal("fetch", async () => new Response("{}")); |
| 225 | await expect(svc(during).oauthCallback(person, "code", state)).rejects.toMatchObject({ status: 422, detail: expect.stringMatching(/access token/) }); |
| 226 | await expect(svc(after).oauthCallback(person, "code", state)).rejects.toMatchObject({ status: 422, detail: expect.stringMatching(/OAuth state/) }); |
| 227 | await expect(svc(during).oauthCallback(person, "code", `u1.${hex16(OTHER, "github-oauth:u1")}`)).rejects.toMatchObject({ status: 422, detail: expect.stringMatching(/OAuth state/) }); |
| 228 | }); |
| 229 | }); |
| 230 | }); |
| 231 | |
| 232 | describe("sealing again with the current key", () => { |
| 233 | const person = { id: "u1", kind: "user", login: "ann" } as never; |
| 234 | |
| 235 | it("a retried import seals the token it keeps with the new key", async () => { |
| 236 | const token = await encryptSecret(before, "import:imp-1", "ghp_x"); |
| 237 | const row = { id: "imp-1", parent_id: null, kind: "repo", status: "failed", created_by: "u1", target_owner_id: "u1", repo_id: null, attempt: 1, token_ciphertext: token, source: "octo/app" }; |
| 238 | const writes: unknown[][] = []; |
| 239 | const db = { prepare: () => ({ bind: (...a: unknown[]) => ({ run: async () => void writes.push(a), first: async () => ({ n: 0 }) }) }) }; |
| 240 | const s = new ImportService({ ...during, DB: db, IMPORT_WORKFLOW: { create: async () => ({}) } } as unknown as Env); |
| 241 | Object.assign(s, { row: async () => row, audit: async () => undefined, canImportInto: async () => true }); |
| 242 | Object.assign(s.dir, { account: async () => ({ id: "u1", kind: "user", login: "ann" }) }); |
| 243 | await s.retry("imp-1", person, null); |
| 244 | const stored = writes.map((w) => w[1]).find((v) => typeof v === "string" && v.startsWith("v2.")) as string; |
| 245 | expect(stored.split(".")[1]).toBe(kidOf(NEW)); |
| 246 | expect(await decryptSecret(after, "import:imp-1", stored)).toBe("ghp_x"); |
| 247 | }); |
| 248 | }); |