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

Access 3a: the /api/v1 repository routes ask may(), shadowed first, then their inline checks go #18165

opened this

Merged 6h 37m ago, live in production

torque/forge:torque/18091-access-3a-the-api-v1-repository-routes-a → main 0 commits fork

  • Merged. torque/18091-access-3a-the-api-v1-repository-routes-a was merged into main as 7ba81ba.

Review

Sign in to review this change.
19 files changed +596 −32
docs/ROLES.md +5
@@ -20,6 +20,11 @@ app); a token also carries its stored scope. `may(principal, action, resource)`
2020 (`src/core/may.ts`) takes this principal, so there is one way to say who is
2121 asking.
2222
23 The `/api/v1/repos/…` routes ask it through `src/http/repo_may.ts` and count
24 any answer that parts from the check they made before in
25 `access_disagreement` (`docs/features/may.md`); `test/repo-routes-may.test.ts`
26 walks every one of them and keeps inline `isAdmin` checks out of their files.
27
2328 An account is a **guest**, a **member** or an **admin**. Admin is the
2429 `is_admin` flag; a member is a row in the `member` table; everyone else is a
2530 guest. `src/core/roles.ts` holds the one table below, and `test/roles.test.ts`
docs/features/may.md +10
@@ -29,3 +29,13 @@ that is not there and one you may not read answer alike.
2929 **MCP.** `whoami_can` lists `actions`, the same names; `repo` adds read, write and admin there.
3030
3131 **Terminal.** Open "What I can do": the last line is `You may:` and the same list.
32
33 **The repository routes ask it.** Every `/api/v1/repos/:owner/:name…` route asks `may` with the credential you send
34 (`src/http/repo_may.ts`): reading the repository is `repo.read`, a change is `repo.write` or `repo.admin`, and a token's
35 scope is part of the answer. What a read *shows* (a writer's label counts, an admin's flag values and upstream, the
36 `permissions` on `GET /api/v1/repos/:owner/:name`) follows your account, so an `ro` token reads what its account reads.
37
38 While the routes move behind `may`, each is also worked out the way it was before; where the two answers part, the
39 forge counts it, by route, action and kind of caller, with no account, token or repository named. Whoever keeps the
40 forge reads the count with `SELECT * FROM access_disagreement ORDER BY seen DESC` in its database. An empty table is
41 the evidence that moving the door changed nobody's access.
scripts/gate.ts +12
@@ -659,6 +659,17 @@ export function tlsPeerRefusal(root = "."): string[] {
659659 return tlsPeerProblems(root, existsSync(allowFile) ? JSON.parse(readFileSync(allowFile, "utf8")) : []);
660660 }
661661
662 /**
663 * The repository API asks `mayRepo` (#18091): no inline `isAdmin`, `scopeAllows`, signed-out or
664 * account-kind check in the files that add `/api/v1/repos/` routes, but those
665 * `src/kernel/repo_route_checks.ts` names by route with why.
666 */
667 export function repoRouteRefusal(root = "."): string[] {
668 if (!existsSync(join(root, "src/kernel/repo_route_checks.ts"))) return [];
669 const { repoRouteRefusalAt } = require("../src/kernel/repo_route_checks.ts") as typeof import("../src/kernel/repo_route_checks.ts");
670 return repoRouteRefusalAt(root);
671 }
672
662673 /**
663674 * Tests wait for a signal, not a clock (#14321): each file under `test/` held
664675 * to its committed count of fixed waits, `mock.module` calls and raised
@@ -1060,6 +1071,7 @@ export const GATE_RULES: readonly GateRule[] = [
10601071 { name: "README cap", kind: "refusal", file: "src/kernel/readme_cap.ts", satisfy: "put the feature's how-to in docs/features/<name>.md, not README.md", run: readmeCapRefusal },
10611072 { name: "billing never deletes", kind: "refusal", file: "src/kernel/destroy_reach.ts", satisfy: "no call path from the billing webhook deletes a forge, an app or a child", run: billingDeletesRefusal },
10621073 { name: "tls peer", kind: "refusal", file: "src/kernel/tls_peer.ts", satisfy: "open client TLS sockets with connectPeer, or list the file in scripts/tls-peer-allow.json with a reason", run: tlsPeerRefusal },
1074 { name: "repository routes ask mayRepo", kind: "refusal", file: "src/kernel/repo_route_checks.ts", satisfy: "ask mayRepo (src/http/repo_may.ts) in a /api/v1/repos/ route, not isAdmin, scopeAllows, !ctx.auth.user or ctx.auth.user.kind; a forge-wide check is named in INLINE_ALLOWED by route with why", run: repoRouteRefusal },
10631075 { name: "test honesty", kind: "refusal", file: "scripts/test_honesty.ts", satisfy: "wait on a signal (test/helpers/poll.ts), not Bun.sleep(<n>), mock.module or a raised timeout; counts only shrink", run: testHonestyRefusal },
10641076 { name: "comment width", kind: "note", file: "src/kernel/comment_wrap.ts", satisfy: "bun scripts/gate.ts --fix, and commit what it rewraps", run: (c) => wrapNote(c) },
10651077 { name: "before/after looks", kind: "note", file: "src/kernel/look_rule.ts", satisfy: "a commit line `Looks: <path>` naming a page of app.looks in forge.json, or `No look: <why>`", run: lookNote },
src/core/access_disagreement.ts added +28
@@ -0,0 +1,28 @@
1 /**
2 * Where `may` and the check it replaced answered differently (#18091). The repository routes ask
3 * `may(principal, …)`; the check before it asked the account alone and left a token's scope to
4 * `requireScope`. Each time the two part, one row is counted: the door, the action, the kind of
5 * principal and what `may` said. No account, token or repository is written, so the table can be
6 * read by anyone who keeps the forge without learning who asked.
7 *
8 * Read it with `SELECT * FROM access_disagreement ORDER BY seen DESC` (docs/ROLES.md).
9 */
10
11 import type { Database } from "bun:sqlite";
12 import type { Action } from "./may.ts";
13 import type { PrincipalKind } from "./principal.ts";
14
15 /** Count one disagreement: `may` said `said`, the old check said the opposite. */
16 export function noteDisagreement(
17 db: Database,
18 door: string,
19 action: Action,
20 principal: PrincipalKind,
21 said: boolean,
22 ): void {
23 db.query(
24 `INSERT INTO access_disagreement (door, action, principal, may, seen, last_at)
25 VALUES (?1, ?2, ?3, ?4, 1, ?5)
26 ON CONFLICT (door, action, principal, may) DO UPDATE SET seen = seen + 1, last_at = excluded.last_at`,
27 ).run(door, action, principal, said ? 1 : 0, new Date().toISOString());
28 }
src/core/migration-pins/20261204090000-access-disagreement.pin added +1
@@ -0,0 +1,1 @@
1 e772919de3f54b07b2885a97569d0a805bc8e53e47770a8d6e108a45c1f9da09
src/core/migrations/20261204090000-access-disagreement.ts added +14
@@ -0,0 +1,14 @@
1 // Access 3a (#18091): where `may` and the check a repository route made before it answered
2 // differently, counted by door, action and the kind of principal asking. No account, token or
3 // repository is named: a row says only that the two answers parted, where and for what kind.
4 export default `
5 CREATE TABLE IF NOT EXISTS access_disagreement (
6 door TEXT NOT NULL,
7 action TEXT NOT NULL,
8 principal TEXT NOT NULL,
9 may INTEGER NOT NULL,
10 seen INTEGER NOT NULL DEFAULT 1,
11 last_at TEXT NOT NULL,
12 PRIMARY KEY (door, action, principal, may)
13 );
14 `;
src/http/api.ts +10 −10
@@ -146,7 +146,6 @@ import {
146146 type Pull,
147147 } from "../core/pulls.ts";
148148 import {
149 canAdmin,
150149 canRead,
151150 countsForRepos,
152151 getRepo,
@@ -155,7 +154,6 @@ import {
155154 visibleReposMarker,
156155 type Repo,
157156 type RepoCounts,
158 canWrite,
159157 getRepoById,
160158 isLanding,
161159 } from "../core/repos.ts";
@@ -309,6 +307,7 @@ import {
309307 tryAgain,
310308 retryAfterOf,
311309 } from "./respond.ts";
310 import { accountMayRepo, mayRepo } from "./repo_may.ts";
312311 import { exploreApi } from "./explore_json.ts";
313312 import { frontInput, frontJson, setFront } from "../actions/front.ts";
314313 import { COPIES_PER_DAY, makeItYours } from "../actions/make_it_yours.ts";
@@ -1150,7 +1149,7 @@ export function appLimitResponse(ctx: Ctx, ownerName: string): Response {
11501149 /** The repo a route names, if the viewer may see it. */
11511150 export function loadRepo(ctx: Ctx): Repo | undefined {
11521151 const repo = getRepo(ctx.app.db, ctx.params.owner!, ctx.params.name!);
1153 return repo && canRead(ctx.app.db, repo, ctx.auth.user) ? repo : undefined;
1152 return repo && mayRepo(ctx, "repo", "repo.read", repo) ? repo : undefined;
11541153 }
11551154
11561155 function dirOf(ctx: Ctx, repo: Repo): string {
@@ -1733,13 +1732,14 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
17331732 const upstream = upstreamFacts(ctx.app.db, repo, ctx.auth.user);
17341733 // `facts` is already cut to the viewer; the rest are reader fields. `permissions` is what this
17351734 // viewer may do here, as a Gitea client reads it: another forge connected to this one as an
1736 // origin asks it before proposing, to push a branch here or to its own fork (#10262).
1735 // origin asks it before proposing, to push a branch here or to its own fork (#10262). They are
1736 // the account's, as Gitea's are, whatever token carries the request (`http/repo_may.ts`).
17371737 const viewer = ctx.auth.user;
17381738 // `fork`: whether this forge would take the viewer's fork, so a proposal is never planned
17391739 // through a fork the new-account guard refuses.
17401740 const permissions = {
1741 push: viewer !== undefined && canWrite(ctx.app.db, repo, viewer),
1742 admin: viewer !== undefined && canAdmin(ctx.app.db, repo, viewer),
1741 push: accountMayRepo(ctx, "repo.write", repo),
1742 admin: accountMayRepo(ctx, "repo.admin", repo),
17431743 fork: viewer !== undefined && !forkHeld(ctx.app, viewer, repo),
17441744 };
17451745 const res = json({ ...facts, audience, upstream, credit, permissions });
@@ -1757,7 +1757,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
17571757 if (!repo) return notFound();
17581758 const input = await body(ctx.request);
17591759 // The caller can already read this repository, so saying no is no leak.
1760 if (input.archived !== undefined && !canAdmin(ctx.app.db, repo, ctx.auth.user))
1760 if (input.archived !== undefined && !mayRepo(ctx, "repo.archive", "repo.admin", repo))
17611761 return apiError("forbidden", 403, "only an admin archives or wakes");
17621762 if (input.landing !== undefined && !isLanding(input.landing))
17631763 return apiError("bad_landing", 422, "landing is linear or merge");
@@ -1782,7 +1782,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
17821782 // so a request that cannot have this field saves none of the others —
17831783 // and before the record is looked at, so the refusal is the same
17841784 // whether there is a hidden trail or none.
1785 if (ctx.auth.user?.kind === "agent" || !canAdmin(ctx.app.db, repo, ctx.auth.user))
1785 if (!mayRepo(ctx, "repo.provenance", "repo.admin", repo, "people"))
17861786 return respondAccess("not_found", 422);
17871787 if (getProvenance(ctx.app.db, repo.id) === undefined)
17881788 return apiError("no_provenance", 422, FAMILY_WORDS.no_provenance);
@@ -3782,9 +3782,9 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
37823782 if (denied) return denied;
37833783 const found = loadPull(ctx);
37843784 if ("error" in found) return found.error;
3785 if (!ctx.auth.user || !canWrite(ctx.app.db, found.repo, ctx.auth.user))
3785 if (!mayRepo(ctx, "pull.check", "repo.write", found.repo))
37863786 return apiError("forbidden", 403, "only a writer can ask for a check");
3787 const asked = await askCheck(ctx.app, ctx.auth.user, found.repo, found.pull);
3787 const asked = await askCheck(ctx.app, ctx.auth.user!, found.repo, found.pull);
37883788 if (!asked.ok) return apiError(asked.error, 409, asked.message);
37893789 return json({ run: asked.run, place: asked.place ?? null, says: askedWords(asked) ?? CHECK_ASKED }, 202);
37903790 },
src/http/api/app.ts +3 −2
@@ -16,7 +16,7 @@ import { previewBuild, previewBuildRefusalText } from "../../actions/build_previ
1616 import { SETTING_WORDS } from "../../actions/setting_words.ts";
1717 import { appLog } from "../../actions/app_log.ts";
1818 import { appsRuntime } from "../../apps/runtime_registry.ts";
19 import { canAdmin, canRead, getRepo } from "../../core/repos.ts";
19 import { canRead, getRepo } from "../../core/repos.ts";
2020 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
2121 import type { Result } from "../../kernel/result.ts";
2222 import { appJson, appLimitResponse, loadRepo } from "../api.ts";
@@ -24,6 +24,7 @@ import type { Ctx, Handler } from "../context.ts";
2424 import { holds, weakEtag } from "../etag.ts";
2525 import { BUILD_ASKS_WINDOW_MS } from "../../actions/build_preview.ts";
2626 import { apiError, body, json, notFound, requireScope, respondAccess, str, tryAgain, unauthorized } from "../respond.ts";
27 import { accountMayRepo } from "../repo_may.ts";
2728 import { DEFAULT_ENV_SCOPE } from "../../core/app_env.ts";
2829 import { getAppByRepo } from "../../core/apps.ts";
2930 import { normalizeHost } from "../../core/domains.ts";
@@ -86,7 +87,7 @@ export function appRoutes(router: Router<Handler>): void {
8687 if (!repo) return notFound();
8788 const rows = await servedFlags(ctx.app, repo);
8889 // The viewer ids a flag lists are personal data: only the repository's admin is told them.
89 const admin = ctx.auth.user !== undefined && canAdmin(ctx.app.db, repo, ctx.auth.user);
90 const admin = accountMayRepo(ctx, "repo.admin", repo);
9091 return tagged(ctx, {
9192 flags: rows.map((r) => ({ name: r.name, why: r.why, default: r.default, value: admin ? (r.value ?? null) : withoutViewers(r.value) })),
9293 });
src/http/api/deepsec.ts +2 −2
@@ -14,10 +14,10 @@
1414 import { fileFindings } from "../../checks/deepsec.ts";
1515 import { FILES_MAX } from "../../checks/deepsec_findings.ts";
1616 import { getPull } from "../../core/pulls.ts";
17 import { canWrite } from "../../core/repos.ts";
1817 import { loadRepo } from "../api.ts";
1918 import type { Handler } from "../context.ts";
2019 import { apiError, body, forbidden, json, notFound, requireScope } from "../respond.ts";
20 import { mayRepo } from "../repo_may.ts";
2121 import type { Router } from "../router.ts";
2222
2323 export function deepsecRoutes(router: Router<Handler>): void {
@@ -26,7 +26,7 @@ export function deepsecRoutes(router: Router<Handler>): void {
2626 if (denied) return denied;
2727 const repo = loadRepo(ctx);
2828 if (!repo) return notFound();
29 if (!canWrite(ctx.app.db, repo, ctx.auth.user)) return forbidden();
29 if (!mayRepo(ctx, "deepsec", "repo.write", repo)) return forbidden();
3030 const input = await body(ctx.request);
3131 const files = input["files"];
3232 const runs = input["runs"] ?? [];
src/http/api/hooks.ts +5 −5
@@ -8,13 +8,13 @@
88 */
99
1010 import { createWebhook, deleteWebhook, pauseWebhook, redeliverWebhook } from "../../actions/repos.ts";
11 import { canAdmin } from "../../core/repos.ts";
1211 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
1312 import { getWebhook, listWebhooks, pingWebhook, recentDeliveries } from "../../core/webhooks.ts";
1413 import { loadRepo, pageParams, slicePage } from "../api.ts";
1514 import type { Ctx, Handler } from "../context.ts";
1615 import { holds, weakEtag } from "../etag.ts";
1716 import { body, json, notFound, requireScope, respondAccess, str, tryAgain } from "../respond.ts";
17 import { mayRepo } from "../repo_may.ts";
1818 import type { Router } from "../router.ts";
1919
2020 /**
@@ -36,7 +36,7 @@ export function hookRoutes(router: Router<Handler>): void {
3636 const denied = requireScope(ctx, "admin");
3737 if (denied) return denied;
3838 const repo = loadRepo(ctx);
39 if (!repo || !canAdmin(ctx.app.db, repo, ctx.auth.user)) return notFound();
39 if (!repo || !mayRepo(ctx, "hooks.list", "repo.admin", repo)) return notFound();
4040 const page = pageParams(ctx);
4141 if (page instanceof Response) return page;
4242 const rows = timePhase(ctx.request, "hooks", () => listWebhooks(ctx.app.db, repo.id));
@@ -50,7 +50,7 @@ export function hookRoutes(router: Router<Handler>): void {
5050 // A token short of admin learns nothing: the same 404 as a missing hook.
5151 if (denied) return denied.status === 403 ? notFound() : denied;
5252 const repo = loadRepo(ctx);
53 if (!repo || !canAdmin(ctx.app.db, repo, ctx.auth.user)) return notFound();
53 if (!repo || !mayRepo(ctx, "hooks.deliveries", "repo.admin", repo)) return notFound();
5454 if (!getWebhook(ctx.app.db, repo.id, ctx.params.id!)) return notFound();
5555 return tagged(ctx, { items: recentDeliveries(ctx.app.db, ctx.params.id!, 20) });
5656 });
@@ -59,7 +59,7 @@ export function hookRoutes(router: Router<Handler>): void {
5959 const denied = requireScope(ctx, "admin");
6060 if (denied) return denied.status === 403 ? notFound() : denied;
6161 const repo = loadRepo(ctx);
62 if (!repo || !canAdmin(ctx.app.db, repo, ctx.auth.user)) return notFound();
62 if (!repo || !mayRepo(ctx, "hooks.ping", "repo.admin", repo)) return notFound();
6363 const hook = getWebhook(ctx.app.db, repo.id, ctx.params.id!);
6464 if (!hook) return notFound();
6565 const pinged = pingWebhook(ctx.app.db, `${ctx.params.owner}/${ctx.params.name}`, hook);
@@ -73,7 +73,7 @@ export function hookRoutes(router: Router<Handler>): void {
7373 // As for ping: a token short of admin learns nothing, the same 404.
7474 if (denied) return denied.status === 403 ? notFound() : denied;
7575 const repo = loadRepo(ctx);
76 if (!repo || !canAdmin(ctx.app.db, repo, ctx.auth.user)) return notFound();
76 if (!repo || !mayRepo(ctx, "hooks.pause", "repo.admin", repo)) return notFound();
7777 const done = pauseWebhook(ctx.app, ctx.auth.user, repo, ctx.params.id!, pause);
7878 if (!done.ok) return notFound();
7979 return json({ id: ctx.params.id!, active: !pause });
src/http/api/issues.ts +1 −2
@@ -394,9 +394,8 @@ export function issueRoutes(router: Router<Handler>): void {
394394 if (denied) return denied;
395395 const found = loadIssue(ctx);
396396 if ("error" in found) return found.error;
397 if (ctx.auth.user === undefined) return apiError("unauthorized", 401, "sign in to record an estimate");
398397 const input = await body(ctx.request);
399 const made = recordEstimate(ctx.app, ctx.auth.user, found.repo, found.issue, input);
398 const made = recordEstimate(ctx.app, ctx.auth.user!, found.repo, found.issue, input);
400399 return made.ok
401400 ? json(made.value, 201)
402401 : apiError(made.error.kind, made.error.kind === "forbidden" ? 403 : 422, made.error.message);
src/http/api/labels.ts +2 −2
@@ -8,11 +8,11 @@ import { createLabel, deleteLabel, updateLabel } from "../../actions/repos.ts";
88 import { LABEL_WORDS } from "../../actions/label_words.ts";
99 import { labelsWithOpen, listLabels } from "../../core/issues.ts";
1010 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
11 import { canWrite } from "../../core/repos.ts";
1211 import { loadRepo, pageOf, pageParams } from "../api.ts";
1312 import { holds, weakEtag } from "../etag.ts";
1413 import type { Handler } from "../context.ts";
1514 import { body, json, notFound, requireScope, respondAccess, str } from "../respond.ts";
15 import { accountMayRepo } from "../repo_may.ts";
1616 import type { Router } from "../router.ts";
1717
1818 export function labelsRoutes(router: Router<Handler>): void {
@@ -24,7 +24,7 @@ export function labelsRoutes(router: Router<Handler>): void {
2424 if (page instanceof Response) return page;
2525 // Sealed items are counted, so only a writer is told how many are open.
2626 const rows = timePhase(ctx.request, "labels", () =>
27 labelsWithOpen(ctx.app.db, repo.id, canWrite(ctx.app.db, repo, ctx.auth.user)),
27 labelsWithOpen(ctx.app.db, repo.id, accountMayRepo(ctx, "repo.write", repo)),
2828 );
2929 const res = timePhase(ctx.request, "render", () => pageOf(rows, page));
3030 if (res.status !== 200) return res;
src/http/api/outside_checks.ts +3 −3
@@ -9,10 +9,10 @@
99 */
1010
1111 import { parseReport, recordReport } from "../../checks/outside_checks.ts";
12 import { canWrite } from "../../core/repos.ts";
1312 import { loadPull, pullHeadOid } from "../api.ts";
1413 import type { Handler } from "../context.ts";
1514 import { apiError, body, json, requireScope } from "../respond.ts";
15 import { mayRepo } from "../repo_may.ts";
1616 import type { Router } from "../router.ts";
1717
1818 export function outsideChecksRoutes(router: Router<Handler>): void {
@@ -21,9 +21,9 @@ export function outsideChecksRoutes(router: Router<Handler>): void {
2121 if (denied) return denied;
2222 const found = loadPull(ctx);
2323 if ("error" in found) return found.error;
24 const user = ctx.auth.user;
25 if (!user || user.kind === "agent" || !canWrite(ctx.app.db, found.repo, user))
24 if (!mayRepo(ctx, "pull.outside_check", "repo.write", found.repo, "people"))
2625 return apiError("forbidden", 403, "only a person who can write here reports a check");
26 const user = ctx.auth.user!;
2727 if (found.pull.state !== "open") return apiError("not_open", 409, "only an open pull is reported on");
2828 const input = await body(ctx.request);
2929 const report = parseReport(ctx.params.check!, input);
src/http/api/pulls.ts +2 −2
@@ -58,7 +58,6 @@ import {
5858 import {
5959 getRepo,
6060 type Repo,
61 canWrite,
6261 } from "../../core/repos.ts";
6362 import {
6463 isReviewState,
@@ -105,6 +104,7 @@ import {
105104 str,
106105 tryAgain,
107106 } from "../respond.ts";
107 import { mayRepo } from "../repo_may.ts";
108108 import type { Router } from "../router.ts";
109109 import { ANSWER_WORDS } from "../../core/arg_words.ts";
110110 import {
@@ -235,7 +235,7 @@ export function pullRoutes(router: Router<Handler>): void {
235235 const denied = requireScope(ctx, "rw");
236236 if (denied) return denied;
237237 const repo = loadRepo(ctx);
238 if (!repo || !canWrite(ctx.app.db, repo, ctx.auth.user)) return notFound();
238 if (!repo || !mayRepo(ctx, "proposal_token", "repo.write", repo)) return notFound();
239239 const input = await boundedBody(ctx.request, PROPOSAL_BODY_MAX);
240240 if (input === "too_large")
241241 return apiError("too_large", 413, `at most ${PROPOSAL_BODY_MAX} bytes`);
src/http/api/repo_source.ts +2 −2
@@ -4,11 +4,11 @@
44 * address is judged by `sourceText` before anything is kept.
55 */
66
7 import { canAdmin } from "../../core/repos.ts";
87 import { setRepoSource } from "../../core/repo_source.ts";
98 import { loadRepo } from "../api.ts";
109 import type { Handler } from "../context.ts";
1110 import { apiError, body, json, notFound, requireScope, str } from "../respond.ts";
11 import { mayRepo } from "../repo_may.ts";
1212 import type { Router } from "../router.ts";
1313
1414 export function repoSourceRoutes(router: Router<Handler>): void {
@@ -16,7 +16,7 @@ export function repoSourceRoutes(router: Router<Handler>): void {
1616 const denied = requireScope(ctx, "admin");
1717 if (denied) return denied;
1818 const repo = loadRepo(ctx);
19 if (!repo || !canAdmin(ctx.app.db, repo, ctx.auth.user)) return notFound();
19 if (!repo || !mayRepo(ctx, "repo.source", "repo.admin", repo)) return notFound();
2020 const input = await body(ctx.request);
2121 const saved = setRepoSource(ctx.app.db, repo.id, str(input.source));
2222 if (!saved.ok) return apiError("bad_source", 422, saved.error);
src/http/api/upstream.ts +3 −2
@@ -21,7 +21,7 @@ import { ENABLED_WORDS } from "../../core/arg_words.ts";
2121 import { forkFlows } from "../../core/fork_flows.ts";
2222 import { followWords } from "../../actions/follow.ts";
2323 import { driftOfForks, MAX_RANKED_FORKS, type RankedFork } from "../../actions/forks.ts";
24 import { canAdmin, forkParentFor, visibleForks } from "../../core/repos.ts";
24 import { forkParentFor, visibleForks } from "../../core/repos.ts";
2525 import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts";
2626 import { storageLimitMessage } from "../../core/storage.ts";
2727 import { getFollow, isFollowTaking } from "../../core/upstream_follow.ts";
@@ -29,6 +29,7 @@ import { holds, weakEtag } from "../etag.ts";
2929 import { loadRepo, pageParams, slicePage } from "../api.ts";
3030 import type { Handler } from "../context.ts";
3131 import { apiError, body, json, notFound, requireScope, respondAccess, str, tryAgain, WINDOW } from "../respond.ts";
32 import { accountMayRepo } from "../repo_may.ts";
3233 import type { Router } from "../router.ts";
3334
3435 /** Seconds until the oldest fork in the last day ages out and frees a place. */
@@ -47,7 +48,7 @@ export function upstreamRoutes(router: Router<Handler>): void {
4748 if (denied) return denied;
4849 const read = timePhase(ctx.request, "upstream", () => {
4950 const repo = loadRepo(ctx);
50 if (!repo || !canAdmin(ctx.app.db, repo, ctx.auth.user)) return undefined;
51 if (!repo || !accountMayRepo(ctx, "repo.admin", repo)) return undefined;
5152 return getFollow(ctx.app.db, repo.id) ?? null;
5253 });
5354 if (read === undefined) return notFound();
src/http/repo_may.ts added +53
@@ -0,0 +1,53 @@
1 /**
2 * The one check a `/api/v1/repos/…` route makes (#18091): `may(principal, action, { repo })`
3 * (`core/may.ts`), asked with the credential the request carries.
4 *
5 * Before this, a route asked the account alone (`canRead`, `canWrite`, `canAdmin` with
6 * `ctx.auth.user`) and left a token's scope to `requireScope`. That answer is still worked out
7 * beside `may`'s, and when the two part the door, action and kind of principal are counted
8 * (`core/access_disagreement.ts`): the comparison that moves this door without changing who gets
9 * in. Only a token carries a scope, so only a token's answer can part from its account's; a
10 * session or an anonymous visitor costs one rule read, as before.
11 *
12 * Two questions, kept apart on purpose:
13 * - `mayRepo`: may this request do this? The gate of every change, and of reading the repository.
14 * - `accountMayRepo`: what may the account behind it do? For a read the request already passed
15 * `repo.read` for, whose reach depends on the account's standing (a writer's label counts, an
16 * admin's flag values and upstream, Gitea's `permissions`): an `ro` token reads what its account
17 * reads, as it did before `may`, and is never told its account is less than it is.
18 */
19
20 import { noteDisagreement } from "../core/access_disagreement.ts";
21 import { holds } from "../core/may.ts";
22 import { principalOf, principalOfUser } from "../core/principal.ts";
23 import type { Repo } from "../core/repos.ts";
24 import type { Ctx } from "./context.ts";
25
26 export type RepoAction = "repo.read" | "repo.write" | "repo.admin";
27
28 /**
29 * Who a door is for beyond the action: `anyone` the action allows, or `people`, an account that is
30 * not an agent (a record of where a repository came from, a check reported from outside: a
31 * person's word, never a crew member's). Said here, so no route asks the account's kind itself.
32 */
33 export type RepoAudience = "anyone" | "people";
34
35 /**
36 * May this request take `action` on `repo`? `door` names the route in the disagreement count; an
37 * agent is turned away from a `people` door whatever the action says, by either answer.
38 */
39 export function mayRepo(ctx: Ctx, door: string, action: RepoAction, repo: Repo, audience: RepoAudience = "anyone"): boolean {
40 if (audience === "people" && ctx.auth.user?.kind === "agent") return false;
41 const asking = principalOf(ctx.auth);
42 const said = holds(ctx.app.db, asking, action, { repo });
43 if ("scope" in asking) {
44 const before = holds(ctx.app.db, principalOfUser(ctx.auth.user), action, { repo });
45 if (before !== said) noteDisagreement(ctx.app.db, door, action, asking.kind, said);
46 }
47 return said;
48 }
49
50 /** May the account behind this request take `action` on `repo`, whatever credential carries it? */
51 export function accountMayRepo(ctx: Ctx, action: RepoAction, repo: Repo): boolean {
52 return holds(ctx.app.db, principalOfUser(ctx.auth.user), action, { repo });
53 }
src/kernel/repo_route_checks.ts added +136
@@ -0,0 +1,136 @@
1 /**
2 * The repository API asks one function (#18091): every `/api/v1/repos/:owner/:name…` route says who
3 * may pass by `mayRepo` (`http/repo_may.ts`), never by reading the account inline. This is the scan
4 * the gate holds the route files to: in `src/http/api.ts` and each `src/http/api/*.ts` that adds a
5 * repository route, every inline `isAdmin`, `scopeAllows`, signed-out test (`!ctx.auth.user`) and
6 * account-kind test (`ctx.auth.user?.kind`) is found, and named by the route or function it sits
7 * in.
8 *
9 * One is allowed only when `INLINE_ALLOWED` names that file, place and check with why: a forge-wide
10 * route whose check is not about a repository and moves with the forge-wide door, or a repository
11 * route whose test is not a permission. A check inside a repository route that is not named is
12 * refused, as is one in a forge-wide route not named, so swapping one inline check for another
13 * fails too; an entry nothing matches any more is refused, so the list only shrinks.
14 */
15
16 import { existsSync, readdirSync, readFileSync } from "node:fs";
17 import { join } from "node:path";
18
19 export type InlineCheck = "isAdmin" | "scopeAllows" | "signedOut" | "accountKind";
20
21 /** One inline check found: the file, where it sits (`GET /api/v1/…` or `name()`) and its line. */
22 export interface InlineFound {
23 readonly file: string;
24 readonly where: string;
25 readonly check: InlineCheck;
26 readonly line: number;
27 }
28
29 /** One inline check allowed to stay, by file, place and kind, and why. */
30 export interface InlineAllowed {
31 readonly file: string;
32 readonly where: string;
33 readonly check: InlineCheck;
34 readonly why: string;
35 }
36
37 const CHECKS: readonly (readonly [InlineCheck, RegExp])[] = [
38 ["isAdmin", /\bisAdmin\b/g],
39 ["scopeAllows", /\bscopeAllows\b/g],
40 // A gate, not a label: `!ctx.auth.user`, or `=== undefined` opening a condition or in a chain.
41 ["signedOut", /!\s*ctx\.auth\.user\b(?!\s*\??\.)|(?:\bif\s*\(|\|\||&&)\s*ctx\.auth\.user\s*===?\s*(?:undefined|null)\b/g],
42 ["accountKind", /\bctx\.auth\.user\s*\??\.\s*kind\b/g],
43 ];
44
45 const FORGE_WIDE = "a forge-wide route: not about a repository, it moves with the forge-wide door";
46
47 /** The checks that stay, each named by where it is. Only shrinks. */
48 export const INLINE_ALLOWED: readonly InlineAllowed[] = [
49 { file: "src/http/api.ts", where: "boardsAdmin()", check: "signedOut", why: `the boards' admin, ${FORGE_WIDE}` },
50 { file: "src/http/api.ts", where: "boardsAdmin()", check: "isAdmin", why: `the boards' admin, ${FORGE_WIDE}` },
51 { file: "src/http/api.ts", where: "boardsAdmin()", check: "accountKind", why: `the boards' admin, ${FORGE_WIDE}` },
52 { file: "src/http/api.ts", where: "GET /api/v1/users/:username/repos", check: "signedOut", why: FORGE_WIDE },
53 { file: "src/http/api.ts", where: "GET /api/v1/telemetry/routes", check: "signedOut", why: FORGE_WIDE },
54 { file: "src/http/api.ts", where: "GET /api/v1/telemetry/routes", check: "isAdmin", why: FORGE_WIDE },
55 { file: "src/http/api.ts", where: "GET /api/v1/crew/week", check: "isAdmin", why: FORGE_WIDE },
56 { file: "src/http/api.ts", where: "GET /api/v1/crew/now", check: "signedOut", why: FORGE_WIDE },
57 { file: "src/http/api.ts", where: "POST /api/v1/conversation-tokens", check: "signedOut", why: FORGE_WIDE },
58 { file: "src/http/api.ts", where: "GET /api/v1/fleet/ops", check: "signedOut", why: FORGE_WIDE },
59 { file: "src/http/api.ts", where: "GET /api/v1/family", check: "isAdmin", why: FORGE_WIDE },
60 { file: "src/http/api.ts", where: "GET /api/v1/usage", check: "signedOut", why: FORGE_WIDE },
61 { file: "src/http/api.ts", where: "GET /api/v1/fleet/graph", check: "signedOut", why: FORGE_WIDE },
62 {
63 file: "src/http/api/issues.ts",
64 where: "POST /api/v1/repos/:owner/:name/issues",
65 check: "signedOut",
66 why: "which door a stranger is shown (report instead), not whether they pass: requireScope refuses them next either way",
67 },
68 {
69 file: "src/http/api/statement.ts",
70 where: "GET /api/v1/repos/:owner/:name/statement",
71 check: "signedOut",
72 why: "a stranger is told not_found before the scope's 401, so a statement is never said to exist: who is asking, not what the repository allows",
73 },
74 {
75 file: "src/http/api/cdn.ts",
76 where: "GET /api/v1/repos/:owner/:name/cdn",
77 check: "signedOut",
78 why: "a rate, not a permission: `loadRepo` already asked mayRepo, and a stranger's reads are counted by address",
79 },
80 ];
81
82 /** The route a handler registers, or the function it is: what an inline check is named by. */
83 const PLACE = /router\.add\(\s*"([A-Z]+)"\s*,\s*"([^"]+)"|^(?:export\s+)?(?:async\s+)?function\s+([A-Za-z0-9_]+)/gm;
84
85 /** Every inline check in `text`, named by the last route or top-level function before it. */
86 export function inlineChecks(file: string, text: string): InlineFound[] {
87 const places: { at: number; name: string }[] = [];
88 for (const m of text.matchAll(PLACE))
89 places.push({ at: m.index ?? 0, name: m[3] !== undefined ? `${m[3]}()` : `${m[1]} ${m[2]}` });
90 const found: (InlineFound & { at: number })[] = [];
91 for (const [check, re] of CHECKS)
92 for (const m of text.matchAll(re)) {
93 const at = m.index ?? 0;
94 const place = places.filter((p) => p.at <= at).at(-1);
95 found.push({ file, where: place?.name ?? "(top of file)", check, line: text.slice(0, at).split("\n").length, at });
96 }
97 return found.sort((a, b) => a.at - b.at).map(({ at: _, ...f }) => f);
98 }
99
100 /** The files the repository routes live in: `http/api.ts` and every module that adds one. */
101 export function repoRouteFiles(root: string): string[] {
102 const dir = join(root, "src/http/api");
103 const mods = existsSync(dir)
104 ? readdirSync(dir)
105 .filter((f) => f.endsWith(".ts"))
106 .map((f) => `src/http/api/${f}`)
107 .filter((f) => readFileSync(join(root, f), "utf8").includes("/api/v1/repos/"))
108 : [];
109 return [...(existsSync(join(root, "src/http/api.ts")) ? ["src/http/api.ts"] : []), ...mods.sort()];
110 }
111
112 const key = (x: { file: string; where: string; check: InlineCheck }): string => `${x.file}|${x.where}|${x.check}`;
113
114 /** What the gate says: each inline check not allowed, and each allowance nothing uses. */
115 export function repoRouteCheckProblems(found: readonly InlineFound[], allowed: readonly InlineAllowed[] = INLINE_ALLOWED): string[] {
116 const named = new Set(allowed.map(key));
117 const used = new Set(found.map(key));
118 const out: string[] = [];
119 for (const f of found)
120 if (!named.has(key(f)))
121 out.push(
122 f.where.includes(" /api/v1/repos/")
123 ? `rule "repository routes ask mayRepo": ${f.file}:${f.line} ${f.check} in ${f.where}; ask mayRepo (src/http/repo_may.ts) instead`
124 : `rule "repository routes ask mayRepo": ${f.file}:${f.line} ${f.check} in ${f.where}; a new inline check in a repository route file: ask mayRepo, or name it in INLINE_ALLOWED (src/kernel/repo_route_checks.ts) with why`,
125 );
126 for (const a of allowed)
127 if (!used.has(key(a)))
128 out.push(`rule "repository routes ask mayRepo": INLINE_ALLOWED names ${a.check} in ${a.where} (${a.file}), which is gone; remove the entry`);
129 return out;
130 }
131
132 /** The scan of the tree at `root`. */
133 export function repoRouteRefusalAt(root: string): string[] {
134 const found = repoRouteFiles(root).flatMap((f) => inlineChecks(f, readFileSync(join(root, f), "utf8")));
135 return repoRouteCheckProblems(found);
136 }
test/repo-routes-may.test.ts added +304
@@ -0,0 +1,304 @@
1 /**
2 * Access 3a (#18091): every `/api/v1/repos/:owner/:name…` route asks `may` (`http/repo_may.ts`),
3 * and beside it the account-only check it replaced; where the two part, a row is counted in
4 * `access_disagreement`. The walk below asks every repository route, by every verb it answers,
5 * as anonymous, a guest, a member, a team writer, an organization admin and the site's admin
6 * (each signed in and by an `ro`, `rw` and `admin` token) and by the narrower token kinds, on a
7 * public and a private repository, and finds no disagreement; `PATCH`'s inner branches are sent
8 * the bodies that reach them. The gate (`src/kernel/repo_route_checks.ts`) keeps the inline checks
9 * from coming back into the files those routes live in; here it is shown to bite.
10 */
11 import { afterAll, beforeAll, expect, test } from "bun:test";
12 import { mkdtemp, rm } from "node:fs/promises";
13 import { tmpdir } from "node:os";
14 import { join } from "node:path";
15 import { createAgent } from "../src/actions/crew.ts";
16 import { openPull } from "../src/actions/pulls.ts";
17 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
18 import { createApp, type App } from "../src/app.ts";
19 import { mintContribute } from "../src/core/contribute_token.ts";
20 import { addTeamMember, createOrg, createTeam } from "../src/core/orgs.ts";
21 import { mintProposalToken } from "../src/core/proposal_token.ts";
22 import { getRepo, type Repo } from "../src/core/repos.ts";
23 import { mintRunToken } from "../src/core/run_token.ts";
24 import { createSession } from "../src/core/sessions.ts";
25 import { createToken } from "../src/core/tokens.ts";
26 import { createUser, type User } from "../src/core/users.ts";
27 import { mintViaToken } from "../src/core/via_token.ts";
28 import type { Ctx } from "../src/http/context.ts";
29 import { accountMayRepo, mayRepo } from "../src/http/repo_may.ts";
30 import { buildApiRouter, forgeHttp } from "../src/http/server.ts";
31 import { inlineChecks, INLINE_ALLOWED, repoRouteCheckProblems } from "../src/kernel/repo_route_checks.ts";
32 import { GATE_RULES, repoRouteRefusal } from "../scripts/gate.ts";
33 import { quietLogs } from "./helpers/globals.ts";
34 import { promote } from "./helpers/members.ts";
35
36 quietLogs();
37
38 const HOST = "forge.test";
39 const PEOPLE = ["boss", "gina", "nina", "wes", "wren"] as const;
40 type Person = (typeof PEOPLE)[number];
41
42 let dataDir = "";
43 const cellsBefore = process.env["FORGE_CELLS"];
44 let app: App;
45 const users = {} as Record<Person, User>;
46
47 beforeAll(async () => {
48 process.env["FORGE_CELLS"] = "off"; // env-restored: afterAll
49 dataDir = await mkdtemp(join(tmpdir(), "forge-repo-may-"));
50 app = createApp({ dataDir, port: 0, host: HOST });
51 for (const name of PEOPLE) {
52 const made = await createUser(app.db, {
53 origin: "seed", trusted: true, username: name, email: `${name}@forge.local`,
54 password: "a-good-passphrase", adminIfFirst: name === "boss",
55 });
56 if (!made.ok) throw new Error(String(made.error));
57 users[name] = made.value;
58 }
59 // gina stays a guest; nina is a member who reaches neither repository by a team.
60 promote(app.db, users.boss, users.nina, users.wes, users.wren);
61 const org = createOrg(app.db, "acme", users.wren.id);
62 if (!org.ok) throw new Error(String(org.error));
63 const team = createTeam(app.db, org.value.id, "Writers", "write");
64 if (!team.ok) throw new Error(String(team.error));
65 addTeamMember(app.db, team.value, users.wes.id);
66 for (const [name, visibility] of [["pub", "public"], ["priv", "private"]] as const) await makeRepo(name, visibility);
67 });
68
69 afterAll(async () => {
70 if (cellsBefore === undefined) delete process.env["FORGE_CELLS"];
71 else process.env["FORGE_CELLS"] = cellsBefore;
72 app.close();
73 await rm(dataDir, { recursive: true, force: true });
74 });
75
76 /**
77 * A repository with a commit, a branch and pull #1, so the routes that read them go past the door.
78 */
79 async function makeRepo(name: string, visibility: "public" | "private"): Promise<Repo> {
80 const made = await createRepo(app, users.wren, { owner: "acme", name, visibility });
81 if (!made.ok) throw new Error(String(made.error));
82 for (const [branch, file] of [[undefined, "forge.json"], ["topic", "t.txt"]] as const) {
83 const done = await commitToBranch(app, users.wren, made.value, {
84 ...(branch === undefined ? {} : { branch }),
85 message: "change",
86 files: [{ path: file, content: file === "forge.json" ? "{}" : "x" }],
87 });
88 if (!done.ok) throw new Error(JSON.stringify(done.error));
89 }
90 const pull = await openPull(app, users.wren, made.value, { title: "t", body: "", baseBranch: "main", headBranch: "topic" });
91 if (!pull.ok) throw new Error(JSON.stringify(pull.error));
92 return made.value;
93 }
94
95 /** The repository by name, made again when a route before (a delete, a rename) took it away. */
96 async function present(name: "pub" | "priv"): Promise<Repo> {
97 return getRepo(app.db, "acme", name) ?? (await makeRepo(name, name === "pub" ? "public" : "private"));
98 }
99
100 type Caller = { label: string; headers: (repo: Repo) => Record<string, string> };
101 const bearer = (label: string, token: (repo: Repo) => string): Caller => ({ label, headers: (repo) => ({ authorization: `Bearer ${token(repo)}` }) });
102 const until = (ms: number): string => new Date(Date.now() + ms).toISOString();
103 const plain = (who: Person, scope: "ro" | "rw" | "admin"): Caller =>
104 bearer(`${who} ${scope} token`, () => createToken(app.db, users[who].id, scope, scope).token);
105 const session = (who: Person): Caller => ({
106 label: `${who} session`,
107 headers: () => ({ cookie: `forge_session=${createSession(app.db, users[who].id).token}`, origin: `http://${HOST}` }),
108 });
109
110 /**
111 * Who asks: anonymous; a guest, a member and the repository's admin signed in; a team writer by an
112 * `ro` and an `rw` token, the repository's admin by an `ro` and an `admin` token; and the narrower
113 * token kinds. Only a token carries a scope, so only a token can find `may` and the old check
114 * apart: `ro` on a writer's and an admin's account is where they would.
115 */
116 const CALLERS: Caller[] = [
117 { label: "anonymous", headers: () => ({}) },
118 session("gina"),
119 session("nina"),
120 session("wren"),
121 plain("wes", "ro"),
122 plain("wes", "rw"),
123 plain("wren", "ro"),
124 plain("wren", "admin"),
125 bearer("wes via token", () => {
126 const via = mintViaToken(app.db, users.wes.id, "conversation:abc123", "hello", until(1_800_000));
127 if (!via.ok) throw new Error(via.error);
128 return via.value.token;
129 }),
130 bearer("wren proposal token", (repo) => {
131 const proposal = mintProposalToken(app.db, users.wren.id, repo.id, { child: "kid", origin: "https://kid.example/" });
132 if (!proposal.ok) throw new Error(proposal.error);
133 return proposal.value.token;
134 }),
135 bearer("wren run token", (repo) =>
136 mintRunToken(app.db, users.wren.id, `run${Math.random()}`, { repoId: repo.id, forkId: repo.id }, until(3_600_000)).token),
137 bearer("gina contribute token", (repo) =>
138 mintContribute(app.db, { userId: users.gina.id, repoId: repo.id, agent: "codex", origin: "claimed", source: `s${Math.random()}` }, new Date()).token),
139 ];
140
141 const fill = (pattern: string, name: string): string =>
142 pattern
143 .replace(/:([a-zA-Z_]+)/g, (_, k: string) => ({ owner: "acme", name, number: "1", id: "1" })[k] ?? "x")
144 .replace(/\*[a-zA-Z_]+/, "x");
145
146 const disagreements = () => app.db.query("SELECT door, action, principal, may, seen FROM access_disagreement").all();
147
148 /** Every repository route; the one that deletes the repository last, so it is made again once. */
149 const ROUTES = buildApiRouter()
150 .routes()
151 .filter((r) => r.pattern.startsWith("/api/v1/repos/:owner/:name"))
152 .sort((a, b) => Number(a.method === "DELETE" && a.pattern === "/api/v1/repos/:owner/:name") - Number(b.method === "DELETE" && b.pattern === "/api/v1/repos/:owner/:name"));
153 /** Under the narrowest gate's 120 a minute for one token: a fresh credential after this many. */
154 const PER_CREDENTIAL = 100;
155 let held: ReturnType<typeof forgeHttp> | undefined;
156 const passed = new Map<string, number>();
157
158 for (const name of ["pub", "priv"] as const)
159 for (const caller of CALLERS)
160 test(`${caller.label} on acme/${name}: every repository route, and may agrees with the check before it`, async () => {
161 expect(ROUTES.length).toBeGreaterThan(100);
162 const http = (held ??= forgeHttp(app));
163 let headers = caller.headers(await present(name));
164 let carried = 0;
165 for (const { method, pattern } of ROUTES) {
166 const repo = await present(name);
167 if (++carried > PER_CREDENTIAL) [headers, carried] = [caller.headers(repo), 1];
168 const res = await http.handle(new Request(`http://${HOST}${fill(pattern, name)}`, {
169 method,
170 headers: { ...headers, "content-type": "application/json" },
171 ...(method === "GET" || method === "HEAD" ? {} : { body: "{}" }),
172 }));
173 await res.body?.cancel();
174 if (res.status < 400) passed.set(caller.label, (passed.get(caller.label) ?? 0) + 1);
175 }
176 expect(disagreements()).toEqual([]);
177 });
178
179 /**
180 * Answered under 400 nowhere in the walk, and why: a via token reaches only `/mcp` (`via_gate.ts`),
181 * and a proposal token only git and the opening of its one pull, which `{}` does not do.
182 */
183 const NOWHERE = new Set(["wes via token", "wren proposal token"]);
184
185 test("the walk has teeth: every caller got past some door, but those whose gate reaches none of them", () => {
186 for (const caller of CALLERS)
187 if (NOWHERE.has(caller.label)) expect(passed.get(caller.label) ?? 0, caller.label).toBe(0);
188 else expect(passed.get(caller.label) ?? 0, caller.label).toBeGreaterThan(0);
189 });
190
191 /** A request's context as the routes read it: a token of `scope` for `user`. */
192 const tokenCtx = (user: User, scope: "ro" | "rw" | "admin"): Ctx =>
193 ({ app, auth: { user, scope, via: "token" } }) as unknown as Ctx;
194
195 test("where may and the account's rule part, the door, action and principal kind are counted and may's answer stands", async () => {
196 const repo = await present("priv");
197 const before = disagreements().length;
198 // wes writes acme/priv by a team; an ro token of his may read it and change nothing.
199 expect(accountMayRepo(tokenCtx(users.wes, "ro"), "repo.write", repo)).toBe(true);
200 expect(mayRepo(tokenCtx(users.wes, "ro"), "test.door", "repo.write", repo)).toBe(false);
201 expect(mayRepo(tokenCtx(users.wes, "ro"), "test.door", "repo.write", repo)).toBe(false);
202 expect(mayRepo(tokenCtx(users.wes, "rw"), "test.door", "repo.write", repo)).toBe(true);
203 const rows = disagreements().slice(before);
204 expect(rows).toEqual([{ door: "test.door", action: "repo.write", principal: "ro_token", may: 0, seen: 2 }]);
205 app.db.run("DELETE FROM access_disagreement WHERE door = 'test.door'");
206 });
207
208 /**
209 * The walk above sends `{}`, which never reaches the branches inside
210 * `PATCH /api/v1/repos/:owner/:name` that ask `mayRepo` themselves: `archived`, `showProvenance` (a
211 * person's: an agent is refused) and `landing`. Here each caller, and an agent that is the site's
212 * admin by a session and an `admin` token, sends each, on a public and a private repository.
213 */
214 const BODIES: readonly Record<string, unknown>[] = [{ archived: true }, { archived: false }, { showProvenance: true }, { landing: "merge" }];
215 const said = new Map<string, string>();
216
217 test("PATCH with archived, showProvenance and landing: every caller, both repositories, and no disagreement", async () => {
218 const made = await createAgent(app, users.boss, { username: "patchbot", brief: "x" });
219 if (!made.ok) throw new Error(String(made.error));
220 app.db.query("UPDATE user SET is_admin = 1 WHERE id = ?1").run(made.value.user.id);
221 const agent = made.value.user.id;
222 const callers: Caller[] = [
223 ...CALLERS,
224 { label: "agent session", headers: () => ({ cookie: `forge_session=${createSession(app.db, agent).token}`, origin: `http://${HOST}` }) },
225 bearer("agent admin token", () => createToken(app.db, agent, "admin", "admin").token),
226 ];
227 const http = (held ??= forgeHttp(app));
228 for (const name of ["pub", "priv"] as const)
229 for (const caller of callers)
230 for (const input of BODIES) {
231 const repo = await present(name);
232 const res = await http.handle(new Request(`http://${HOST}/api/v1/repos/acme/${name}`, {
233 method: "PATCH",
234 headers: { ...caller.headers(repo), "content-type": "application/json" },
235 body: JSON.stringify(input),
236 }));
237 const out = (await res.json().catch(() => ({}))) as { error?: string };
238 said.set(`${caller.label} ${name} ${JSON.stringify(input)}`, `${res.status} ${out.error ?? ""}`.trim());
239 }
240 expect(disagreements()).toEqual([]);
241 // The branches were reached: the admin passes each, a member is refused at the archive, and an
242 // agent, the site's admin, is refused the provenance field before the record is looked at (the
243 // admin is told there is none) and the archive by the settings themselves.
244 const at = (who: string, name: string, input: Record<string, unknown>) => said.get(`${who} ${name} ${JSON.stringify(input)}`);
245 for (const via of ["wren session", "wren admin token"])
246 for (const name of ["pub", "priv"]) {
247 expect(at(via, name, { archived: true }), via).toBe("200");
248 expect(at(via, name, { landing: "merge" }), via).toBe("200");
249 expect(at(via, name, { showProvenance: true }), via).toBe("422 no_provenance");
250 }
251 expect(at("wren ro token", "priv", { archived: true })).toBe("403 forbidden");
252 expect(at("nina session", "pub", { archived: true })).toBe("403 forbidden");
253 expect(at("nina session", "priv", { archived: true })).toBe("404 not_found");
254 for (const via of ["agent session", "agent admin token"])
255 for (const name of ["pub", "priv"]) {
256 expect(at(via, name, { showProvenance: true }), via).toBe("404 not_found");
257 expect(at(via, name, { archived: true }), via).toBe("404 not_found");
258 expect(at(via, name, { landing: "merge" }), via).toBe("200");
259 }
260 });
261
262 test("the gate holds the repository route files: an inline check in a repository route is refused, by route", () => {
263 expect(GATE_RULES.some((r) => r.name === "repository routes ask mayRepo")).toBe(true);
264 expect(repoRouteRefusal(".")).toEqual([]);
265 const text = [
266 'router.add("GET", "/api/v1/usage", (ctx) => {',
267 " if (!ctx.auth.user) return unauthorized();",
268 "});",
269 'router.add("PATCH", "/api/v1/repos/:owner/:name/x", (ctx) => {',
270 " if (!ctx.auth.user || ctx.auth.user.isAdmin) return forbidden();",
271 ' if (ctx.auth.user?.kind === "agent" || !scopeAllows(ctx.auth.scope, "rw")) return forbidden();',
272 " if (ctx.auth.user === undefined) return notFound();",
273 " const viewer = ctx.auth.user === undefined ? 'anon' : ctx.auth.user.id;",
274 "});",
275 ].join("\n");
276 const found = inlineChecks("src/http/api.ts", text);
277 expect(found.map((f) => `${f.line} ${f.check} ${f.where}`)).toEqual([
278 "2 signedOut GET /api/v1/usage",
279 "5 signedOut PATCH /api/v1/repos/:owner/:name/x",
280 "5 isAdmin PATCH /api/v1/repos/:owner/:name/x",
281 "6 accountKind PATCH /api/v1/repos/:owner/:name/x",
282 "6 scopeAllows PATCH /api/v1/repos/:owner/:name/x",
283 "7 signedOut PATCH /api/v1/repos/:owner/:name/x",
284 ]);
285 const usage = { file: "src/http/api.ts", where: "GET /api/v1/usage", check: "signedOut", why: "forge-wide" } as const;
286 const problems = repoRouteCheckProblems(found, [usage]);
287 expect(problems).toHaveLength(5);
288 expect(problems.every((p) => p.includes("PATCH /api/v1/repos/:owner/:name/x") && p.includes("ask mayRepo"))).toBe(true);
289 // A swap: the allowed route's signed-out check becomes an admin check, and both are said.
290 const swapped = inlineChecks("src/http/api.ts", 'router.add("GET", "/api/v1/usage", (ctx) => {\n if (!ctx.auth.user?.isAdmin) return x;\n});');
291 expect(repoRouteCheckProblems(swapped, [usage])).toEqual([
292 'rule "repository routes ask mayRepo": src/http/api.ts:2 isAdmin in GET /api/v1/usage; a new inline check in a repository route file: ask mayRepo, or name it in INLINE_ALLOWED (src/kernel/repo_route_checks.ts) with why',
293 'rule "repository routes ask mayRepo": INLINE_ALLOWED names signedOut in GET /api/v1/usage (src/http/api.ts), which is gone; remove the entry',
294 ]);
295 });
296
297 test("every check left in the repository route files is named by route, and the forge-wide ones are not repository routes", () => {
298 const repoRoutes = INLINE_ALLOWED.filter((a) => a.where.includes(" /api/v1/repos/")).map((a) => `${a.where} ${a.check}`);
299 expect(repoRoutes).toEqual([
300 "POST /api/v1/repos/:owner/:name/issues signedOut",
301 "GET /api/v1/repos/:owner/:name/statement signedOut",
302 "GET /api/v1/repos/:owner/:name/cdn signedOut",
303 ]);
304 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs