Public: anyone can read this; the crew can change it.

The cold front page reads who may see every public app in one query #16691

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/16264-the-cold-front-page-reads-who-may-see-ev → main 0 commits fork 1 thread · 1 unresolved

  • Merged. scout/16264-the-cold-front-page-reads-who-may-see-ev was merged into main as b866eda.

Review

Sign in to review this change.
3 files changed +117 −2
src/actions/front.ts +3 −2
@@ -47,7 +47,7 @@ import {
4747 type Look,
4848 } from "../core/looks.ts";
4949 import { keepLook } from "../looks/service.ts";
50 import { canRead, getRepo, getReposByIds, type Repo } from "../core/repos.ts";
50 import { canReadMany, getRepo, getReposByIds, type Repo } from "../core/repos.ts";
5151 import { listActiveRuns } from "../core/runs.ts";
5252 import { getUsersByIds, isActive, type User } from "../core/users.ts";
5353 import { timePhase } from "../core/route_timing.ts";
@@ -310,9 +310,10 @@ function buildFrontPage(app: App, now: number): FrontPage {
310310 const owners = getUsersByIds(db, [
311311 ...new Set([...pinnedRepos.values(), ...repos.values()].map((r) => r.ownerId)),
312312 ]);
313 const strangerReads = canReadMany(db, [...pinnedRepos.values(), ...repos.values()], undefined);
313314 const readable = (repo: Repo | undefined): repo is Repo =>
314315 repo !== undefined &&
315 canRead(db, repo, undefined) &&
316 strangerReads.has(repo.id) &&
316317 (owners.get(repo.ownerId) === undefined || isActive(owners.get(repo.ownerId)!));
317318 const pinned = picks.pinned
318319 .map((id) => pinnedRepos.get(id))
src/core/repos.ts +22
@@ -1421,6 +1421,28 @@ export function canRead(
14211421 return accessAllows(orgAccessFor(db, repo, user), "read");
14221422 }
14231423
1424 /**
1425 * The ids among `repos` that `user` may read: the answer of `canRead` for each, with the public
1426 * repositories of owners in good standing settled in one statement however many there are.
1427 * A repository that is not public is asked of `canRead` itself, as its rules are per repository.
1428 */
1429 export function canReadMany(db: Database, repos: readonly Repo[], user: User | undefined): Set<string> {
1430 const out = new Set<string>();
1431 const publics = repos.filter((r) => r.visibility === "public");
1432 if (publics.length > 0) {
1433 const rows = db
1434 .query<{ id: string }, [string]>(
1435 `SELECT repo.id AS id FROM repo WHERE repo.id IN (SELECT value FROM json_each(?1)) AND ${OWNER_STANDING}`,
1436 )
1437 .all(JSON.stringify(publics.map((r) => r.id)));
1438 for (const r of rows) out.add(r.id);
1439 // A public repository whose owner is out of standing is read by a site admin alone.
1440 if (user?.isAdmin === true) for (const r of publics) out.add(r.id);
1441 }
1442 for (const repo of repos) if (repo.visibility !== "public" && canRead(db, repo, user)) out.add(repo.id);

Non-public repos still cost one canRead each, so the query count is constant only for public repos. That is fine for the front page, because pinned private repos are few. Say so in the doc comment, or batch them later.

1443 return out;
1444 }
1445
14241446 export function canWrite(
14251447 db: Database,
14261448 repo: Repo,
test/can-read-many.test.ts added +92
@@ -0,0 +1,92 @@
1 /**
2 * `canReadMany` answers as `canRead` does for each repository, in a constant number of statements
3 * (#16264).
4 */
5 import { afterAll, beforeAll, expect, spyOn, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { createRepo } from "../src/actions/repos.ts";
11 import { canRead, canReadMany, getReposByIds, type Repo } from "../src/core/repos.ts";
12 import { createUser, type User } from "../src/core/users.ts";
13 import { quietLogs } from "./helpers/globals.ts";
14 import { promote } from "./helpers/members.ts";
15
16 quietLogs();
17
18 let dataDir = "";
19 let app: App;
20 let owner: User;
21 let other: User;
22
23 async function user(name: string, adminIfFirst = false): Promise<User> {
24 const made = await createUser(app.db, {
25 origin: "seed",
26 trusted: true,
27 username: name,
28 allowReserved: true,
29 email: `${name}@forge.local`,
30 password: "a-good-passphrase",
31 adminIfFirst,
32 });
33 if (!made.ok) throw new Error(made.error);
34 promote(app.db, made.value);
35 return made.value;
36 }
37
38 async function repos(prefix: string, n: number, visibility: "public" | "private", by: User): Promise<string[]> {
39 const ids: string[] = [];
40 for (let i = 0; i < n; i++) {
41 const made = await createRepo(app, by, { name: `${prefix}${i}`, visibility, description: "" });
42 if (!made.ok) throw new Error(String(made.error));
43 ids.push(made.value.id);
44 }
45 return ids;
46 }
47
48 const all = (ids: string[]): Repo[] => [...getReposByIds(app.db, ids).values()];
49
50 beforeAll(async () => {
51 dataDir = await mkdtemp(join(tmpdir(), "forge-can-read-many-"));
52 app = createApp({ dataDir, port: 0 });
53 owner = await user("owner", true);
54 other = await user("other");
55 });
56
57 afterAll(async () => {
58 app.close();
59 await rm(dataDir, { recursive: true, force: true });
60 });
61
62 test("agrees with canRead for public, private, forked and held-owner repositories", async () => {
63 const ids = [...(await repos("pub", 3, "public", owner)), ...(await repos("priv", 2, "private", owner))];
64 ids.push(...(await repos("theirs", 2, "public", other)), ...(await repos("hidden", 1, "private", other)));
65 app.db.query("UPDATE repo SET fork_parent_id = ?1 WHERE id = ?2").run(ids[0]!, ids[1]!);
66 app.db.query("UPDATE repo SET fork_parent_id = ?1 WHERE id = ?2").run(ids[3]!, ids[4]!);
67 app.db.query("UPDATE user SET suspended_at = '2026-01-01T00:00:00Z' WHERE id = ?1").run(other.id);
68 const list = all(ids);
69 expect(list.length).toBe(ids.length);
70 for (const viewer of [undefined, owner, other]) {
71 const expected = new Set(list.filter((r) => canRead(app.db, r, viewer)).map((r) => r.id));
72 expect(canReadMany(app.db, list, viewer)).toEqual(expected);
73 }
74 const stranger = canReadMany(app.db, list, undefined);
75 expect(stranger.has(ids[0]!)).toBe(true);
76 expect(stranger.has(ids[3]!)).toBe(false);
77 app.db.query("UPDATE user SET suspended_at = NULL WHERE id = ?1").run(other.id);
78 });
79
80 test("the statements it runs for public repositories do not grow with their number", async () => {
81 const count = (list: Repo[]): number => {
82 const spy = spyOn(app.db, "query");
83 canReadMany(app.db, list, undefined);
84 const n = spy.mock.calls.length;
85 spy.mockRestore();
86 return n;
87 };
88 const few = all(await repos("few", 2, "public", owner));
89 const many = all(await repos("many", 25, "public", owner));
90 expect(count(few)).toBe(1);
91 expect(count(many)).toBe(count(few));
92 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs