Public: anyone can read this; the crew can change it.
Propose upstream: a child sends a change back to its parent as a pull #1764
scout/forge:scout/424-propose-upstream-a-child-sends-a-change → main 6 commits fork 3 threads · 3 unresolved
20 files
changed +1671
−10
README.md +23
| @@ -166,6 +166,29 @@ taking a release is not done here. This forge publishes its own | ||
| 166 | 166 | `/releases.json` (the version names, each linking to that document), so any |
| 167 | 167 | forge can be a parent. The terminal shows the count, not the release names. |
| 168 | 168 | |
| 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. | |
| 179 | Pushes are held to 8 MB, a request to 32 KB, a body to 8 KB, six proposals an | |
| 180 | hour and twenty open at once per child. The pull's header names the child, its | |
| 181 | origin and the source change from validated text and a body that closes issues | |
| 182 | is refused; people and crew review it and a person merges as with any pull. | |
| 183 | ||
| 184 | On the child, set `FORGE_PARENT_URL`, `FORGE_PARENT_PROPOSAL_TOKEN` and the | |
| 185 | forge's own `url`. A local change then shows "Propose upstream" (or | |
| 186 | `POST /api/v1/repos/:owner/:name/pulls/:n/propose-upstream`), which pushes the | |
| 187 | head over HTTPS (token in git's environment, never argv) and opens the pull. | |
| 188 | The change then shows the parent's state — open, merged, closed — refreshed in | |
| 189 | the background when a minute old (`GET …/pulls/:n/upstream`). Left out: a | |
| 190 | re-send after the change moves on, and proposing a fork's or mirror's change. | |
| 191 | ||
| 169 | 192 | ## Health |
| 170 | 193 | |
| 171 | 194 | `GET /api/v1/health` (and the MCP `health` tool) answer a site admin with |
scripts/gate.ts +1
| @@ -131,6 +131,7 @@ export const GATE: readonly string[] = [ | ||
| 131 | 131 | "test/pull-mergeable.test.ts", |
| 132 | 132 | "test/pull-variants.test.ts", |
| 133 | 133 | "test/pull-checks-line.test.ts", |
| 134 | "test/proposals.test.ts", | |
| 134 | 135 | "test/pulls.test.ts", |
| 135 | 136 | "test/api-reader-marks.test.ts", |
| 136 | 137 | "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 | // An agent row: no password ever verifies, and the default branch | |
| 67 | // is out of its reach even if a grant were widened. | |
| 68 | agent: true, | |
| 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"); | |
| 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 +238
| @@ -0,0 +1,238 @@ | ||
| 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 | async function call( | |
| 62 | seat: { url: string; token: string }, | |
| 63 | method: "GET" | "POST", | |
| 64 | path: string, | |
| 65 | body?: unknown, | |
| 66 | ): Promise<{ status: number; json: Record<string, unknown> }> { | |
| 67 | const res = await fetch(`${seat.url}${path}`, { | |
| 68 | method, | |
| 69 | redirect: "error", | |
| 70 | signal: AbortSignal.timeout(TIMEOUT_MS), | |
| 71 | headers: { | |
| 72 | accept: "application/json", | |
| 73 | authorization: `Bearer ${seat.token}`, | |
| 74 | ...(body === undefined ? {} : { "content-type": "application/json" }), | |
| 75 | }, | |
| 76 | ...(body === undefined ? {} : { body: JSON.stringify(body) }), | |
| 77 | }); | |
| 78 | const text = (await res.text()).slice(0, MAX_ANSWER); | |
| 79 | let json: Record<string, unknown> = {}; | |
| 80 | try { | |
| 81 | const parsed: unknown = JSON.parse(text); | |
| 82 | if (typeof parsed === "object" && parsed !== null) | |
| 83 | json = parsed as Record<string, unknown>; | |
| 84 | } catch { | |
| 85 | // An answer that is not JSON is a status and nothing more. | |
| 86 | } | |
| 87 | return { status: res.status, json }; | |
| 88 | } | |
| 89 | ||
| 90 | const refused = (reason: string): ProposeParentError => ({ | |
| 91 | kind: "refused", | |
| 92 | reason, | |
| 93 | }); | |
| 94 | ||
| 95 | /** What the parent said was wrong, in a line, without anything it quoted at length. */ | |
| 96 | const said = (json: Record<string, unknown>, status: number): string => { | |
| 97 | const m = json["message"] ?? json["error"]; | |
| 98 | return typeof m === "string" ? m.slice(0, 200) : `the parent answered ${status}`; | |
| 99 | }; | |
| 100 | ||
| 101 | export async function proposeToParent( | |
| 102 | app: App, | |
| 103 | actor: User | undefined, | |
| 104 | repo: Repo, | |
| 105 | pull: Pull, | |
| 106 | ): Promise<Result<Sent, ProposeParentError>> { | |
| 107 | const writer = requireWriter(app, actor, repo); | |
| 108 | if (!writer.ok) return writer; | |
| 109 | const seat = parentSeat(app); | |
| 110 | if (seat === undefined) return err("no_parent"); | |
| 111 | // A change that lives in this repository: not a mirror's, not a fork's. | |
| 112 | if (repo.origin !== null || pull.crossRepo || pull.originHeadRepo !== null) | |
| 113 | return err("not_local"); | |
| 114 | const already = sentOf(app.db, repo.id, pull.number); | |
| 115 | if (already !== undefined) return ok(already); | |
| 116 | if (app.config.url === undefined) | |
| 117 | return err(refused("this forge does not know its own address")); | |
| 118 | if (!isSafeOid(pull.headOid)) return err(refused("the change has no head")); | |
| 119 | ||
| 120 | try { | |
| 121 | const seen = await call(seat, "GET", "/api/v1/proposals/grant"); | |
| 122 | const { child, repo: target } = seen.json; | |
| 123 | if (seen.status !== 200 || typeof child !== "string" || typeof target !== "string") | |
| 124 | return err(refused(said(seen.json, seen.status))); | |
| 125 | const [owner, name, ...rest] = target.split("/"); | |
| 126 | const branch = `child/${child}/pull-${pull.number}`; | |
| 127 | if ( | |
| 128 | owner === undefined || | |
| 129 | name === undefined || | |
| 130 | rest.length > 0 || | |
| 131 | !isSafeName(owner) || | |
| 132 | !isSafeName(name) || | |
| 133 | !isSafeRef(branch) | |
| 134 | ) | |
| 135 | return err(refused("the parent named something unusable")); | |
| 136 | const remote = safeRemoteUrl(`${seat.url}/${owner}/${name}.git`); | |
| 137 | if (remote === undefined) return err(refused("the parent's address is unusable")); | |
| 138 | ||
| 139 | const pushed = await runGitCapture( | |
| 140 | ["push", "--quiet", remote, `${pull.headOid}:refs/heads/${branch}`], | |
| 141 | { | |
| 142 | cwd: repoDir(app.reposRoot, repo.ownerName, repo.name), | |
| 143 | env: gitAuthEnv(seat.url, `Bearer ${seat.token}`), | |
| 144 | timeoutMs: PUSH_MS, | |
| 145 | }, | |
| 146 | ); | |
| 147 | if (pushed.code !== 0) | |
| 148 | return err( | |
| 149 | refused( | |
| 150 | redact(pushed.stderr.trim(), seat.token).slice(0, 300) || | |
| 151 | "the push was refused", | |
| 152 | ), | |
| 153 | ); | |
| 154 | ||
| 155 | const words = pull.body.slice(0, 8 * 1024); | |
| 156 | const opened = await call(seat, "POST", "/api/v1/proposals", { | |
| 157 | title: pull.title.replace(/[\x00-\x1f\x7f]/g, " ").slice(0, 200), | |
| 158 | // A body that names issues to close would be refused; the title and | |
| 159 | // the source change say enough. | |
| 160 | ...(closesFromBody(words).length > 0 ? {} : { body: words }), | |
| 161 | branch, | |
| 162 | origin: app.config.url, | |
| 163 | source: `${repo.ownerName}/${repo.name}#${pull.number}`, | |
| 164 | }); | |
| 165 | const number = opened.json["number"]; | |
| 166 | if (opened.status !== 201 || typeof number !== "number") | |
| 167 | return err(refused(said(opened.json, opened.status))); | |
| 168 | recordSent(app.db, repo.id, pull.number, number, `${seat.url}/${owner}/${name}`); | |
| 169 | app.bus.append({ | |
| 170 | kind: "pull.proposed_upstream", | |
| 171 | repoId: repo.id, | |
| 172 | actorId: writer.value.id, | |
| 173 | payload: { number: pull.number, parent: number }, | |
| 174 | }); | |
| 175 | return ok(sentOf(app.db, repo.id, pull.number)!); | |
| 176 | } catch { | |
| 177 | return err(refused("the parent could not be reached")); | |
| 178 | } | |
| 179 | } | |
| 180 | ||
| 181 | const refreshing = new Map<string, Promise<void>>(); | |
| 182 | ||
| 183 | /** Asks the parent where the proposal stands and keeps the answer. Never throws. */ | |
| 184 | export function refreshUpstream( | |
| 185 | app: App, | |
| 186 | repo: Repo, | |
| 187 | pull: Pull, | |
| 188 | ): Promise<void> { | |
| 189 | const key = `${repo.id}#${pull.number}`; | |
| 190 | const going = refreshing.get(key); | |
| 191 | if (going !== undefined) return going; | |
| 192 | const job = (async () => { | |
| 193 | const seat = parentSeat(app); | |
| 194 | const sent = sentOf(app.db, repo.id, pull.number); | |
| 195 | if (seat === undefined || sent === undefined) return; | |
| 196 | try { | |
| 197 | const answer = await call(seat, "GET", `/api/v1/proposals/${sent.parentNumber}`); | |
| 198 | const state = answer.json["state"]; | |
| 199 | if ( | |
| 200 | answer.status === 200 && | |
| 201 | typeof state === "string" && | |
| 202 | STATES.includes(state) | |
| 203 | ) | |
| 204 | noteState( | |
| 205 | app.db, | |
| 206 | repo.id, | |
| 207 | pull.number, | |
| 208 | state as UpstreamState, | |
| 209 | new Date().toISOString(), | |
| 210 | ); | |
| 211 | } catch { | |
| 212 | // The last state heard stands; the next view tries again. | |
| 213 | } | |
| 214 | })().finally(() => refreshing.delete(key)); | |
| 215 | refreshing.set(key, job); | |
| 216 | return job; | |
| 217 | } | |
| 218 | ||
| 219 | /** | |
| 220 | * What this change's proposal last was, at once. A state older than a | |
| 221 | * minute starts a refresh in the background; the caller does not wait. | |
| 222 | */ | |
| 223 | export function upstreamOf( | |
| 224 | app: App, | |
| 225 | repo: Repo, | |
| 226 | pull: Pull, | |
| 227 | now: number = Date.now(), | |
| 228 | ): { sent: Sent; refresh: Promise<void> | undefined } | undefined { | |
| 229 | const sent = sentOf(app.db, repo.id, pull.number); | |
| 230 | if (sent === undefined) return undefined; | |
| 231 | const stale = | |
| 232 | sent.checkedAt === null || now - Date.parse(sent.checkedAt) >= FRESH_MS; | |
| 233 | return { | |
| 234 | sent, | |
| 235 | refresh: | |
| 236 | stale && sent.state === "open" ? refreshUpstream(app, repo, pull) : undefined, | |
| 237 | }; | |
| 238 | } |
src/app.ts +5
| @@ -159,6 +159,11 @@ export interface ForgeConfig { | ||
| 159 | 159 | parentUrl?: string; |
| 160 | 160 | /** Lets `parentUrl` be plain http. Tests only; boot never sets it. */ |
| 161 | 161 | 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; | |
| 162 | 167 | /** How many `releases/<sha>/` checkouts to keep (`FORGE_RELEASES_KEEP`). @default 5 */ |
| 163 | 168 | releasesKeep?: number; |
| 164 | 169 | /** |
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 @@ | ||
| 8 | 8 | * itself (only a writer could push it there), and a fork's pull opened by a |
| 9 | 9 | * writer or the crew from a fork that same person owns. A pull whose head |
| 10 | 10 | * 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. | |
| 12 | 14 | */ |
| 13 | 15 | import type { Database } from "bun:sqlite"; |
| 16 | import { proposalOfIssue } from "./proposals.ts"; | |
| 14 | 17 | import { getIssueById, getPull, type Pull } from "./pulls.ts"; |
| 15 | 18 | import { canWrite, getRepoById, onCrew, type Repo } from "./repos.ts"; |
| 16 | 19 | import { listReviews } from "./reviews.ts"; |
| @@ -26,7 +29,13 @@ export function pullMayRun( | ||
| 26 | 29 | pull: Pull, |
| 27 | 30 | headOid: string, |
| 28 | 31 | ): 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 = | |
| 35 | pull.headBranch.startsWith("child/") || | |
| 36 | proposalOfIssue(db, pull.id) !== undefined; | |
| 37 | return proposed ? approvedAt(db, repo, pull, headOid) : true; | |
| 38 | } | |
| 30 | 39 | if (pull.crossRepo && pull.originHeadRepo === null) { |
| 31 | 40 | const author = getUserById(db, pull.authorId); |
| 32 | 41 | const head = getRepoById(db, pull.headRepoId); |
src/core/schema.ts +37
| @@ -1741,6 +1741,43 @@ export const migrations: readonly string[] = [ | ||
| 1741 | 1741 | ALTER TABLE repo ADD COLUMN decisions_by TEXT NOT NULL DEFAULT 'me' |
| 1742 | 1742 | CHECK (decisions_by IN ('me', 'decider', 'decider_tell')); |
| 1743 | 1743 | `, |
| 1744 | // 86 — proposing upstream (#424). The parent mints a token for one child, | |
| 1745 | // good for one repository and nothing else (`proposal_grant`; the token row | |
| 1746 | // itself says `ro` and a missing grant can only make it weaker). Each | |
| 1747 | // proposal a child opens is one row (`proposal`) naming the child, its | |
| 1748 | // origin and the source change, kept as validated text. On the child, | |
| 1749 | // `proposal_sent` remembers the pull it sent and what the parent last said. | |
| 1750 | ` | |
| 1751 | CREATE TABLE proposal_grant ( | |
| 1752 | token_id TEXT PRIMARY KEY REFERENCES token(id) ON DELETE CASCADE, | |
| 1753 | user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE, | |
| 1754 | repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE, | |
| 1755 | child TEXT NOT NULL, | |
| 1756 | created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), | |
| 1757 | UNIQUE (repo_id, child) | |
| 1758 | ); | |
| 1759 | CREATE INDEX proposal_grant_user ON proposal_grant(user_id); | |
| 1760 | CREATE TABLE proposal ( | |
| 1761 | issue_id TEXT PRIMARY KEY REFERENCES issue(id) ON DELETE CASCADE, | |
| 1762 | repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE, | |
| 1763 | user_id TEXT NOT NULL, | |
| 1764 | child TEXT NOT NULL, | |
| 1765 | origin TEXT NOT NULL, | |
| 1766 | source TEXT NOT NULL, | |
| 1767 | created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')) | |
| 1768 | ); | |
| 1769 | CREATE INDEX proposal_by_user ON proposal(user_id, created_at); | |
| 1770 | CREATE TABLE proposal_sent ( | |
| 1771 | repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE, | |
| 1772 | pull_number INTEGER NOT NULL, | |
| 1773 | parent_number INTEGER NOT NULL, | |
| 1774 | parent_url TEXT NOT NULL, | |
| 1775 | state TEXT NOT NULL DEFAULT 'open', | |
| 1776 | checked_at TEXT, | |
| 1777 | created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), | |
| 1778 | PRIMARY KEY (repo_id, pull_number) | |
| 1779 | ); | |
| 1780 | `, | |
| 1744 | 1781 | ]; |
| 1745 | 1782 | |
| 1746 | 1783 | /** |
src/core/tokens.ts +19 −3
| @@ -10,9 +10,19 @@ import { id, secret } from "../kernel/id.ts"; | ||
| 10 | 10 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 11 | 11 | import { getUserById, isActive, type User } from "./users.ts"; |
| 12 | 12 | |
| 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"; | |
| 14 | 19 | |
| 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 | }; | |
| 16 | 26 | |
| 17 | 27 | export function scopeAllows(held: TokenScope, needed: TokenScope): boolean { |
| 18 | 28 | return rank[held] >= rank[needed]; |
| @@ -96,7 +106,13 @@ export function verifyToken( | ||
| 96 | 106 | row.id, |
| 97 | 107 | ); |
| 98 | 108 | } |
| 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 }); | |
| 100 | 116 | } |
| 101 | 117 | |
| 102 | 118 | export function listTokens(db: Database, userId: string): TokenInfo[] { |
src/git/smart-http.ts +2 −2
| @@ -12,7 +12,7 @@ import { | ||
| 12 | 12 | counted, |
| 13 | 13 | FETCH_MAX, |
| 14 | 14 | GZIP_MAX, |
| 15 | PUSH_MAX, | |
| 15 | pushCapFor, | |
| 16 | 16 | readBounded, |
| 17 | 17 | } from "../http/limits.ts"; |
| 18 | 18 | import { gitEnv, transferGate } from "./env.ts"; |
| @@ -208,7 +208,7 @@ async function feedStdin( | ||
| 208 | 208 | } |
| 209 | 209 | if (!gone) await write(inflated); |
| 210 | 210 | } else { |
| 211 | const max = service === "git-receive-pack" ? PUSH_MAX : FETCH_MAX; | |
| 211 | const max = service === "git-receive-pack" ? pushCapFor(request) : FETCH_MAX; | |
| 212 | 212 | for await (const chunk of counted(request.body, max, stop)) { |
| 213 | 213 | if (gone) break; |
| 214 | 214 | await write(chunk); |
src/http/limits.ts +20 −1
| @@ -48,13 +48,32 @@ export const noteSignedIn = (request: Request): void => { | ||
| 48 | 48 | signedIn.add(request); |
| 49 | 49 | }; |
| 50 | 50 | |
| 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 | ||
| 51 | 65 | /** The most a shared reader keeps of this request's body. */ |
| 52 | 66 | 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 | ); | |
| 54 | 71 | |
| 55 | 72 | /** A request rebuilt from another (a replay) keeps what was noted of it. */ |
| 56 | 73 | export const carryNotes = (from: Request, to: Request): void => { |
| 57 | 74 | if (signedIn.has(from)) signedIn.add(to); |
| 75 | const ceiling = ceilings.get(from); | |
| 76 | if (ceiling !== undefined) ceilings.set(to, ceiling); | |
| 58 | 77 | const close = closers.get(from); |
| 59 | 78 | if (close !== undefined) closers.set(to, close); |
| 60 | 79 | }; |
src/http/mcp.ts +32
| @@ -80,6 +80,7 @@ import { getIssue, getIssueById, listOpenAgentPullsVisibleTo } from "../core/iss | ||
| 80 | 80 | import { waitsForPerson } from "../crew/review.ts"; |
| 81 | 81 | import { attachLook } from "../actions/attach_look.ts"; |
| 82 | 82 | import { lookUrl } from "../core/looks.ts"; |
| 83 | import { proposeToParent } from "../actions/propose_parent.ts"; | |
| 83 | 84 | import { getPull, pullDir, pullMergeState } from "../core/pulls.ts"; |
| 84 | 85 | import { repoGraph } from "../core/dependencies.ts"; |
| 85 | 86 | import { pillarView } from "../core/pillars.ts"; |
| @@ -948,6 +949,37 @@ const TOOLS: readonly Tool[] = [ | ||
| 948 | 949 | }); |
| 949 | 950 | }, |
| 950 | 951 | }, |
| 952 | { | |
| 953 | name: "propose_upstream", | |
| 954 | description: | |
| 955 | "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.", | |
| 956 | inputSchema: { | |
| 957 | type: "object", | |
| 958 | properties: { | |
| 959 | repo: REPO_ARG, | |
| 960 | number: { type: "integer", minimum: 1 }, | |
| 961 | }, | |
| 962 | required: ["repo", "number"], | |
| 963 | }, | |
| 964 | writes: true, | |
| 965 | async run(ctx, user, args) { | |
| 966 | const repo = repoArg(ctx, user, args); | |
| 967 | if (isAnswer(repo)) return repo; | |
| 968 | const n = args["number"]; | |
| 969 | const pull = | |
| 970 | typeof n === "number" && Number.isInteger(n) && n > 0 | |
| 971 | ? getPull(ctx.app.db, repo.id, n) | |
| 972 | : undefined; | |
| 973 | if (pull === undefined || !mayView(ctx.app.db, repo, pull, user)) | |
| 974 | return bad("no_such_pull", `no pull #${String(n)}`); | |
| 975 | const sent = await proposeToParent(ctx.app, user, repo, pull); | |
| 976 | if (sent.ok) return good({ ...sent.value }); | |
| 977 | const e = sent.error; | |
| 978 | return typeof e === "string" | |
| 979 | ? bad(e, "this change cannot be proposed upstream from here") | |
| 980 | : bad("refused", e.reason); | |
| 981 | }, | |
| 982 | }, | |
| 951 | 983 | { |
| 952 | 984 | name: "following", |
| 953 | 985 | 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
| @@ -31,6 +31,7 @@ import { | ||
| 31 | 31 | BODY_MAX, |
| 32 | 32 | carryNotes, |
| 33 | 33 | mustClose, |
| 34 | noteCeiling, | |
| 34 | 35 | noteSignedIn, |
| 35 | 36 | readBounded, |
| 36 | 37 | REQUEST_MAX, |
| @@ -41,6 +42,14 @@ import { trackPullHead } from "../core/pulls.ts"; | ||
| 41 | 42 | import { createRepo } from "../actions/repos.ts"; |
| 42 | 43 | import { sessionOf } from "../core/sessions.ts"; |
| 43 | 44 | import { scopeAllows, verifyToken } from "../core/tokens.ts"; |
| 45 | import { | |
| 46 | grantOfUser, | |
| 47 | mayCall as proposerMayCall, | |
| 48 | MAX_BRANCHES, | |
| 49 | MAX_PUSH, | |
| 50 | namespaceOf, | |
| 51 | refusal as proposerRefusal, | |
| 52 | } from "../core/proposals.ts"; | |
| 44 | 53 | import { forgeHost } from "../core/commit_identity.ts"; |
| 45 | 54 | import { |
| 46 | 55 | ensureEdgeUser, |
| @@ -53,6 +62,7 @@ import { liveResponse, readyResponse } from "./health.ts"; | ||
| 53 | 62 | import { runGit } from "../git/env.ts"; |
| 54 | 63 | import { noteRefusedInternal } from "../kernel/internal_refused.ts"; |
| 55 | 64 | import { hookEnv, ZERO_OID, type HookRequest } from "../git/hooks.ts"; |
| 65 | import { runGitCapture } from "../git/env.ts"; | |
| 56 | 66 | import { repoDir } from "../git/repos.ts"; |
| 57 | 67 | import { |
| 58 | 68 | advertiseRefs, |
| @@ -408,12 +418,15 @@ import { | ||
| 408 | 418 | } from "./context.ts"; |
| 409 | 419 | import { |
| 410 | 420 | apiError, |
| 421 | forbidden, | |
| 411 | 422 | json, |
| 412 | 423 | noRoute, |
| 413 | 424 | notFound, |
| 414 | 425 | prefersHtml, |
| 415 | 426 | securityFloor, |
| 416 | 427 | } from "./respond.ts"; |
| 428 | import { proposeSubmit } from "../web/studio/upstream.ts"; | |
| 429 | import { proposalRoutes } from "./proposals.ts"; | |
| 417 | 430 | import { RateLimiter, type Verdict } from "../core/ratelimit.ts"; |
| 418 | 431 | import { |
| 419 | 432 | MAX_KEY_LENGTH, |
| @@ -933,6 +946,7 @@ export function buildRouter(): Router<Handler> { | ||
| 933 | 946 | router.add("POST", "/:owner/:name/pulls/:number/ship", shipSubmit); |
| 934 | 947 | router.add("POST", "/:owner/:name/pulls/:number/say", saySubmit); |
| 935 | 948 | router.add("POST", "/:owner/:name/pulls/:number/take-back", takeBackSubmit); |
| 949 | router.add("POST", "/:owner/:name/pulls/:number/propose-upstream", proposeSubmit); | |
| 936 | 950 | router.add("POST", "/:owner/:name/pulls/:number/hold", holdSubmit); |
| 937 | 951 | router.add("POST", "/:owner/:name/pulls/:number/release", releaseSubmit); |
| 938 | 952 | // What an issue waits for: link and unlink, from the issue page. |
| @@ -1198,6 +1212,7 @@ export function buildApiRouter(): Router<Handler> { | ||
| 1198 | 1212 | const router = new Router<Handler>(); |
| 1199 | 1213 | apiRoutes(router); |
| 1200 | 1214 | feedRoutes(router); |
| 1215 | proposalRoutes(router); | |
| 1201 | 1216 | return router; |
| 1202 | 1217 | } |
| 1203 | 1218 | |
| @@ -1228,6 +1243,18 @@ async function withGitAccess( | ||
| 1228 | 1243 | // Anonymous callers get a challenge wherever credentials could help; |
| 1229 | 1244 | // authenticated-but-unauthorized callers get a 404 that hides existence. |
| 1230 | 1245 | if (!repo) return ctx.auth.user ? notFound() : gitChallenge(); |
outdated
Pushes through here are capped in size, but not in how many branches a token may create. Limit branches or total bytes per grant in the hook, or a child can fill the parent's disk 8 MB at a time. |
||
| 1246 | // A child's proposal token pushes to the one repository it was minted | |
| 1247 | // for and reads nothing; which branches is the pre-receive hook's to say. | |
| 1248 | if (ctx.auth.scope === "propose") { | |
| 1249 | const grant = | |
| 1250 | ctx.auth.user === undefined ? undefined : grantOfUser(ctx.app.db, ctx.auth.user.id); | |
| 1251 | if (!write || grant === undefined || grant.repoId !== repo.id) | |
| 1252 | return notFound(); | |
| 1253 | return serve( | |
| 1254 | repoDir(ctx.app.reposRoot, repo.ownerName, repo.name), | |
| 1255 | repo.id, | |
| 1256 | ); | |
| 1257 | } | |
| 1231 | 1258 | if (write) { |
| 1232 | 1259 | if (!ctx.auth.user) return gitChallenge(); |
| 1233 | 1260 | if ( |
| @@ -1477,7 +1504,39 @@ async function handleHook(app: App, request: Request): Promise<Response> { | ||
| 1477 | 1504 | const actor = input.actorId |
| 1478 | 1505 | ? getUserById(app.db, input.actorId) |
| 1479 | 1506 | : undefined; |
| 1507 | // A child forge's proposer moves nothing but its own namespace in its | |
| 1508 | // own repository (`core/proposals.ts`). | |
| 1509 | const proposer = | |
| 1510 | actor === undefined ? undefined : grantOfUser(app.db, actor.id); | |
| 1511 | // Each push is capped in bytes; the number of branches a child may hold | |
| 1512 | // is capped here, so a token cannot fill the disk 8 MB at a time. | |
| 1513 | if (proposer !== undefined) { | |
| 1514 | const held = await runGitCapture( | |
| 1515 | [ | |
| 1516 | "for-each-ref", | |
| 1517 | "--format=%(refname)", | |
| 1518 | `refs/heads/${namespaceOf(proposer.child)}`, | |
| 1519 | ], | |
| 1520 | { cwd: repoDir(app.reposRoot, repo.ownerName, repo.name) }, | |
| 1521 | ); | |
| 1522 | const existing = held.stdout.split("\n").filter((l) => l !== "").length; | |
| 1523 | const created = input.updates.filter((u) => /^0+$/.test(u.oldOid)).length; | |
| 1524 | if (held.code !== 0 || existing + created > MAX_BRANCHES) | |
| 1525 | return new Response( | |
| 1526 | `a child may hold at most ${MAX_BRANCHES} proposal branches; close some first`, | |
| 1527 | { status: 403 }, | |
| 1528 | ); | |
| 1529 | } | |
| 1480 | 1530 | for (const update of input.updates) { |
| 1531 | if (proposer !== undefined) { | |
| 1532 | const refused = proposerRefusal( | |
| 1533 | proposer, | |
| 1534 | repo.id, | |
| 1535 | update.ref, | |
| 1536 | update.newOid, | |
| 1537 | ); | |
| 1538 | if (refused !== null) return new Response(refused, { status: 403 }); | |
| 1539 | } | |
| 1481 | 1540 | // The pull namespace belongs to the forge, never to pushers. |
| 1482 | 1541 | if (update.ref.startsWith("refs/pull/")) { |
| 1483 | 1542 | return new Response(`${update.ref}: refs/pull/* is reserved`, { |
| @@ -1928,11 +1987,20 @@ async function answerGet( | ||
| 1928 | 1987 | // The two things standing between one runaway agent and everybody |
| 1929 | 1988 | // else's latency, applied before a handler runs and after auth is |
| 1930 | 1989 | // known — a limit needs an identity, and a replay needs a credential. |
| 1990 | // A child's proposal token knocks on a few doors only, and its bodies are | |
| 1991 | // held far below the forge's ceilings. | |
| 1992 | if (auth.scope === "propose") { | |
| 1993 | if (!proposerMayCall(request.method, url.pathname)) return forbidden(); | |
| 1994 | noteCeiling(request, MAX_PUSH); | |
| 1995 | } | |
| 1931 | 1996 | const credential = tokenCredential(request, auth); |
| 1932 | 1997 | const verdict = |
| 1933 | 1998 | credential === undefined |
| 1934 | 1999 | ? undefined |
| 1935 | : limiter.take(credential, auth.scope ?? "ro"); | |
| 2000 | : limiter.take( | |
| 2001 | credential, | |
| 2002 | auth.scope === undefined || auth.scope === "propose" ? "ro" : auth.scope, | |
| 2003 | ); | |
| 1936 | 2004 | if (verdict !== undefined && !verdict.allowed) { |
| 1937 | 2005 | return withRateHeaders(tooManyRequests(verdict), verdict); |
| 1938 | 2006 | } |
src/main.ts +3
| @@ -134,6 +134,9 @@ if (parentProblem !== null) { | ||
| 134 | 134 | const app = createApp({ |
| 135 | 135 | dataDir, |
| 136 | 136 | ...(parentUrl === "" ? {} : { parentUrl }), |
| 137 | ...((process.env.FORGE_PARENT_PROPOSAL_TOKEN ?? "").trim() === "" | |
| 138 | ? {} | |
| 139 | : { parentProposalToken: process.env.FORGE_PARENT_PROPOSAL_TOKEN!.trim() }), | |
| 137 | 140 | port: Number(process.env.PORT ?? 3000), |
| 138 | 141 | ...(process.env.FORGE_HOST === undefined |
| 139 | 142 | ? {} |
src/tui/screens/pull.ts +71
| @@ -47,6 +47,12 @@ import { | ||
| 47 | 47 | type EnvStatus, envsFor } from "../../apps/runtime.ts"; |
| 48 | 48 | import { getAppByRepo } from "../../core/apps.ts"; |
| 49 | 49 | import { getIssue, type Issue } from "../../core/issues.ts"; |
| 50 | import { | |
| 51 | parentSeat, | |
| 52 | proposeToParent, | |
| 53 | upstreamOf, | |
| 54 | } from "../../actions/propose_parent.ts"; | |
| 55 | import { proposalOfIssue } from "../../core/proposals.ts"; | |
| 50 | 56 | import { pullMayRun } from "../../core/pull_trust.ts"; |
| 51 | 57 | import { getPull, variantSiblings, type Pull } from "../../core/pulls.ts"; |
| 52 | 58 | import { voteVariant } from "../../actions/variants.ts"; |
| @@ -370,6 +376,65 @@ export function pullScreen( | ||
| 370 | 376 | createdAt: string; |
| 371 | 377 | }[] => (detail?.comments ?? []).filter((c) => !reviewIds().has(c.id)); |
| 372 | 378 | |
| 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() || parentSeat(f.app) === 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 | ||
| 373 | 438 | const entries = (): ThreadEntry[] => [ |
| 374 | 439 | ...(detail === undefined |
| 375 | 440 | ? [] |
| @@ -384,6 +449,7 @@ export function pullScreen( | ||
| 384 | 449 | : { note: detail.issue.originUrl }), |
| 385 | 450 | }, |
| 386 | 451 | ]), |
| 452 | ...upstreamNotes(), | |
| 387 | 453 | ...conversation().map((comment) => ({ |
| 388 | 454 | kind: "comment" as const, |
| 389 | 455 | actor: who(comment.authorName, comment.originAuthor), |
| @@ -661,6 +727,7 @@ export function pullScreen( | ||
| 661 | 727 | ...(mayApproveHere() |
| 662 | 728 | ? [binding(["A"], "approve to run here")] |
| 663 | 729 | : []), |
| 730 | ...(mayPropose() ? [binding(["U"], "propose upstream")] : []), | |
| 664 | 731 | binding(["a"], "assign"), |
| 665 | 732 | binding(["m"], "merge", { disabled: state() !== "ready" }), |
| 666 | 733 | ...(tab === 1 && view.threadHere() !== null |
| @@ -855,6 +922,10 @@ export function pullScreen( | ||
| 855 | 922 | review(); |
| 856 | 923 | return true; |
| 857 | 924 | } |
| 925 | if (e.key === "U" && mayPropose()) { | |
| 926 | proposeUp(); | |
| 927 | return true; | |
| 928 | } | |
| 858 | 929 | if (e.key === "A" && mayApproveHere()) { |
| 859 | 930 | approveToRun(); |
| 860 | 931 | return true; |
src/web/studio/change.ts +3 −1
| @@ -80,6 +80,7 @@ import { tellLine, tellsAnswered } from "./branch_tell.ts"; | ||
| 80 | 80 | import { holdCard } from "./hold.ts"; |
| 81 | 81 | import { pullMayRun } from "../../core/pull_trust.ts"; |
| 82 | 82 | import { changeHref } from "./nouns.ts"; |
| 83 | import { proposalNote, upstreamCard } from "./upstream.ts"; | |
| 83 | 84 | import { pullWord, servingHistory, wordBadge, type WordCtx } from "./words.ts"; |
| 84 | 85 | |
| 85 | 86 | /** The pull and its repo, or the response that refuses to say why not. */ |
| @@ -527,6 +528,7 @@ async function changeConversation( | ||
| 527 | 528 | ), |
| 528 | 529 | ); |
| 529 | 530 | |
| 531 | const upstreamSection = upstreamCard(ctx, repo, pull, thread); | |
| 530 | 532 | const siblings = variantSiblings(db, [pull])[0] ?? []; |
| 531 | 533 | const glyph = originGlyph(repo); |
| 532 | 534 | const headOid = status?.headOid ?? pull.headOid; |
| @@ -561,7 +563,7 @@ async function changeConversation( | ||
| 561 | 563 | <div id="pull-check">${checkLine}</div> ${holdCard(ctx, repo, pull, { act: true })} |
| 562 | 564 | ${approveHereCard(ctx, repo, pull, headOid, `${thread}/approve-here`)} |
| 563 | 565 | ${when(wall, (w) => wallCard(w))} ${decisionSection} |
| 564 | ${takeBackSection} | |
| 566 | ${takeBackSection} ${upstreamSection ?? null} ${proposalNote(ctx, pull) ?? null} | |
| 565 | 567 | ${when(record, (r) => lookCard(ctx, repo, r, pull, pull.headOid))} |
| 566 | 568 | <div class="split"> |
| 567 | 569 | <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 | parentSeat, | |
| 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 = parentSeat(ctx.app); | |
| 38 | if (seat === undefined || repo.origin !== null || pull.crossRepo) return undefined; | |
| 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", () => { | ||
| 177 | 177 | "outsiders", |
| 178 | 178 | "decisions_by", |
| 179 | 179 | "probe", |
| 180 | "propose_upstream", | |
| 180 | 181 | "following", |
| 181 | 182 | "spawn", |
| 182 | 183 | "forges", |
test/proposals.test.ts added +352
| @@ -0,0 +1,352 @@ | ||
| 1 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 2 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 3 | import { tmpdir } from "node:os"; | |
| 4 | import { join } from "node:path"; | |
| 5 | import { createApp, type App } from "../src/app.ts"; | |
| 6 | import { getPull } from "../src/core/pulls.ts"; | |
| 7 | import { getRepo } from "../src/core/repos.ts"; | |
| 8 | import { pullMayRun } from "../src/core/pull_trust.ts"; | |
| 9 | import { branchProblem, mayCall, refusal } from "../src/core/proposals.ts"; | |
| 10 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 11 | import { gitClientEnv } from "./helpers/git-client.ts"; | |
| 12 | ||
| 13 | /** | |
| 14 | * Proposing upstream: a parent, a child, a real git client. The token the | |
| 15 | * parent mints for a child makes branches under its namespace and opens | |
| 16 | * pulls from them, and is refused everywhere else. | |
| 17 | */ | |
| 18 | ||
| 19 | const PASSWORD = "alice-login-secret"; | |
| 20 | const basic = (u: string, s: string) => | |
| 21 | `Basic ${Buffer.from(`${u}:${s}`).toString("base64")}`; | |
| 22 | ||
| 23 | const env = gitClientEnv(); | |
| 24 | async function git(args: string[], cwd: string) { | |
| 25 | const proc = Bun.spawn(["git", ...args], { | |
| 26 | cwd, | |
| 27 | env, | |
| 28 | stdout: "pipe", | |
| 29 | stderr: "pipe", | |
| 30 | }); | |
| 31 | const [out, err, code] = await Promise.all([ | |
| 32 | new Response(proc.stdout).text(), | |
| 33 | new Response(proc.stderr).text(), | |
| 34 | proc.exited, | |
| 35 | ]); | |
| 36 | return { code, out: out.trim(), err: err.trim() }; | |
| 37 | } | |
| 38 | ||
| 39 | describe("unit: what a proposer may do", () => { | |
| 40 | const grant = { tokenId: "t", userId: "u", repoId: "r", child: "kid" }; | |
| 41 | test("only branches under its own namespace, never a delete", () => { | |
| 42 | const ok = "a".repeat(40); | |
| 43 | expect(refusal(grant, "r", "refs/heads/child/kid/x", ok)).toBeNull(); | |
| 44 | expect(refusal(grant, "r", "refs/heads/main", ok)).not.toBeNull(); | |
| 45 | expect(refusal(grant, "r", "refs/heads/child/other/x", ok)).not.toBeNull(); | |
| 46 | expect(refusal(grant, "r", "refs/heads/child/kid/", ok)).not.toBeNull(); | |
| 47 | expect(refusal(grant, "r", "refs/heads/child/kid/../main", ok)).not.toBeNull(); | |
| 48 | expect(refusal(grant, "r", "refs/tags/child/kid/x", ok)).not.toBeNull(); | |
| 49 | expect(refusal(grant, "r", "refs/heads/child/kid/x", "0".repeat(40))).not.toBeNull(); | |
| 50 | expect(refusal(grant, "elsewhere", "refs/heads/child/kid/x", ok)).not.toBeNull(); | |
| 51 | }); | |
| 52 | test("hostile branch names are refused at the boundary", () => { | |
| 53 | for (const b of [ | |
| 54 | "main", | |
| 55 | "child/kid/<script>alert(1)</script>", | |
| 56 | "child/kid/a b", | |
| 57 | "child/kid/a..b", | |
| 58 | "child/kid/x\n", | |
| 59 | "child/kid/`x`", | |
| 60 | "child/kid/x.lock", | |
| 61 | "child/kid//x", | |
| 62 | "refs/heads/child/kid/x", | |
| 63 | 42, | |
| 64 | ]) | |
| 65 | expect(branchProblem(grant, b)).not.toBeNull(); | |
| 66 | expect(branchProblem(grant, "child/kid/pull-3")).toBeNull(); | |
| 67 | }); | |
| 68 | test("a proposal token knocks on few doors", () => { | |
| 69 | expect(mayCall("POST", "/api/v1/proposals")).toBe(true); | |
| 70 | expect(mayCall("GET", "/alice/shared.git/info/refs")).toBe(true); | |
| 71 | expect(mayCall("POST", "/alice/shared.git/git-receive-pack")).toBe(true); | |
| 72 | expect(mayCall("POST", "/alice/shared.git/git-upload-pack")).toBe(false); | |
| 73 | expect(mayCall("GET", "/api/v1/repos/alice/shared")).toBe(false); | |
| 74 | expect(mayCall("POST", "/api/v1/repos/alice/shared/pulls")).toBe(false); | |
| 75 | expect(mayCall("GET", "/")).toBe(false); | |
| 76 | }); | |
| 77 | }); | |
| 78 | ||
| 79 | describe("parent and child", () => { | |
| 80 | let dirs: string[] = []; | |
| 81 | let parent: App; | |
| 82 | let parentServers: Servers; | |
| 83 | let child: App; | |
| 84 | let childServers: Servers; | |
| 85 | let work: string; | |
| 86 | let token = ""; | |
| 87 | let clone = ""; | |
| 88 | ||
| 89 | const mk = async (p: string) => { | |
| 90 | const d = await mkdtemp(join(tmpdir(), p)); | |
| 91 | dirs.push(d); | |
| 92 | return d; | |
| 93 | }; | |
| 94 | const asAlice = (base: string, path: string, init?: RequestInit) => { | |
| 95 | const headers = new Headers(init?.headers); | |
| 96 | if (init?.body !== undefined) headers.set("content-type", "application/json"); | |
| 97 | headers.set("authorization", basic("alice", PASSWORD)); | |
| 98 | return fetch(`${base}${path}`, { ...init, headers }); | |
| 99 | }; | |
| 100 | const asChild = (path: string, init?: RequestInit, secret = token) => { | |
| 101 | const headers = new Headers(init?.headers); | |
| 102 | if (init?.body !== undefined) headers.set("content-type", "application/json"); | |
| 103 | headers.set("authorization", `Bearer ${secret}`); | |
| 104 | return fetch(`${parentServers.url}${path}`, { ...init, headers }); | |
| 105 | }; | |
| 106 | const remote = (secret = token) => | |
| 107 | `http://x:${secret}@localhost:${parentServers.port}/alice/shared.git`; | |
| 108 | const push = (ref: string, secret = token) => | |
| 109 | git(["push", remote(secret), `HEAD:refs/heads/${ref}`], clone); | |
| 110 | const propose = (over: Record<string, unknown> = {}, secret = token) => | |
| 111 | asChild( | |
| 112 | "/api/v1/proposals", | |
| 113 | { | |
| 114 | method: "POST", | |
| 115 | body: JSON.stringify({ | |
| 116 | title: "Faster gears", | |
| 117 | body: "Spins faster.", | |
| 118 | branch: "child/kid/one", | |
| 119 | origin: "https://kid.example.test", | |
| 120 | source: "bob/gears#7", | |
| 121 | ...over, | |
| 122 | }), | |
| 123 | }, | |
| 124 | secret, | |
| 125 | ); | |
| 126 | const mint = async (name: string) => { | |
| 127 | const res = await asAlice(parentServers.url, "/api/v1/repos/alice/shared/proposal-tokens", { | |
| 128 | method: "POST", | |
| 129 | body: JSON.stringify({ child: name }), | |
| 130 | }); | |
| 131 | return ((await res.json()) as { token: string }).token; | |
| 132 | }; | |
| 133 | ||
| 134 | beforeAll(async () => { | |
| 135 | work = await mk("forge-prop-work-"); | |
| 136 | parent = createApp({ dataDir: await mk("forge-prop-p-"), port: 0 }); | |
| 137 | parentServers = await serve(parent); | |
| 138 | await fetch(`${parentServers.url}/api/v1/users`, { | |
| 139 | method: "POST", | |
| 140 | headers: { "content-type": "application/json" }, | |
| 141 | body: JSON.stringify({ username: "alice", email: "[email protected]", password: PASSWORD }), | |
| 142 | }); | |
| 143 | await asAlice(parentServers.url, "/api/v1/repos", { | |
| 144 | method: "POST", | |
| 145 | body: JSON.stringify({ name: "shared", visibility: "public" }), | |
| 146 | }); | |
| 147 | await asAlice(parentServers.url, "/api/v1/repos/alice/shared/contents", { | |
| 148 | method: "POST", | |
| 149 | body: JSON.stringify({ | |
| 150 | branch: "main", | |
| 151 | message: "first", | |
| 152 | files: [{ path: "a.txt", content: "one\n" }], | |
| 153 | }), | |
| 154 | }); | |
| 155 | const minted = await asAlice( | |
| 156 | parentServers.url, | |
| 157 | "/api/v1/repos/alice/shared/proposal-tokens", | |
| 158 | { method: "POST", body: JSON.stringify({ child: "kid" }) }, | |
| 159 | ); | |
| 160 | expect(minted.status).toBe(201); | |
| 161 | token = ((await minted.json()) as { token: string }).token; | |
| 162 | ||
| 163 | clone = join(work, "clone"); | |
| 164 | const c = await git( | |
| 165 | ["clone", "-q", `http://alice:${PASSWORD}@localhost:${parentServers.port}/alice/shared.git`, clone], | |
| 166 | work, | |
| 167 | ); | |
| 168 | expect(c.code).toBe(0); | |
| 169 | await Bun.write(join(clone, "b.txt"), "two\n"); | |
| 170 | await git(["add", "."], clone); | |
| 171 | expect((await git(["commit", "-qm", "faster"], clone)).code).toBe(0); | |
| 172 | expect((await push("child/kid/one")).code).toBe(0); | |
| 173 | }); | |
| 174 | ||
| 175 | afterAll(async () => { | |
| 176 | parentServers.stop(); | |
| 177 | childServers?.stop(); | |
| 178 | parent.close(); | |
| 179 | child?.close(); | |
| 180 | for (const d of dirs) await rm(d, { recursive: true, force: true }); | |
| 181 | }); | |
| 182 | ||
| 183 | test("a non-admin cannot mint, a bad child name is refused", async () => { | |
| 184 | const bad = await asAlice(parentServers.url, "/api/v1/repos/alice/shared/proposal-tokens", { | |
| 185 | method: "POST", | |
| 186 | body: JSON.stringify({ child: "../Evil" }), | |
| 187 | }); | |
| 188 | expect(bad.status).toBe(422); | |
| 189 | const anon = await fetch(`${parentServers.url}/api/v1/repos/alice/shared/proposal-tokens`, { | |
| 190 | method: "POST", | |
| 191 | headers: { "content-type": "application/json" }, | |
| 192 | body: JSON.stringify({ child: "x" }), | |
| 193 | }); | |
| 194 | expect([401, 403]).toContain(anon.status); | |
| 195 | }); | |
| 196 | ||
| 197 | test("the token is refused on main and in other namespaces", async () => { | |
| 198 | expect((await push("main")).code).not.toBe(0); | |
| 199 | expect((await push("child/other/x")).code).not.toBe(0); | |
| 200 | expect((await push("child/kid/x y")).code).not.toBe(0); | |
| 201 | expect((await push("child/kid/../../main")).code).not.toBe(0); | |
| 202 | }); | |
| 203 | ||
| 204 | test("the token reads and writes nothing else", async () => { | |
| 205 | expect((await asChild("/api/v1/repos/alice/shared")).status).toBeGreaterThanOrEqual(400); | |
| 206 | const pull = await asChild("/api/v1/repos/alice/shared/pulls", { | |
| 207 | method: "POST", | |
| 208 | body: JSON.stringify({ title: "x", head: "child/kid/one", base: "main" }), | |
| 209 | }); | |
| 210 | expect(pull.status).toBeGreaterThanOrEqual(400); | |
| 211 | }); | |
| 212 | ||
| 213 | test("a branch under its namespace is accepted, and a pull opens from it", async () => { | |
| 214 | const grant = await asChild("/api/v1/proposals/grant"); | |
| 215 | expect(await grant.json()).toMatchObject({ child: "kid", namespace: "child/kid/" }); | |
| 216 | const res = await propose(); | |
| 217 | expect(res.status).toBe(201); | |
| 218 | const { number } = (await res.json()) as { number: number }; | |
| 219 | const state = await asChild(`/api/v1/proposals/${number}`); | |
| 220 | expect(await state.json()).toEqual({ number, state: "open" }); | |
| 221 | ||
| 222 | // The parent's page names the child, its origin and the source change. | |
| 223 | const page = await asAlice(parentServers.url, `/alice/shared/pulls/${number}`); | |
| 224 | const text = await page.text(); | |
| 225 | expect(text).toContain("kid"); | |
| 226 | expect(text).toContain("https://kid.example.test"); | |
| 227 | expect(text).toContain("bob/gears#7"); | |
| 228 | ||
| 229 | // The child's code runs nothing here until a writer approves that head. | |
| 230 | const repo = getRepo(parent.db, "alice", "shared")!; | |
| 231 | const pull = getPull(parent.db, repo.id, number)!; | |
| 232 | expect(pullMayRun(parent.db, repo, pull, pull.headOid)).toBe(false); | |
| 233 | const approved = await asAlice( | |
| 234 | parentServers.url, | |
| 235 | `/api/v1/repos/alice/shared/pulls/${number}/review-states`, | |
| 236 | { method: "POST", body: JSON.stringify({ state: "approved" }) }, | |
| 237 | ); | |
| 238 | expect(approved.status).toBeLessThan(300); | |
| 239 | expect(pullMayRun(parent.db, repo, pull, pull.headOid)).toBe(true); | |
| 240 | ||
| 241 | // Merging on the parent shows as merged to the child. | |
| 242 | const merged = await asAlice( | |
| 243 | parentServers.url, | |
| 244 | `/api/v1/repos/alice/shared/pulls/${number}/merge`, | |
| 245 | { method: "POST", body: "{}" }, | |
| 246 | ); | |
| 247 | expect(merged.status).toBeLessThan(300); | |
| 248 | expect(await (await asChild(`/api/v1/proposals/${number}`)).json()).toEqual({ | |
| 249 | number, | |
| 250 | state: "merged", | |
| 251 | }); | |
| 252 | }); | |
| 253 | ||
| 254 | test("hostile words and oversize bodies are refused at the parent", async () => { | |
| 255 | for (const over of [ | |
| 256 | { branch: "main" }, | |
| 257 | { branch: "child/kid/<img src=x onerror=alert(1)>" }, | |
| 258 | { origin: "javascript:alert(1)" }, | |
| 259 | { origin: "https://u:[email protected]" }, | |
| 260 | { origin: "https://x.test/`><script>" }, | |
| 261 | { source: "bob/gears#7`<script>" }, | |
| 262 | { title: "line\nbreak" }, | |
| 263 | { title: "x".repeat(201) }, | |
| 264 | { body: "x".repeat(8 * 1024 + 1) }, | |
| 265 | { body: "Fixes #1" }, | |
| 266 | ]) { | |
| 267 | const res = await propose(over); | |
| 268 | expect(res.status).toBeGreaterThanOrEqual(400); | |
| 269 | expect(res.status).toBeLessThan(500); | |
| 270 | } | |
| 271 | const huge = await propose({ body: "x".repeat(200 * 1024) }); | |
| 272 | expect(huge.status).toBe(413); | |
| 273 | }); | |
| 274 | ||
| 275 | test("the child proposes, and shows the state the parent reports", async () => { | |
| 276 | child = createApp({ | |
| 277 | dataDir: await mk("forge-prop-c-"), | |
| 278 | port: 0, | |
| 279 | parentUrl: parentServers.url, | |
| 280 | url: "https://kid.example.test", | |
| 281 | parentLoopback: true, | |
| 282 | parentProposalToken: token, | |
| 283 | }); | |
| 284 | childServers = await serve(child); | |
| 285 | await fetch(`${childServers.url}/api/v1/users`, { | |
| 286 | method: "POST", | |
| 287 | headers: { "content-type": "application/json" }, | |
| 288 | body: JSON.stringify({ username: "bob", email: "[email protected]", password: PASSWORD }), | |
| 289 | }); | |
| 290 | const as = (path: string, init?: RequestInit) => { | |
| 291 | const headers = new Headers(init?.headers); | |
| 292 | if (init?.body !== undefined) headers.set("content-type", "application/json"); | |
| 293 | headers.set("authorization", basic("bob", PASSWORD)); | |
| 294 | return fetch(`${childServers.url}${path}`, { ...init, headers }); | |
| 295 | }; | |
| 296 | await as("/api/v1/repos", { | |
| 297 | method: "POST", | |
| 298 | body: JSON.stringify({ name: "gears", visibility: "public" }), | |
| 299 | }); | |
| 300 | const files = (branch: string, name: string) => | |
| 301 | as("/api/v1/repos/bob/gears/contents", { | |
| 302 | method: "POST", | |
| 303 | body: JSON.stringify({ | |
| 304 | branch, | |
| 305 | message: "m", | |
| 306 | files: [{ path: name, content: "x\n" }], | |
| 307 | }), | |
| 308 | }); | |
| 309 | await files("main", "a.txt"); | |
| 310 | await files("feature", "c.txt"); | |
| 311 | const opened = await as("/api/v1/repos/bob/gears/pulls", { | |
| 312 | method: "POST", | |
| 313 | body: JSON.stringify({ title: "Gears", head: "feature", base: "main" }), | |
| 314 | }); | |
| 315 | expect(opened.status).toBe(201); | |
| 316 | const { number } = (await opened.json()) as { number: number }; | |
| 317 | ||
| 318 | const sent = await as(`/api/v1/repos/bob/gears/pulls/${number}/propose-upstream`, { | |
| 319 | method: "POST", | |
| 320 | body: "{}", | |
| 321 | }); | |
| 322 | expect(sent.status).toBe(201); | |
| 323 | const view = (await sent.json()) as { parentNumber: number; state: string }; | |
| 324 | expect(view.state).toBe("open"); | |
| 325 | ||
| 326 | const page = await as(`/bob/gears/pulls/${number}`); | |
| 327 | expect(await page.text()).toContain("waiting for review"); | |
| 328 | const again = await as(`/api/v1/repos/bob/gears/pulls/${number}/upstream`); | |
| 329 | expect(((await again.json()) as { state: string }).state).toBe("open"); | |
| 330 | }); | |
| 331 | ||
| 332 | test("a child may hold only so many branches, proposal or not", async () => { | |
| 333 | const busy = await mint("cap"); | |
| 334 | const many = Array.from({ length: 31 }, (_, i) => `HEAD:refs/heads/child/cap/many${i}`); | |
| 335 | expect((await git(["push", remote(busy), ...many], clone)).code).not.toBe(0); | |
| 336 | expect((await git(["push", remote(busy), ...many.slice(0, 5)], clone)).code).toBe(0); | |
| 337 | }); | |
| 338 | ||
| 339 | test("the parent limits how many a child sends in an hour", async () => { | |
| 340 | const busy = await mint("busy"); | |
| 341 | const seen: number[] = []; | |
| 342 | for (let i = 0; i < 8; i++) { | |
| 343 | await Bun.write(join(clone, `n${i}-${Date.now()}.txt`), `${i}\n`); | |
| 344 | await git(["add", "."], clone); | |
| 345 | await git(["commit", "-qm", `n${i}`], clone); | |
| 346 | expect((await push(`child/busy/n${i}`, busy)).code).toBe(0); | |
| 347 | seen.push((await propose({ branch: `child/busy/n${i}` }, busy)).status); | |
| 348 | } | |
| 349 | expect(seen).toContain(429); | |
| 350 | expect(seen.indexOf(429)).toBeGreaterThan(0); | |
| 351 | }); | |
| 352 | }); |
new above
offline
High: this opens a same-repo pull, and
pullMayRuntrusts every same-repo pull on the assumption that only a writer pushed the branch. The child's code then runs in checks and previews with no approval. Mark proposals untrusted incore/pull_trust.tsso they wait for a writer's approval of the head.