Skip to content
refs
History
164 lines · 8.9 KBRaw
1import assert from "node:assert/strict";
2import { readdirSync, readFileSync } from "node:fs";
3import { DatabaseSync } from "node:sqlite";
4import { test } from "node:test";
5import type { Actor } from "../contract/actor.ts";
6import { parseGitRoute } from "../git.ts";
7import { Policy } from "../policy.ts";
8import { sessionUser, sha256 } from "../auth.ts";
9import { activateUser, findRepoRecord, namespacePolicy, repoFacts, slugError } from "../repos.ts";
10import { listLabels, listTasks } from "../tasks.ts";
11
12const migrations = new URL("../../../migrations/", import.meta.url);
13
14function d1(sqlite: DatabaseSync): D1Database {
15 const prepare = (sql: string, params: unknown[] = []): D1PreparedStatement =>
16 ({
17 sql,
18 bind: (...values: unknown[]) => prepare(sql, values),
19 all: async () => ({ results: sqlite.prepare(sql).all(...(params as never[])) }),
20 run: async () => ({ meta: { changes: Number(sqlite.prepare(sql).run(...(params as never[])).changes) } }),
21 first: async (column?: string) => {
22 const row = (sqlite.prepare(sql).get(...(params as never[])) ?? null) as Record<string, unknown> | null;
23 return column ? (row?.[column] ?? null) : row;
24 },
25 }) as unknown as D1PreparedStatement;
26 const batch = async (statements: D1PreparedStatement[]) => {
27 sqlite.exec("BEGIN");
28 try {
29 const results = [];
30 for (const statement of statements) results.push(/^\s*(INSERT|UPDATE|DELETE)/i.test((statement as unknown as { sql?: string }).sql ?? "") ? await statement.run() : await statement.all());
31 sqlite.exec("COMMIT");
32 return results;
33 } catch (error) {
34 sqlite.exec("ROLLBACK");
35 throw error;
36 }
37 };
38 return { prepare, batch, exec: (sql: string) => sqlite.exec(sql) } as unknown as D1Database;
39}
40
41function seeded(): D1Database {
42 const sqlite = new DatabaseSync(":memory:");
43 for (const file of readdirSync(migrations).sort()) sqlite.exec(readFileSync(new URL(file, migrations), "utf8"));
44 sqlite.exec(`
45 INSERT INTO namespaces (id, slug, name, created_at) VALUES ('ns-a', 'alice', 'alice', 0), ('ns-b', 'bob', 'bob', 0);
46 INSERT INTO users (id, email, name, password_hash, created_at) VALUES ('alice', 'a@example.com', 'Alice', 'x', 0), ('bob', 'b@example.com', 'Bob', 'x', 0);
47 INSERT INTO memberships (namespace_id, user_id, role, created_at) VALUES ('ns-a', 'alice', 'owner', 0), ('ns-b', 'bob', 'owner', 0);
48 INSERT INTO repos (id, namespace_id, name, visibility, artifacts_name, creator_id, created_at) VALUES
49 ('a-secret', 'ns-a', 'app', 'private', 'a-secret', 'alice', 0),
50 ('a-open', 'ns-a', 'site', 'public', 'a-open', 'alice', 0),
51 ('b-app', 'ns-b', 'app', 'private', 'b-app', 'bob', 0);
52 INSERT INTO tasks (repo_id, number, title, author_id, created_at, updated_at) VALUES ('a-secret', 1, 'alice task', 'alice', 0, 0), ('b-app', 1, 'bob task', 'bob', 0, 0);
53 INSERT INTO labels (id, namespace_id, name, color, created_at) VALUES ('la', 'ns-a', 'bug', 'red', 0), ('lb', 'ns-b', 'bug', 'blue', 0);
54 `);
55 return d1(sqlite);
56}
57
58const human = (id: string): Actor => ({ kind: "human", person: { id, name: id, email: `${id}@example.com` }, via: "session" });
59
60test("a private repository is visible only to members of its namespace", async () => {
61 const db = seeded();
62 const secret = repoFacts((await findRepoRecord(db, "alice/app"))!);
63 const alice = await namespacePolicy(db, new Policy(human("alice"), null), "ns-a");
64 const bob = await namespacePolicy(db, new Policy(human("bob"), null), "ns-a");
65 assert.equal(alice.canSeeRepo(secret), true);
66 assert.equal(alice.canWriteRepo(secret), true);
67 assert.equal(bob.canSeeRepo(secret), false);
68 assert.equal(bob.canWriteRepo(secret), false);
69 assert.equal(bob.canCreateRepos(), false);
70 assert.equal(bob.canManageMembers(), false);
71 assert.equal(bob.canUseTasks(), false);
72});
73
74test("anyone can read another namespace's public repository, but only members write to it", async () => {
75 const db = seeded();
76 const site = repoFacts((await findRepoRecord(db, "alice/site"))!);
77 const bob = await namespacePolicy(db, new Policy(human("bob"), null), "ns-a");
78 const anonymous = await namespacePolicy(db, new Policy({ kind: "anonymous" }, null), "ns-a");
79 assert.equal(bob.canSeeRepo(site), true);
80 assert.equal(bob.canWriteRepo(site), false);
81 assert.equal(anonymous.canSeeRepo(site), true);
82});
83
84test("each namespace has its own repository names", async () => {
85 const db = seeded();
86 assert.equal((await findRepoRecord(db, "alice/app"))?.id, "a-secret");
87 assert.equal((await findRepoRecord(db, "bob/app"))?.id, "b-app");
88 assert.equal(await findRepoRecord(db, "bob/site"), null);
89});
90
91test("task lists and labels stay inside their namespace", async () => {
92 const db = seeded();
93 const { page } = await listTasks(db, { namespaceId: "ns-b", status: "open" });
94 assert.deepEqual(page.items.map((task) => task.title), ["bob task"]);
95 assert.deepEqual((await listLabels(db, "ns-a")).map((label) => label.id), ["la"]);
96});
97
98test("git URLs name the namespace and the repository", () => {
99 const route = parseGitRoute("GET", new URL("https://git.example/alice/app.git/info/refs?service=git-upload-pack"));
100 assert.equal(route?.repo, "alice/app");
101 assert.equal(parseGitRoute("GET", new URL("https://git.example/app.git/info/refs?service=git-upload-pack")), null);
102});
103
104test("a handle must be a lowercase slug that no route uses", () => {
105 assert.equal(slugError("aman-k"), undefined);
106 assert.ok(slugError("Aman"));
107 assert.ok(slugError("-aman"));
108 assert.ok(slugError("tasks"));
109 assert.ok(slugError("a".repeat(40)));
110});
111
112test("activating a waitlisted user creates their namespace once, and only then can they hold a session", async () => {
113 const db = seeded();
114 (db as unknown as { exec(sql: string): void }).exec(
115 `INSERT INTO users (id, email, name, password_hash, handle, status, created_at) VALUES ('carol', 'c@example.com', 'Carol', 'x', 'carol', 'waitlisted', 0);
116 INSERT INTO sessions (token_hash, user_id, expires_at) VALUES ('${await sha256("carol-token")}', 'carol', 9999999999);`,
117 );
118 assert.equal(await sessionUser(db, "carol-token"), null);
119
120 const first = await db.batch(activateUser(db, "carol", 1));
121 assert.equal(first.at(-1)!.meta.changes, 1);
122 const again = await db.batch(activateUser(db, "carol", 2));
123 assert.equal(again.at(-1)!.meta.changes, 0);
124
125 assert.equal((await sessionUser(db, "carol-token"))?.id, "carol");
126 const namespace = await db.prepare("SELECT id FROM namespaces WHERE slug = 'carol'").first<{ id: string }>();
127 const owner = await namespacePolicy(db, new Policy(human("carol"), null), namespace!.id);
128 assert.equal(owner.role, "owner");
129 assert.equal(owner.personal, true);
130 assert.equal(owner.canCreateRepos(), true);
131 assert.equal(owner.canManageMembers(), false);
132});
133
134test("an organization's owner manages its members", async () => {
135 const db = seeded();
136 const owner = await namespacePolicy(db, new Policy(human("alice"), null), "ns-a");
137 assert.equal(owner.personal, false);
138 assert.equal(owner.canManageMembers(), true);
139});
140
141test("an agent grant stops granting repository access once its expiry time passes", () => {
142 const actor = { kind: "human", person: { id: "u1", name: "Aman", email: "a@x" }, via: "session" } as const;
143 const grant = { repos: [{ name: "refs/demo", access: "write" as const }], org: "member" as const, expiresAt: 1000 };
144 const repo = { name: "refs/demo", visibility: "private" as const, creatorId: "u1" };
145 assert.equal(new Policy(actor, "member", [grant], false, 999).canWriteRepo(repo), true);
146 assert.equal(new Policy(actor, "member", [grant], false, 1001).canWriteRepo(repo), false);
147});
148
149test("CI runs and secrets stay inside their repository and namespace", async () => {
150 const db = seeded();
151 await db.prepare("INSERT INTO ci_runs (id, repo_id, sha, ref, trigger, actor_kind, trust, secrets, trust_reason, state, config_hash, created_at) VALUES ('run-a', 'a-secret', 'abc', 'refs/heads/main', 'push', 'human', 'trusted', 'repo', 'x', 'queued', 'h', 0)").run();
152 await db.prepare("INSERT INTO ci_namespace_secrets (namespace_id, name, ciphertext, wrapped_key, updated_by, updated_at) VALUES ('ns-a', 'TOKEN', 'c', 'k', 'alice', 0)").run();
153 const env = { DB: db } as unknown as Env;
154 const { openNamespaceSecrets, openRepoCi } = await import("../handles/ci.ts");
155 const bobRepo = (await findRepoRecord(db, "bob/app"))!;
156 const bobPolicy = await namespacePolicy(db, new Policy(human("bob"), null), "ns-b");
157 const ci = openRepoCi(env, bobPolicy, bobRepo);
158 assert.deepEqual(await ci.runs(), []);
159 await assert.rejects(ci.run("run-a"), /not_found|No run/);
160 await assert.rejects(ci.logs("run-a", "test"), /not_found|No run/);
161 assert.deepEqual(await openNamespaceSecrets(env, bobPolicy, { id: "ns-b", slug: "bob", name: "bob", kind: "user" }).list(), []);
162 assert.equal((await namespacePolicy(db, new Policy(human("bob"), null), "ns-a")).canManageCiSecrets(), false);
163 assert.equal((await namespacePolicy(db, new Policy(human("alice"), null), "ns-a")).canManageCiSecrets(), true);
164});