import { beforeEach, describe, expect, mock, test } from "bun:test"; import { fakeD1 } from "../metering/fake-d1.test-helper"; import { memoryScopes } from "../scoped-db/testing"; import { sha256Hex } from "../crypto"; import { seedJob, seedRun } from "./ci-fixtures.test-helper"; let d1 = fakeD1(); let scopes = memoryScopes(); mock.module("cloudflare:workers", () => ({ env: { get DB() { return d1.binding; }, PUBLIC_URL: "https://forge.test", }, waitUntil: () => undefined, })); mock.module("../scoped-db", () => ({ repoDb: (id: string) => scopes.repoDb(id), accountDb: (id: string) => scopes.accountDb(id), stmt: scopes.module.stmt, })); const { jobTokenAccess } = await import("./job-token"); const TOKEN = "gitfor_job_secret"; function request(): Request { return new Request("https://forge.test/x.git/info/refs", { headers: { authorization: `Bearer ${TOKEN}` } }); } beforeEach(async () => { d1 = fakeD1(); scopes = memoryScopes(); const hash = await sha256Hex(TOKEN); d1.db.exec(` INSERT INTO accounts (id, name, kind) VALUES ('o1', 'acme', 'org'), ('u1', 'alice', 'user'); INSERT INTO repos (id, owner_id, name) VALUES ('r1', 'o1', 'app'); `); d1.db.query("INSERT INTO scope_locators VALUES ('job_token', ?, 'r1')").run(hash); const repo = scopes.raw("repo", "r1"); seedRun(repo, { id: "w1", repo_id: "r1", actor_id: "u1" }); seedJob(repo, { id: "j1", run_id: "w1", repo_id: "r1" }); repo.query("INSERT INTO job_tokens VALUES (?, 'j1', 'r1', '{}', ?)").run(hash, Date.now() + 60_000); }); describe("job tokens of disabled accounts", () => { test("refuse once the triggering user or the repo owner is disabled", async () => { expect((await jobTokenAccess(request()))?.jobId).toBe("j1"); d1.db.exec("UPDATE accounts SET disabled_at = 1 WHERE id = 'u1'"); expect(await jobTokenAccess(request())).toBeNull(); d1.db.exec( "UPDATE accounts SET disabled_at = NULL WHERE id = 'u1'; UPDATE accounts SET disabled_at = 1 WHERE id = 'o1'", ); expect(await jobTokenAccess(request())).toBeNull(); }); test("runs without an actor still work", async () => { scopes.raw("repo", "r1").exec("UPDATE workflow_runs SET actor_id = NULL"); expect((await jobTokenAccess(request()))?.jobId).toBe("j1"); }); });