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

Propose upstream: a child sends a change back to its parent as a pull #1781

Closed opened this
Closed without merging

scout/forge:scout/424-propose-upstream-a-child-sends-a-change → main 9 commits fork 10 threads · 10 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
20 files changed +1998 −10
README.md +31
@@ -166,6 +166,37 @@ taking a release is not done here. This forge publishes its own
166166 `/releases.json` (the version names, each linking to that document), so any
167167 forge can be a parent. The terminal shows the count, not the release names.
168168
169 ### Propose upstream
170
171 A child's improvement can go back to its parent as a pull. On the parent, a
172 repository admin mints a token for one child:
173 `POST /api/v1/repos/:owner/:name/proposal-tokens {"child":"kid"}` (name:
174 lowercase letters, digits, dashes; minting again replaces the old token). The
175 token has scope `propose`, below `ro`: it can push branches named
176 `child/<name>/…` to that one repository (branch names limited to
177 `A-Za-z0-9._/-`, no deletes, never the default branch, hook-enforced) and call
178 `POST /api/v1/proposals` to open a pull from one; nothing else answers it. (It reads nothing, with one disclosure: the
179 `git-receive-pack` ref advertisement a push begins with lists the
180 repository's refs, as it does for any pusher.) The token dies with its
181 grant, so deleting the repository leaves no token behind. The proposer is an
182 ordinary account with no password, never crew: its pulls wait for a writer's
183 approval and are never in the crew's lanes or landed by the forge.
184 Pushes are held to 8 MB, a request to 32 KB, a body to 8 KB, six proposals an
185 hour and twenty open at once per child. The pull's header names the child, its
186 origin and the source change from validated text and a body that closes issues
187 is refused; people and crew review it and a person merges as with any pull.
188
189 On the child, set `FORGE_PARENT_URL`, `FORGE_PARENT_PROPOSAL_TOKEN`,
190 `FORGE_PARENT_REPO` (`owner/name`, the parent repository the token is for) and
191 the forge's own `url`. Only the local repository with that repository's name
192 may propose (page, API, MCP and terminal alike); every other one offers
193 nothing and is refused. A local change there then shows "Propose upstream" (or
194 `POST /api/v1/repos/:owner/:name/pulls/:n/propose-upstream`), which pushes the
195 head over HTTPS (token in git's environment, never argv) and opens the pull.
196 The change then shows the parent's state — open, merged, closed — refreshed in
197 the background when a minute old (`GET …/pulls/:n/upstream`). Left out: a
198 re-send after the change moves on, and proposing a fork's or mirror's change.
199
169200 ## Health
170201
171202 `GET /api/v1/health` (and the MCP `health` tool) answer a site admin with
scripts/gate.ts +1
@@ -133,6 +133,7 @@ export const GATE: readonly string[] = [
133133 "test/pull-mergeable.test.ts",
134134 "test/pull-variants.test.ts",
135135 "test/pull-checks-line.test.ts",
136 "test/proposals.test.ts",
136137 "test/pulls.test.ts",
137138 "test/api-reader-marks.test.ts",
138139 "test/app-members.test.ts",
src/actions/proposals.ts added +192
@@ -0,0 +1,192 @@
1 /**
2 * Proposals, parent side: a child forge's change arrives as an ordinary pull.
3 *
4 * `mintProposalToken` is an admin's act: a token for one child that can
5 * create branches `child/<name>/…` in one repository and open a pull from
6 * one, and do nothing else (`core/proposals.ts` names every door). The pull
7 * a proposal opens is the parent's own: the people and crew review it, a
8 * person merges it. The words the child chose are validated and bounded
9 * here, and the header naming the child, its origin and the source change
10 * is written by the parent from validated text, not taken as sent.
11 */
12
13 import type { App } from "../app.ts";
14 import {
15 bodyProblem,
16 branchProblem,
17 childNameProblem,
18 grantFor,
19 insertGrant,
20 MAX_OPEN,
21 originProblem,
22 PER_HOUR,
23 proposalLoad,
24 proposalOfIssue,
25 recordProposal,
26 sourceProblem,
27 titleProblem,
28 type Grant,
29 type UpstreamState,
30 } from "../core/proposals.ts";
31 import { closesFromBody, createPull, getPull, type Pull } from "../core/pulls.ts";
32 import type { Repo } from "../core/repos.ts";
33 import { createToken, revokeToken } from "../core/tokens.ts";
34 import { createUser, getUserById, getUserByName, type User } from "../core/users.ts";
35 import { repoDir } from "../git/repos.ts";
36 import { err, ok, type Result } from "../kernel/result.ts";
37 import { requireRepoAdmin } from "./access.ts";
38
39 export type MintError = "not_found" | "invalid_child" | "mirror";
40
41 /**
42 * A fresh proposal token for `child` on `repo`; the one already minted for
43 * that child stops working. The secret is returned once.
44 */
45 export async function mintProposalToken(
46 app: App,
47 actor: User | undefined,
48 repo: Repo,
49 child: string,
50 ): Promise<Result<{ token: string; child: string }, MintError>> {
51 const admin = requireRepoAdmin(app, actor, repo);
52 if (!admin.ok) return admin;
53 if (childNameProblem(child) !== null) return err("invalid_child");
54 // A mirror's pulls are the origin's; a child's branch has nowhere to open one.
55 if (repo.origin !== null) return err("mirror");
56
57 const before = grantFor(app.db, repo.id, child);
58 let proposer = before === undefined ? undefined : getUserById(app.db, before.userId);
59 if (proposer === undefined) {
60 const username = `child-${child}-${repo.id.slice(-6).toLowerCase()}`;
61 proposer = getUserByName(app.db, username);
62 if (proposer === undefined) {
63 const made = await createUser(app.db, {
64 username,
65 email: `${username}@proposals.invalid`,
66 // A stranger, not crew: no password is stored so none ever verifies
67 // and nobody signs in as it. Its pulls are never the crew's work.
68 allowReserved: true,
outdated

agent: true puts the child's pulls into the crew's lanes (agent-pulls list, review stats, sendToReview, and landIfGreen in autonomous repositories). A stranger's code should not count as crew work.

69 displayName: `${child} (child forge)`,
70 });
71 if (!made.ok) return err("invalid_child");
72 proposer = made.value;
73 }
74 }
75 if (before !== undefined) revokeToken(app.db, before.tokenId);
76 const minted = createToken(app.db, proposer.id, `proposals from ${child}`, "ro");

Minted as ro and only narrowed by a lookup somewhere else. Store a scope that cannot verify on its own, so a missing grant means refused, not wider access.

77 insertGrant(app.db, {
78 tokenId: minted.id,
79 userId: proposer.id,
80 repoId: repo.id,
81 child,
82 });
83 app.bus.append({
84 kind: "proposal.token_minted",
85 repoId: repo.id,
86 actorId: admin.value.id,
87 payload: { child },
88 });
89 return ok({ token: minted.token, child });
90 }
91
92 export interface ProposalInput {
93 readonly title: unknown;
94 readonly body?: unknown;
95 readonly branch: unknown;
96 readonly origin: unknown;
97 readonly source: unknown;
98 }
99
100 export type ProposalError =
101 | { readonly kind: "invalid"; readonly reason: string }
102 | { readonly kind: "rate_limited"; readonly reason: string }
103 | { readonly kind: "no_branch" }
104 | { readonly kind: "refused"; readonly reason: string };
105
106 /** Opens the pull for a proposal whose branch the child has pushed. */
107 export async function receiveProposal(
108 app: App,
109 grant: Grant,
110 repo: Repo,
111 input: ProposalInput,
112 ): Promise<Result<Pull, ProposalError>> {
113 const problem =
114 titleProblem(input.title) ??
115 bodyProblem(input.body) ??
116 branchProblem(grant, input.branch) ??
117 originProblem(input.origin) ??
118 sourceProblem(input.source);
119 if (problem !== null) return err({ kind: "invalid", reason: problem });
120 const title = (input.title as string).trim();
121 const words = typeof input.body === "string" ? input.body : "";
122 const origin = input.origin as string;
123 const source = input.source as string;
124 // A proposal asks to be reviewed; it does not get to close the parent's
125 // issues, sealed or not, by naming them.
126 if (closesFromBody(words).length > 0)
127 return err({ kind: "invalid", reason: "body must not close issues" });
128
129 const proposer = getUserById(app.db, grant.userId);
130 if (proposer === undefined) return err({ kind: "refused", reason: "gone" });
131 const load = proposalLoad(app.db, proposer.id);
132 if (load.lastHour >= PER_HOUR)
133 return err({
134 kind: "rate_limited",
135 reason: `at most ${PER_HOUR} proposals an hour`,
136 });
137 if (load.open >= MAX_OPEN)
138 return err({
139 kind: "rate_limited",
140 reason: `at most ${MAX_OPEN} proposals open at once`,
141 });
142
143 const header = `Proposed by the child forge \`${grant.child}\` (\`${origin}\`) from its change \`${source}\`.`;
144 const created = await createPull(
145 app.db,
146 repoDir(app.reposRoot, repo.ownerName, repo.name),
147 {
148 repoId: repo.id,
149 authorId: proposer.id,
150 title,
151 body: words === "" ? header : `${header}\n\n${words}`,
152 baseBranch: repo.defaultBranch,
153 headBranch: input.branch as string,
154 },
155 );
156 if (!created.ok) {
157 return created.error === "unknown_head" || created.error === "invalid_branch"
158 ? err({ kind: "no_branch" })
159 : err({ kind: "refused", reason: created.error });
160 }
161 recordProposal(app.db, {
162 issueId: created.value.id,
163 repoId: repo.id,
164 userId: proposer.id,
165 child: grant.child,
166 origin,
167 source,
168 });
169 app.bus.append({
170 kind: "pull.opened",
171 repoId: repo.id,
172 actorId: proposer.id,
173 payload: { number: created.value.number, child: grant.child },
174 });
175 return ok(created.value);
176 }
177
178 /** Where one of this proposer's pulls stands; undefined for anyone else's. */
179 export function proposalState(
180 app: App,
181 grant: Grant,
182 number: number,
183 ): { number: number; state: UpstreamState } | undefined {
184 const pull = getPull(app.db, grant.repoId, number);
185 if (pull === undefined) return undefined;
186 const mine = proposalOfIssue(app.db, pull.id);
187 if (mine === undefined || mine.child !== grant.child) return undefined;
188 return {
189 number,
190 state: pull.mergedAt !== null ? "merged" : pull.state === "open" ? "open" : "closed",
191 };
192 }
src/actions/propose_parent.ts added +271
@@ -0,0 +1,271 @@
1 /**
2 * Propose upstream, child side: one change goes back to the forge this one
3 * was spawned from.
4 *
5 * The parent minted a token for this child (`FORGE_PARENT_PROPOSAL_TOKEN`)
6 * that can create branches under `child/<name>/` in one repository and open
7 * a pull from one. This pushes the change's head there over HTTPS, asks the
8 * parent to open the pull, and remembers the number. It never touches the
9 * parent's default branch — the token cannot — and it never waits on the
10 * parent for a page: the state shown is the last one heard, refreshed in the
11 * background when it is a minute old.
12 *
13 * The token rides in git's environment for the one push (`gitAuthEnv`), never
14 * in argv or a stored URL, and is scrubbed from anything said back.
15 */
16
17 import type { App } from "../app.ts";
18 import { parentUrlProblem } from "../core/parent_releases.ts";
19 import {
20 noteState,
21 recordSent,
22 sentOf,
23 type Sent,
24 type UpstreamState,
25 } from "../core/proposals.ts";
26 import { closesFromBody, type Pull } from "../core/pulls.ts";
27 import type { Repo } from "../core/repos.ts";
28 import type { User } from "../core/users.ts";
29 import { runGitCapture } from "../git/env.ts";
30 import { isSafeName, isSafeOid, isSafeRef } from "../git/guard.ts";
31 import { repoDir } from "../git/repos.ts";
32 import { err, ok, type Result } from "../kernel/result.ts";
33 import { gitAuthEnv, redact, safeRemoteUrl } from "../origins/credentials.ts";
34 import { requireWriter, type AccessError } from "./access.ts";
35
36 export type ProposeParentError =
37 | AccessError
38 | "no_parent"
39 | "not_local"
40 | { readonly kind: "refused"; readonly reason: string };
41
42 const TIMEOUT_MS = 10_000;
43 const PUSH_MS = 120_000;
44 const MAX_ANSWER = 64 * 1024;
45 const FRESH_MS = 60_000;
46
47 const STATES: readonly string[] = ["open", "merged", "closed"];
48
49 /** The parent this forge proposes to, or undefined when it is not set up to. */
50 export function parentSeat(
51 app: App,
52 ): { url: string; token: string } | undefined {
53 const { parentUrl, parentProposalToken, parentLoopback } = app.config;
54 if (parentUrl === undefined || parentProposalToken === undefined)
55 return undefined;
56 return parentUrlProblem(parentUrl, parentLoopback === true) === null
57 ? { url: parentUrl.replace(/\/+$/, ""), token: parentProposalToken }
58 : undefined;
59 }
60
61 /**
62 * The seat for proposing from `repo`: only the local repository that has
63 * the parent repository's name may send there, so a change in any other
64 * (a private one, an unrelated one) never leaves with the token.
65 */
66 export function parentSeatFor(
67 app: App,
68 repo: Repo,
69 ): { url: string; token: string } | undefined {
70 const seat = parentSeat(app);
71 const { parentRepo } = app.config;
72 if (seat === undefined || parentRepo === undefined) return undefined;
outdated

Only the name is matched; the owner is not checked. A same-named repo under any other local owner, including a private one, gets the seat. Compare the full owner/name (or a configured local repo).

73 return parentRepo === `${repo.ownerName}/${repo.name}` ? seat : undefined;
74 }
75
76 /** At most MAX_ANSWER bytes of the body; the rest of the stream is dropped unread. */
77 async function readCapped(res: Response): Promise<string> {
78 if (res.body === null) return "";
79 const reader = res.body.getReader();
80 const chunks: Uint8Array[] = [];
81 let have = 0;
82 while (have < MAX_ANSWER) {
83 const { done, value } = await reader.read();
84 if (done) break;
85 chunks.push(value.subarray(0, MAX_ANSWER - have));
86 have += chunks[chunks.length - 1]!.length;
87 }
88 await reader.cancel().catch(() => undefined);
89 return new TextDecoder().decode(Buffer.concat(chunks));
90 }
91
92 async function call(
93 seat: { url: string; token: string },
94 method: "GET" | "POST",
outdated

Low: this reads the whole response before slicing it. Read at most MAX_ANSWER bytes from res.body.

95 path: string,
96 body?: unknown,
97 ): Promise<{ status: number; json: Record<string, unknown> }> {
98 const res = await fetch(`${seat.url}${path}`, {
99 method,
100 redirect: "error",
101 signal: AbortSignal.timeout(TIMEOUT_MS),
102 headers: {
103 accept: "application/json",
104 authorization: `Bearer ${seat.token}`,
105 ...(body === undefined ? {} : { "content-type": "application/json" }),
106 },
107 ...(body === undefined ? {} : { body: JSON.stringify(body) }),
108 });
109 const text = await readCapped(res);
110 let json: Record<string, unknown> = {};
111 try {
112 const parsed: unknown = JSON.parse(text);
outdated

Any local repository's change can go to the single parent repository the token names. Refuse when this repo is not the one that /api/v1/proposals/grant returns (or a configured match). Otherwise unrelated or private history is pushed upstream.

113 if (typeof parsed === "object" && parsed !== null)
114 json = parsed as Record<string, unknown>;
115 } catch {
116 // An answer that is not JSON is a status and nothing more.
117 }
118 return { status: res.status, json };
119 }
120
121 const refused = (reason: string): ProposeParentError => ({
122 kind: "refused",
123 reason,
124 });
125
126 /** What the parent said was wrong, in a line, without anything it quoted at length. */
127 const said = (json: Record<string, unknown>, status: number): string => {
128 const m = json["message"] ?? json["error"];
129 return typeof m === "string" ? m.slice(0, 200) : `the parent answered ${status}`;
130 };
131
132 export async function proposeToParent(
133 app: App,
134 actor: User | undefined,
135 repo: Repo,
136 pull: Pull,
137 ): Promise<Result<Sent, ProposeParentError>> {
138 const writer = requireWriter(app, actor, repo);
139 if (!writer.ok) return writer;
140 const seat = parentSeatFor(app, repo);
141 if (seat === undefined) return err("no_parent");
142 // A change that lives in this repository: not a mirror's, not a fork's.
outdated

Same here: name !== repo.name lets bob/shared propose to the parent's alice/shared. Check repo.ownerName too.

143 if (repo.origin !== null || pull.crossRepo || pull.originHeadRepo !== null)
144 return err("not_local");
145 const already = sentOf(app.db, repo.id, pull.number);
146 if (already !== undefined) return ok(already);
147 if (app.config.url === undefined)
148 return err(refused("this forge does not know its own address"));
149 if (!isSafeOid(pull.headOid)) return err(refused("the change has no head"));
150
151 try {
152 const seen = await call(seat, "GET", "/api/v1/proposals/grant");
153 const { child, repo: target } = seen.json;
154 if (seen.status !== 200 || typeof child !== "string" || typeof target !== "string")
155 return err(refused(said(seen.json, seen.status)));
156 const [owner, name, ...rest] = target.split("/");
157 if (target !== app.config.parentRepo)
158 return err(refused("this repository is not the one the parent takes proposals for"));
159 const branch = `child/${child}/pull-${pull.number}`;
160 if (
161 owner === undefined ||
162 name === undefined ||
163 rest.length > 0 ||
164 !isSafeName(owner) ||
165 !isSafeName(name) ||
166 !isSafeRef(branch)
167 )
168 return err(refused("the parent named something unusable"));
169 const remote = safeRemoteUrl(`${seat.url}/${owner}/${name}.git`);
170 if (remote === undefined) return err(refused("the parent's address is unusable"));
171
172 const pushed = await runGitCapture(
173 ["push", "--quiet", remote, `${pull.headOid}:refs/heads/${branch}`],
174 {
175 cwd: repoDir(app.reposRoot, repo.ownerName, repo.name),
176 env: gitAuthEnv(seat.url, `Bearer ${seat.token}`),
177 timeoutMs: PUSH_MS,
178 },
179 );
180 if (pushed.code !== 0)
181 return err(
182 refused(
183 redact(pushed.stderr.trim(), seat.token).slice(0, 300) ||
184 "the push was refused",
185 ),
186 );
187
188 const words = pull.body.slice(0, 8 * 1024);
189 const opened = await call(seat, "POST", "/api/v1/proposals", {
190 title: pull.title.replace(/[\x00-\x1f\x7f]/g, " ").slice(0, 200),
191 // A body that names issues to close would be refused; the title and
192 // the source change say enough.
193 ...(closesFromBody(words).length > 0 ? {} : { body: words }),
194 branch,
195 origin: app.config.url,
196 source: `${repo.ownerName}/${repo.name}#${pull.number}`,
197 });
198 const number = opened.json["number"];
199 if (opened.status !== 201 || typeof number !== "number")
200 return err(refused(said(opened.json, opened.status)));
201 recordSent(app.db, repo.id, pull.number, number, `${seat.url}/${owner}/${name}`);
202 app.bus.append({
203 kind: "pull.proposed_upstream",
204 repoId: repo.id,
205 actorId: writer.value.id,
206 payload: { number: pull.number, parent: number },
207 });
208 return ok(sentOf(app.db, repo.id, pull.number)!);
209 } catch {
210 return err(refused("the parent could not be reached"));
211 }
212 }
213
214 const refreshing = new Map<string, Promise<void>>();
215
216 /** Asks the parent where the proposal stands and keeps the answer. Never throws. */
217 export function refreshUpstream(
218 app: App,
219 repo: Repo,
220 pull: Pull,
221 ): Promise<void> {
222 const key = `${repo.id}#${pull.number}`;
223 const going = refreshing.get(key);
224 if (going !== undefined) return going;
225 const job = (async () => {
226 const seat = parentSeat(app);
227 const sent = sentOf(app.db, repo.id, pull.number);
228 if (seat === undefined || sent === undefined) return;
229 try {
230 const answer = await call(seat, "GET", `/api/v1/proposals/${sent.parentNumber}`);
231 const state = answer.json["state"];
232 if (
233 answer.status === 200 &&
234 typeof state === "string" &&
235 STATES.includes(state)
236 )
237 noteState(
238 app.db,
239 repo.id,
240 pull.number,
241 state as UpstreamState,
242 new Date().toISOString(),
243 );
244 } catch {
245 // The last state heard stands; the next view tries again.
246 }
247 })().finally(() => refreshing.delete(key));
248 refreshing.set(key, job);
249 return job;
250 }
251
252 /**
253 * What this change's proposal last was, at once. A state older than a
254 * minute starts a refresh in the background; the caller does not wait.
255 */
256 export function upstreamOf(
257 app: App,
258 repo: Repo,
259 pull: Pull,
260 now: number = Date.now(),
261 ): { sent: Sent; refresh: Promise<void> | undefined } | undefined {
262 const sent = sentOf(app.db, repo.id, pull.number);
263 if (sent === undefined) return undefined;
264 const stale =
265 sent.checkedAt === null || now - Date.parse(sent.checkedAt) >= FRESH_MS;
266 return {
267 sent,
268 refresh:
269 stale && sent.state === "open" ? refreshUpstream(app, repo, pull) : undefined,
270 };
271 }
src/app.ts +11
@@ -159,6 +159,17 @@ export interface ForgeConfig {
159159 parentUrl?: string;
160160 /** Lets `parentUrl` be plain http. Tests only; boot never sets it. */
161161 parentLoopback?: boolean;
162 /**
163 * The token this forge's parent minted for it (`FORGE_PARENT_PROPOSAL_TOKEN`):
164 * it can push `child/<name>/…` branches and open pulls there, nothing else.
165 */
166 parentProposalToken?: string;
167 /**
168 * The parent repository that token is for (`FORGE_PARENT_REPO`, `owner/name`).
169 * Only a local repository of the same name may propose to it; without it
170 * nothing is offered.
171 */
172 parentRepo?: string;
162173 /** How many `releases/<sha>/` checkouts to keep (`FORGE_RELEASES_KEEP`). @default 5 */
163174 releasesKeep?: number;
164175 /**
src/core/proposals.ts added +304
@@ -0,0 +1,304 @@
1 /**
2 * Proposals from a child forge: what the parent keeps, and what it refuses.
3 *
4 * A parent mints a token for one child, good for one repository. The token
5 * can push branches named `child/<name>/…` there and open a pull from one;
6 * nothing else — not a read, not the default branch, not another child's
7 * namespace. Its scope is `propose`, below `ro`, so every ordinary check
8 * refuses it; the few doors it may knock on are named in `mayCall`, and the
9 * pre-receive hook asks `refusal` of every ref it moves.
10 *
11 * Everything a child says about itself (its name, origin, the source change)
12 * is held to a narrow alphabet here, at the boundary, so what is stored and
13 * later rendered never carries markup, a backtick or a control byte. The
14 * limits are the parent's: they do not depend on the child behaving.
15 */
16
17 import type { Database } from "bun:sqlite";
18 import { isSafeRef } from "../git/guard.ts";
19
20 export const MAX_TITLE = 200;
21 /** A proposal's own words; the parent adds its header on top. */
22 export const MAX_BODY = 8 * 1024;
23 export const MAX_ORIGIN = 200;
24 export const MAX_SOURCE = 120;
25 /** A whole proposal request, read at most this far. */
26 export const MAX_REQUEST = 32 * 1024;
27 /** A proposal's push (a pack), counted against this instead of the forge's ceiling. */
28 export const MAX_PUSH = 8 * 1024 * 1024;
29 /** Proposals one child may open per hour, and may have open at once. */
30 export const PER_HOUR = 6;
31 export const MAX_OPEN = 20;
32 /** Branches under one child's namespace at once; pushes are 8 MB each. */
33 export const MAX_BRANCHES = 30;
34
35 export interface Grant {
36 readonly tokenId: string;
37 readonly userId: string;
38 readonly repoId: string;
39 readonly child: string;
40 }
41
42 /** The child's name: it is a branch path segment and a username suffix. */
43 export const childNameProblem = (name: string): string | null =>
44 /^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/.test(name)
45 ? null
46 : "a child's name is lowercase letters, digits and dashes, up to 32";
47
48 export const namespaceOf = (child: string): string => `child/${child}/`;
49
50 interface GrantRow {
51 token_id: string;
52 user_id: string;
53 repo_id: string;
54 child: string;
55 }
56
57 const toGrant = (r: GrantRow): Grant => ({
58 tokenId: r.token_id,
59 userId: r.user_id,
60 repoId: r.repo_id,
61 child: r.child,
62 });
63
64 export function grantOfUser(db: Database, userId: string): Grant | undefined {
65 const row = db
66 .query<GrantRow, [string]>("SELECT * FROM proposal_grant WHERE user_id = ?1")
67 .get(userId);
68 return row === null ? undefined : toGrant(row);
69 }
70
71 export function grantFor(
72 db: Database,
73 repoId: string,
74 child: string,
75 ): Grant | undefined {
76 const row = db
77 .query<GrantRow, [string, string]>(
78 "SELECT * FROM proposal_grant WHERE repo_id = ?1 AND child = ?2",
79 )
80 .get(repoId, child);
81 return row === null ? undefined : toGrant(row);
82 }
83
84 export function insertGrant(db: Database, grant: Grant): void {
85 db.query(
86 "INSERT INTO proposal_grant (token_id, user_id, repo_id, child) VALUES (?1, ?2, ?3, ?4)",
87 ).run(grant.tokenId, grant.userId, grant.repoId, grant.child);
88 }
89
90 /**
91 * Why a proposer may not move `ref` in `repoId` to `newOid`, or null. Only
92 * its own repository, only a branch under its namespace, never a delete;
93 * the ref must pass the same hygiene as every ref the forge hands to git.
94 */
95 export function refusal(
96 grant: Grant,
97 repoId: string,
98 ref: string,
99 newOid: string,
100 ): string | null {
101 if (repoId !== grant.repoId) return "this token proposes to another repository";
102 const prefix = `refs/heads/${namespaceOf(grant.child)}`;
103 if (
104 !ref.startsWith(prefix) ||
105 ref.length === prefix.length ||
106 !/^[A-Za-z0-9._/-]+$/.test(ref.slice(prefix.length)) ||
107 !isSafeRef(ref)
108 )
109 return `${ref}: a proposal may only create branches named ${namespaceOf(grant.child)}…`;
110 if (/^0+$/.test(newOid)) return `${ref}: a proposal may not delete a branch`;
111 return null;
112 }
113
114 /**
115 * The only requests a `propose` token is let through to (the rest are
116 * refused before a handler runs): the proposal API, and the write half of
117 * git. Whether the repository and the branch are the token's is asked again
118 * where each is served.
119 */
120 export function mayCall(method: string, pathname: string): boolean {
121 if (pathname === "/api/v1/proposals" || pathname.startsWith("/api/v1/proposals/"))
122 return method === "GET" || method === "POST";
123 return (
124 /^\/[^/]+\/[^/]+\.git\/info\/refs$/.test(pathname) ||
125 (method === "POST" && /^\/[^/]+\/[^/]+\.git\/git-receive-pack$/.test(pathname))
126 );
127 }
128
129 // ---- what a child may say ----
130
131 const PLAIN = /^[\x21-\x7e]+$/;
132
133 /** An origin: an http(s) URL with no credentials and nothing that could end a span. */
134 export function originProblem(raw: unknown): string | null {
135 if (typeof raw !== "string" || raw === "" || raw.length > MAX_ORIGIN)
136 return "origin must be a URL";
137 if (!PLAIN.test(raw) || /[`<>"\\|]/.test(raw)) return "origin must be a plain URL";
138 let u: URL;
139 try {
140 u = new URL(raw);
141 } catch {
142 return "origin must be a URL";
143 }
144 if (u.protocol !== "https:" && u.protocol !== "http:") return "origin must be http(s)";
145 if (u.username !== "" || u.password !== "") return "origin must not carry credentials";
146 return null;
147 }
148
149 /** The source change: `owner/name#number` on the child. */
150 export const sourceProblem = (raw: unknown): string | null =>
151 typeof raw === "string" &&
152 raw.length <= MAX_SOURCE &&
153 /^[A-Za-z0-9][A-Za-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._-]*#[1-9][0-9]{0,8}$/.test(raw)
154 ? null
155 : "source must look like owner/name#number";
156
157 /** Title: one line of text, no control bytes. */
158 export const titleProblem = (raw: unknown): string | null =>
159 typeof raw === "string" &&
160 raw.trim() !== "" &&
161 raw.length <= MAX_TITLE &&
162 !/[\x00-\x1f\x7f]/.test(raw)
163 ? null
164 : `title is one line of 1 to ${MAX_TITLE} characters`;
165
166 export const bodyProblem = (raw: unknown): string | null =>
167 raw === undefined || (typeof raw === "string" && raw.length <= MAX_BODY && !raw.includes("\0"))
168 ? null
169 : `body is at most ${MAX_BODY} characters`;
170
171 /** The branch under the child's namespace a proposal comes from. */
172 export function branchProblem(grant: Grant, raw: unknown): string | null {
173 if (typeof raw !== "string") return "branch must be text";
174 return refusal(grant, grant.repoId, `refs/heads/${raw}`, "1") === null
175 ? null
176 : `branch must be named ${namespaceOf(grant.child)}…`;
177 }
178
179 // ---- the ledger ----
180
181 export interface Recorded {
182 readonly issueId: string;
183 readonly repoId: string;
184 readonly userId: string;
185 readonly child: string;
186 readonly origin: string;
187 readonly source: string;
188 readonly createdAt: string;
189 }
190
191 interface RecordedRow {
192 issue_id: string;
193 repo_id: string;
194 user_id: string;
195 child: string;
196 origin: string;
197 source: string;
198 created_at: string;
199 }
200
201 const toRecorded = (r: RecordedRow): Recorded => ({
202 issueId: r.issue_id,
203 repoId: r.repo_id,
204 userId: r.user_id,
205 child: r.child,
206 origin: r.origin,
207 source: r.source,
208 createdAt: r.created_at,
209 });
210
211 export function recordProposal(db: Database, p: Omit<Recorded, "createdAt">): void {
212 db.query(
213 "INSERT INTO proposal (issue_id, repo_id, user_id, child, origin, source) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
214 ).run(p.issueId, p.repoId, p.userId, p.child, p.origin, p.source);
215 }
216
217 export function proposalOfIssue(db: Database, issueId: string): Recorded | undefined {
218 const row = db
219 .query<RecordedRow, [string]>("SELECT * FROM proposal WHERE issue_id = ?1")
220 .get(issueId);
221 return row === null ? undefined : toRecorded(row);
222 }
223
224 /** Proposals this proposer opened in the last hour, and how many are still open. */
225 export function proposalLoad(
226 db: Database,
227 userId: string,
228 now: number = Date.now(),
229 ): { lastHour: number; open: number } {
230 const since = new Date(now - 3_600_000).toISOString();
231 const lastHour =
232 db
233 .query<{ n: number }, [string, string]>(
234 "SELECT COUNT(*) AS n FROM proposal WHERE user_id = ?1 AND created_at > ?2",
235 )
236 .get(userId, since)?.n ?? 0;
237 const open =
238 db
239 .query<{ n: number }, [string]>(
240 `SELECT COUNT(*) AS n FROM proposal p JOIN issue i ON i.id = p.issue_id
241 WHERE p.user_id = ?1 AND i.state = 'open'`,
242 )
243 .get(userId)?.n ?? 0;
244 return { lastHour, open };
245 }
246
247 // ---- the child's side of the ledger ----
248
249 export type UpstreamState = "open" | "merged" | "closed";
250
251 export interface Sent {
252 readonly parentNumber: number;
253 readonly parentUrl: string;
254 readonly state: UpstreamState;
255 readonly checkedAt: string | null;
256 }
257
258 interface SentRow {
259 parent_number: number;
260 parent_url: string;
261 state: UpstreamState;
262 checked_at: string | null;
263 }
264
265 export function sentOf(db: Database, repoId: string, pull: number): Sent | undefined {
266 const r = db
267 .query<SentRow, [string, number]>(
268 "SELECT parent_number, parent_url, state, checked_at FROM proposal_sent WHERE repo_id = ?1 AND pull_number = ?2",
269 )
270 .get(repoId, pull);
271 return r === null
272 ? undefined
273 : {
274 parentNumber: r.parent_number,
275 parentUrl: r.parent_url,
276 state: r.state,
277 checkedAt: r.checked_at,
278 };
279 }
280
281 export function recordSent(
282 db: Database,
283 repoId: string,
284 pull: number,
285 parentNumber: number,
286 parentUrl: string,
287 ): void {
288 db.query(
289 `INSERT OR IGNORE INTO proposal_sent (repo_id, pull_number, parent_number, parent_url)
290 VALUES (?1, ?2, ?3, ?4)`,
291 ).run(repoId, pull, parentNumber, parentUrl);
292 }
293
294 export function noteState(
295 db: Database,
296 repoId: string,
297 pull: number,
298 state: UpstreamState,
299 at: string,
300 ): void {
301 db.query(
302 "UPDATE proposal_sent SET state = ?3, checked_at = ?4 WHERE repo_id = ?1 AND pull_number = ?2",
303 ).run(repoId, pull, state, at);
304 }
src/core/pull_trust.ts +11 −2
@@ -8,9 +8,12 @@
88 * itself (only a writer could push it there), and a fork's pull opened by a
99 * writer or the crew from a fork that same person owns. A pull whose head
1010 * lives in a fork on another forge (a mirror's) is someone else's code and
11 * waits like a reader's.
11 * waits like a reader's. A proposal from a child forge is the exception to
12 * "only a writer could push it": its token pushes `child/…` branches here
13 * without being a writer, so those pulls wait for approval too.
1214 */
1315 import type { Database } from "bun:sqlite";
16 import { proposalOfIssue } from "./proposals.ts";
1417 import { getIssueById, getPull, type Pull } from "./pulls.ts";
1518 import { canWrite, getRepoById, onCrew, type Repo } from "./repos.ts";
1619 import { listReviews } from "./reviews.ts";
@@ -26,7 +29,13 @@ export function pullMayRun(
2629 pull: Pull,
2730 headOid: string,
2831 ): boolean {
29 if (!pull.crossRepo && pull.originHeadRepo === null) return true;
32 if (!pull.crossRepo && pull.originHeadRepo === null) {
33 // A child's proposal token pushes into this repository without writing it.
34 const proposed =

Good gate, but untested. Add a case where a child/… pull's check is refused until a person who can write approves the head.

35 pull.headBranch.startsWith("child/") ||
36 proposalOfIssue(db, pull.id) !== undefined;
37 return proposed ? approvedAt(db, repo, pull, headOid) : true;
38 }
3039 if (pull.crossRepo && pull.originHeadRepo === null) {
3140 const author = getUserById(db, pull.authorId);
3241 const head = getRepoById(db, pull.headRepoId);
src/core/schema.ts +44
@@ -1754,6 +1754,50 @@ export const migrations: readonly string[] = [
17541754 );
17551755 CREATE INDEX deploy_pull_issue ON deploy_pull(issue_id);
17561756 `,
1757 // 87 — proposing upstream (#424). The parent mints a token for one child,
1758 // good for one repository and nothing else (`proposal_grant`; the token row
1759 // itself says `ro` and a missing grant can only make it weaker). Each
1760 // proposal a child opens is one row (`proposal`) naming the child, its
1761 // origin and the source change, kept as validated text. On the child,
1762 // `proposal_sent` remembers the pull it sent and what the parent last said.
1763 `
1764 CREATE TABLE proposal_grant (
1765 token_id TEXT PRIMARY KEY REFERENCES token(id) ON DELETE CASCADE,
1766 user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
1767 repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE,
1768 child TEXT NOT NULL,
1769 created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
1770 UNIQUE (repo_id, child)
1771 );
1772 CREATE INDEX proposal_grant_user ON proposal_grant(user_id);
1773 CREATE TABLE proposal (
1774 issue_id TEXT PRIMARY KEY REFERENCES issue(id) ON DELETE CASCADE,
1775 repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE,
1776 user_id TEXT NOT NULL,
1777 child TEXT NOT NULL,
1778 origin TEXT NOT NULL,
1779 source TEXT NOT NULL,
1780 created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
1781 );
1782 CREATE INDEX proposal_by_user ON proposal(user_id, created_at);
1783 CREATE TABLE proposal_sent (
1784 repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE,
1785 pull_number INTEGER NOT NULL,
1786 parent_number INTEGER NOT NULL,
1787 parent_url TEXT NOT NULL,
1788 state TEXT NOT NULL DEFAULT 'open',
1789 checked_at TEXT,
1790 created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
1791 PRIMARY KEY (repo_id, pull_number)
1792 );
1793 -- A proposal token dies with its grant: the grant is what narrows the
1794 -- token's stored ro, so one that vanished (its repository deleted) must
1795 -- not leave a plain read token behind.
1796 CREATE TRIGGER proposal_grant_token_dies AFTER DELETE ON proposal_grant
1797 BEGIN
1798 DELETE FROM token WHERE id = OLD.token_id;
1799 END;
outdated

Migration 87 ships in this same pull, so no real database has orphaned proposal tokens. On those databases this only deletes tokens that a person named 'proposals from …'. Move the trigger into 87 and drop this migration.

1800 `,
17571801 ];
17581802
17591803 /**
src/core/tokens.ts +19 −3
@@ -10,9 +10,19 @@ import { id, secret } from "../kernel/id.ts";
1010 import { err, ok, type Result } from "../kernel/result.ts";
1111 import { getUserById, isActive, type User } from "./users.ts";
1212
13 export type TokenScope = "ro" | "rw" | "admin";
13 /**
14 * `propose` is below `ro`: a child's proposal token (`core/proposals.ts`)
15 * satisfies no ordinary scope, so every check that asks for one refuses it.
16 * It is not a column value; `verifyToken` reads it from the grant.
17 */
18 export type TokenScope = "propose" | "ro" | "rw" | "admin";
1419
15 const rank: Record<TokenScope, number> = { ro: 0, rw: 1, admin: 2 };
20 const rank: Record<TokenScope, number> = {
21 propose: -1,
22 ro: 0,
23 rw: 1,
24 admin: 2,
25 };
1626
1727 export function scopeAllows(held: TokenScope, needed: TokenScope): boolean {
1828 return rank[held] >= rank[needed];
@@ -96,7 +106,13 @@ export function verifyToken(
96106 row.id,
97107 );
98108 }
99 return ok({ user, scope: row.scope });
109 const proposes =
110 db
111 .query<{ n: number }, [string]>(
112 "SELECT 1 AS n FROM proposal_grant WHERE token_id = ?1",
113 )
114 .get(row.id) !== null;
115 return ok({ user, scope: proposes ? "propose" : row.scope });

High: this fails open. If the grant row is gone (it cascades when the repo is deleted), row.scope is ro and the token becomes a full read token. Refuse a proposer's token when it has no grant, or delete the token together with the grant.

100116 }
101117
102118 export function listTokens(db: Database, userId: string): TokenInfo[] {
src/git/smart-http.ts +2 −2
@@ -12,7 +12,7 @@ import {
1212 counted,
1313 FETCH_MAX,
1414 GZIP_MAX,
15 PUSH_MAX,
15 pushCapFor,
1616 readBounded,
1717 } from "../http/limits.ts";
1818 import { gitEnv, transferGate } from "./env.ts";
@@ -208,7 +208,7 @@ async function feedStdin(
208208 }
209209 if (!gone) await write(inflated);
210210 } else {
211 const max = service === "git-receive-pack" ? PUSH_MAX : FETCH_MAX;
211 const max = service === "git-receive-pack" ? pushCapFor(request) : FETCH_MAX;
212212 for await (const chunk of counted(request.body, max, stop)) {
213213 if (gone) break;
214214 await write(chunk);
src/http/limits.ts +20 −1
@@ -48,13 +48,32 @@ export const noteSignedIn = (request: Request): void => {
4848 signedIn.add(request);
4949 };
5050
51 const ceilings = new WeakMap<Request, number>();
52
53 /**
54 * A caller whose body is held below every ordinary ceiling, a push's pack
55 * included (a child forge's proposal token: `core/proposals.ts`).
56 */
57 export const noteCeiling = (request: Request, bytes: number): void => {
58 ceilings.set(request, bytes);
59 };
60
61 /** The most a push's pack may be for this request. */
62 export const pushCapFor = (request: Request): number =>
63 Math.min(PUSH_MAX, ceilings.get(request) ?? PUSH_MAX);
64
5165 /** The most a shared reader keeps of this request's body. */
5266 export const bodyCapFor = (request: Request): number =>
53 signedIn.has(request) ? BODY_MAX : STRANGER_MAX;
67 Math.min(
68 signedIn.has(request) ? BODY_MAX : STRANGER_MAX,
69 ceilings.get(request) ?? Infinity,
70 );
5471
5572 /** A request rebuilt from another (a replay) keeps what was noted of it. */
5673 export const carryNotes = (from: Request, to: Request): void => {
5774 if (signedIn.has(from)) signedIn.add(to);
75 const ceiling = ceilings.get(from);
76 if (ceiling !== undefined) ceilings.set(to, ceiling);
5877 const close = closers.get(from);
5978 if (close !== undefined) closers.set(to, close);
6079 };
src/http/mcp.ts +32
@@ -81,6 +81,7 @@ import { getIssue, getIssueById, listOpenAgentPullsVisibleTo } from "../core/iss
8181 import { waitsForPerson } from "../crew/review.ts";
8282 import { attachLook } from "../actions/attach_look.ts";
8383 import { lookUrl } from "../core/looks.ts";
84 import { proposeToParent } from "../actions/propose_parent.ts";
8485 import { getPull, pullDir, pullMergeState } from "../core/pulls.ts";
8586 import { repoGraph } from "../core/dependencies.ts";
8687 import { pillarView } from "../core/pillars.ts";
@@ -949,6 +950,37 @@ const TOOLS: readonly Tool[] = [
949950 });
950951 },
951952 },
953 {
954 name: "propose_upstream",
955 description:
956 "Send a change made here back to the forge this one was spawned from, as a pull there (a branch under child/<this forge>/…; never the parent's default branch). Returns the parent's pull number and its state: open, merged or closed. Asked again, it returns the state heard.",
957 inputSchema: {
958 type: "object",
959 properties: {
960 repo: REPO_ARG,
961 number: { type: "integer", minimum: 1 },
962 },
963 required: ["repo", "number"],
964 },
965 writes: true,
966 async run(ctx, user, args) {
967 const repo = repoArg(ctx, user, args);
968 if (isAnswer(repo)) return repo;
969 const n = args["number"];
970 const pull =
971 typeof n === "number" && Number.isInteger(n) && n > 0
972 ? getPull(ctx.app.db, repo.id, n)
973 : undefined;
974 if (pull === undefined || !mayView(ctx.app.db, repo, pull, user))
975 return bad("no_such_pull", `no pull #${String(n)}`);
976 const sent = await proposeToParent(ctx.app, user, repo, pull);
977 if (sent.ok) return good({ ...sent.value });
978 const e = sent.error;
979 return typeof e === "string"
980 ? bad(e, "this change cannot be proposed upstream from here")
981 : bad("refused", e.reason);
982 },
983 },
952984 {
953985 name: "following",
954986 description:
src/http/proposals.ts added +176
@@ -0,0 +1,176 @@
1 /**
2 * The proposal API. A parent's admin mints a token for a child
3 * (`POST …/proposal-tokens`); the child, holding it, asks who it is
4 * (`GET /api/v1/proposals/grant`), pushes its branch with git, opens the
5 * pull (`POST /api/v1/proposals`) and reads where it stands
6 * (`GET /api/v1/proposals/:number`). The token reaches nothing else
7 * (`core/proposals.ts`, `mayCall`).
8 */
9
10 import { proposeToParent, upstreamOf } from "../actions/propose_parent.ts";
11 import {
12 mintProposalToken,
13 proposalState,
14 receiveProposal,
15 } from "../actions/proposals.ts";
16 import {
17 grantOfUser,
18 MAX_REQUEST,
19 namespaceOf,
20 type Grant,
21 } from "../core/proposals.ts";
22 import { getPull } from "../core/pulls.ts";
23 import { canRead, getRepo, getRepoById, type Repo } from "../core/repos.ts";
24 import { mayView } from "../core/sealed.ts";
25 import type { Ctx, Handler } from "./context.ts";
26 import {
27 apiError,
28 boundedBody,
29 forbidden,
30 json,
31 notFound,
32 requireScope,
33 str,
34 } from "./respond.ts";
35 import type { Router } from "./router.ts";
36
37 /** The grant behind a proposal token, and the repository it is for. */
38 function seat(ctx: Ctx): { grant: Grant; repo: Repo } | Response {
39 if (ctx.auth.scope !== "propose" || ctx.auth.user === undefined)
40 return forbidden();
41 const grant = grantOfUser(ctx.app.db, ctx.auth.user.id);
42 const repo = grant === undefined ? undefined : getRepoById(ctx.app.db, grant.repoId);
43 return grant === undefined || repo === undefined ? notFound() : { grant, repo };
44 }
45
46 /** This forge's own change that a proposal upstream is about. */
47 function ownChange(ctx: Ctx) {
48 const repo = getRepo(ctx.app.db, ctx.params.owner!, ctx.params.name!);
49 if (!repo || !canRead(ctx.app.db, repo, ctx.auth.user)) return undefined;
50 const number = Number(ctx.params.number);
51 const pull = Number.isSafeInteger(number)
52 ? getPull(ctx.app.db, repo.id, number)
53 : undefined;
54 return pull && mayView(ctx.app.db, repo, pull, ctx.auth.user)
55 ? { repo, pull }
56 : undefined;
57 }
58
59 export function proposalRoutes(router: Router<Handler>): void {
60 // The child's side: send a change to the parent, and read where it stands.
61 router.add(
62 "POST",
63 "/api/v1/repos/:owner/:name/pulls/:number/propose-upstream",
64 async (ctx) => {
65 const denied = requireScope(ctx, "rw");
66 if (denied) return denied;
67 const found = ownChange(ctx);
68 if (!found) return notFound();
69 const sent = await proposeToParent(ctx.app, ctx.auth.user, found.repo, found.pull);
70 if (!sent.ok) {
71 if (sent.error === "not_found") return notFound();
72 if (sent.error === "unauthorized" || sent.error === "forbidden")
73 return forbidden();
74 return apiError(
75 typeof sent.error === "string" ? sent.error : "refused",
76 422,
77 typeof sent.error === "string"
78 ? "this forge cannot propose that change upstream"
79 : sent.error.reason,
80 );
81 }
82 return json(sent.value, 201);
83 },
84 );
85 router.add(
86 "GET",
87 "/api/v1/repos/:owner/:name/pulls/:number/upstream",
88 (ctx) => {
89 const found = ownChange(ctx);
90 if (!found) return notFound();
91 const view = upstreamOf(ctx.app, found.repo, found.pull);
92 return view === undefined ? notFound() : json(view.sent);
93 },
94 );
95
96 router.add("POST", "/api/v1/repos/:owner/:name/proposal-tokens", async (ctx) => {
97 const denied = requireScope(ctx, "admin");
98 if (denied) return denied;
99 const repo = getRepo(ctx.app.db, ctx.params.owner!, ctx.params.name!);
100 if (!repo) return notFound();
101 const input = await boundedBody(ctx.request, 1024);
102 if (input === "too_large") return apiError("too_large", 413, "too large");
103 const minted = await mintProposalToken(
104 ctx.app,
105 ctx.auth.user,
106 repo,
107 str(input.child),
108 );
109 if (!minted.ok) {
110 if (minted.error === "not_found") return notFound();
111 return apiError(
112 minted.error,
113 422,
114 minted.error === "mirror"
115 ? "a mirror's pulls are its origin's; nothing can be proposed here"
116 : "a child's name is lowercase letters, digits and dashes, up to 32",
117 );
118 }
119 return json(
120 {
121 child: minted.value.child,
122 token: minted.value.token,
123 namespace: namespaceOf(minted.value.child),
124 repo: `${repo.ownerName}/${repo.name}`,
125 },
126 201,
127 );
128 });
129
130 router.add("GET", "/api/v1/proposals/grant", (ctx) => {
131 const held = seat(ctx);
132 if (held instanceof Response) return held;
133 return json({
134 child: held.grant.child,
135 repo: `${held.repo.ownerName}/${held.repo.name}`,
136 namespace: namespaceOf(held.grant.child),
137 });
138 });
139
140 router.add("POST", "/api/v1/proposals", async (ctx) => {
141 const held = seat(ctx);
142 if (held instanceof Response) return held;
143 const input = await boundedBody(ctx.request, MAX_REQUEST);
144 if (input === "too_large")
145 return apiError("too_large", 413, "a proposal is at most 32 KB of words");
146 const opened = await receiveProposal(ctx.app, held.grant, held.repo, {
147 title: input.title,
148 body: input.body,
149 branch: input.branch,
150 origin: input.origin,
151 source: input.source,
152 });
153 if (!opened.ok) {
154 const e = opened.error;
155 if (e.kind === "rate_limited") return apiError("rate_limited", 429, e.reason);
156 if (e.kind === "no_branch")
157 return apiError("no_branch", 422, "push the branch first");
158 return apiError(
159 e.kind === "invalid" ? "invalid_proposal" : "refused",
160 422,
161 e.reason,
162 );
163 }
164 return json({ number: opened.value.number, state: "open" }, 201);
165 });
166
167 router.add("GET", "/api/v1/proposals/:number", (ctx) => {
168 const held = seat(ctx);
169 if (held instanceof Response) return held;
170 const number = Number(ctx.params.number);
171 const state = Number.isSafeInteger(number)
172 ? proposalState(ctx.app, held.grant, number)
173 : undefined;
174 return state === undefined ? notFound() : json(state);
175 });
176 }
src/http/server.ts +69 −1
@@ -34,6 +34,7 @@ import {
3434 BODY_MAX,
3535 carryNotes,
3636 mustClose,
37 noteCeiling,
3738 noteSignedIn,
3839 readBounded,
3940 REQUEST_MAX,
@@ -44,6 +45,14 @@ import { trackPullHead } from "../core/pulls.ts";
4445 import { createRepo } from "../actions/repos.ts";
4546 import { sessionOf } from "../core/sessions.ts";
4647 import { scopeAllows, verifyToken } from "../core/tokens.ts";
48 import {
49 grantOfUser,
50 mayCall as proposerMayCall,
51 MAX_BRANCHES,
52 MAX_PUSH,
53 namespaceOf,
54 refusal as proposerRefusal,
55 } from "../core/proposals.ts";
4756 import { forgeHost } from "../core/commit_identity.ts";
4857 import {
4958 ensureEdgeUser,
@@ -56,6 +65,7 @@ import { liveResponse, readyResponse } from "./health.ts";
5665 import { runGit } from "../git/env.ts";
5766 import { noteRefusedInternal } from "../kernel/internal_refused.ts";
5867 import { hookEnv, ZERO_OID, type HookRequest } from "../git/hooks.ts";
68 import { runGitCapture } from "../git/env.ts";
5969 import { repoDir } from "../git/repos.ts";
6070 import {
6171 advertiseRefs,
@@ -412,12 +422,15 @@ import {
412422 } from "./context.ts";
413423 import {
414424 apiError,
425 forbidden,
415426 json,
416427 noRoute,
417428 notFound,
418429 prefersHtml,
419430 securityFloor,
420431 } from "./respond.ts";
432 import { proposeSubmit } from "../web/studio/upstream.ts";
433 import { proposalRoutes } from "./proposals.ts";
421434 import { RateLimiter, type Verdict } from "../core/ratelimit.ts";
422435 import {
423436 MAX_KEY_LENGTH,
@@ -945,6 +958,7 @@ export function buildRouter(): Router<Handler> {
945958 router.add("POST", "/:owner/:name/pulls/:number/ship", shipSubmit);
946959 router.add("POST", "/:owner/:name/pulls/:number/say", saySubmit);
947960 router.add("POST", "/:owner/:name/pulls/:number/take-back", takeBackSubmit);
961 router.add("POST", "/:owner/:name/pulls/:number/propose-upstream", proposeSubmit);
948962 router.add("POST", "/:owner/:name/pulls/:number/hold", holdSubmit);
949963 router.add("POST", "/:owner/:name/pulls/:number/release", releaseSubmit);
950964 // What an issue waits for: link and unlink, from the issue page.
@@ -1210,6 +1224,7 @@ export function buildApiRouter(): Router<Handler> {
12101224 const router = new Router<Handler>();
12111225 apiRoutes(router);
12121226 feedRoutes(router);
1227 proposalRoutes(router);
12131228 return router;
12141229 }
12151230
@@ -1240,6 +1255,18 @@ async function withGitAccess(
12401255 // Anonymous callers get a challenge wherever credentials could help;
12411256 // authenticated-but-unauthorized callers get a 404 that hides existence.
12421257 if (!repo) return ctx.auth.user ? notFound() : gitChallenge();
1258 // A child's proposal token pushes to the one repository it was minted
1259 // for and reads nothing; which branches is the pre-receive hook's to say.
1260 if (ctx.auth.scope === "propose") {
1261 const grant =
1262 ctx.auth.user === undefined ? undefined : grantOfUser(ctx.app.db, ctx.auth.user.id);
1263 if (!write || grant === undefined || grant.repoId !== repo.id)
1264 return notFound();
1265 return serve(
1266 repoDir(ctx.app.reposRoot, repo.ownerName, repo.name),
1267 repo.id,
1268 );
1269 }
12431270 if (write) {
12441271 if (!ctx.auth.user) return gitChallenge();
12451272 if (
@@ -1489,7 +1516,39 @@ async function handleHook(app: App, request: Request): Promise<Response> {
14891516 const actor = input.actorId
14901517 ? getUserById(app.db, input.actorId)
14911518 : undefined;
1519 // A child forge's proposer moves nothing but its own namespace in its
1520 // own repository (`core/proposals.ts`).
1521 const proposer =
1522 actor === undefined ? undefined : grantOfUser(app.db, actor.id);
1523 // Each push is capped in bytes; the number of branches a child may hold
1524 // is capped here, so a token cannot fill the disk 8 MB at a time.
1525 if (proposer !== undefined) {
1526 const held = await runGitCapture(
1527 [
1528 "for-each-ref",
1529 "--format=%(refname)",
1530 `refs/heads/${namespaceOf(proposer.child)}`,
1531 ],
1532 { cwd: repoDir(app.reposRoot, repo.ownerName, repo.name) },
1533 );
1534 const existing = held.stdout.split("\n").filter((l) => l !== "").length;
1535 const created = input.updates.filter((u) => /^0+$/.test(u.oldOid)).length;
1536 if (held.code !== 0 || existing + created > MAX_BRANCHES)
1537 return new Response(
1538 `a child may hold at most ${MAX_BRANCHES} proposal branches; close some first`,
1539 { status: 403 },
1540 );
1541 }
14921542 for (const update of input.updates) {
1543 if (proposer !== undefined) {
1544 const refused = proposerRefusal(
1545 proposer,
1546 repo.id,
1547 update.ref,
1548 update.newOid,
1549 );
1550 if (refused !== null) return new Response(refused, { status: 403 });
1551 }
14931552 // The pull namespace belongs to the forge, never to pushers.
14941553 if (update.ref.startsWith("refs/pull/")) {
14951554 return new Response(`${update.ref}: refs/pull/* is reserved`, {
@@ -1966,11 +2025,20 @@ async function answerGet(
19662025 // The two things standing between one runaway agent and everybody
19672026 // else's latency, applied before a handler runs and after auth is
19682027 // known — a limit needs an identity, and a replay needs a credential.
2028 // A child's proposal token knocks on a few doors only, and its bodies are
2029 // held far below the forge's ceilings.
2030 if (auth.scope === "propose") {
2031 if (!proposerMayCall(request.method, url.pathname)) return forbidden();
2032 noteCeiling(request, MAX_PUSH);
2033 }
19692034 const credential = tokenCredential(request, auth);
19702035 const verdict =
19712036 credential === undefined
19722037 ? undefined
1973 : limiter.take(credential, auth.scope ?? "ro");
2038 : limiter.take(
2039 credential,
2040 auth.scope === undefined || auth.scope === "propose" ? "ro" : auth.scope,
2041 );
19742042 if (verdict !== undefined && !verdict.allowed) {
19752043 return withRateHeaders(tooManyRequests(verdict), verdict);
19762044 }
src/main.ts +6
@@ -134,6 +134,12 @@ if (parentProblem !== null) {
134134 const app = createApp({
135135 dataDir,
136136 ...(parentUrl === "" ? {} : { parentUrl }),
137 ...((process.env.FORGE_PARENT_PROPOSAL_TOKEN ?? "").trim() === ""
138 ? {}
139 : { parentProposalToken: process.env.FORGE_PARENT_PROPOSAL_TOKEN!.trim() }),
140 ...((process.env.FORGE_PARENT_REPO ?? "").trim() === ""
141 ? {}
142 : { parentRepo: process.env.FORGE_PARENT_REPO!.trim() }),
137143 port: Number(process.env.PORT ?? 3000),
138144 ...(process.env.FORGE_HOST === undefined
139145 ? {}
src/tui/screens/pull.ts +71
@@ -47,6 +47,12 @@ import {
4747 type EnvStatus, envsFor } from "../../apps/runtime.ts";
4848 import { getAppByRepo } from "../../core/apps.ts";
4949 import { getIssue, type Issue } from "../../core/issues.ts";
50 import {
51 parentSeatFor,
52 proposeToParent,
53 upstreamOf,
54 } from "../../actions/propose_parent.ts";
55 import { proposalOfIssue } from "../../core/proposals.ts";
5056 import { pullMayRun } from "../../core/pull_trust.ts";
5157 import { getPull, variantSiblings, type Pull } from "../../core/pulls.ts";
5258 import { voteVariant } from "../../actions/variants.ts";
@@ -370,6 +376,65 @@ export function pullScreen(
370376 createdAt: string;
371377 }[] => (detail?.comments ?? []).filter((c) => !reviewIds().has(c.id));
372378
379 /** What the parent has said of this change, or a child's note on one it sent. */
380 const upstreamNotes = (): ThreadEntry[] => {
381 const row = repo === undefined ? undefined : getPull(f.db, repo.id, number);
382 if (repo === undefined || row === undefined) return [];
383 const notes: string[] = [];
384 const view = upstreamOf(f.app, repo, row);
385 if (view !== undefined)
386 notes.push(
387 `Proposed upstream as change ${view.sent.parentNumber} at ${view.sent.parentUrl}: ${view.sent.state}.`,
388 );
389 const from = proposalOfIssue(f.db, row.id);
390 if (from !== undefined)
391 notes.push(
392 `Proposed by the child forge ${from.child} (${from.origin}) from its change ${from.source}.`,
393 );
394 return notes.map((body) => ({
395 kind: "comment" as const,
396 actor: "forge",
397 at: row.createdAt,
398 body,
399 }));
400 };
401
402 /** Whether `U` is on offer: a local change not yet sent to a parent that takes proposals. */
403 const mayPropose = (): boolean => {
404 if (repo === undefined || !mayWrite() || parentSeatFor(f.app, repo) === undefined)
405 return false;
406 const row = getPull(f.db, repo.id, number);
407 return (
408 row !== undefined &&
409 repo.origin === null &&
410 !row.crossRepo &&
411 row.state === "open" &&
412 upstreamOf(f.app, repo, row) === undefined
413 );
414 };
415
416 /** `U` — send this change to the parent forge as a proposal. */
417 const proposeUp = (): void => {
418 if (repo === undefined) return;
419 const target = repo;
420 const row = getPull(f.db, target.id, number);
421 if (row === undefined) return;
422 runAsync(ctx, async () => {
423 const sent = await proposeToParent(f.app, f.user, target, row);
424 if (!sent.ok) {
425 ctx.toast(
426 typeof sent.error === "string"
427 ? errorText(sent.error)
428 : sent.error.reason,
429 "danger",
430 );
431 return;
432 }
433 await reload();
434 ctx.toast("proposed upstream", "success");
435 });
436 };
437
373438 const entries = (): ThreadEntry[] => [
374439 ...(detail === undefined
375440 ? []
@@ -384,6 +449,7 @@ export function pullScreen(
384449 : { note: detail.issue.originUrl }),
385450 },
386451 ]),
452 ...upstreamNotes(),
387453 ...conversation().map((comment) => ({
388454 kind: "comment" as const,
389455 actor: who(comment.authorName, comment.originAuthor),
@@ -661,6 +727,7 @@ export function pullScreen(
661727 ...(mayApproveHere()
662728 ? [binding(["A"], "approve to run here")]
663729 : []),
730 ...(mayPropose() ? [binding(["U"], "propose upstream")] : []),
664731 binding(["a"], "assign"),
665732 binding(["m"], "merge", { disabled: state() !== "ready" }),
666733 ...(tab === 1 && view.threadHere() !== null
@@ -855,6 +922,10 @@ export function pullScreen(
855922 review();
856923 return true;
857924 }
925 if (e.key === "U" && mayPropose()) {
926 proposeUp();
927 return true;
928 }
858929 if (e.key === "A" && mayApproveHere()) {
859930 approveToRun();
860931 return true;
src/web/studio/change.ts +3 −1
@@ -80,6 +80,7 @@ import { tellLine, tellsAnswered } from "./branch_tell.ts";
8080 import { holdCard } from "./hold.ts";
8181 import { pullMayRun } from "../../core/pull_trust.ts";
8282 import { changeHref } from "./nouns.ts";
83 import { proposalNote, upstreamCard } from "./upstream.ts";
8384 import { pullWord, servingHistory, wordBadge, type WordCtx } from "./words.ts";
8485
8586 /** The pull and its repo, or the response that refuses to say why not. */
@@ -527,6 +528,7 @@ async function changeConversation(
527528 ),
528529 );
529530
531 const upstreamSection = upstreamCard(ctx, repo, pull, thread);
530532 const siblings = variantSiblings(db, [pull])[0] ?? [];
531533 const glyph = originGlyph(repo);
532534 const headOid = status?.headOid ?? pull.headOid;
@@ -561,7 +563,7 @@ async function changeConversation(
561563 <div id="pull-check">${checkLine}</div> ${holdCard(ctx, repo, pull, { act: true })}
562564 ${approveHereCard(ctx, repo, pull, headOid, `${thread}/approve-here`)}
563565 ${when(wall, (w) => wallCard(w))} ${decisionSection}
564 ${takeBackSection}
566 ${takeBackSection} ${upstreamSection ?? null} ${proposalNote(ctx, pull) ?? null}
565567 ${when(record, (r) => lookCard(ctx, repo, r, pull, pull.headOid))}
566568 <div class="split">
567569 <div>
src/web/studio/upstream.ts added +112
@@ -0,0 +1,112 @@
1 /**
2 * Proposing upstream in the studio: the one button on a change, and what the
3 * parent has said of it since; and, on the parent, the note on a pull that
4 * a child sent. Words from a child are shown through `html`, which escapes.
5 */
6
7 import {
8 parentSeatFor,
9 proposeToParent,
10 upstreamOf,
11 } from "../../actions/propose_parent.ts";
12 import { ageWords } from "../../core/parent_releases.ts";
13 import { proposalOfIssue } from "../../core/proposals.ts";
14 import { getPull, type Pull } from "../../core/pulls.ts";
15 import { canWrite, type Repo } from "../../core/repos.ts";
16 import { mayView } from "../../core/sealed.ts";
17 import type { Ctx } from "../../http/context.ts";
18 import { loadRepo, notFoundPage, repoBase, signInFirst } from "../chrome.ts";
19 import { readForm } from "../form.ts";
20 import { html, type Html } from "../html.ts";
21 import { flashOrJson } from "../layout.ts";
22 import { btn, card } from "../ui.ts";
23
24 const WORDS: Record<string, string> = {
25 open: "open — waiting for review",
26 merged: "merged",
27 closed: "closed without merging",
28 };
29
30 /** The child's card on a change: the button, or where the proposal stands. */
31 export function upstreamCard(
32 ctx: Ctx,
33 repo: Repo,
34 pull: Pull,
35 thread: string,
36 ): Html | undefined {
37 const seat = parentSeatFor(ctx.app, repo);
38 if (seat === undefined || repo.origin !== null || pull.crossRepo) return undefined;

Same point for the page: the card shows on every repository on this forge. Show it only on the repo that matches the parent's grant.

39 const host = new URL(seat.url).host;
40 const view = upstreamOf(ctx.app, repo, pull);
41 if (view !== undefined) {
42 const { sent } = view;
43 const heard =
44 sent.checkedAt === null
45 ? ""
46 : ` Last heard ${ageWords(Date.now() - Date.parse(sent.checkedAt))} ago.`;
47 return card(
48 html`<p>
49 Proposed to ${host} as
50 <a href="${sent.parentUrl}/pulls/${sent.parentNumber}"
51 >change ${sent.parentNumber}</a
52 >: <strong>${WORDS[sent.state] ?? sent.state}</strong>.<span
53 class="muted small"
54 >${heard}</span
55 >
56 </p>`,
57 );
58 }
59 if (ctx.auth.user === undefined || !canWrite(ctx.app.db, repo, ctx.auth.user))
60 return undefined;
61 return card(
62 html`<p class="muted small">
63 Send this change to ${host} as a proposal. It goes in a branch of its
64 own; their people review it and a person there merges it.
65 </p>
66 <form method="post" action="${thread}/propose-upstream" class="bar mt">
67 ${btn("Propose upstream", { size: "sm", variant: "primary" })}
68 </form>`,
69 );
70 }
71
72 /** The parent's note on a pull a child sent. */
73 export function proposalNote(ctx: Ctx, pull: Pull): Html | undefined {
74 const sent = proposalOfIssue(ctx.app.db, pull.id);
75 if (sent === undefined) return undefined;
76 return html`<p class="muted small">
77 Proposed by the child forge <strong>${sent.child}</strong> (${sent.origin})
78 from its change ${sent.source}.
79 </p>`;
80 }
81
82 /** POST /:owner/:name/pulls/:number/propose-upstream */
83 export async function proposeSubmit(ctx: Ctx): Promise<Response> {
84 const repo = loadRepo(ctx);
85 if (!repo) return notFoundPage(ctx);
86 if (!ctx.auth.user) return signInFirst(ctx);
87 const form = await readForm(ctx, "rw");
88 if (form instanceof Response) return form;
89 const number = Number(ctx.params.number);
90 const pull = Number.isInteger(number)
91 ? getPull(ctx.app.db, repo.id, number)
92 : undefined;
93 if (!pull || !mayView(ctx.app.db, repo, pull, ctx.auth.user))
94 return notFoundPage(ctx);
95 const thread = `${repoBase(repo)}/pulls/${pull.number}`;
96 const sent = await proposeToParent(ctx.app, ctx.auth.user, repo, pull);
97 if (!sent.ok) {
98 const why =
99 typeof sent.error === "string"
100 ? sent.error === "no_parent"
101 ? "this forge has no parent to propose to"
102 : sent.error === "not_local"
103 ? "only a change made here can be proposed"
104 : "you cannot do that here"
105 : sent.error.reason;
106 return flashOrJson(ctx, thread, {
107 tone: "danger",
108 message: `That could not be proposed: ${why}.`,
109 });
110 }
111 return flashOrJson(ctx, thread, { message: "Proposed upstream." });
112 }
test/mcp.test.ts +1
@@ -177,6 +177,7 @@ describe("the forge over MCP", () => {
177177 "outsiders",
178178 "decisions_by",
179179 "probe",
180 "propose_upstream",
180181 "following",
181182 "spawn",
182183 "forges",
test/proposals.test.ts added +622
@@ -0,0 +1,622 @@
1 import { proveAll } from "./helpers/verified.ts";
2 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App } from "../src/app.ts";
7 import { getPull } from "../src/core/pulls.ts";
8 import { sentOf } from "../src/core/proposals.ts";
9 import { submitReview } from "../src/core/reviews.ts";
10 import { getUserById } from "../src/core/users.ts";
11 import { createForgeApp } from "../src/tui/forge.ts";
12 import { pullScreen } from "../src/tui/screens/pull.ts";
13 import { local } from "../src/tui/screens/where.ts";
14 import { headlessTerminal } from "../src/tui/term/terminal.ts";
15 import { settleApp } from "./helpers/tui.ts";
16 import { getRepo } from "../src/core/repos.ts";
17 import { pullMayRun } from "../src/core/pull_trust.ts";
18 import { branchProblem, mayCall, refusal } from "../src/core/proposals.ts";
19 import { serve, type Servers } from "../src/http/server.ts";
20 import { gitClientEnv } from "./helpers/git-client.ts";
21
22 /**
23 * Proposing upstream: a parent, a child, a real git client. The token the
24 * parent mints for a child makes branches under its namespace and opens
25 * pulls from them, and is refused everywhere else.
26 */
27
28 const PASSWORD = "alice-login-secret";
29 const basic = (u: string, s: string) =>
30 `Basic ${Buffer.from(`${u}:${s}`).toString("base64")}`;
31
32 const env = gitClientEnv();
33 async function git(args: string[], cwd: string) {
34 const proc = Bun.spawn(["git", ...args], {
35 cwd,
36 env,
37 stdout: "pipe",
38 stderr: "pipe",
39 });
40 const [out, err, code] = await Promise.all([
41 new Response(proc.stdout).text(),
42 new Response(proc.stderr).text(),
43 proc.exited,
44 ]);
45 return { code, out: out.trim(), err: err.trim() };
46 }
47
48 describe("unit: what a proposer may do", () => {
49 const grant = { tokenId: "t", userId: "u", repoId: "r", child: "kid" };
50 test("only branches under its own namespace, never a delete", () => {
51 const ok = "a".repeat(40);
52 expect(refusal(grant, "r", "refs/heads/child/kid/x", ok)).toBeNull();
53 expect(refusal(grant, "r", "refs/heads/main", ok)).not.toBeNull();
54 expect(refusal(grant, "r", "refs/heads/child/other/x", ok)).not.toBeNull();
55 expect(refusal(grant, "r", "refs/heads/child/kid/", ok)).not.toBeNull();
56 expect(refusal(grant, "r", "refs/heads/child/kid/../main", ok)).not.toBeNull();
57 expect(refusal(grant, "r", "refs/tags/child/kid/x", ok)).not.toBeNull();
58 expect(refusal(grant, "r", "refs/heads/child/kid/x", "0".repeat(40))).not.toBeNull();
59 expect(refusal(grant, "elsewhere", "refs/heads/child/kid/x", ok)).not.toBeNull();
60 });
61 test("hostile branch names are refused at the boundary", () => {
62 for (const b of [
63 "main",
64 "child/kid/<script>alert(1)</script>",
65 "child/kid/a b",
66 "child/kid/a..b",
67 "child/kid/x\n",
68 "child/kid/`x`",
69 "child/kid/x.lock",
70 "child/kid//x",
71 "refs/heads/child/kid/x",
72 42,
73 ])
74 expect(branchProblem(grant, b)).not.toBeNull();
75 expect(branchProblem(grant, "child/kid/pull-3")).toBeNull();
76 });
77 test("a proposal token knocks on few doors", () => {
78 expect(mayCall("POST", "/api/v1/proposals")).toBe(true);
79 expect(mayCall("GET", "/alice/shared.git/info/refs")).toBe(true);
80 expect(mayCall("POST", "/alice/shared.git/git-receive-pack")).toBe(true);
81 expect(mayCall("POST", "/alice/shared.git/git-upload-pack")).toBe(false);
82 expect(mayCall("GET", "/api/v1/repos/alice/shared")).toBe(false);
83 expect(mayCall("POST", "/api/v1/repos/alice/shared/pulls")).toBe(false);
84 expect(mayCall("GET", "/")).toBe(false);
85 });
86 });
87
88 describe("parent and child", () => {
89 let dirs: string[] = [];
90 let parent: App;
91 let parentServers: Servers;
92 let child: App;
93 let childServers: Servers;
94 let work: string;
95 let token = "";
96 let clone = "";
97
98 const mk = async (p: string) => {
99 const d = await mkdtemp(join(tmpdir(), p));
100 dirs.push(d);
101 return d;
102 };
103 const asAlice = (base: string, path: string, init?: RequestInit) => {
104 const headers = new Headers(init?.headers);
105 if (init?.body !== undefined) headers.set("content-type", "application/json");
106 headers.set("authorization", basic("alice", PASSWORD));
107 return fetch(`${base}${path}`, { ...init, headers });
108 };
109 const asChild = (path: string, init?: RequestInit, secret = token) => {
110 const headers = new Headers(init?.headers);
111 if (init?.body !== undefined) headers.set("content-type", "application/json");
112 headers.set("authorization", `Bearer ${secret}`);
113 return fetch(`${parentServers.url}${path}`, { ...init, headers });
114 };
115 const remote = (secret = token) =>
116 `http://x:${secret}@localhost:${parentServers.port}/alice/shared.git`;
117 const push = (ref: string, secret = token) =>
118 git(["push", remote(secret), `HEAD:refs/heads/${ref}`], clone);
119 const propose = (over: Record<string, unknown> = {}, secret = token) =>
120 asChild(
121 "/api/v1/proposals",
122 {
123 method: "POST",
124 body: JSON.stringify({
125 title: "Faster gears",
126 body: "Spins faster.",
127 branch: "child/kid/one",
128 origin: "https://kid.example.test",
129 source: "bob/gears#7",
130 ...over,
131 }),
132 },
133 secret,
134 );
135 const mint = async (name: string) => {
136 const res = await asAlice(parentServers.url, "/api/v1/repos/alice/shared/proposal-tokens", {
137 method: "POST",
138 body: JSON.stringify({ child: name }),
139 });
140 return ((await res.json()) as { token: string }).token;
141 };
142
143 beforeAll(async () => {
144 work = await mk("forge-prop-work-");
145 parent = createApp({ dataDir: await mk("forge-prop-p-"), port: 0 });
146 parentServers = await serve(parent);
147 await fetch(`${parentServers.url}/api/v1/users`, {
148 method: "POST",
149 headers: { "content-type": "application/json" },
150 body: JSON.stringify({ username: "alice", email: "[email protected]", password: PASSWORD }),
151 });
152 await asAlice(parentServers.url, "/api/v1/repos", {
153 method: "POST",
154 body: JSON.stringify({ name: "shared", visibility: "public" }),
155 });
156 await asAlice(parentServers.url, "/api/v1/repos/alice/shared/contents", {
157 method: "POST",
158 body: JSON.stringify({
159 branch: "main",
160 message: "first",
161 files: [{ path: "a.txt", content: "one\n" }],
162 }),
163 });
164 const minted = await asAlice(
165 parentServers.url,
166 "/api/v1/repos/alice/shared/proposal-tokens",
167 { method: "POST", body: JSON.stringify({ child: "kid" }) },
168 );
169 expect(minted.status).toBe(201);
170 token = ((await minted.json()) as { token: string }).token;
171
172 clone = join(work, "clone");
173 const c = await git(
174 ["clone", "-q", `http://alice:${PASSWORD}@localhost:${parentServers.port}/alice/shared.git`, clone],
175 work,
176 );
177 expect(c.code).toBe(0);
178 await Bun.write(join(clone, "b.txt"), "two\n");
179 await git(["add", "."], clone);
180 expect((await git(["commit", "-qm", "faster"], clone)).code).toBe(0);
181 expect((await push("child/kid/one")).code).toBe(0);
182 });
183
184 afterAll(async () => {
185 parentServers.stop();
186 childServers?.stop();
187 parent.close();
188 child?.close();
189 for (const d of dirs) await rm(d, { recursive: true, force: true });
190 });
191
192 test("a non-admin cannot mint, a bad child name is refused", async () => {
193 const bad = await asAlice(parentServers.url, "/api/v1/repos/alice/shared/proposal-tokens", {
194 method: "POST",
195 body: JSON.stringify({ child: "../Evil" }),
196 });
197 expect(bad.status).toBe(422);
198 const anon = await fetch(`${parentServers.url}/api/v1/repos/alice/shared/proposal-tokens`, {
199 method: "POST",
200 headers: { "content-type": "application/json" },
201 body: JSON.stringify({ child: "x" }),
202 });
203 expect([401, 403]).toContain(anon.status);
204 });
205
206 test("the token is refused on main and in other namespaces", async () => {
207 expect((await push("main")).code).not.toBe(0);
208 expect((await push("child/other/x")).code).not.toBe(0);
209 expect((await push("child/kid/x y")).code).not.toBe(0);
210 expect((await push("child/kid/../../main")).code).not.toBe(0);
211 });
212
213 test("the token reads and writes nothing else", async () => {
214 expect((await asChild("/api/v1/repos/alice/shared")).status).toBeGreaterThanOrEqual(400);
215 const pull = await asChild("/api/v1/repos/alice/shared/pulls", {
216 method: "POST",
217 body: JSON.stringify({ title: "x", head: "child/kid/one", base: "main" }),
218 });
219 expect(pull.status).toBeGreaterThanOrEqual(400);
220 });
221
222 test("a branch under its namespace is accepted, and a pull opens from it", async () => {
223 const grant = await asChild("/api/v1/proposals/grant");
224 expect(await grant.json()).toMatchObject({ child: "kid", namespace: "child/kid/" });
225 const res = await propose();
226 expect(res.status).toBe(201);
227 const { number } = (await res.json()) as { number: number };
228 const state = await asChild(`/api/v1/proposals/${number}`);
229 expect(await state.json()).toEqual({ number, state: "open" });
230
231 // The parent's page names the child, its origin and the source change.
232 const page = await asAlice(parentServers.url, `/alice/shared/pulls/${number}`);
233 const text = await page.text();
234 expect(text).toContain("kid");
235 expect(text).toContain("https://kid.example.test");
236 expect(text).toContain("bob/gears#7");
237
238 // The child's code runs nothing here until a writer approves that head.
239 const repo = getRepo(parent.db, "alice", "shared")!;
240 const pull = getPull(parent.db, repo.id, number)!;
241 expect(pullMayRun(parent.db, repo, pull, pull.headOid)).toBe(false);
242 const approved = await asAlice(
243 parentServers.url,
244 `/api/v1/repos/alice/shared/pulls/${number}/review-states`,
245 { method: "POST", body: JSON.stringify({ state: "approved" }) },
246 );
247 expect(approved.status).toBeLessThan(300);
248 expect(pullMayRun(parent.db, repo, pull, pull.headOid)).toBe(true);
249
250 // Merging on the parent shows as merged to the child.
251 const merged = await asAlice(
252 parentServers.url,
253 `/api/v1/repos/alice/shared/pulls/${number}/merge`,
254 { method: "POST", body: "{}" },
255 );
256 expect(merged.status).toBeLessThan(300);
257 expect(await (await asChild(`/api/v1/proposals/${number}`)).json()).toEqual({
258 number,
259 state: "merged",
260 });
261 });
262
263 test("hostile words and oversize bodies are refused at the parent", async () => {
264 for (const over of [
265 { branch: "main" },
266 { branch: "child/kid/<img src=x onerror=alert(1)>" },
267 { origin: "javascript:alert(1)" },
268 { origin: "https://u:[email protected]" },
269 { origin: "https://x.test/`><script>" },
270 { source: "bob/gears#7`<script>" },
271 { title: "line\nbreak" },
272 { title: "x".repeat(201) },
273 { body: "x".repeat(8 * 1024 + 1) },
274 { body: "Fixes #1" },
275 ]) {
276 const res = await propose(over);
277 expect(res.status).toBeGreaterThanOrEqual(400);
278 expect(res.status).toBeLessThan(500);
279 }
280 const huge = await propose({ body: "x".repeat(200 * 1024) });
281 expect(huge.status).toBe(413);
282 });
283
284 test("the child proposes, and shows the state the parent reports", async () => {
285 child = createApp({
286 dataDir: await mk("forge-prop-c-"),
287 port: 0,
288 parentUrl: parentServers.url,
289 url: "https://kid.example.test",
290 parentLoopback: true,
291 parentProposalToken: token,
292 parentRepo: "alice/shared",
293 });
294 childServers = await serve(child);
295 await fetch(`${childServers.url}/api/v1/users`, {
296 method: "POST",
297 headers: { "content-type": "application/json" },
298 body: JSON.stringify({ username: "alice", email: "[email protected]", password: PASSWORD }),
299 });
300 const as = (path: string, init?: RequestInit) => {
301 const headers = new Headers(init?.headers);
302 if (init?.body !== undefined) headers.set("content-type", "application/json");
303 headers.set("authorization", basic("alice", PASSWORD));
304 return fetch(`${childServers.url}${path}`, { ...init, headers });
305 };
306 await as("/api/v1/repos", {
307 method: "POST",
308 body: JSON.stringify({ name: "shared", visibility: "public" }),
309 });
310 const files = (branch: string, name: string) =>
311 as("/api/v1/repos/alice/shared/contents", {
312 method: "POST",
313 body: JSON.stringify({
314 branch,
315 message: "m",
316 files: [{ path: name, content: "x\n" }],
317 }),
318 });
319 await files("main", "a.txt");
320 await files("feature", "c.txt");
321 const opened = await as("/api/v1/repos/alice/shared/pulls", {
322 method: "POST",
323 body: JSON.stringify({ title: "Gears", head: "feature", base: "main" }),
324 });
325 expect(opened.status).toBe(201);
326 const { number } = (await opened.json()) as { number: number };
327
328 const sent = await as(`/api/v1/repos/alice/shared/pulls/${number}/propose-upstream`, {
329 method: "POST",
330 body: "{}",
331 });
332 expect(sent.status).toBe(201);
333 const view = (await sent.json()) as { parentNumber: number; state: string };
334 expect(view.state).toBe("open");
335
336 const page = await as(`/alice/shared/pulls/${number}`);
337 expect(await page.text()).toContain("waiting for review");
338 const again = await as(`/api/v1/repos/alice/shared/pulls/${number}/upstream`);
339 expect(((await again.json()) as { state: string }).state).toBe("open");
340
341 // Only the repository the parent takes proposals for may send. Any other
342 // repository here — its page, its API — is refused and offers nothing.
343 await as("/api/v1/repos", {
344 method: "POST",
345 body: JSON.stringify({ name: "private-notes", visibility: "private" }),
346 });
347 await as("/api/v1/repos/alice/private-notes/contents", {
348 method: "POST",
349 body: JSON.stringify({
350 branch: "main",
351 message: "m",
352 files: [{ path: "s.txt", content: "secret\n" }],
353 }),
354 });
355 await as("/api/v1/repos/alice/private-notes/contents", {
356 method: "POST",
357 body: JSON.stringify({
358 branch: "f",
359 message: "m",
360 files: [{ path: "t.txt", content: "x\n" }],
361 }),
362 });
363 const other = (await (
364 await as("/api/v1/repos/alice/private-notes/pulls", {
365 method: "POST",
366 body: JSON.stringify({ title: "Mine", head: "f", base: "main" }),
367 })
368 ).json()) as { number: number };
369 const refusedOther = await as(
370 `/api/v1/repos/alice/private-notes/pulls/${other.number}/propose-upstream`,
371 { method: "POST", body: "{}" },
372 );
373 expect(refusedOther.status).toBe(422);
374 const otherPage = await as(`/alice/private-notes/pulls/${other.number}`);
375 expect(await otherPage.text()).not.toContain("Propose upstream");
376
377 // The MCP tool sends a second change from the right repository, and
378 // refuses the other one.
379 await files("second", "d.txt");
380 const second = (await (
381 await as("/api/v1/repos/alice/shared/pulls", {
382 method: "POST",
383 body: JSON.stringify({ title: "More gears", head: "second", base: "main" }),
384 })
385 ).json()) as { number: number };
386 let rpc = 100;
387 const tool = async (repo: string, n: number) => {
388 const res = await fetch(`${childServers.url}/mcp`, {
389 method: "POST",
390 headers: {
391 "content-type": "application/json",
392 accept: "application/json, text/event-stream",
393 authorization: basic("alice", PASSWORD),
394 },
395 body: JSON.stringify({
396 jsonrpc: "2.0",
397 id: rpc++,
398 method: "tools/call",
399 params: { name: "propose_upstream", arguments: { repo, number: n } },
400 }),
401 });
402 const body = (await res.json()) as any;
403 return { error: body.result?.isError === true, text: body.result?.content?.[0]?.text as string };
404 };
405 const viaMcp = await tool("alice/shared", second.number);
406 expect(viaMcp.error).toBe(false);
407 expect(JSON.parse(viaMcp.text).state).toBe("open");
408 const aliceRepo = getRepo(child.db, "alice", "shared")!;
409 expect(sentOf(child.db, aliceRepo.id, second.number)).toBeDefined();
410 const mcpOther = await tool("alice/private-notes", other.number);
411 expect(mcpOther.error).toBe(true);
412 expect(sentOf(child.db, getRepo(child.db, "alice", "private-notes")!.id, other.number)).toBeUndefined();
413
414 // The terminal's U is offered on the right repository's change only, and sends it.
415 await files("third", "e.txt");
416 const third = (await (
417 await as("/api/v1/repos/alice/shared/pulls", {
418 method: "POST",
419 body: JSON.stringify({ title: "Even more", head: "third", base: "main" }),
420 })
421 ).json()) as { number: number };
422 const alice = getUserById(child.db, aliceRepo.ownerId)!;
423 const screenFor = async (repo: typeof aliceRepo, n: number, until: (t: string) => boolean) => {
424 const terminal = headlessTerminal(140, 44);
425 const { app: tui, session } = createForgeApp(
426 child,
427 { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:alice", user: alice },
428 { terminal, exitHooks: false },
429 );
430 tui.start();
431 tui.ctx.push(pullScreen(session, tui.ctx, local(session, repo), n));
432 const end = Date.now() + 20_000;
433 while (!until(tui.screen.toText())) {
434 if (Date.now() > end) throw new Error(tui.screen.toText());
435 await settleApp(tui);
436 await Bun.sleep(20);
437 }
438 return tui;
439 };
440 const noteRepo = getRepo(child.db, "alice", "private-notes")!;
441 const elsewhere = await screenFor(noteRepo, other.number, (t) => t.includes("Mine"));
442 try {
443 expect(elsewhere.screen.toText()).not.toContain("propose upstream");
444 } finally {
445 elsewhere.stop();
446 }
447 // A same-named repository under another local owner is not the parent's:
448 // no button, no U, and a refusal from the API and the MCP tool.
449 await fetch(`${childServers.url}/api/v1/users`, {
450 method: "POST",
451 headers: { "content-type": "application/json" },
452 body: JSON.stringify({ username: "mallory", email: "[email protected]", password: PASSWORD }),
453 });
454 proveAll(child);
455 const asM = (path: string, init?: RequestInit) => {
456 const headers = new Headers(init?.headers);
457 if (init?.body !== undefined) headers.set("content-type", "application/json");
458 headers.set("authorization", basic("mallory", PASSWORD));
459 return fetch(`${childServers.url}${path}`, { ...init, headers });
460 };
461 const made = await asM("/api/v1/repos", {
462 method: "POST",
463 body: JSON.stringify({ name: "shared", visibility: "private" }),
464 });
465 expect(made.status, await made.clone().text()).toBe(201);
466 for (const [branch, name] of [["main", "m.txt"], ["mf", "n.txt"]] as const)
467 await asM("/api/v1/repos/mallory/shared/contents", {
468 method: "POST",
469 body: JSON.stringify({ branch, message: "m", files: [{ path: name, content: "x\n" }] }),
470 });
471 const mine = (await (
472 await asM("/api/v1/repos/mallory/shared/pulls", {
473 method: "POST",
474 body: JSON.stringify({ title: "Private", head: "mf", base: "main" }),
475 })
476 ).json()) as { number: number };
477 const viaApi = await asM(`/api/v1/repos/mallory/shared/pulls/${mine.number}/propose-upstream`, {
478 method: "POST",
479 body: "{}",
480 });
481 expect(viaApi.status).toBe(422);
482 expect(await (await asM(`/mallory/shared/pulls/${mine.number}`)).text()).not.toContain(
483 "Propose upstream",
484 );
485 const malloryRepo = getRepo(child.db, "mallory", "shared")!;
486 expect(sentOf(child.db, malloryRepo.id, mine.number)).toBeUndefined();
487 const malloryUser = getUserById(child.db, malloryRepo.ownerId)!;
488 const mTerm = headlessTerminal(140, 44);
489 const { app: mTui, session: mSession } = createForgeApp(
490 child,
491 { sshUsername: "mallory", remoteAddress: "127.0.0.1", fingerprint: "SHA256:m", user: malloryUser },
492 { terminal: mTerm, exitHooks: false },
493 );
494 mTui.start();
495 mTui.ctx.push(pullScreen(mSession, mTui.ctx, local(mSession, malloryRepo), mine.number));
496 try {
497 const end = Date.now() + 20_000;
498 while (!mTui.screen.toText().includes("Private") && Date.now() < end) {
499 await settleApp(mTui);
500 await Bun.sleep(20);
501 }
502 expect(mTui.screen.toText()).not.toContain("propose upstream");
503 mTui.dispatch({ type: "key", key: "U", ctrl: false, alt: false, shift: true });
504 await settleApp(mTui);
505 expect(sentOf(child.db, malloryRepo.id, mine.number)).toBeUndefined();
506 } finally {
507 mTui.stop();
508 }
509 const mcpMallory = await (async () => {
510 const res = await fetch(`${childServers.url}/mcp`, {
511 method: "POST",
512 headers: {
513 "content-type": "application/json",
514 accept: "application/json, text/event-stream",
515 authorization: basic("mallory", PASSWORD),
516 },
517 body: JSON.stringify({
518 jsonrpc: "2.0",
519 id: 999,
520 method: "tools/call",
521 params: { name: "propose_upstream", arguments: { repo: "mallory/shared", number: mine.number } },
522 }),
523 });
524 return ((await res.json()) as any).result?.isError === true;
525 })();
526 expect(mcpMallory).toBe(true);
527
528 const tui = await screenFor(aliceRepo, third.number, (t) => t.includes("propose upstream"));
529 try {
530 tui.dispatch({ type: "key", key: "U", ctrl: false, alt: false, shift: true });
531 const end = Date.now() + 20_000;
532 while (sentOf(child.db, aliceRepo.id, third.number) === undefined && Date.now() < end)
533 await Bun.sleep(20);
534 expect(sentOf(child.db, aliceRepo.id, third.number)).toBeDefined();
535 } finally {
536 tui.stop();
537 }
538 }, 60_000);
539
540 test("a child's pull waits for a writer to approve its head, and is not crew", async () => {
541 const t = await mint("rev");
542 await Bun.write(join(clone, `rev-${Date.now()}.txt`), "rev\n");
543 await git(["add", "."], clone);
544 await git(["commit", "-qm", "rev"], clone);
545 expect((await push("child/rev/x", t)).code).toBe(0);
546 const res = await propose({ branch: "child/rev/x" }, t);
547 expect(res.status).toBe(201);
548 const { number } = (await res.json()) as { number: number };
549 const repo = getRepo(parent.db, "alice", "shared")!;
550 const pull = getPull(parent.db, repo.id, number)!;
551 const head = (await git(["rev-parse", "HEAD"], clone)).out;
552 expect(pullMayRun(parent.db, repo, pull, head)).toBe(false);
553 const proposer = getUserById(parent.db, pull.authorId)!;
554 expect(proposer.kind).toBe("user");
555 const alice = getUserById(parent.db, repo.ownerId)!;
556 submitReview(parent.db, {
557 issueId: pull.id,
558 authorId: proposer.id,
559 state: "approved",
560 commitOid: head,
561 });
562 expect(pullMayRun(parent.db, repo, pull, head)).toBe(false);
563 submitReview(parent.db, {
564 issueId: pull.id,
565 authorId: alice.id,
566 state: "approved",
567 commitOid: head,
568 });
569 expect(pullMayRun(parent.db, repo, pull, head)).toBe(true);
570 });
571
572 test("a token whose repository is deleted is refused, not demoted to a read token", async () => {
573 await asAlice(parentServers.url, "/api/v1/repos", {
574 method: "POST",
575 body: JSON.stringify({ name: "doomed", visibility: "public" }),
576 });
577 const minted = await asAlice(
578 parentServers.url,
579 "/api/v1/repos/alice/doomed/proposal-tokens",
580 { method: "POST", body: JSON.stringify({ child: "gone" }) },
581 );
582 const t = ((await minted.json()) as { token: string }).token;
583 const mcp = () =>
584 fetch(`${parentServers.url}/mcp`, {
585 method: "POST",
586 headers: {
587 "content-type": "application/json",
588 accept: "application/json, text/event-stream",
589 authorization: `Bearer ${t}`,
590 },
591 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }),
592 });
593 expect((await mcp()).status).toBeGreaterThanOrEqual(400);
594 const del = await asAlice(parentServers.url, "/api/v1/repos/alice/doomed", {
595 method: "DELETE",
596 });
597 expect(del.status).toBeLessThan(300);
598 expect((await asChild("/api/v1/user", undefined, t)).status).toBe(401);
599 expect((await mcp()).status).toBe(401);
600 });
601
602 test("a child may hold only so many branches, proposal or not", async () => {
603 const busy = await mint("cap");
604 const many = Array.from({ length: 31 }, (_, i) => `HEAD:refs/heads/child/cap/many${i}`);
605 expect((await git(["push", remote(busy), ...many], clone)).code).not.toBe(0);
606 expect((await git(["push", remote(busy), ...many.slice(0, 5)], clone)).code).toBe(0);
607 });
608
609 test("the parent limits how many a child sends in an hour", async () => {
610 const busy = await mint("busy");
611 const seen: number[] = [];
612 for (let i = 0; i < 8; i++) {
613 await Bun.write(join(clone, `n${i}-${Date.now()}.txt`), `${i}\n`);
614 await git(["add", "."], clone);
615 await git(["commit", "-qm", `n${i}`], clone);
616 expect((await push(`child/busy/n${i}`, busy)).code).toBe(0);
617 seen.push((await propose({ branch: `child/busy/n${i}` }, busy)).status);
618 }
619 expect(seen).toContain(429);
620 expect(seen.indexOf(429)).toBeGreaterThan(0);
621 });
622 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs