Something went wrong. Try again.
Tangled Spindle built on Cloudflare Workers
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228import { env, exports } from "cloudflare:workers";import { beforeEach, describe, expect, it } from "vitest";import { assertOutput, didDoc, getRecordRoute, keypair, knot, knotService, pds, pdsService, record, repoDid as repo, routeFetch, serviceToken, spindle,} from "./helpers";import { injectSecrets, secretMask } from "../src/secrets";
const host = "treadle.example.com";const owner = env.OWNER_DID;const stranger = "did:plc:ssssssssssssssssssssssss";const ownerKey = keypair("p256");const strangerKey = keypair();const repoKey = keypair();let manifestSpindle: string;
beforeEach(() => { manifestSpindle = spindle; routeFetch({ [`GET https://plc.directory/${owner}`]: () => Response.json(didDoc(owner, ownerKey, [pdsService])), [`GET https://plc.directory/${stranger}`]: () => Response.json(didDoc(stranger, strangerKey)), [`GET https://plc.directory/${repo}`]: () => Response.json(didDoc(repo, repoKey, [knotService])), [getRecordRoute(knot, repo, "org.tangled.repo.manifest", "self")]: () => record({ declaration: { owner, name: "My.Repo" }, spindle: manifestSpindle }), [getRecordRoute(pds, owner, "org.tangled.repo.declaration", "my.repo")]: () => record({ repo }), });});
function call( method: string, body: Record<string, string> = {}, { key = ownerKey, iss = owner, act, }: { key?: typeof ownerKey; iss?: string; act?: string } = {},): Promise<Response> { const nsid = `org.tangled.secret.${method}`; const token = serviceToken(key, { iss, lxm: nsid, ...(act === undefined ? {} : { act: { sub: act } }), }); const headers = { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }; const url = `https://${host}/xrpc/${nsid}`; return method === "listSecrets" ? exports.default.fetch(`${url}?${new URLSearchParams({ repo, ...body }).toString()}`, { headers, }) : exports.default.fetch(url, { method: "POST", headers, body: JSON.stringify(body) });}
describe("org.tangled.secret", () => { it("adds, lists and removes secrets without returning values", async () => { expect((await call("addSecret", { repo, key: "API_TOKEN", value: "s3cret" })).status).toBe( 200, ); const duplicate = await call("addSecret", { repo, key: "API_TOKEN", value: "other" }); expect(duplicate.status).toBe(409); expect(await duplicate.json()).toMatchObject({ error: "SecretAlreadyExists" });
const list = await call("listSecrets"); expect(list.status).toBe(200); const body: unknown = await list.json(); assertOutput("org.tangled.secret.listSecrets", body); expect(body).toMatchObject({ secrets: [{ key: "API_TOKEN", createdBy: owner }] }); expect(JSON.stringify(body)).not.toContain("s3cret"); expect(await exports.Secrets.getByName(repo).values(["API_TOKEN", "NONE"])).toEqual({ API_TOKEN: "s3cret", });
expect((await call("removeSecret", { repo, key: "API_TOKEN" })).status).toBe(200); const missing = await call("removeSecret", { repo, key: "API_TOKEN" }); expect(missing.status).toBe(404); expect(await missing.json()).toMatchObject({ error: "SecretNotFound" }); expect(await (await call("listSecrets")).json()).toEqual({ secrets: [] }); });
it.each([ ["a key that is not a variable name", { repo, key: "A-B", value: "x" }], ["a long key", { repo, key: "A".repeat(51), value: "x" }], ["an empty value", { repo, key: "A", value: "" }], ["a NUL in the value", { repo, key: "A", value: "a\0b" }], ["a long value", { repo, key: "A", value: "é".repeat(2049) }], ["no repo DID", { repo: "x", key: "A", value: "x" }], ])("refuses %s", async (_, input) => { const res = await call("addSecret", input); expect(res.status).toBe(400); expect(await res.json()).toMatchObject({ error: "InvalidRequest" }); });
it("refuses a list without a repo DID", async () => { const res = await call("listSecrets", { repo: "x" }); expect(res.status).toBe(400); });
it.each(["addSecret", "listSecrets", "removeSecret"])( "refuses a token from another DID for %s", async (method) => { const body = method === "listSecrets" ? {} : { repo, key: "A", value: "x" }; const res = await call(method, body, { key: strangerKey, iss: stranger }); expect(res.status).toBe(403); const unauthenticated = await exports.default.fetch( `https://${host}/xrpc/org.tangled.secret.${method}?repo=${repo}`, ); expect(unauthenticated.status).toBe(401); }, );
it("accepts a repo token and records its actor", async () => { const actor = "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa"; const token = { key: repoKey, iss: repo, act: actor }; const add = await call("addSecret", { repo, key: "REPO_TOKEN", value: "x" }, token); expect(add.status).toBe(200); expect(await (await call("listSecrets", {}, token)).json()).toMatchObject({ secrets: [{ key: "REPO_TOKEN", createdBy: actor }], }); expect((await call("removeSecret", { repo, key: "REPO_TOKEN" }, token)).status).toBe(200); });
it("refuses a repo that this spindle does not serve", async () => { manifestSpindle = "did:web:other.example.com"; const res = await call("listSecrets"); expect(res.status).toBe(404); expect(await res.json()).toMatchObject({ error: "RepoNotFound" }); });});
describe("secretMask", () => { it("masks a value, each of its lines and its base64 forms", () => { const mask = secretMask(["line1\nline2", "ab"]); expect(mask("x line1\nline2 y")).toBe("x *** y"); expect(mask("line2 and line1")).toBe("*** and ***"); expect(mask(btoa("line1\nline2"))).toBe("***"); expect(mask(`[${btoa("ab")}] [${btoa("ab").replace(/=+$/, "")}]`)).toBe("[***] [***]"); expect(secretMask(["a.b+c"])("aXb+c a.b+c")).toBe("aXb+c ***"); });
it("masks a value with ANSI codes inside, and keeps the codes of other lines", () => { const mask = secretMask(["s3cret"]); expect(mask("\u001b[1mkey\u001b[0m s3\u001b[31mcret")).toBe("key ***"); expect(mask("\u001b[1mkey\u001b[0m")).toBe("\u001b[1mkey\u001b[0m"); });
it("keeps text without secrets", () => { expect(secretMask([])("text")).toBe("text"); expect(secretMask([""])("text")).toBe("text"); });});
describe("injectSecrets", () => { const placeholder = "p".repeat(64); const token = { placeholder, value: "s3cret", hosts: ["api.example.com"], headers: ["Authorization"], }; const send = (url: string, headers: Record<string, string>, secrets = [token]) => injectSecrets(new Request(url, { method: "POST", headers, body: placeholder }), secrets);
it("swaps the placeholder in the named headers for an allowed host", async () => { const request = send(`https://api.example.com/x?t=${placeholder}`, { Authorization: `Bearer ${placeholder}`, "X-Other": placeholder, }); expect(request.headers.get("Authorization")).toBe("Bearer s3cret"); expect(request.headers.get("X-Other")).toBe(placeholder); expect(request.url).toBe(`https://api.example.com/x?t=${placeholder}`); expect(request.method).toBe("POST"); expect(request.redirect).toBe("manual"); expect(await request.text()).toBe(placeholder); });
it("swaps in custom headers and in Basic credentials", () => { const basic = new TextEncoder().encode(`user:${placeholder}`).toBase64(); const request = send( "https://api.example.com/", { Authorization: `Basic ${basic}`, "X-Auth-Key": placeholder }, [{ ...token, headers: ["Authorization", "x-auth-key"] }], ); expect(request.headers.get("Authorization")).toBe( `Basic ${new TextEncoder().encode("user:s3cret").toBase64()}`, ); expect(request.headers.get("X-Auth-Key")).toBe("s3cret"); const plain = send("https://api.example.com/", { Authorization: `Basic ${placeholder}x` }); expect(plain.headers.get("Authorization")).toBe("Basic s3cretx"); });
it.each([ ["another host", "https://attacker.example/"], ["a host that ends like an allowed host", "https://evil-api.example.com/"], ["plain HTTP", "http://api.example.com/"], ["another port", "https://api.example.com:8443/"], ])("forwards a request to %s unchanged", (_, url) => { const request = send(url, { Authorization: `Bearer ${placeholder}` }); expect(request.headers.get("Authorization")).toBe(`Bearer ${placeholder}`); expect(request.redirect).toBe("manual"); });
it.each([ ["a.example.com", true], ["a.b.example.com", true], ["example.com", false], ["aexample.com", false], ])("matches *.example.com against %s: %s", (hostname, swapped) => { const request = send(`https://${hostname}/`, { Authorization: placeholder }, [ { ...token, hosts: ["*.example.com"] }, ]); expect(request.headers.get("Authorization")).toBe(swapped ? "s3cret" : placeholder); });});