Public: anyone can read this; the crew can change it.
The owner grants one of his apps, or one crew member, read access to a read-only work repo #16750
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/10521-the-owner-grants-one-of-his-apps-or-one → main 0 commits fork 2 threads · 2 unresolved
25 files
changed +886
−6
- docs/features/read-grants.md
- src/actions/origin_read_grant.ts
- src/actions/search.ts
- src/core/account_purge.ts
- src/core/agents.ts
- src/core/apps.ts
- src/core/decisions.ts
- src/core/migration-pins/20261130110000-origin-read-grant.pin
- src/core/migrations/20261130110000-origin-read-grant.ts
- src/core/origin_read_grant.ts
- src/core/repos.ts
- src/core/tokens.ts
- src/core/users.ts
- src/crew/brief.ts
- src/crew/runner.ts
- src/http/context.ts
- src/http/read_grant_gate.ts
- src/http/run_gate.ts
- src/http/server.ts
- src/tui/screens/readgrants.ts
- src/tui/screens/workspace.ts
- src/web/pages/board.ts
- src/web/pages/read-grants.ts
- src/web/pages/settings.ts
- test/origin-read-grant.test.ts
docs/features/read-grants.md added +15
| @@ -0,0 +1,15 @@ | ||
| 1 | --- | |
| 2 | topic: Backups and moving | |
| 3 | row: Read grants | |
| 4 | --- | |
| 5 | # Read grants | |
| 6 | ||
| 7 | A mirror of a read-only origin is private to its owner. On that repository's settings page, **Who may read this**, the owner names one of his apps (its slug) or one crew member and grants it a read. The grant is scoped to that repository and to reads: its commits, branches and pulls over the API. It is listed with a Revoke, and each grant and revoke is a row in the decision ledger (`grant`, answered `granted` or `revoked`). | |
| 8 | ||
| 9 | - **App:** the app's own token (`app:<slug>/production`) reads `/api/v1/repos/<owner>/<name>`, `/commits`, `/branches` and `/pulls` once its app is granted (`src/http/read_grant_gate.ts`). Any other path, an ungranted app, or a revoked one answers 404. A write is `origin_read_only` (409), granted or not. | |
| 10 | - **Crew member:** a granted agent, on any of its tokens, reads the same three over the API and nothing else of the mirror: issues, contents and files answer 404, a write is `origin_read_only` (`readGrantGate`; `runGate` lets a run's token through to it) and its brief names the repository (`readable` in `src/crew/brief.ts`). An ungranted agent's brief says nothing of it. | |
| 11 | - **Web:** the section on `/<owner>/<name>/settings` (`src/web/pages/read-grants.ts`), only for the repository's admin and only on a read-only mirror. | |
| 12 | - **Terminal:** `forge tui`, the palette command "Who may read this" while the mirror is open (`src/tui/screens/readgrants.ts`): `a` grants an app, `c` a crew member, `x` revokes. | |
| 13 | - Lists: an ungranted or revoked app's token never sees the mirror in `/api/v1/repos`, search or explore (`canRead` and the visibility SQL ask the app's grant), and its search leaves out the owner's connected-origin catalog. | |
| 14 | - Try it: connect an origin read-only, mirror a repository, open its settings, grant `morning-paper`, then `curl -H "authorization: Bearer $FORGE_TOKEN" $FORGE_URL/api/v1/repos/<owner>/<name>/commits` with that app's token. | |
| 15 | - Tests: `test/origin-read-grant.test.ts`. |
src/actions/origin_read_grant.ts added +88
| @@ -0,0 +1,88 @@ | ||
| 1 | /** | |
| 2 | * The owner lets one of his apps, or one crew member, read a read-only mirror (#10521). Only the | |
| 3 | * mirror's admin may, only on a mirror of a read-only origin, and only for an app of his own or an | |
| 4 | * agent on the crew of one of his repositories. The grant is a read and never a write: the gates | |
| 5 | * that refuse writes through a read-only origin (`origin_read_only`) do not look at grants. | |
| 6 | * Every grant and revoke is written to the decision ledger, by whom and for whom. | |
| 7 | */ | |
| 8 | ||
| 9 | import type { App } from "../app.ts"; | |
| 10 | import { getAppBySlug } from "../core/apps.ts"; | |
| 11 | import { recordDecision } from "../core/decisions.ts"; | |
| 12 | import { originForRepo } from "../core/origins.ts"; | |
| 13 | import { addGrant, listGrants, removeGrant, type GrantKind, type ReadGrant } from "../core/origin_read_grant.ts"; | |
| 14 | import { canAdmin, getRepoById, type Repo } from "../core/repos.ts"; | |
| 15 | import { getUserByName, type User } from "../core/users.ts"; | |
| 16 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 17 | ||
| 18 | export type GrantError = "not_found" | "not_read_only" | "unknown_grantee" | "invalid"; | |
| 19 | ||
| 20 | export const GRANT_ERRORS: Readonly<Record<GrantError, string>> = { | |
| 21 | not_found: "No such repository.", | |
| 22 | not_read_only: "Only a mirror of a read-only origin takes a read grant.", | |
| 23 | unknown_grantee: "Name one of your apps (its slug) or a crew member on one of your repositories.", | |
| 24 | invalid: "Choose an app or a crew member, and name it.", | |
| 25 | }; | |
| 26 | ||
| 27 | /** Whether `repo` mirrors an origin connected read-only. */ | |
| 28 | export function isReadOnlyMirror(app: App, repo: Repo): boolean { | |
| 29 | return originForRepo(app.db, repo.id)?.origin.readOnly === true; | |
| 30 | } | |
| 31 | ||
| 32 | /** | |
| 33 | * The grantee's id when `name` is an app of the repo's owner or a crew member of one of their | |
| 34 | * repos. | |
| 35 | */ | |
| 36 | function resolve(app: App, repo: Repo, kind: GrantKind, name: string): { id: string; name: string } | undefined { | |
| 37 | if (kind === "app") { | |
| 38 | const found = getAppBySlug(app.db, name); | |
| 39 | const home = found === undefined ? undefined : getRepoById(app.db, found.repoId); | |
| 40 | return found !== undefined && home?.ownerId === repo.ownerId && home.id !== repo.id ? { id: found.id, name: found.slug } : undefined; | |
| 41 | } | |
| 42 | const user = getUserByName(app.db, name); | |
| 43 | if (user === undefined || user.kind !== "agent") return undefined; | |
| 44 | const onCrew = app.db | |
| 45 | .query( | |
| 46 | "SELECT 1 FROM repo_crew c JOIN repo r ON r.id = c.repo_id WHERE c.user_id = ?1 AND r.owner_id = ?2 LIMIT 1", | |
| 47 | ) | |
| 48 | .get(user.id, repo.ownerId); | |
| 49 | return onCrew === null ? undefined : { id: user.id, name: user.username }; | |
| 50 | } | |
| 51 | ||
| 52 | function record(app: App, actor: User, repo: Repo, kind: GrantKind, name: string, answer: "granted" | "revoked"): void { | |
| 53 | recordDecision(app.db, { | |
| 54 | kind: "grant", | |
| 55 | repoId: repo.id, | |
| 56 | state: { read: `${repo.ownerName}/${repo.name}`, grantee: kind, name }, | |
| 57 | answer, | |
| 58 | p: 1, | |
| 59 | by: actor.username, | |
| 60 | ms: 0, | |
| 61 | }); | |
| 62 | } | |
| 63 | ||
| 64 | function gate(app: App, actor: User | undefined, repo: Repo): GrantError | undefined { | |
| 65 | if (actor === undefined || !canAdmin(app.db, repo, actor)) return "not_found"; | |
| 66 | return isReadOnlyMirror(app, repo) ? undefined : "not_read_only"; | |
| 67 | } | |
| 68 | ||
| 69 | export function grantRead(app: App, actor: User | undefined, repo: Repo, kind: string, name: string): Result<ReadGrant[], GrantError> { | |
| 70 | const refused = gate(app, actor, repo); | |
| 71 | if (refused !== undefined) return err(refused); | |
| 72 | if ((kind !== "app" && kind !== "crew") || name.trim() === "" || name.length > 100) return err("invalid"); | |
| 73 | const who = resolve(app, repo, kind, name.trim()); | |
| 74 | if (who === undefined) return err("unknown_grantee"); | |
| 75 | if (addGrant(app.db, repo.id, kind, who.id, actor!.id)) record(app, actor!, repo, kind, who.name, "granted"); | |
| 76 | return ok(listGrants(app.db, repo.id)); | |
| 77 | } | |
| 78 | ||
| 79 | export function revokeRead(app: App, actor: User | undefined, repo: Repo, kind: string, granteeId: string): Result<ReadGrant[], GrantError> { | |
| 80 | const refused = gate(app, actor, repo); | |
| 81 | if (refused !== undefined) return err(refused); | |
| 82 | if (kind !== "app" && kind !== "crew") return err("invalid"); | |
| 83 | const was = listGrants(app.db, repo.id).find((g) => g.kind === kind && g.granteeId === granteeId); | |
| 84 | if (was !== undefined && removeGrant(app.db, repo.id, kind, granteeId)) record(app, actor!, repo, kind, was.name, "revoked"); | |
| 85 | return ok(listGrants(app.db, repo.id)); | |
| 86 | } | |
| 87 | ||
| 88 | export { listGrants }; |
src/actions/search.ts +3 −1
| @@ -160,7 +160,9 @@ export async function search( | ||
| 160 | 160 | ? matchOneRepo(input.repo, q, hasEnterableApp(app, actor, input.repo)) |
| 161 | 161 | : [ |
| 162 | 162 | ...searchLocalRepos(app.db, actor, q, limit), |
| 163 | ...(actor ? searchOriginRepos(app.db, actor.id, q, limit) : []), | |
| 163 | // An app's token never reads the owner's connected-origin catalog: it names mirrors | |
| 164 | // (#10521). | |
| 165 | ...(actor && actor.appId === undefined ? searchOriginRepos(app.db, actor.id, q, limit) : []), | |
| 164 | 166 | ]; |
| 165 | 167 | |
| 166 | 168 | // Named whenever it did work: asked for, or the pass issues and code share. |
src/core/account_purge.ts +3
| @@ -117,6 +117,7 @@ export const COVERED: Readonly<Record<string, Coverage>> = { | ||
| 117 | 117 | "maintenance_duty_state.by": FORMER, |
| 118 | 118 | "maintenance_quiet.set_by": FORMER, |
| 119 | 119 | "member.promoted_by": FORMER, |
| 120 | "origin_read_grant.granted_by": FORMER, | |
| 120 | 121 | "model_grant.granted_by": FORMER, |
| 121 | 122 | "model_review.decided_by": FORMER, |
| 122 | 123 | "oauth_refresh.user_id": DELETE, |
| @@ -361,6 +362,8 @@ export function purgeAccount(db: Database, userId: string, now: Date): PurgeOutc | ||
| 361 | 362 | // `entitlement.payer` is an address, not an id: an ended plan forgets who paid. |
| 362 | 363 | const email = db.query<{ email: string }, [string]>("SELECT email FROM user WHERE id = ?1").get(userId)?.email ?? ""; |
| 363 | 364 | if (email !== "") kept += db.query("UPDATE entitlement SET payer = '' WHERE payer = ?1 COLLATE NOCASE").run(email).changes; |
| 365 | // A read grant to this person (as a crew member) goes with them (#10521). | |
| 366 | db.query("DELETE FROM origin_read_grant WHERE grantee_id = ?1").run(userId); | |
| 364 | 367 | // The row itself; its cascades take emails, keys, tokens, sessions, passkeys and settings. |
| 365 | 368 | db.query("DELETE FROM user WHERE id = ?1").run(userId); |
| 366 | 369 | return { ok: true, counts: { ...own, deleted, kept, events, scrubbed } }; |
src/core/agents.ts +1
| @@ -289,6 +289,7 @@ export function deleteAgent(db: Database, userId: string): boolean { | ||
| 289 | 289 | .run(userId).changes; |
| 290 | 290 | if (removed === 0) return false; |
| 291 | 291 | db.query("DELETE FROM token WHERE user_id = ?1").run(userId); |
| 292 | db.query("DELETE FROM origin_read_grant WHERE kind = 'crew' AND grantee_id = ?1").run(userId); | |
| 292 | 293 | try { |
| 293 | 294 | db.query("DELETE FROM user WHERE id = ?1 AND is_agent = 1").run(userId); |
| 294 | 295 | } catch (error) { |
src/core/apps.ts +1
| @@ -237,6 +237,7 @@ export function deleteApp(db: Database, appId: string): boolean { | ||
| 237 | 237 | db.run("DELETE FROM app_feature_setting WHERE app_id = ?1", [appId]); |
| 238 | 238 | clearFires(db, appId); |
| 239 | 239 | db.run("DELETE FROM pull_run WHERE app_id = ?1", [appId]); |
| 240 | db.run("DELETE FROM origin_read_grant WHERE kind = 'app' AND grantee_id = ?1", [appId]); | |
| 240 | 241 | for (const t of ["timer", "timer_run", "timer_sync"]) db.run(`DELETE FROM ${t} WHERE app_id = ?1`, [appId]); |
| 241 | 242 | return db.query("DELETE FROM app WHERE id = ?1").run(appId).changes > 0; |
| 242 | 243 | })(); |
src/core/decisions.ts +5 −1
| @@ -26,6 +26,9 @@ import { id as newId } from "../kernel/id.ts"; | ||
| 26 | 26 | * interval opens (`recordPlacement`): its answer is the placement, its state |
| 27 | 27 | * the inputs, the reason and the body target. Like a guard it is counted, |
| 28 | 28 | * not listed among the crew's decisions. |
| 29 | * | |
| 30 | * `grant` is the owner granting or revoking a read of a read-only mirror | |
| 31 | * (`actions/origin_read_grant.ts`): its answer is `granted` or `revoked`. | |
| 29 | 32 | */ |
| 30 | 33 | export type DecisionKind = |
| 31 | 34 | | "next" |
| @@ -34,7 +37,8 @@ export type DecisionKind = | ||
| 34 | 37 | | "lean" |
| 35 | 38 | | "guard" |
| 36 | 39 | | "hand" |
| 37 | | "place"; | |
| 40 | | "place" | |
| 41 | | "grant"; | |
| 38 | 42 | |
| 39 | 43 | export interface Decision { |
| 40 | 44 | readonly id: string; |
src/core/migration-pins/20261130110000-origin-read-grant.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 0b2f1b431a831a62cab69a669025531a49da7c0ce3c5726520afaae66cfd0a0f |
src/core/migrations/20261130110000-origin-read-grant.ts added +14
| @@ -0,0 +1,14 @@ | ||
| 1 | // The owner's read grant on a read-only mirror (#10521): one row per repository and grantee, an app | |
| 2 | // of his (`kind` app, the app's id) or a crew member (`kind` crew, the agent's user id). It lets | |
| 3 | // the grantee read; nothing in it ever lets it write. Additive. | |
| 4 | export default ` | |
| 5 | CREATE TABLE origin_read_grant ( | |
| 6 | repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE, | |
| 7 | kind TEXT NOT NULL CHECK (kind IN ('app', 'crew')), | |
| 8 | grantee_id TEXT NOT NULL, | |
| 9 | granted_by TEXT NOT NULL, | |
| 10 | created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), | |
| 11 | PRIMARY KEY (repo_id, kind, grantee_id) | |
| 12 | ) WITHOUT ROWID; | |
| 13 | CREATE INDEX origin_read_grant_grantee ON origin_read_grant(kind, grantee_id); | |
| 14 | `; |
src/core/origin_read_grant.ts added +64
| @@ -0,0 +1,64 @@ | ||
| 1 | /** | |
| 2 | * Who the owner lets read one read-only mirror (#10521): an app he owns or a crew member, scoped to | |
| 3 | * that repository and to reads. Plain rows in, plain rows out; `actions/origin_read_grant.ts` is | |
| 4 | * the gate that writes them, and `http/read_grant_gate.ts` and `canRead` are what read them. | |
| 5 | */ | |
| 6 | ||
| 7 | import type { Database } from "bun:sqlite"; | |
| 8 | ||
| 9 | export type GrantKind = "app" | "crew"; | |
| 10 | ||
| 11 | export interface ReadGrant { | |
| 12 | readonly repoId: string; | |
| 13 | readonly kind: GrantKind; | |
| 14 | readonly granteeId: string; | |
| 15 | /** What the owner sees: the app's slug or the crew member's username. */ | |
| 16 | readonly name: string; | |
| 17 | readonly createdAt: string; | |
| 18 | } | |
| 19 | ||
| 20 | export function addGrant(db: Database, repoId: string, kind: GrantKind, granteeId: string, by: string): boolean { | |
| 21 | return ( | |
| 22 | db | |
| 23 | .query("INSERT OR IGNORE INTO origin_read_grant (repo_id, kind, grantee_id, granted_by) VALUES (?1, ?2, ?3, ?4)") | |
| 24 | .run(repoId, kind, granteeId, by).changes > 0 | |
| 25 | ); | |
| 26 | } | |
| 27 | ||
| 28 | export function removeGrant(db: Database, repoId: string, kind: GrantKind, granteeId: string): boolean { | |
| 29 | return db.query("DELETE FROM origin_read_grant WHERE repo_id = ?1 AND kind = ?2 AND grantee_id = ?3").run(repoId, kind, granteeId).changes > 0; | |
| 30 | } | |
| 31 | ||
| 32 | export function hasGrant(db: Database, repoId: string, kind: GrantKind, granteeId: string): boolean { | |
| 33 | return ( | |
| 34 | db | |
| 35 | .query("SELECT 1 FROM origin_read_grant WHERE repo_id = ?1 AND kind = ?2 AND grantee_id = ?3") | |
| 36 | .get(repoId, kind, granteeId) !== null | |
| 37 | ); | |
| 38 | } | |
| 39 | ||
| 40 | /** A repository's grants, apps then crew, each by name. */ | |
| 41 | export function listGrants(db: Database, repoId: string): ReadGrant[] { | |
| 42 | return db | |
| 43 | .query<{ kind: GrantKind; grantee_id: string; name: string | null; created_at: string }, [string]>( | |
| 44 | `SELECT g.kind, g.grantee_id, g.created_at, | |
| 45 | CASE g.kind WHEN 'app' THEN (SELECT slug FROM app WHERE app.id = g.grantee_id) | |
| 46 | ELSE (SELECT username FROM user WHERE user.id = g.grantee_id) END AS name | |
| 47 | FROM origin_read_grant g WHERE g.repo_id = ?1 ORDER BY g.kind, g.created_at, g.grantee_id`, | |
| 48 | ) | |
| 49 | .all(repoId) | |
| 50 | .filter((r) => r.name !== null) | |
| 51 | .map((r) => ({ repoId, kind: r.kind, granteeId: r.grantee_id, name: r.name!, createdAt: r.created_at })); | |
| 52 | } | |
| 53 | ||
| 54 | /** The repositories granted to a crew member, as `owner/name`, for its brief. */ | |
| 55 | export function crewGrantedRepos(db: Database, userId: string): string[] { | |
| 56 | return db | |
| 57 | .query<{ full: string }, [string]>( | |
| 58 | `SELECT u.username || '/' || r.name AS full | |
| 59 | FROM origin_read_grant g JOIN repo r ON r.id = g.repo_id JOIN user u ON u.id = r.owner_id | |
| 60 | WHERE g.kind = 'crew' AND g.grantee_id = ?1 ORDER BY full`, | |
| 61 | ) | |
| 62 | .all(userId) | |
| 63 | .map((r) => r.full); | |
| 64 | } |
src/core/repos.ts +22
| @@ -30,6 +30,7 @@ import { isContributor } from "./invites.ts"; | ||
| 30 | 30 | import { forgetListings } from "./listings.ts"; |
| 31 | 31 | import { clearDeleting, isDeleting, markDeleting } from "./repo_deleting.ts"; |
| 32 | 32 | import { forgetRepoCursors } from "./origins.ts"; |
| 33 | import { hasGrant } from "./origin_read_grant.ts"; | |
| 33 | 34 | import { NOT_AGENT, NOT_ARCHIVED, NOT_UNCLAIMED } from "./offered.ts"; |
| 34 | 35 | import { likeEscape, NOT_STANDING, pageLimit } from "./issues.ts"; |
| 35 | 36 | import { |
| @@ -1065,6 +1066,12 @@ function visibleClause( | ||
| 1065 | 1066 | params.push(options.cursor); |
| 1066 | 1067 | where += ` AND repo.id < ?${params.length}`; |
| 1067 | 1068 | } |
| 1069 | // An app's token sees a read-only mirror only when its owner granted that app (#10521). | |
| 1070 | if (viewer?.appId !== undefined) { | |
| 1071 | params.push(viewer.appId); | |
| 1072 | where += ` AND (NOT EXISTS (SELECT 1 FROM origin WHERE origin.id = repo.origin_id AND origin.read_only = 1) | |
| 1073 | OR EXISTS (SELECT 1 FROM origin_read_grant g WHERE g.repo_id = repo.id AND g.kind = 'app' AND g.grantee_id = ?${params.length}))`; | |
| 1074 | } | |
| 1068 | 1075 | if (options.withoutArchived === true) where += ` AND ${NOT_ARCHIVED}`; |
| 1069 | 1076 | if (options.archivedOnly === true) where += " AND repo.archived_at IS NOT NULL"; |
| 1070 | 1077 | if (options.templatesOnly === true) where += " AND repo.is_template = 1"; |
| @@ -1399,16 +1406,28 @@ export function reposByNameOrOwner(db: Database, owner: string, name: string, li | ||
| 1399 | 1406 | .map(toRepo); |
| 1400 | 1407 | } |
| 1401 | 1408 | |
| 1409 | /** | |
| 1410 | * Whether an app's token may read this mirror: it is not read-only, or the app was granted it | |
| 1411 | * (#10521). | |
| 1412 | */ | |
| 1413 | function appMayRead(db: Database, repo: Repo, appId: string): boolean { | |
| 1414 | const ro = db.query("SELECT 1 FROM origin WHERE id = ?1 AND read_only = 1").get(repo.origin?.originId ?? ""); | |
| 1415 | return ro === null || hasGrant(db, repo.id, "app", appId); | |
| 1416 | } | |
| 1417 | ||
| 1402 | 1418 | export function canRead( |
| 1403 | 1419 | db: Database, |
| 1404 | 1420 | repo: Repo, |
| 1405 | 1421 | user: User | undefined, |
| 1406 | 1422 | ): boolean { |
| 1423 | if (user?.appId !== undefined && repo.origin !== null && !appMayRead(db, repo, user.appId)) return false; | |
| 1407 | 1424 | if (!ownerInStanding(db, repo)) return user?.isAdmin === true; |
| 1408 | 1425 | if (repo.visibility === "public") return true; |
| 1409 | 1426 | if (personalOrDirect(repo, user)) return true; |
| 1410 | 1427 | if (onCrew(db, repo, user)) return true; |
| 1411 | 1428 | if (contributes(db, repo, user)) return true; |
| 1429 | // A crew member the owner granted a read-only mirror to reads it, and only reads (#10521). | |
| 1430 | if (repo.origin !== null && user?.kind === "agent" && hasGrant(db, repo.id, "crew", user.id)) return true; | |
| 1412 | 1431 | // The work on a sealed report is read by whoever may see the report on |
| 1413 | 1432 | // its base: the base's writers and crew, and nobody else (`sealed.ts`). |
| 1414 | 1433 | if (repo.sealedFor !== null) { |
| @@ -1440,6 +1459,9 @@ export function canReadMany(db: Database, repos: readonly Repo[], user: User | u | ||
| 1440 | 1459 | if (user?.isAdmin === true) for (const r of publics) out.add(r.id); |
| 1441 | 1460 | } |
| 1442 | 1461 | for (const repo of repos) if (repo.visibility !== "public" && canRead(db, repo, user)) out.add(repo.id); |
| 1462 | if (user?.appId !== undefined) | |
| 1463 | for (const repo of repos) | |
| 1464 | if (repo.origin !== null && out.has(repo.id) && !appMayRead(db, repo, user.appId)) out.delete(repo.id); | |
| 1443 | 1465 | return out; |
| 1444 | 1466 | } |
| 1445 | 1467 |
src/core/tokens.ts +4 −1
| @@ -81,7 +81,7 @@ export function verifyToken( | ||
| 81 | 81 | db: Database, |
| 82 | 82 | presented: string, |
| 83 | 83 | ): Result< |
| 84 | { user: User; scope: TokenScope; name: string; id: string; proposal?: Proposal; run?: RunScope; via?: string; contribute?: ContributeScope }, | |
| 84 | { user: User; scope: TokenScope; name: string; id: string; proposal?: Proposal; run?: RunScope; via?: string; contribute?: ContributeScope; app?: string }, | |
| 85 | 85 | "invalid_token" |
| 86 | 86 | > { |
| 87 | 87 | const row = db |
| @@ -183,6 +183,9 @@ export function verifyToken( | ||
| 183 | 183 | }); |
| 184 | 184 | // The forge's own agent, speaking for this person (`core/via_token.ts`). |
| 185 | 185 | if (row.v_via !== null) return ok({ user, name: row.name, id: row.id, scope: row.scope, via: row.v_via }); |
| 186 | // An app's production token acts as its owner but is the app's: which app, for the read grants | |
| 187 | // (`http/read_grant_gate.ts`). | |
| 188 | if (row.a_app !== null) return ok({ user, name: row.name, id: row.id, scope: row.scope, app: row.a_app }); | |
| 186 | 189 | return ok({ user, name: row.name, id: row.id, scope: row.scope }); |
| 187 | 190 | } |
| 188 | 191 |
src/core/users.ts +5
| @@ -28,6 +28,11 @@ export interface User { | ||
| 28 | 28 | * tokens the forge mints for a run (docs/APPS.md). |
| 29 | 29 | */ |
| 30 | 30 | readonly kind: "user" | "org" | "agent"; |
| 31 | /** | |
| 32 | * Set only on the user an app's production token acts as: the app's id, so reads of a read-only | |
| 33 | * mirror can ask for its grant (#10521). | |
| 34 | */ | |
| 35 | readonly appId?: string; | |
| 31 | 36 | /** |
| 32 | 37 | * Which address the commits the forge writes for this person carry: the |
| 33 | 38 | * no-reply one on the forge's host, or — by explicit opt-in — `email` |
src/crew/brief.ts +15
| @@ -65,6 +65,8 @@ export interface BriefInput { | ||
| 65 | 65 | * it writes obey the cells and the cells it does not touch stay decided. |
| 66 | 66 | */ |
| 67 | 67 | readonly policy?: PolicyBrief | undefined; |
| 68 | /** Read-only mirrors its owner granted this crew member to read, as `owner/name` (#10521). */ | |
| 69 | readonly readable?: readonly string[] | undefined; | |
| 68 | 70 | /** Device aliases the run may `ssh` to (`crew/devices.ts`), alias → entry. */ |
| 69 | 71 | readonly devices?: Readonly<Record<string, string>> | undefined; |
| 70 | 72 | /** |
| @@ -158,6 +160,18 @@ export function promptVersion(agent: Agent, role?: CrewRole): string { | ||
| 158 | 160 | return hasher.digest("hex").slice(0, 10); |
| 159 | 161 | } |
| 160 | 162 | |
| 163 | /** | |
| 164 | * The mirrors this crew member may read, said only when there are some: a grant is never hinted at. | |
| 165 | */ | |
| 166 | function readableLines(repos: readonly string[]): string[] { | |
| 167 | if (repos.length === 0) return []; | |
| 168 | return [ | |
| 169 | "", | |
| 170 | "The owner lets you read these read-only work repositories over the API, never write to them:", | |
| 171 | ...repos.map((r) => ` curl -sH "authorization: Bearer $FORGE_TOKEN" "$FORGE_URL/api/v1/repos/${r}/commits" (also /branches and /pulls)`), | |
| 172 | ]; | |
| 173 | } | |
| 174 | ||
| 161 | 175 | export function systemPrompt(input: BriefInput): string { |
| 162 | 176 | const { agent, repo } = input; |
| 163 | 177 | const lines = [ |
| @@ -262,6 +276,7 @@ export function systemPrompt(input: BriefInput): string { | ||
| 262 | 276 | "", |
| 263 | 277 | ...SANDBOX_LINES, |
| 264 | 278 | ...deviceLines(input.devices ?? {}), |
| 279 | ...readableLines(input.readable ?? []), | |
| 265 | 280 | "", |
| 266 | 281 | "Work carefully and finish. If the task is unclear, impossible, or not something you should do, do not guess: make your last message start with `DECLINED:` followed by exactly why. Nothing is pushed then, and a person reads it.", |
| 267 | 282 | "If the issue is already done on the base branch, decline with `DECLINED: already done on main in <commit>` naming the full or abbreviated id of each commit that did it (at most five); the forge checks they are on the base, and a person closes the issue.", |
src/crew/runner.ts +2
| @@ -11,6 +11,7 @@ | ||
| 11 | 11 | * what the forge has. |
| 12 | 12 | */ |
| 13 | 13 | |
| 14 | import { crewGrantedRepos } from "../core/origin_read_grant.ts"; | |
| 14 | 15 | import { storedText } from "../kernel/blocked.ts"; |
| 15 | 16 | import { failureBrief } from "./failure_brief.ts"; |
| 16 | 17 | import { holdsNaming } from "./desk_posts.ts"; |
| @@ -1403,6 +1404,7 @@ async function work( | ||
| 1403 | 1404 | firstBuild: record !== undefined && pull === undefined && issue.kind === "issue" && isFirstBuild(app.db, repo.id, issue.number), |
| 1404 | 1405 | previewUrl, |
| 1405 | 1406 | ownApp: ownApp(app, repo), |
| 1407 | readable: crewGrantedRepos(app.db, agent.user.id), | |
| 1406 | 1408 | policy, |
| 1407 | 1409 | // What this runner calls the forge's tools; the brief says those names. |
| 1408 | 1410 | tools: briefTools(), |
src/http/context.ts +2
| @@ -37,6 +37,8 @@ export interface Auth { | ||
| 37 | 37 | readonly run?: RunScope; |
| 38 | 38 | /** Set for an outside agent's contribute token (`http/contribute_gate.ts`). */ |
| 39 | 39 | readonly contribute?: ContributeScope; |
| 40 | /** Set for an app's production token: the app's id (`http/read_grant_gate.ts`). */ | |
| 41 | readonly appId?: string; | |
| 40 | 42 | /** Set for a via token: the forge's own agent, speaking for this person in |
| 41 | 43 | * this conversation (`conversation:<id>`, `core/via_token.ts`). */ |
| 42 | 44 | readonly through?: string; |
src/http/read_grant_gate.ts added +81
| @@ -0,0 +1,81 @@ | ||
| 1 | /** | |
| 2 | * The gate an app's own token passes at a read-only mirror (#10521). A production app's token acts | |
| 3 | * as its owner, who may read every mirror of a read-only origin; the app may not, unless the owner | |
| 4 | * granted that app this repository (`origin_read_grant`). Allowed, a grant is reads of the | |
| 5 | * repository, its commits, branches and pulls, and nothing else: a write is `origin_read_only`, | |
| 6 | * every other path under it and every ungranted app's request answers `not_found`, the same as a | |
| 7 | * repository that is not there. A request for any other repository, or with any other credential, | |
| 8 | * passes untouched. | |
| 9 | * | |
| 10 | * Lists decide it too: an app's token acts as a user carrying its `appId`, and `canRead` and the | |
| 11 | * visibility SQL (`core/repos.ts`) drop a read-only mirror the app was not granted, so search, | |
| 12 | * explore and `/api/v1/repos` never name it. A crew member's grant is the same three reads over | |
| 13 | * every kind of agent token: past them the mirror answers `not_found`. | |
| 14 | */ | |
| 15 | ||
| 16 | import type { App } from "../app.ts"; | |
| 17 | import { isReadOnlyMirror } from "../actions/origin_read_grant.ts"; | |
| 18 | import { hasGrant } from "../core/origin_read_grant.ts"; | |
| 19 | import { getRepo } from "../core/repos.ts"; | |
| 20 | import type { Auth } from "./context.ts"; | |
| 21 | import { apiError } from "./respond.ts"; | |
| 22 | ||
| 23 | /** What a granted app reads under the repository. */ | |
| 24 | const READS = /^(?:|\/(?:commits|branches|pulls)(?:\/.*)?)$/; | |
| 25 | ||
| 26 | export function readGrantGate(app: App, request: Request, url: URL, auth: Auth): Response | undefined { | |
| 27 | const crewId = auth.user?.kind === "agent" ? auth.user.id : undefined; | |
| 28 | if (auth.appId === undefined && crewId === undefined) return undefined; | |
| 29 | const api = url.pathname.startsWith("/api/v1/repos/"); | |
| 30 | // Judged on the decoded path, as the router reads it: `%61lice` is `alice`. | |
| 31 | let parts: string[]; | |
| 32 | try { | |
| 33 | parts = decodeURIComponent(api ? url.pathname.slice("/api/v1/repos/".length) : url.pathname.slice(1)).split("/"); | |
| 34 | } catch { | |
| 35 | return apiError("not_found", 404, "not found"); | |
| 36 | } | |
| 37 | const owner = parts[0] ?? ""; | |
| 38 | const name = (parts[1] ?? "").replace(/\.git$/i, ""); | |
| 39 | if (owner === "" || name === "") return undefined; | |
| 40 | const repo = getRepo(app.db, owner, name); | |
| 41 | if (repo === undefined || !isReadOnlyMirror(app, repo)) return undefined; | |
| 42 | const hidden = (): Response => apiError("not_found", 404, "not found"); | |
| 43 | const granted = | |
| 44 | auth.appId !== undefined | |
| 45 | ? hasGrant(app.db, repo.id, "app", auth.appId) | |
| 46 | : hasGrant(app.db, repo.id, "crew", crewId!); | |
| 47 | // A crew member without a grant is left to `canRead`, as before. | |
| 48 | if (!granted) return auth.appId !== undefined ? hidden() : undefined; | |
| 49 | const method = request.method; | |
| 50 | if (method !== "GET" && method !== "HEAD") | |
| 51 | return apiError( | |
| 52 | "origin_read_only", | |
| 53 | 409, | |
| 54 | "this repository mirrors a read-only origin: a grant lets an app read it, never write; nothing was changed", | |
| 55 | ); | |
| 56 | return api && READS.test(`/${parts.slice(2).join("/")}`.replace(/^\/$/, "")) ? undefined : hidden(); | |
| 57 | } | |
| 58 | ||
| 59 | /** | |
| 60 | * Whether a crew run's token may make this request on a mirror its crew member was granted: a read | |
| 61 | * of the repository, its commits, branches or pulls over the API, and nothing more. `runGate` asks | |
| 62 | * it last, so every other door of the run stays shut; the handler still applies `canRead`. | |
| 63 | */ | |
| 64 | export function crewGrantedRead(app: App, request: Request, url: URL, auth: Auth): boolean { | |
| 65 | if ((request.method !== "GET" && request.method !== "HEAD") || auth.user?.kind !== "agent") return false; | |
| 66 | if (!url.pathname.startsWith("/api/v1/repos/")) return false; | |
| 67 | let parts: string[]; | |
| 68 | try { | |
| 69 | parts = decodeURIComponent(url.pathname.slice("/api/v1/repos/".length)).split("/"); | |
| 70 | } catch { | |
| 71 | return false; | |
| 72 | } | |
| 73 | if (parts.length < 2) return false; | |
| 74 | const repo = getRepo(app.db, parts[0]!, parts[1]!); | |
| 75 | return ( | |
| 76 | repo !== undefined && | |
| 77 | hasGrant(app.db, repo.id, "crew", auth.user.id) && | |
| 78 | READS.test(`/${parts.slice(2).join("/")}`.replace(/^\/$/, "")) && | |
| 79 | isReadOnlyMirror(app, repo) | |
| 80 | ); | |
| 81 | } |
src/http/run_gate.ts +3
| @@ -28,6 +28,7 @@ import { getRepoById, type Repo } from "../core/repos.ts"; | ||
| 28 | 28 | import { forgeRepoOf } from "../release/gate.ts"; |
| 29 | 29 | import type { Auth } from "./context.ts"; |
| 30 | 30 | import { movedTarget } from "./moved.ts"; |
| 31 | import { crewGrantedRead } from "./read_grant_gate.ts"; | |
| 31 | 32 | import { apiError } from "./respond.ts"; |
| 32 | 33 | |
| 33 | 34 | const hidden = (): Response => apiError("not_found", 404, "not found"); |
| @@ -181,6 +182,8 @@ export function runGate( | ||
| 181 | 182 | // A path one of these repositories moved from (#570): the run was briefed |
| 182 | 183 | // before the move, so it passes on to the 308 that names the new path, |
| 183 | 184 | // which this gate then judges like any other. A push is refused there. |
| 185 | // A read-only mirror the owner granted this crew member, read-only (#10521). | |
| 186 | if (crewGrantedRead(app, request, url, auth)) return undefined; | |
| 184 | 187 | const moved = movedTarget(app.db, url); |
| 185 | 188 | if (moved !== undefined && (moved.id === repo.id || moved.id === fork.id || moved.id === parent?.id)) |
| 186 | 189 | return undefined; |
src/http/server.ts +11 −2
| @@ -589,6 +589,8 @@ import { originGate, refusesInJson } from "./origin_gate.ts"; | ||
| 589 | 589 | import { proposalGate } from "./proposal_gate.ts"; |
| 590 | 590 | import { contributeGate } from "./contribute_gate.ts"; |
| 591 | 591 | import { runGate } from "./run_gate.ts"; |
| 592 | import { readGrantAdd, readGrantRevoke } from "../web/pages/read-grants.ts"; | |
| 593 | import { readGrantGate } from "./read_grant_gate.ts"; | |
| 592 | 594 | import { viaGate } from "./via_gate.ts"; |
| 593 | 595 | import { checksRecheckRoutes } from "./checks_recheck.ts"; |
| 594 | 596 | import { feedRoutes } from "./feed.ts"; |
| @@ -793,7 +795,7 @@ async function resolveAuth(app: App, request: Request): Promise<Auth> { | ||
| 793 | 795 | const verified = verifyToken(app.db, secret); |
| 794 | 796 | if (verified.ok) { |
| 795 | 797 | return { |
| 796 | user: verified.value.user, | |
| 798 | user: verified.value.app ? { ...verified.value.user, appId: verified.value.app } : verified.value.user, | |
| 797 | 799 | scope: verified.value.scope, |
| 798 | 800 | via: "token", |
| 799 | 801 | tokenName: verified.value.name, |
| @@ -802,6 +804,7 @@ async function resolveAuth(app: App, request: Request): Promise<Auth> { | ||
| 802 | 804 | ...(verified.value.run ? { run: verified.value.run } : {}), |
| 803 | 805 | ...(verified.value.contribute ? { contribute: verified.value.contribute } : {}), |
| 804 | 806 | ...(verified.value.via ? { through: verified.value.via } : {}), |
| 807 | ...(verified.value.app ? { appId: verified.value.app } : {}), | |
| 805 | 808 | }; |
| 806 | 809 | } |
| 807 | 810 | return NO_MATCH; |
| @@ -821,7 +824,7 @@ async function resolveAuth(app: App, request: Request): Promise<Auth> { | ||
| 821 | 824 | const verified = verifyToken(app.db, secret); |
| 822 | 825 | if (verified.ok) { |
| 823 | 826 | return { |
| 824 | user: verified.value.user, | |
| 827 | user: verified.value.app ? { ...verified.value.user, appId: verified.value.app } : verified.value.user, | |
| 825 | 828 | scope: verified.value.scope, |
| 826 | 829 | via: "token", |
| 827 | 830 | tokenName: verified.value.name, |
| @@ -832,6 +835,7 @@ async function resolveAuth(app: App, request: Request): Promise<Auth> { | ||
| 832 | 835 | ...(verified.value.run ? { run: verified.value.run } : {}), |
| 833 | 836 | ...(verified.value.contribute ? { contribute: verified.value.contribute } : {}), |
| 834 | 837 | ...(verified.value.via ? { through: verified.value.via } : {}), |
| 838 | ...(verified.value.app ? { appId: verified.value.app } : {}), | |
| 835 | 839 | }; |
| 836 | 840 | } |
| 837 | 841 | return NO_MATCH; |
| @@ -1878,6 +1882,8 @@ export function buildRouter(): Router<Handler> { | ||
| 1878 | 1882 | router.add("POST", "/:owner/:name/settings/transfer", transferSubmit); |
| 1879 | 1883 | router.add("POST", "/:owner/:name/settings/provenance", provenanceSubmit); |
| 1880 | 1884 | router.add("POST", "/:owner/:name/settings/mirror/stop", mirrorStop); |
| 1885 | router.add("POST", "/:owner/:name/settings/read-grants", readGrantAdd); | |
| 1886 | router.add("POST", "/:owner/:name/settings/read-grants/:kind/:id/delete", readGrantRevoke); | |
| 1881 | 1887 | router.add("POST", "/:owner/:name/settings/proposal-tokens", proposalTokenMint); |
| 1882 | 1888 | router.add( |
| 1883 | 1889 | "POST", |
| @@ -3396,6 +3402,9 @@ async function answer( | ||
| 3396 | 3402 | // A crew run's token reaches its own repository and nothing else. |
| 3397 | 3403 | const runRefusal = runGate(app, request, url, auth); |
| 3398 | 3404 | if (runRefusal !== undefined) return runRefusal; |
| 3405 | // An app's token reads a read-only mirror only when its owner granted that app (#10521). | |
| 3406 | const grantRefusal = readGrantGate(app, request, url, auth); | |
| 3407 | if (grantRefusal !== undefined) return grantRefusal; | |
| 3399 | 3408 | // A conversation's token reaches /mcp alone, where the fence is. |
| 3400 | 3409 | const viaRefusal = viaGate(request, url, auth); |
| 3401 | 3410 | if (viaRefusal !== undefined) return viaRefusal; |
src/tui/screens/readgrants.ts added +99
| @@ -0,0 +1,99 @@ | ||
| 1 | /** | |
| 2 | * Read grants on a read-only mirror, in the terminal (#10521): the settings page's block | |
| 3 | * (`web/pages/read-grants.ts`) from the same actions (`actions/origin_read_grant.ts`) and the same | |
| 4 | * gate: the mirror's admin. `a` grants one of your apps (type its slug), `c` a crew member (type | |
| 5 | * its username), `x` revokes the one under the cursor, after a confirm. A grant is only ever a | |
| 6 | * read. | |
| 7 | */ | |
| 8 | ||
| 9 | import { GRANT_ERRORS, grantRead, isReadOnlyMirror, listGrants, revokeRead } from "../../actions/origin_read_grant.ts"; | |
| 10 | import { canAdmin, type Repo } from "../../core/repos.ts"; | |
| 11 | import type { Ctx, Screen } from "../app/app.ts"; | |
| 12 | import { binding } from "../app/keys.ts"; | |
| 13 | import type { Command } from "../app/palette.ts"; | |
| 14 | import type { Session } from "../session.ts"; | |
| 15 | import { style } from "../term/style.ts"; | |
| 16 | import { truncate } from "../term/width.ts"; | |
| 17 | import { fill, len, split } from "../ui/layout.ts"; | |
| 18 | import { ListState, confirmScreen, drawList, later, promptScreen, type ListRow } from "./common.ts"; | |
| 19 | ||
| 20 | /** An admin of a mirror of a read-only origin, the only one who grants. */ | |
| 21 | export const mayGrantRead = (f: Session, repo: Repo): boolean => | |
| 22 | f.user !== undefined && canAdmin(f.db, repo, f.user) && isReadOnlyMirror(f.app, repo); | |
| 23 | ||
| 24 | export function readGrantsScreen(f: Session, ctx: Ctx, repo: Repo): Screen { | |
| 25 | const state = new ListState(); | |
| 26 | const where = `${repo.ownerName}/${repo.name}`; | |
| 27 | const rows = () => (mayGrantRead(f, repo) ? listGrants(f.db, repo.id) : []); | |
| 28 | const screen: Screen = { | |
| 29 | title: `${where} — Who may read this`, | |
| 30 | keys: [binding(["j", "k"], "move cursor"), binding(["a"], "grant an app"), binding(["c"], "grant a crew member"), binding(["x"], "revoke")], | |
| 31 | render(area, s) { | |
| 32 | const c = ctx.theme.c; | |
| 33 | const [head, list] = split(area, "v", [len(1), fill(1)]); | |
| 34 | const said = mayGrantRead(f, repo) | |
| 35 | ? "Grants are reads only. a grants one of your apps, c a crew member, x revokes." | |
| 36 | : "Only the admin of a mirror of a read-only origin grants reads."; | |
| 37 | s.text(head!.x, head!.y, truncate(said, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w); | |
| 38 | const shown: ListRow[] = rows().map((g) => ({ title: g.name, note: g.kind === "app" ? "app · reads only" : "crew member · reads only", meta: g.createdAt.slice(0, 10) })); | |
| 39 | drawList(s, list!, c, state, shown); | |
| 40 | }, | |
| 41 | key(e) { | |
| 42 | const all = rows(); | |
| 43 | if (state.key(e, all.length)) return true; | |
| 44 | if (e.ctrl || e.alt || (e.key !== "a" && e.key !== "c" && e.key !== "x")) return false; | |
| 45 | if (!mayGrantRead(f, repo)) { | |
| 46 | ctx.toast(GRANT_ERRORS.not_read_only, "danger"); | |
| 47 | return true; | |
| 48 | } | |
| 49 | if (e.key === "x") { | |
| 50 | const at = all[state.index]; | |
| 51 | if (at === undefined) return true; | |
| 52 | void later(ctx, () => | |
| 53 | confirmScreen(ctx, screen, { | |
| 54 | title: "Revoke read", | |
| 55 | body: [`${at.name} can no longer read ${where}.`], | |
| 56 | actions: [{ label: "Cancel", variant: "ghost" }, { label: "Revoke" }], | |
| 57 | selected: 0, | |
| 58 | onChoose: (i) => { | |
| 59 | if (i !== 1) return; | |
| 60 | const done = revokeRead(f.app, f.user, repo, at.kind, at.granteeId); | |
| 61 | ctx.toast(done.ok ? `${at.name} revoked.` : GRANT_ERRORS[done.error], done.ok ? undefined : "danger"); | |
| 62 | ctx.invalidate(); | |
| 63 | }, | |
| 64 | }), | |
| 65 | ); | |
| 66 | return true; | |
| 67 | } | |
| 68 | const kind = e.key === "a" ? "app" : "crew"; | |
| 69 | void later(ctx, () => | |
| 70 | promptScreen(ctx, screen, { | |
| 71 | title: kind === "app" ? "Grant an app" : "Grant a crew member", | |
| 72 | label: kind === "app" ? "App slug" : "Crew username", | |
| 73 | onSubmit: (value) => { | |
| 74 | const made = grantRead(f.app, f.user, repo, kind, value); | |
| 75 | if (!made.ok) return GRANT_ERRORS[made.error]; | |
| 76 | ctx.toast("Granted: it may read this repository, and only read."); | |
| 77 | ctx.invalidate(); | |
| 78 | return undefined; | |
| 79 | }, | |
| 80 | }), | |
| 81 | ); | |
| 82 | return true; | |
| 83 | }, | |
| 84 | }; | |
| 85 | return screen; | |
| 86 | } | |
| 87 | ||
| 88 | /** The palette's command while a mirror the viewer administers is open. */ | |
| 89 | export function readGrantsCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] { | |
| 90 | if (repo === undefined || !mayGrantRead(f, repo)) return []; | |
| 91 | return [ | |
| 92 | { | |
| 93 | id: "read-grants", | |
| 94 | title: `${repo.ownerName}/${repo.name} — Who may read this`, | |
| 95 | hint: "let one of your apps or a crew member read this read-only mirror, or take it back", | |
| 96 | run: () => ctx.push(readGrantsScreen(f, ctx, repo)), | |
| 97 | }, | |
| 98 | ]; | |
| 99 | } |
src/tui/screens/workspace.ts +2
| @@ -216,6 +216,7 @@ import { trafficCommands } from "./trafficview.ts"; | ||
| 216 | 216 | import { chaptersCommands } from "./chapters.ts"; |
| 217 | 217 | import { cutOverCommands } from "./cutover.ts"; |
| 218 | 218 | import { outsideAgentsCommands } from "./outsideagents.ts"; |
| 219 | import { readGrantsCommands } from "./readgrants.ts"; | |
| 219 | 220 | import { crewDevicesCommands } from "./crewdevices.ts"; |
| 220 | 221 | import { crewSwitchCommands } from "./crewswitch.ts"; |
| 221 | 222 | import { walletCapCommands } from "./wallet.ts"; |
| @@ -2456,6 +2457,7 @@ export function workspaceScreen( | ||
| 2456 | 2457 | ...recheckWindowCommands(f, ctx, repo, () => screen), |
| 2457 | 2458 | ...deskCommands(f, ctx, repo), |
| 2458 | 2459 | ...outsideAgentsCommands(f, ctx, repo), |
| 2460 | ...readGrantsCommands(f, ctx, repo), | |
| 2459 | 2461 | ...crewDevicesCommands(f, ctx, repo), |
| 2460 | 2462 | ...cutOverCommands(f, ctx, repo), |
| 2461 | 2463 | ...crewSwitchCommands(f, ctx, repo), |
src/web/pages/board.ts +1
| @@ -161,6 +161,7 @@ const KIND_WORDS: Record<DecisionKind, string> = { | ||
| 161 | 161 | // Never listed (`listDecisionsForRepos` leaves guards out); named for the type. |
| 162 | 162 | guard: "not started", |
| 163 | 163 | place: "where it runs", |
| 164 | grant: "read grant", | |
| 164 | 165 | }; |
| 165 | 166 | |
| 166 | 167 | const money = (n: number): string => `$${n.toFixed(2)}`; |
src/web/pages/read-grants.ts added +87
| @@ -0,0 +1,87 @@ | ||
| 1 | /** | |
| 2 | * Read grants on a read-only mirror's settings (#10521): the owner names one of his apps or a crew | |
| 3 | * member, and it may read this repository (never write); each grant is listed with a Revoke. The | |
| 4 | * rules are `actions/origin_read_grant.ts`'s; this draws the section and takes the two forms. | |
| 5 | */ | |
| 6 | ||
| 7 | import { GRANT_ERRORS, grantRead, isReadOnlyMirror, listGrants, revokeRead } from "../../actions/origin_read_grant.ts"; | |
| 8 | import { canAdmin, type Repo } from "../../core/repos.ts"; | |
| 9 | import type { Ctx } from "../../http/context.ts"; | |
| 10 | import { forbiddenPage, loadRepo, NOT_YOURS_TO_DO, repoBase, repoNotFound } from "../chrome.ts"; | |
| 11 | import { field, readForm } from "../form.ts"; | |
| 12 | import { html, type Html } from "../html.ts"; | |
| 13 | import { flashTo } from "../layout.ts"; | |
| 14 | import { btn, confirmAction, field as formField, selectField, time } from "../ui.ts"; | |
| 15 | ||
| 16 | /** | |
| 17 | * The section, or null when this is not a read-only mirror or the viewer does not administer it. | |
| 18 | */ | |
| 19 | export function readGrantsSection(ctx: Ctx, repo: Repo): Html | null { | |
| 20 | if (!canAdmin(ctx.app.db, repo, ctx.auth.user) || !isReadOnlyMirror(ctx.app, repo)) return null; | |
| 21 | const base = repoBase(repo); | |
| 22 | const grants = listGrants(ctx.app.db, repo.id); | |
| 23 | return html`<section class="settings-block" id="read-grants"> | |
| 24 | <h2>Who may read this</h2> | |
| 25 | <p class="muted">Let one of your apps, or one crew member, read this mirror's commits, branches and pulls, and nothing else, until you revoke it.</p> | |
| 26 | ${grants.length === 0 | |
| 27 | ? html`<p class="muted small">No one else reads it.</p>` | |
| 28 | : html`<dl class="status-rows"> | |
| 29 | ${grants.map( | |
| 30 | (g) => html`<div class="status-row"> | |
| 31 | <dt>${g.name}</dt> | |
| 32 | <dd class="muted">${g.kind === "app" ? "app" : "crew member"} · reads only · since ${time(g.createdAt)}</dd> | |
| 33 | <dd class="status-act"> | |
| 34 | ${confirmAction({ action: `${base}/settings/read-grants/${g.kind}/${g.granteeId}/delete`, verb: "Revoke", size: "sm" })} | |
| 35 | </dd> | |
| 36 | </div>`, | |
| 37 | )} | |
| 38 | </dl>`} | |
| 39 | <form method="post" action="${base}/settings/read-grants" class="stack"> | |
| 40 | ${selectField({ | |
| 41 | label: "Who", | |
| 42 | name: "kind", | |
| 43 | options: [ | |
| 44 | { value: "app", label: "One of my apps" }, | |
| 45 | { value: "crew", label: "A crew member" }, | |
| 46 | ], | |
| 47 | })} | |
| 48 | ${formField({ label: "App slug or crew username", name: "name", mono: true, required: true, maxlength: 100, autocomplete: "off" })} | |
| 49 | <div class="form-actions">${btn("Grant read", { variant: "primary" })}</div> | |
| 50 | </form> | |
| 51 | </section>`; | |
| 52 | } | |
| 53 | ||
| 54 | async function adminPost(ctx: Ctx) { | |
| 55 | const repo = loadRepo(ctx); | |
| 56 | if (!repo) return repoNotFound(ctx); | |
| 57 | const form = await readForm(ctx, "rw"); | |
| 58 | if (form instanceof Response) return form; | |
| 59 | if (!canAdmin(ctx.app.db, repo, ctx.auth.user)) return forbiddenPage(ctx, NOT_YOURS_TO_DO); | |
| 60 | return { repo, form }; | |
| 61 | } | |
| 62 | ||
| 63 | // POST /:owner/:name/settings/read-grants | |
| 64 | export async function readGrantAdd(ctx: Ctx): Promise<Response> { | |
| 65 | const gate = await adminPost(ctx); | |
| 66 | if (gate instanceof Response) return gate; | |
| 67 | const { repo, form } = gate; | |
| 68 | const made = grantRead(ctx.app, ctx.auth.user, repo, field(form, "kind"), field(form, "name")); | |
| 69 | return flashTo( | |
| 70 | ctx, | |
| 71 | `${repoBase(repo)}/settings`, | |
| 72 | made.ok ? { message: "Granted: it may read this repository, and only read." } : { tone: "danger", message: GRANT_ERRORS[made.error] }, | |
| 73 | ); | |
| 74 | } | |
| 75 | ||
| 76 | // POST /:owner/:name/settings/read-grants/:kind/:id/delete | |
| 77 | export async function readGrantRevoke(ctx: Ctx): Promise<Response> { | |
| 78 | const gate = await adminPost(ctx); | |
| 79 | if (gate instanceof Response) return gate; | |
| 80 | const { repo } = gate; | |
| 81 | const done = revokeRead(ctx.app, ctx.auth.user, repo, ctx.params.kind ?? "", ctx.params.id ?? ""); | |
| 82 | return flashTo( | |
| 83 | ctx, | |
| 84 | `${repoBase(repo)}/settings`, | |
| 85 | done.ok ? { message: "Revoked: it can no longer read this repository." } : { tone: "danger", message: GRANT_ERRORS[done.error] }, | |
| 86 | ); | |
| 87 | } |
src/web/pages/settings.ts +3 −1
| @@ -131,6 +131,7 @@ import { liveClientJs } from "../live.ts"; | ||
| 131 | 131 | import { outsideAgentsJs } from "./outside-agents-live.ts"; |
| 132 | 132 | import { crewDevicesJs } from "./crew_devices.ts"; |
| 133 | 133 | import { proposalTokensSection } from "./proposal-tokens.ts"; |
| 134 | import { readGrantsSection } from "./read-grants.ts"; | |
| 134 | 135 | import { secretsSection } from "./secrets.ts"; |
| 135 | 136 | import { checkMemoryAt } from "../../apps/check-memory.ts"; |
| 136 | 137 | import { followChoiceForm, followSourcesCard, followUpstreamCard } from "./upstream-follow.ts"; |
| @@ -421,6 +422,7 @@ export async function settingsPage( | ||
| 421 | 422 | })} |
| 422 | 423 | </div> |
| 423 | 424 | </section>`; |
| 425 | const grantsBlock = readGrantsSection(ctx, repo); | |
| 424 | 426 | const trailHelp = getProvenance(ctx.app.db, repo.id); |
| 425 | 427 | const help = pageHelp( |
| 426 | 428 | [ |
| @@ -436,7 +438,7 @@ export async function settingsPage( | ||
| 436 | 438 | repo, |
| 437 | 439 | "general", |
| 438 | 440 | "Settings", |
| 439 | html`${help}${lead}${mirror ? html`<div class="mt">${mirror}</div>` : null}<div class="mt">${body}</div>${trail | |
| 441 | html`${help}${lead}${mirror ? html`<div class="mt">${mirror}</div>` : null}${grantsBlock ? html`<div class="mt">${grantsBlock}</div>` : null}<div class="mt">${body}</div>${trail | |
| 440 | 442 | ? html`<div class="mt">${trail}</div>` |
| 441 | 443 | : null}${upstream ? html`<div class="mt">${upstream}</div>` : null}${sources ? html`<div class="mt">${sources}</div>` : null}<div class="mt">${wave}</div><div class="mt">${archive}</div><div class="mt">${move}</div>${proposals |
| 442 | 444 | ? html`<div class="mt">${proposals}</div>` |
test/origin-read-grant.test.ts added +354
| @@ -0,0 +1,354 @@ | ||
| 1 | /** | |
| 2 | * The owner grants one of his apps, or one crew member, a read of a read-only mirror (#10521): | |
| 3 | * scoped to that repository and to reads, listed with a revoke, written to the decision ledger. | |
| 4 | * A granted app's token reads its commits, branches and pulls; an ungranted app gets 404, and again | |
| 5 | * after a revoke; a write is `origin_read_only` whoever holds the grant; a granted crew member's | |
| 6 | * brief names it and an ungranted one's does not. | |
| 7 | */ | |
| 8 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 9 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 10 | import { tmpdir } from "node:os"; | |
| 11 | import { join } from "node:path"; | |
| 12 | import { createApp, type App } from "../src/app.ts"; | |
| 13 | import { createSession } from "../src/core/sessions.ts"; | |
| 14 | import { addCrew, createAgentRow, type Agent } from "../src/core/agents.ts"; | |
| 15 | import { createApp as createAppRow } from "../src/core/apps.ts"; | |
| 16 | import { mintAppToken } from "../src/apps/token.ts"; | |
| 17 | import { mintRunToken } from "../src/core/run_token.ts"; | |
| 18 | import { deleteAgent } from "../src/core/agents.ts"; | |
| 19 | import { deleteApp } from "../src/core/apps.ts"; | |
| 20 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 21 | import { readGrantsScreen } from "../src/tui/screens/readgrants.ts"; | |
| 22 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 23 | import { settleApp } from "./helpers/tui.ts"; | |
| 24 | import { listGrants } from "../src/core/origin_read_grant.ts"; | |
| 25 | import { createToken } from "../src/core/tokens.ts"; | |
| 26 | import { createUser, getUserByName } from "../src/core/users.ts"; | |
| 27 | import { createIssue } from "../src/core/issues.ts"; | |
| 28 | import { getRepo } from "../src/core/repos.ts"; | |
| 29 | import { listDecisionsForRepos } from "../src/core/decisions.ts"; | |
| 30 | import { grantRead, revokeRead } from "../src/actions/origin_read_grant.ts"; | |
| 31 | import { systemPrompt } from "../src/crew/brief.ts"; | |
| 32 | import { crewGrantedRepos } from "../src/core/origin_read_grant.ts"; | |
| 33 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 34 | import { syncsSettled } from "../src/origins/sync.ts"; | |
| 35 | import { mirrorAndWait, newFakeState, serveFakeForge, type FakeForge } from "./fake-origin.ts"; | |
| 36 | import { seedAdmin } from "./helpers/admin.ts"; | |
| 37 | import { proveAll } from "./helpers/verified.ts"; | |
| 38 | ||
| 39 | ||
| 40 | const LOGIN = "octo"; | |
| 41 | const TOKEN = "octo-grant-secret-7e2a"; | |
| 42 | const PASSWORD = "alice-login-secret"; | |
| 43 | const NAME = "quillmoth"; | |
| 44 | const basic = (u: string, p: string) => `Basic ${Buffer.from(`${u}:${p}`).toString("base64")}`; | |
| 45 | ||
| 46 | describe("a read grant on a read-only mirror", () => { | |
| 47 | const dirs: string[] = []; | |
| 48 | let app: App; | |
| 49 | let servers: Servers; | |
| 50 | let originApp: App; | |
| 51 | let originServers: Servers; | |
| 52 | let fake: FakeForge; | |
| 53 | let cookie = ""; | |
| 54 | let morning = ""; // the granted app's token | |
| 55 | let other = ""; // an app of the owner's that is not granted | |
| 56 | let morningId = ""; | |
| 57 | let crew: Agent; | |
| 58 | let stranger: Agent; | |
| 59 | let crewToken = ""; | |
| 60 | let strangerToken = ""; | |
| 61 | ||
| 62 | const api = (path: string, init?: RequestInit) => { | |
| 63 | const headers = new Headers(init?.headers); | |
| 64 | headers.set("content-type", "application/json"); | |
| 65 | headers.set("authorization", basic("alice", PASSWORD)); | |
| 66 | return fetch(`${servers.url}${path}`, { ...init, headers }); | |
| 67 | }; | |
| 68 | const withToken = (token: string, path: string, init?: RequestInit) => | |
| 69 | fetch(`${servers.url}${path}`, { ...init, headers: { authorization: `Bearer ${token}`, "content-type": "application/json" } }); | |
| 70 | const mirror = () => getRepo(app.db, "alice", NAME)!; | |
| 71 | const alice = () => getUserByName(app.db, "alice")!; | |
| 72 | ||
| 73 | beforeAll(async () => { | |
| 74 | for (const p of ["forge-rog-", "forge-rog-up-"]) dirs.push(await mkdtemp(join(tmpdir(), p))); | |
| 75 | originApp = createApp({ dataDir: dirs[1]!, port: 0 }); | |
| 76 | originServers = await serve(originApp); | |
| 77 | await seedAdmin(originApp, { username: LOGIN, email: "[email protected]", password: TOKEN }); | |
| 78 | const oh = { "content-type": "application/json", authorization: basic(LOGIN, TOKEN) }; | |
| 79 | await fetch(`${originServers.url}/api/v1/repos`, { method: "POST", headers: oh, body: JSON.stringify({ name: NAME, visibility: "public" }) }); | |
| 80 | await fetch(`${originServers.url}/api/v1/repos/octo/${NAME}/contents`, { | |
| 81 | method: "POST", | |
| 82 | headers: oh, | |
| 83 | body: JSON.stringify({ branch: "main", message: "zephyrmarker first commit", files: [{ path: "a.txt", content: "one\n" }] }), | |
| 84 | }); | |
| 85 | const state = newFakeState("github", LOGIN, TOKEN); | |
| 86 | state.repos.push({ | |
| 87 | id: 9, | |
| 88 | fullName: `octo/${NAME}`, | |
| 89 | cloneUrl: `${originServers.url}/octo/${NAME}.git`, | |
| 90 | defaultBranch: "main", | |
| 91 | htmlUrl: `${originServers.url}/octo/${NAME}`, | |
| 92 | push: true, | |
| 93 | }); | |
| 94 | fake = serveFakeForge(state); | |
| 95 | ||
| 96 | app = createApp({ dataDir: dirs[0]!, port: 0 }); | |
| 97 | servers = await serve(app); | |
| 98 | const made = await seedAdmin(app, { username: "alice", email: "[email protected]", password: PASSWORD }); | |
| 99 | if (!made.ok) throw new Error(made.error); | |
| 100 | cookie = `forge_session=${createSession(app.db, made.value.id).token}`; | |
| 101 | ||
| 102 | const connected = (await ( | |
| 103 | await api("/api/v1/user/origins", { method: "POST", body: JSON.stringify({ host: fake.url, kind: "github", token: TOKEN, readOnly: true }) }) | |
| 104 | ).json()) as { id: string }; | |
| 105 | await mirrorAndWait( | |
| 106 | await api(`/api/v1/user/origins/${connected.id}/mirror`, { method: "POST", body: JSON.stringify({ fullName: `octo/${NAME}` }) }), | |
| 107 | ); | |
| 108 | await syncsSettled(); | |
| 109 | ||
| 110 | // Two apps of the owner's, each with its production token; one crew each way. | |
| 111 | for (const slug of ["morning-paper", "other-app"]) { | |
| 112 | await api("/api/v1/repos", { method: "POST", body: JSON.stringify({ name: slug, visibility: "private" }) }); | |
| 113 | const r = getRepo(app.db, "alice", slug)!; | |
| 114 | const rec = createAppRow(app.db, { repoId: r.id, slug, access: "private" }); | |
| 115 | if (!rec.ok) throw new Error(rec.error); | |
| 116 | const t = mintAppToken(app.db, made.value.id, slug, "production").token; | |
| 117 | if (slug === "morning-paper") { | |
| 118 | morning = t; | |
| 119 | morningId = rec.value.id; | |
| 120 | } else other = t; | |
| 121 | } | |
| 122 | const open = getRepo(app.db, "alice", "morning-paper")!; | |
| 123 | const mk = async (name: string) => { | |
| 124 | const u = await createUser(app.db, { username: name, email: `${name}@forge.test`, agent: true, origin: "agent" }); | |
| 125 | if (!u.ok) throw new Error("user"); | |
| 126 | const a = createAgentRow(app.db, { userId: u.value.id, brief: "builds." }); | |
| 127 | addCrew(app.db, open.id, u.value.id); | |
| 128 | return { a, token: createToken(app.db, u.value.id, "t", "rw").token }; | |
| 129 | }; | |
| 130 | const c = await mk("crewmate"); | |
| 131 | const s = await mk("bystander"); | |
| 132 | crew = c.a; | |
| 133 | crewToken = c.token; | |
| 134 | stranger = s.a; | |
| 135 | strangerToken = s.token; | |
| 136 | proveAll(app); | |
| 137 | }); | |
| 138 | ||
| 139 | afterAll(async () => { | |
| 140 | await syncsSettled(); | |
| 141 | fake.stop(); | |
| 142 | servers.stop(); | |
| 143 | originServers.stop(); | |
| 144 | app.close(); | |
| 145 | originApp.close(); | |
| 146 | for (const d of dirs) await rm(d, { recursive: true, force: true }); | |
| 147 | }); | |
| 148 | ||
| 149 | const reads = ["", "/commits", "/branches", "/pulls"].map((s) => `/api/v1/repos/alice/${NAME}${s}`); | |
| 150 | ||
| 151 | test("before any grant no app token reads the mirror: 404", async () => { | |
| 152 | for (const path of reads) { | |
| 153 | expect((await withToken(morning, path)).status, path).toBe(404); | |
| 154 | expect((await withToken(other, path)).status, path).toBe(404); | |
| 155 | } | |
| 156 | }); | |
| 157 | ||
| 158 | test("a stranger and the owner's other repositories are unaffected", async () => { | |
| 159 | expect((await withToken(morning, "/api/v1/repos/alice/morning-paper")).status).toBe(200); | |
| 160 | }); | |
| 161 | ||
| 162 | test("only the owner grants, only to his own app or crew, only on a read-only mirror", async () => { | |
| 163 | const bob = await createUser(app.db, { username: "bob", email: "[email protected]", password: "a-good-passphrase", origin: "seed", trusted: true }); | |
| 164 | if (!bob.ok) throw new Error("bob"); | |
| 165 | const asBob = (await import("../src/core/users.ts")).getUserById(app.db, bob.value.id)!; | |
| 166 | expect(grantRead(app, asBob, mirror(), "app", "morning-paper")).toEqual({ ok: false, error: "not_found" }); | |
| 167 | expect(grantRead(app, alice(), mirror(), "app", "no-such-app")).toEqual({ ok: false, error: "unknown_grantee" }); | |
| 168 | expect(grantRead(app, alice(), mirror(), "crew", "alice")).toEqual({ ok: false, error: "unknown_grantee" }); | |
| 169 | expect(grantRead(app, alice(), mirror(), "root", "x")).toEqual({ ok: false, error: "invalid" }); | |
| 170 | const plain = getRepo(app.db, "alice", "morning-paper")!; | |
| 171 | expect(grantRead(app, alice(), plain, "app", "other-app")).toEqual({ ok: false, error: "not_read_only" }); | |
| 172 | }); | |
| 173 | ||
| 174 | test("the settings page lists a grant with a revoke, and the owner can make one there", async () => { | |
| 175 | const page = (path = `/alice/${NAME}/settings`) => fetch(`${servers.url}${path}`, { headers: { cookie } }); | |
| 176 | const html = await (await page()).text(); | |
| 177 | expect(html).toContain("Who may read this"); | |
| 178 | expect(html).toContain("No one else reads it."); | |
| 179 | const form = new URLSearchParams({ kind: "app", name: "morning-paper" }); | |
| 180 | const res = await fetch(`${servers.url}/alice/${NAME}/settings/read-grants`, { | |
| 181 | method: "POST", | |
| 182 | headers: { cookie, origin: servers.url, "content-type": "application/x-www-form-urlencoded" }, | |
| 183 | body: form, | |
| 184 | redirect: "manual", | |
| 185 | }); | |
| 186 | expect(res.status).toBeLessThan(400); | |
| 187 | const after = await (await page()).text(); | |
| 188 | expect(after).toContain("morning-paper"); | |
| 189 | expect(after).toContain("Revoke"); | |
| 190 | }); | |
| 191 | ||
| 192 | test("a granted app's token reads commits, branches and pulls; another app still gets 404", async () => { | |
| 193 | for (const path of reads) { | |
| 194 | expect((await withToken(morning, path)).status, path).toBe(200); | |
| 195 | expect((await withToken(other, path)).status, path).toBe(404); | |
| 196 | } | |
| 197 | expect(await (await withToken(morning, reads[1]!)).text()).toContain("zephyrmarker"); | |
| 198 | }); | |
| 199 | ||
| 200 | test("the grant is only reads of the repository: other paths stay 404", async () => { | |
| 201 | for (const path of [`/api/v1/repos/alice/${NAME}/issues`, `/api/v1/repos/alice/${NAME}/settings`, `/alice/${NAME}/commits`, `/api/v1/repos/%61lice/${NAME}/issues`]) | |
| 202 | expect((await withToken(morning, path)).status, path).toBe(404); | |
| 203 | }); | |
| 204 | ||
| 205 | test("no grant enables a write: a granted app's write is origin_read_only", async () => { | |
| 206 | for (const [method, path] of [ | |
| 207 | ["POST", `/api/v1/repos/alice/${NAME}/contents`], | |
| 208 | ["PATCH", `/api/v1/repos/alice/${NAME}`], | |
| 209 | ["POST", `/api/v1/repos/alice/${NAME}/issues`], | |
| 210 | ] as const) { | |
| 211 | const res = await withToken(morning, path, { method, body: "{}" }); | |
| 212 | expect(res.status, path).toBe(409); | |
| 213 | expect(((await res.json()) as { error: string }).error).toBe("origin_read_only"); | |
| 214 | } | |
| 215 | // Granted or not, the owner's own write path through the mirror still refuses. | |
| 216 | const owner = await api(`/api/v1/repos/alice/${NAME}`, { method: "PATCH", body: JSON.stringify({ visibility: "public" }) }); | |
| 217 | expect(((await owner.json()) as { error: string }).error).toBe("origin_read_only"); | |
| 218 | }); | |
| 219 | ||
| 220 | test("the grant is in the decision ledger", () => { | |
| 221 | const rows = listDecisionsForRepos(app.db, [mirror().id]).filter((d) => d.kind === "grant"); | |
| 222 | expect(rows.length).toBe(1); | |
| 223 | expect(rows[0]!.answer).toBe("granted"); | |
| 224 | expect(rows[0]!.by).toBe("alice"); | |
| 225 | expect(JSON.stringify(rows[0]!.state)).toContain("morning-paper"); | |
| 226 | }); | |
| 227 | ||
| 228 | test("a revoke ends it: 404 again, and the ledger says so", async () => { | |
| 229 | const out = revokeRead(app, alice(), mirror(), "app", morningId); | |
| 230 | expect(out.ok && out.value).toEqual([]); | |
| 231 | for (const path of reads) expect((await withToken(morning, path)).status, path).toBe(404); | |
| 232 | const answers = listDecisionsForRepos(app.db, [mirror().id]).filter((d) => d.kind === "grant").map((d) => d.answer).sort(); | |
| 233 | expect(answers).toEqual(["granted", "revoked"]); | |
| 234 | }); | |
| 235 | ||
| 236 | test("a granted crew member is told in its brief and reads; an ungranted one is not and does not", async () => { | |
| 237 | const input = (agent: Agent) => ({ | |
| 238 | agent, | |
| 239 | repo: getRepo(app.db, "alice", "morning-paper")!, | |
| 240 | issue: (() => { | |
| 241 | const r = getRepo(app.db, "alice", "morning-paper")!; | |
| 242 | const made = createIssue(app.db, { repoId: r.id, authorId: r.ownerId, title: `Task ${agent.user.username}`, body: "x" }); | |
| 243 | if (!made.ok) throw new Error(made.error); | |
| 244 | return made.value; | |
| 245 | })(), | |
| 246 | branch: "x/1", | |
| 247 | forgeUrl: "http://forge.test", | |
| 248 | isApp: false, | |
| 249 | resuming: false, | |
| 250 | }); | |
| 251 | const commits = `/api/v1/repos/alice/${NAME}/commits`; | |
| 252 | expect((await withToken(crewToken, commits)).status).toBe(404); | |
| 253 | expect(grantRead(app, alice(), mirror(), "crew", "crewmate").ok).toBe(true); | |
| 254 | expect((await withToken(crewToken, commits)).status).toBe(200); | |
| 255 | expect((await withToken(strangerToken, commits)).status).toBe(404); | |
| 256 | const granted = crewGrantedRepos(app.db, crew.user.id); | |
| 257 | expect(granted).toEqual([`alice/${NAME}`]); | |
| 258 | expect(systemPrompt({ ...input(crew), readable: granted })).toContain(`alice/${NAME}`); | |
| 259 | expect(systemPrompt({ ...input(stranger), readable: crewGrantedRepos(app.db, stranger.user.id) })).not.toContain(NAME); | |
| 260 | expect(crewGrantedRepos(app.db, stranger.user.id)).toEqual([]); | |
| 261 | }); | |
| 262 | ||
| 263 | test("a crew member's grant is revoked the same way: the brief goes quiet and the read is 404", async () => { | |
| 264 | const out = revokeRead(app, alice(), mirror(), "crew", crew.user.id); | |
| 265 | expect(out.ok).toBe(true); | |
| 266 | expect((await withToken(crewToken, `/api/v1/repos/alice/${NAME}/commits`)).status).toBe(404); | |
| 267 | expect(crewGrantedRepos(app.db, crew.user.id)).toEqual([]); | |
| 268 | }); | |
| 269 | ||
| 270 | const listed = async (token: string, path: string) => (await (await withToken(token, path)).text()).includes(NAME); | |
| 271 | ||
| 272 | test("lists decide it too: an ungranted or revoked app's repos list and search never name the mirror", async () => { | |
| 273 | const lists = ["/api/v1/repos", `/api/v1/search?q=${NAME}&kind=repo`, `/api/v1/search?q=${NAME}`]; | |
| 274 | for (const path of lists) { | |
| 275 | expect(await listed(morning, path), `revoked ${path}`).toBe(false); | |
| 276 | expect(await listed(other, path), `ungranted ${path}`).toBe(false); | |
| 277 | } | |
| 278 | // The owner's own list still has it, and so does a granted app's. | |
| 279 | expect(await listed(morning, "/api/v1/repos")).toBe(false); | |
| 280 | expect((await (await api("/api/v1/repos")).text()).includes(NAME)).toBe(true); | |
| 281 | expect(grantRead(app, alice(), mirror(), "app", "morning-paper").ok).toBe(true); | |
| 282 | expect(await listed(morning, "/api/v1/repos")).toBe(true); | |
| 283 | expect(await listed(other, "/api/v1/repos")).toBe(false); | |
| 284 | }); | |
| 285 | ||
| 286 | test("a granted crew member reads only commits, branches and pulls, with any agent token", async () => { | |
| 287 | expect(grantRead(app, alice(), mirror(), "crew", "crewmate").ok).toBe(true); | |
| 288 | const base = `/api/v1/repos/alice/${NAME}`; | |
| 289 | for (const s of ["/commits", "/branches", "/pulls"]) expect((await withToken(crewToken, base + s)).status, s).toBe(200); | |
| 290 | for (const s of ["/issues", "/contents", "/contents/a.txt", "/files", "/settings"]) | |
| 291 | expect((await withToken(crewToken, base + s)).status, s).toBe(404); | |
| 292 | const write = await withToken(crewToken, `${base}/issues`, { method: "POST", body: "{}" }); | |
| 293 | expect(write.status).toBe(409); | |
| 294 | expect(((await write.json()) as { error: string }).error).toBe("origin_read_only"); | |
| 295 | }); | |
| 296 | ||
| 297 | test("a run-scoped token of a granted crew member: granted read 200, other path 404, write refused, ungranted 404", async () => { | |
| 298 | const work = getRepo(app.db, "alice", "morning-paper")!; | |
| 299 | const expires = new Date(Date.now() + 3600_000).toISOString(); | |
| 300 | const run = (agent: Agent) => mintRunToken(app.db, agent.user.id, "run", { repoId: work.id, forkId: work.id }, expires).token; | |
| 301 | const granted = run(crew); | |
| 302 | const base = `/api/v1/repos/alice/${NAME}`; | |
| 303 | expect((await withToken(granted, `${base}/commits`)).status).toBe(200); | |
| 304 | expect((await withToken(granted, `${base}/issues`)).status).toBe(404); | |
| 305 | expect((await withToken(granted, `${base}/commits`, { method: "POST", body: "{}" })).status).toBeGreaterThanOrEqual(400); | |
| 306 | expect((await withToken(granted, `${base}/contents`, { method: "POST", body: "{}" })).status).not.toBe(200); | |
| 307 | expect((await withToken(run(stranger), `${base}/commits`)).status).toBe(404); | |
| 308 | }); | |
| 309 | ||
| 310 | test("the web revoke route and the terminal screen", async () => { | |
| 311 | const del = (kind: string, id: string) => | |
| 312 | fetch(`${servers.url}/alice/${NAME}/settings/read-grants/${kind}/${id}/delete`, { | |
| 313 | method: "POST", | |
| 314 | headers: { cookie, origin: servers.url, "content-type": "application/x-www-form-urlencoded" }, | |
| 315 | body: new URLSearchParams({}), | |
| 316 | redirect: "manual", | |
| 317 | }); | |
| 318 | expect((await del("app", morningId)).status).toBeLessThan(400); | |
| 319 | expect((await withToken(morning, `/api/v1/repos/alice/${NAME}/commits`)).status).toBe(404); | |
| 320 | expect((await del("crew", crew.user.id)).status).toBeLessThan(400); | |
| 321 | expect(listGrants(app.db, mirror().id)).toEqual([]); | |
| 322 | // The terminal screen lists a grant and `x`, after a confirm, revokes it. | |
| 323 | expect(grantRead(app, alice(), mirror(), "crew", "crewmate").ok).toBe(true); | |
| 324 | const terminal = headlessTerminal(140, 40); | |
| 325 | const { app: tui, session } = createForgeApp( | |
| 326 | app, | |
| 327 | { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: alice() }, | |
| 328 | { terminal, exitHooks: false }, | |
| 329 | ); | |
| 330 | tui.start(); | |
| 331 | tui.ctx.push(readGrantsScreen(session, tui.ctx, mirror())); | |
| 332 | await settleApp(tui); | |
| 333 | expect(tui.screen.toText()).toContain("crewmate"); | |
| 334 | for (const key of ["x", "right", "enter"]) { | |
| 335 | tui.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false }); | |
| 336 | await settleApp(tui); | |
| 337 | } | |
| 338 | expect(listGrants(app.db, mirror().id)).toEqual([]); | |
| 339 | tui.stop?.(); | |
| 340 | }); | |
| 341 | ||
| 342 | test("a grant goes with its grantee: a deleted app leaves no row", async () => { | |
| 343 | expect(grantRead(app, alice(), mirror(), "app", "other-app").ok).toBe(true); | |
| 344 | const rows = () => (app.db.query("SELECT COUNT(*) AS n FROM origin_read_grant").get() as { n: number }).n; | |
| 345 | const before = rows(); | |
| 346 | expect(before).toBeGreaterThan(0); | |
| 347 | const otherRec = app.db.query<{ id: string }, []>("SELECT id FROM app WHERE slug = 'other-app'").get()!; | |
| 348 | deleteApp(app.db, otherRec.id); | |
| 349 | expect(rows()).toBe(before - 1); | |
| 350 | expect(grantRead(app, alice(), mirror(), "crew", "bystander").ok).toBe(true); | |
| 351 | deleteAgent(app.db, stranger.user.id); | |
| 352 | expect(rows()).toBe(before - 1); | |
| 353 | }); | |
| 354 | }); |
new above
offline
This opens every handler that calls
canRead(issues, contents, files) to a granted crew member, wider than the three reads the grant promises (finding 2). Scope it to commits, branches and pulls, and test with an ordinary agent token.