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

Following an upstream sends a credential only to its exact https origin, fetches the vetted address, and runs one check at a time #3565

Closed opened this
Closed without merging

scout/forge:scout/3557-following-an-upstream-sends-a-credential → main 12 commits fork 7 threads · 7 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
20 files changed +2167 −12
docs/ORIGINS.md +53
@@ -534,6 +534,59 @@ The clone runs as a job in the mirror's registry (`origins/jobs.ts`, kind
534534 app and the crew's first run — and then lands on the repository, which is
535535 the app's page, with what happened as the flash.
536536
537 ## Follow upstream — new upstream commits land by themselves
538
539 A migration forgets the URL for git, but keeps it as the repository's
540 upstream (`repo_upstream`, `core/upstream_follow.ts`): the source and its
541 default branch, its parent offered as the second choice when the host said
542 it is a fork. Following is on when the crew was put on it autonomous, and
543 off — filled in — otherwise. The settings page's **Follow upstream** card
544 turns it on or off and points it anywhere git may be handed (`migrateUrl`,
545 the same private-host rule as migrate); a private upstream uses the
546 person's connected origin on that host (`origins/credentials.ts`).
547
548 Every 30 minutes beside the autonomy tick, or on **Check upstream now**
549 (`actions/upstream_follow.ts`): `ls-remote`, and a fetch only when the tip
550 moved, into `refs/upstream/<branch>` — not a branch, so nothing of ours
551 moves. Then git decides:
552
553 - a fast-forward or a clean `git merge`: a pull
554 `Upstream: N commits from <upstream> (<base>..<tip>)` from
555 `upstream/<tip7>` (the tip, or the clean merge commit on top of ours),
556 opened as the person who turned following on. It lands through the
557 landing gate like any pull — as a **merge**, never a squash, whenever its
558 head carries upstream commits the base lacks (`carriesUpstream`), so
559 upstream's history stays an ancestor and the next check counts only what
560 is new.
561 - a conflict (an upstream deletion of a file we changed is one): an issue
562 with the same title and the files, assigned to a builder as a `converge`
563 run whose brief says merge the staged tip, keep upstream's fixes and our
564 work, explain each resolution. Its pull is reviewed and lands like any
565 crew pull.
566
567 One check runs at a time per repository, whichever door asked — the tick,
568 the page, the terminal or the API; a second is refused `busy` (409 in the
569 API) rather than racing the first to open a second proposal. One proposal
570 stands at a time; one closed unlanded is not opened again until upstream
571 moves, unless a person checks now. A finished check emits
572 `repo.upstream_checked`, so an open About card or page updates. Never a push to the
573 default branch, never a force-push. The About card says
574 "Following <upstream> · last checked HH:MM · N behind"; the tick line's
575 `upstream=` says how far behind and how many were proposed. In the
576 terminal, About (`I`) shows the same as a `following` row — on for every
577 reader, off for admins only, as on the page and in the API — and a writer's
578 `u` checks now. An admin's `f` turns it on or off (asking where, the first
579 time) and `F` points it elsewhere: the same `setFollowUpstream` and the same
580 refusals as the page and the API.
581 Why a check failed is the remote's stderr, redacted, and only writers read
582 it. A `git://` upstream is refused at save: its transport resolves the name
583 itself, past the vetted-address pin. The settings card's "Check upstream now"
584 is the admin's; any writer checks from the API (`POST …/upstream/check`) or the
585 terminal's `u`. What can be saved can be checked: save and check apply the
586 same private-host rule. API:
587 `GET|PUT /api/v1/repos/:owner/:name/upstream`,
588 `POST /api/v1/repos/:owner/:name/upstream/check`.
589
537590 ## API
538591
539592 ```
src/actions/migrate.ts +24
@@ -67,6 +67,10 @@ import {
6767 } from "./repos.ts";
6868 import { tell, toldWords } from "./tell.ts";
6969 import { remoteGitEnv } from "../git/remote-env.ts";
70 import { setFollowUpstream } from "./upstream_follow.ts";
71 import { createLog } from "../kernel/log.ts";
72
73 const log = createLog("migrate");
7074
7175 /** The whole clone — the HEAD probe and the fetch — gets this long. */
7276 export const MIGRATE_TIMEOUT_MS = 120_000;
@@ -127,6 +131,8 @@ interface Resolved {
127131 readonly provider?: Provider;
128132 /** The person, as the source's commits may name them. */
129133 readonly who: Who;
134 /** The source's own parent on its host, when it is a fork: following's second choice. */
135 readonly parentUrl?: string;
130136 }
131137
132138 /** Why the work branch is the one it is: said in the job and the brief. */
@@ -424,6 +430,9 @@ export async function resolveSource(
424430 authEnv: () => provider.value.gitAuthEnv(url),
425431 provider: provider.value,
426432 who: { logins: [origin.login, user.username], emails: [user.email] },
433 ...(remote.value.parent === null
434 ? {}
435 : { parentUrl: `${origin.webUrl.replace(/\/+$/, "")}/${remote.value.parent}` }),
427436 });
428437 }
429438
@@ -533,6 +542,21 @@ async function runMigration(
533542 });
534543 }
535544
545 // The source becomes the upstream this repository follows (#3442): on
546 // when the crew runs it on its own, off — but filled in — otherwise.
547 const followed = await setFollowUpstream(app, user, current, {
548 url: source.url,
549 branch: cloned.value.head ?? work?.name ?? current.defaultBranch,
550 enabled: crew?.autonomous === true,
551 originId: source.originId,
552 ...(source.parentUrl === undefined ? {} : { parentUrl: source.parentUrl }),
553 });
554 if (!followed.ok)
555 log.warn("migrated repository does not follow its source", {
556 repo: `${current.ownerName}/${current.name}`,
557 why: followed.error,
558 });
559
536560 const where = `${current.ownerName}/${current.name}`;
537561 let detail = `migrated as ${where} — ${plural(branches.length, "branch", "branches")}, ${plural(refs.size - branches.length, "tag")}${conversations}`;
538562 if (work !== undefined)
src/actions/upstream_follow.ts added +658
@@ -0,0 +1,658 @@
1 /**
2 * A repository follows its upstream (#3442): an outside git URL and branch
3 * whose new commits land here by themselves, never by a push to the
4 * default branch.
5 *
6 * A check is cheap: one `ls-remote`, and a fetch only when the tip moved,
7 * into `refs/upstream/<branch>` — a ref that is not a branch, so nothing
8 * of ours is ever moved by it. Then git decides, deterministically:
9 *
10 * - the default branch fast-forwards to the upstream tip, or `git merge`
11 * is clean: a pull "Upstream: N commits from <upstream> (<range>)" from
12 * the branch `upstream/<tip>` (the tip itself, or the clean merge commit
13 * on top of the default branch), opened as the person who turned
14 * following on. It lands through the landing gate like any pull, as a
15 * merge, so upstream's history stays an ancestor of ours (`carriesUpstream`).
16 * - the merge conflicts — an upstream deletion of a file we changed is one:
17 * an issue with the same title, the files named, handed to a builder as a
18 * converge run (`crew/brief.ts`): merge the staged tip, keep upstream's
19 * fixes and our work, explain each resolution. Its pull is reviewed and
20 * lands like any crew pull.
21 *
22 * Never a force-push, never a rewrite of our history: one proposal stands
23 * at a time, and the next check after it closes proposes what is left.
24 */
25
26 import type { App } from "../app.ts";
27 import { listCrewRoles } from "../core/agents.ts";
28 import { commitIdentity } from "../core/commit_identity.ts";
29 import { getIssueById, setAssignee } from "../core/issues.ts";
30 import { getOriginFor, listOrigins } from "../core/origins.ts";
31 import { canAdmin, canWrite, getRepoById, type Repo } from "../core/repos.ts";
32 import { listRuns } from "../core/runs.ts";
33 import { storageStale } from "../core/storage.ts";
34 import {
35 getFollow,
36 listFollowing,
37 noteCheck,
38 putFollow,
39 type UpstreamFollow,
40 } from "../core/upstream_follow.ts";
41 import { getUserById, type User } from "../core/users.ts";
42 import { queueAgentRun } from "../crew/dispatch.ts";
43 import { pickBuilder } from "../crew/route.ts";
44 import { createBranch, isBranchName } from "../git/branches.ts";
45 import { runGit, runGitCapture } from "../git/env.ts";
46 import { isSafeOid } from "../git/guard.ts";
47 import { aheadCount, mergeBase, mergeable, resolveOid } from "../git/merge.ts";
48 import { repoDir } from "../git/repos.ts";
49 import { createLog } from "../kernel/log.ts";
50 import { type Resolve, vetHost } from "../kernel/outbound.ts";
51 import { err, ok, type Result } from "../kernel/result.ts";
52 import { providerForOrigin } from "../origins/credential.ts";
53 import { redact, secretsIn } from "../origins/credentials.ts";
54 import { REMOTE_PROTOCOLS } from "../git/remote-env.ts";
55 import { vettedEnv } from "../origins/git-mirror.ts";
56 import { isTrustedHost } from "../origins/trusted-hosts.ts";
57 import { requireRepoAdmin, requireWriter, type AccessError } from "./access.ts";
58 import { openIssue } from "./issues.ts";
59 import { isPrivateHost, migrateUrl } from "./migrate.ts";
60 import { openPull } from "./pulls.ts";
61
62 const log = createLog("upstream-follow");
63
64 /** How often a following repository is checked on its own. */
65 export const FOLLOW_EVERY_MS = 30 * 60_000;
66 /** One check's whole budget: ls-remote and fetch together. */
67 const CHECK_TIMEOUT_MS = 120_000;
68 /** Where the upstream tip is staged: not a branch, so a check moves nothing of ours. */
outdated

High: git here means a transport the pin cannot cover. http.curloptResolve is curl-only, so git:// does its own DNS lookup after the vet, which leaves a DNS-rebinding SSRF that the 30-minute tick repeats. Use REMOTE_PROTOCOLS (https:http), and refuse git: in upstreamUrl.

69 export const stagedRef = (branch: string): string => `refs/upstream/${branch}`;
70 /** The branch a clean proposal is opened from. */
71 const proposalBranch = (tip: string): string => `upstream/${tip.slice(0, 7)}`;
72 /** Every proposal's title begins so; the tick line and the page count them by it. */
73 export const UPSTREAM_TITLE = "Upstream: ";
74
75 /** `github.com/Trevato/SO-ARM100` for `https://github.com/Trevato/SO-ARM100.git`. */
76 export function upstreamLabel(url: string): string {
77 return url
78 .replace(/^[a-z]+:\/\//i, "")
79 .replace(/\/+$/, "")
80 .replace(/\.git$/, "");
81 }
82
83 export type FollowError =
84 | AccessError
85 | "invalid_url"
86 | "private_host"
87 | "invalid_branch"
88 | "archived"
89 /** A mirror's history is its origin's; it follows nothing else. */
90 | "mirrored";
91
92 /** What each refusal says, at every door. */
93 export const FOLLOW_REFUSALS: Record<FollowError | CheckError, string> = {
94 unauthorized: "Sign in to change where this repository follows.",
95 forbidden: "Only this repository's admins change where it follows.",
96 not_found: "That repository is not here.",
97 invalid_url: "That is not a git address the forge will fetch: use https:// or http://, with no password in it.",
98 private_host: "That address is inside the network, not a public repository.",
99 invalid_branch: "That is not a branch name.",
100 archived: "This repository is archived; wake it first.",
101 mirrored: "A mirror follows its origin; it cannot follow another upstream.",
102 off: "Following an upstream is off for this repository.",
103 unreadable: "The upstream could not be read.",
104 no_branch: "The upstream has no such branch.",
105 diverged: "The staged upstream tip could not be fetched.",
106 git: "Git could not prepare the proposal.",
107 nobody: "The person who turned following on can no longer write here; turn it on again.",
108 busy: "Already checking this upstream; its answer is on the way.",
109 };
110
111 /**
112 * The same rule migrate keeps (`resolveSource`): an admin, a forge run for
113 * one person, or a host the admin trusts may be inside the network. Save and
114 * check both ask it, so what can be saved can be checked.
115 */
116 function mayBePrivate(app: App, actor: User, host: string): boolean {
117 return actor.isAdmin || app.config.migrateFromPrivateHosts === true || isTrustedHost(host);
118 }
119
120 /** A pasted address the forge may fetch, refused inside the network unless allowed. */
121 export async function upstreamUrl(
122 app: App,
123 actor: User,
124 raw: string,
125 resolve?: Resolve,
126 ): Promise<Result<string, "invalid_url" | "private_host">> {
127 const url = migrateUrl(raw);
128 // git:// is refused: its transport resolves the name itself, past the pin.
129 if (url === undefined || new URL(url).protocol === "git:") return err("invalid_url");
130 const host = new URL(url).hostname;
131 if (mayBePrivate(app, actor, host)) return ok(url);
132 if (isPrivateHost(host)) return err("private_host");
133 const vetted = await vetHost(host, resolve ? { resolve } : {});
134 if (!vetted.ok && vetted.error === "refused") return err("private_host");
135 return ok(url);
136 }
137
138 /**
139 * Whether an origin's token may travel to this upstream: only to the exact
140 * https origin (scheme, host and port) the person connected. An `http://`
141 * upstream on the same host is fetched anonymously.
142 */
143 export function mayCarryCredential(upstreamUrl: string, webUrl: string): boolean {
144 try {
145 const up = new URL(upstreamUrl);
146 return up.protocol === "https:" && up.origin === new URL(webUrl).origin;
147 } catch {
148 return false;
149 }
150 }
151
152 /** The actor's connected origin at the upstream's https origin: its credential opens a private one. */
153 function originOn(app: App, user: User, url: string): string {
154 return listOrigins(app.db, user.id).find((o) => mayCarryCredential(url, o.webUrl))?.id ?? "";
155 }
156
157 /** The origin to remember: one whose token may go to this url, else none. */
158 function savedOrigin(app: App, user: User, url: string, given: string | undefined): string {
159 if (given === undefined) return originOn(app, user, url);
160 const origin = given === "" ? undefined : getOriginFor(app.db, user.id, given);
161 return origin !== undefined && mayCarryCredential(url, origin.webUrl) ? given : "";
162 }
163
164 /**
165 * Turn following on or off, or point it elsewhere: the repository's admins
166 * only. Whoever saves it on is who the forge acts as.
167 */
168 export async function setFollowUpstream(
169 app: App,
170 actor: User | undefined,
171 repo: Repo,
172 input: {
173 readonly url: string;
174 readonly branch: string;
175 readonly enabled: boolean;
176 readonly parentUrl?: string;
177 /** The origin the source came through, when the caller knows it (migrate). */
178 readonly originId?: string;
179 },
180 resolve?: Resolve,
181 ): Promise<Result<UpstreamFollow, FollowError>> {
182 const admin = requireRepoAdmin(app, actor, repo);
183 if (!admin.ok) return admin;
184 if (repo.archivedAt !== null && input.enabled) return err("archived");
185 if (repo.origin !== null && input.enabled) return err("mirrored");
186 const branch = input.branch.trim();
187 if (!isBranchName(branch)) return err("invalid_branch");
188 const url = await upstreamUrl(app, admin.value, input.url, resolve);
189 if (!url.ok) return url;
190 const parent =
191 input.parentUrl === undefined || input.parentUrl === ""
192 ? undefined
193 : migrateUrl(input.parentUrl);
194 const follow = putFollow(app.db, {
195 repoId: repo.id,
196 url: url.value,
197 branch,
198 enabled: input.enabled,
199 byId: admin.value.id,
200 originId: savedOrigin(app, admin.value, url.value, input.originId),
201 ...(parent === undefined ? {} : { parentUrl: parent }),
202 });
203 app.bus.append({
204 kind: "repo.upstream_follow",
205 repoId: repo.id,
206 actorId: admin.value.id,
207 payload: { url: follow.url, branch: follow.branch, enabled: follow.enabled },

High: repo.upstream_follow isn't in eventAudience's admins list, so this payload (the URL, even when enabled is false) goes to every reader through the stream, the events API and the feed. Classify it as admins in core/event_audience.ts and add a guest-vs-admin audienceFilter test.

208 });
209 return ok(follow);
210 }
211
212 export type CheckError =
213 | "off"
214 | "unreadable"
215 | "no_branch"
216 | "diverged"
217 | "git"
218 | "nobody"
219 /** Another check of this repository is in flight: one at a time, at every door. */
220 | "busy";
221
222 /** What one check found. */
223 export type Checked =
224 | { readonly kind: "up_to_date"; readonly tip: string }
225 /** A proposal is already open; it is the one to land first. */
226 | { readonly kind: "pending"; readonly behind: number; readonly id: string }
227 /** The last proposal of this same tip was closed unlanded: asked again only by a person. */
228 | { readonly kind: "declined"; readonly behind: number; readonly id: string }
229 | { readonly kind: "pull"; readonly behind: number; readonly number: number }
230 | {
231 readonly kind: "conflict";
232 readonly behind: number;
233 readonly number: number;
234 readonly files: readonly string[];
235 readonly builder: string | undefined;
236 };
237
238 /** "Check upstream now": a writer may ask; the check acts as who turned it on. */
239 export async function checkUpstreamNow(
240 app: App,
241 actor: User | undefined,
242 repo: Repo,
243 ): Promise<Result<Checked, AccessError | CheckError>> {
244 const writer = requireWriter(app, actor, repo);
245 if (!writer.ok) return writer;
246 return checkUpstream(app, repo, true);
247 }
248
249 /** Repositories with a check in flight: one at a time each, whoever asked. */
250 const checking = new Set<string>();
251
252 /**
253 * One check, of one repository. Every outcome is noted on its row. The
254 * claim is taken before the first await, so two callers — a double click,
255 * the page and the terminal, a person and the tick — never both read "no
256 * proposal open" and both open one: the second is answered `busy`.
257 */
258 export async function checkUpstream(
259 app: App,
260 repo: Repo,
261 /** A person asked: a proposal they closed of this same tip is opened again. */
262 asked = false,
263 ): Promise<Result<Checked, CheckError>> {
264 if (checking.has(repo.id)) return err("busy");
265 checking.add(repo.id);
266 let checked: Result<Checked, CheckError> = err("git");
267 try {
268 checked = await checkOnce(app, repo, asked);
269 return checked;
270 } finally {
271 checking.delete(repo.id);
272 // An open About card or settings page redraws its "last checked" line;
273 // a following that is off was not checked, and says nothing.
274 if (checked.ok || checked.error !== "off")
275 app.bus.append({
276 kind: "repo.upstream_checked",
277 repoId: repo.id,
278 payload: { behind: getFollow(app.db, repo.id)?.behind ?? 0 },
279 });
280 }
281 }
282
283 async function checkOnce(app: App, repo: Repo, asked: boolean): Promise<Result<Checked, CheckError>> {
284 const follow = getFollow(app.db, repo.id);
285 if (follow === undefined || !follow.enabled || repo.archivedAt !== null || repo.origin !== null)
286 return err("off");
287 const at = new Date().toISOString();
288 const failed = (error: CheckError, why = ""): Result<Checked, CheckError> => {
289 noteCheck(app.db, repo.id, { at, error: why || FOLLOW_REFUSALS[error] });
290 return err(error);
291 };
292 const by = getUserById(app.db, follow.byId);
293 if (by === undefined || !canWrite(app.db, repo, by)) return failed("nobody");
294
295 // The credential, when the upstream is private: the connected origin's,
296 // scoped to this one git invocation (`origins/credentials.ts`).
297 let authEnv: Record<string, string> = {};
298 if (follow.originId !== "") {
299 const origin = getOriginFor(app.db, by.id, follow.originId);
300 const provider = origin === undefined ? undefined : providerForOrigin(app, origin);
301 // Again at each check, rows written by migrate included.
302 if (origin !== undefined && provider?.ok && mayCarryCredential(follow.url, origin.webUrl))
303 authEnv = await provider.value.gitAuthEnv(follow.url);
outdated

vettedEnv pins only what curl fetches, and pinFor puts a git:// URL on port 80. Once git:// is refused this is correct. Until then, this line does not do what its comment claims for a git:// upstream.

304 }
305 // Checked again each time: a name that resolved outside the network may not now.
306 const vetted = await upstreamUrl(app, by, follow.url);
307 if (!vetted.ok) return failed("unreadable", FOLLOW_REFUSALS[vetted.error]);
308 // Pinned to the address the vet resolved, so a second DNS answer cannot redirect the fetch.
309 const pinned = await vettedEnv(
310 follow.url,
311 authEnv,
312 REMOTE_PROTOCOLS,
313 mayBePrivate(app, by, new URL(follow.url).hostname),
314 );
315 if (!pinned.ok) return failed("unreadable", pinned.error.message);
316 const env = pinned.value;
317 const said = (stderr: string): string =>
318 redact(stderr.trim(), ...secretsIn(authEnv)).split("\n").find((l) => l.trim() !== "") ?? "";
319 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
320 const deadline = Date.now() + CHECK_TIMEOUT_MS;
321 const remaining = (): number => Math.max(1_000, deadline - Date.now());
322
323 const listed = await runGitCapture(
324 ["ls-remote", "--", follow.url, `refs/heads/${follow.branch}`],
325 { cwd: dir, env, timeoutMs: remaining() },
326 );
327 if (listed.code !== 0)
328 return failed("unreadable", `The upstream could not be read: ${said(listed.stderr) || "no reason given"}`);
329 const tip = listed.stdout.split("\t")[0]?.trim() ?? "";
330 if (!isSafeOid(tip)) return failed("no_branch");
331
332 // Fetch only when the tip moved: the staged ref is what the last fetch brought.
333 const ref = stagedRef(follow.branch);
334 if ((await resolveOid(dir, ref)) !== tip) {
335 const fetched = await runGitCapture(
336 [
337 "fetch",
338 "--no-tags",
339 "--no-write-fetch-head",
340 "--no-recurse-submodules",
341 "--quiet",
342 "--",
343 follow.url,
344 `+refs/heads/${follow.branch}:${ref}`,
345 ],
346 { cwd: dir, env, timeoutMs: remaining() },
347 );
348 if (fetched.code !== 0)
349 return failed("unreadable", `The upstream could not be fetched: ${said(fetched.stderr) || "no reason given"}`);
350 // What arrived counts against the owner's storage, as a migration's does.
351 storageStale(app, repo.ownerId);
352 }
353 const staged = await resolveOid(dir, ref);
354 if (staged === undefined) return failed("diverged");
355
356 const main = await resolveOid(dir, `refs/heads/${repo.defaultBranch}`);
357 if (main === undefined) return failed("git", "The default branch has no commits yet.");
358 const behind = await aheadCount(dir, main, staged);
359 if (behind === 0) {
360 noteCheck(app.db, repo.id, { at, tip: staged, behind: 0, error: "", pendingId: null });
361 return ok({ kind: "up_to_date", tip: staged });
362 }
363 // One proposal at a time: while it is open, it is the one to land.
364 if (follow.pendingId !== null) {
365 const pending = getIssueById(app.db, follow.pendingId);
366 if (pending !== undefined && pending.state === "open") {
367 noteCheck(app.db, repo.id, { at, tip: staged, behind, error: "" });
368 return ok({ kind: "pending", behind, id: pending.id });
369 }
370 // Closed without landing, and upstream has not moved since: someone
371 // said no to exactly this, and the clock does not ask again.
372 if (pending !== undefined && follow.tip === staged && !asked) {
373 noteCheck(app.db, repo.id, { at, tip: staged, behind, error: "" });
374 return ok({ kind: "declined", behind, id: pending.id });
375 }
376 }
377
378 const base = (await mergeBase(dir, main, staged)) ?? "";
379 const title = `${UPSTREAM_TITLE}${behind} commit${behind === 1 ? "" : "s"} from ${upstreamLabel(follow.url)} (${base === "" ? "" : `${base.slice(0, 7)}..`}${staged.slice(0, 7)})`;
380 const log_ = await runGit(
381 ["log", "--no-merges", "--format=%h %s", "-n", "20", `${main}..${staged}`],
382 { cwd: dir },
383 );
384 const commits = log_.ok
385 ? log_.value.split("\n").filter((l) => l !== "").map((l) => `- ${l}`)
386 : [];
387 const more = behind > commits.length ? [`- … and ${behind - commits.length} more`] : [];
388 const where = `\`${follow.branch}\` of ${follow.url}`;
389
390 const reading = await mergeable(dir, main, staged);
391 if (reading.ok) {
392 // Deterministic: a fast-forward is the tip itself; a clean merge is one
393 // merge commit on top of ours, so the check tests exactly what lands.
394 const fastForward = base === main;
395 let head = staged;
396 if (!fastForward) {
397 const who = commitIdentity(app.config, by);
398 const made = await runGit(
399 [
400 "commit-tree",
401 reading.value.treeOid,
402 "-p",
403 main,
404 "-p",
405 staged,
406 "-m",
407 `Merge ${upstreamLabel(follow.url)} ${follow.branch} (${staged.slice(0, 7)})`,
408 ],
409 {
410 cwd: dir,
411 env: {
412 GIT_AUTHOR_NAME: who.name,
413 GIT_AUTHOR_EMAIL: who.email,
414 GIT_COMMITTER_NAME: who.name,
415 GIT_COMMITTER_EMAIL: who.email,
416 },
417 },
418 );
419 if (!made.ok) return failed("git");
420 head = made.value.trim();
421 }
422 // A branch of this name that someone else made is never the proposal:
423 // it is used only when it already holds exactly `head`, else a name
424 // that carries `head` itself is made.
outdated

High: accepting exists means a branch someone else pushed as upstream/<tip7> becomes the "Upstream:" pull, opened as the admin who turned following on. When it exists, require resolveOid(dir, refs/heads/${name}) === head or fail, and add a test with a squatted branch.

425 let name = proposalBranch(staged);
426 const created = await createBranch(dir, name, head);
427 if (!created.ok) {
428 if (created.error !== "exists") return failed("git");
429 if ((await resolveOid(dir, `refs/heads/${name}`)) !== head) {
430 name = `${name}-${head.slice(0, 7)}`;
431 const again = await createBranch(dir, name, head);
432 if (!again.ok && (again.error !== "exists" || (await resolveOid(dir, `refs/heads/${name}`)) !== head))
433 return failed("git");
434 }
435 }
436 const opened = await openPull(app, by, repo, {
437 title,
438 body: [
439 `New commits on ${where}, taken ${fastForward ? "as a fast-forward" : "with a clean `git merge`"}: no conflicts, nothing decided.`,
440 "",
441 ...commits,
442 ...more,
443 "",
444 "It lands through the landing gate like any pull, as a merge, so upstream's history stays ours.",
445 ].join("\n"),
446 baseBranch: repo.defaultBranch,
447 headBranch: name,
448 });
449 if (!opened.ok) return failed("git", `The pull could not be opened: ${opened.error}`);
450 noteCheck(app.db, repo.id, {
451 at,
452 tip: staged,
453 behind,
454 error: "",
455 pendingId: opened.value.id,
456 opened: true,
457 });
458 log.info("upstream pull opened", {
459 repo: `${repo.ownerName}/${repo.name}`,
460 pull: opened.value.number,
461 behind,
462 });
463 return ok({ kind: "pull", behind, number: opened.value.number });
464 }
465 if (reading.error.kind !== "conflict") return failed("git");
466
467 // Both sides changed the same files: a decision, and the crew drafts it.
468 const files = reading.error.files;
469 const opened = openIssue(app, by, repo, {
470 title,
471 body: [
472 `New commits on ${where} do not merge cleanly with \`${repo.defaultBranch}\`: ${files.length === 1 ? "one file" : `${files.length} files`} changed on both sides.`,
473 "",
474 ...files.map((f) => `- \`${f}\``),
475 "",
476 `The upstream tip is staged here at \`${ref}\` (${staged.slice(0, 7)}). Merge it into a branch — a real merge, never a rebase or squash — keep upstream's fixes, keep this repository's work, and explain each resolution. Never take an upstream deletion of a file this repository changed without saying why. The pull lands like any crew pull.`,
477 "",
478 ...commits,
479 ...more,
480 ].join("\n"),
481 });
482 if (!opened.ok) return failed("git", `The issue could not be opened: ${opened.error}`);
483 let issue = opened.value;
484 const builders = listCrewRoles(app.db, repo.id)
485 .filter((c) => c.role === "builder")
486 .map((c) => c.agent);
487 const inFlight = new Map<string, number>();
488 for (const r of listRuns(app.db, repo.id, { kind: "agent", limit: 50 }))
489 if ((r.state === "running" || r.state === "queued") && r.actorId !== null)
490 inFlight.set(r.actorId, (inFlight.get(r.actorId) ?? 0) + 1);
491 const agent = pickBuilder(issue, builders, inFlight);
492 if (agent !== undefined) {
493 // Assigned without the assignment event, which starts an ordinary run:
494 // this one carries its own reason and brief (as `crew/converge.ts`).
495 issue = setAssignee(app.db, issue.id, agent.user.id) ?? issue;
496 queueAgentRun(app, repo, issue, agent, "converge", undefined, {
497 notBefore: at,
498 attempt: 0,
499 summary: `upstream moved: ${files.join(", ")}`,
500 });
501 }
502 noteCheck(app.db, repo.id, {
503 at,
504 tip: staged,
505 behind,
506 error: "",
507 pendingId: issue.id,
508 opened: true,
509 });
510 log.info("upstream conflict sent to the crew", {
511 repo: `${repo.ownerName}/${repo.name}`,
512 issue: issue.number,
513 files: files.length,
514 builder: agent?.user.username ?? "none",
515 });
516 return ok({
517 kind: "conflict",
518 behind,
519 number: issue.number,
520 files,
521 builder: agent?.user.username,
522 });
523 }
524
525 /** What the crew's brief says about a following repository's converge run. */
526 export function upstreamFollowing(
527 app: App,
528 repoId: string,
529 ): { parent: string; branch: string; ref: string; upstream: true } | undefined {
530 const follow = getFollow(app.db, repoId);
531 if (follow === undefined) return undefined;
532 return {
533 parent: upstreamLabel(follow.url),
534 branch: follow.branch,
535 ref: stagedRef(follow.branch),
536 upstream: true,
537 };
538 }
539
540 /**
541 * Whether a pull's head carries upstream commits the base lacks: such a
542 * pull lands as a merge, never a squash, so upstream's history becomes an
543 * ancestor of ours and the next check counts only what is new. Asked of
544 * git: the staged tip's merge base with the head is not already in the base.
545 */
546 export async function carriesUpstream(
547 app: App,
548 repo: Repo,
549 dir: string,
550 headOid: string,
551 baseOid: string,
552 ): Promise<boolean> {
553 const follow = getFollow(app.db, repo.id);
554 if (follow === undefined) return false;
555 const staged = await resolveOid(dir, stagedRef(follow.branch));
556 if (staged === undefined || !isSafeOid(headOid) || !isSafeOid(baseOid)) return false;
557 const shared = await mergeBase(dir, staged, headOid);
558 if (shared === undefined) return false;
559 const inBase = await runGit(["merge-base", "--is-ancestor", shared, baseOid], { cwd: dir });
560 return !inBase.ok;
561 }
562
563 /** A repository's following, as the API says it: no origin id, no actor id. */
564 export const followJson = (f: UpstreamFollow) => ({
565 url: f.url,
566 branch: f.branch,
567 enabled: f.enabled,
568 parentUrl: f.parentUrl === "" ? null : f.parentUrl,
569 checkedAt: f.checkedAt,
570 tip: f.tip === "" ? null : f.tip,
571 behind: f.behind,
572 error: f.error === "" ? null : f.error,
573 opened: f.opened,
574 });
575
576 /**
577 * Every following repository whose last check is older than
578 * `FOLLOW_EVERY_MS`, checked beside the tick, never in front of it: a
579 * slow upstream must not hold the crew up. Answers how many were started.
580 */
581 export function followTick(app: App, now = Date.now()): number {
582 let started = 0;
583 for (const follow of listFollowing(app.db)) {
584 if (checking.has(follow.repoId)) continue;
585 if (follow.checkedAt !== null && now - Date.parse(follow.checkedAt) < FOLLOW_EVERY_MS)
586 continue;
587 const repo = getRepoById(app.db, follow.repoId);
588 if (repo === undefined || repo.archivedAt !== null) continue;
589 started++;
590 // `checkUpstream` claims the repository before its first await.
591 void checkUpstream(app, repo).catch((error) =>
592 log.error("upstream check failed", {
593 repo: `${repo.ownerName}/${repo.name}`,
594 error: String(error),
595 }),
596 );
597 }
598 return started;
599 }
600
601 /** For the tick line: where a following repository stands, in a few words. */
602 export function followWords(app: App, repoId: string): string | undefined {
603 const follow = getFollow(app.db, repoId);
604 if (follow === undefined || !follow.enabled) return undefined;
605 const pending =
606 follow.pendingId === null ? undefined : getIssueById(app.db, follow.pendingId);
607 const open = pending !== undefined && pending.state === "open" ? `, #${pending.number} open` : "";
608 return `${follow.behind} behind, ${follow.opened} opened${open}`;
609 }
610
611 /**
612 * The following a viewer may read: an enabled one for anyone who reads the
613 * repository, an off one for its admins only — the rule the About line,
614 * the terminal's About card and `GET …/upstream` share.
615 */
616 export function followShown(
617 app: App,
618 repo: Repo,
619 viewer: User | undefined,
620 ): UpstreamFollow | undefined {
621 const follow = getFollow(app.db, repo.id);
622 if (follow === undefined) return undefined;
623 return follow.enabled || canAdmin(app.db, repo, viewer) ? follow : undefined;
624 }
625
626 /**
627 * Where a following repository stands, in words: "3 behind", "up to date",
628 * "off". Why a check failed is the remote's stderr, redacted, and only a
629 * writer is told it; anyone else reads "the last check did not finish".
630 */
631 export function standing(follow: UpstreamFollow, writer: boolean): string {
632 if (!follow.enabled) return "off";
633 if (follow.checkedAt === null) return "not checked yet";
634 if (follow.error !== "") return writer ? follow.error : "the last check did not finish";
635 return follow.behind === 0 ? "up to date" : `${follow.behind} behind`;
636 }
637
638 /** HH:MM in UTC, the instant a check last ran. */
639 export function clockWords(iso: string): string {
640 const at = new Date(iso);
641 return Number.isNaN(at.getTime()) ? "" : `${at.toISOString().slice(11, 16)} UTC`;
642 }
643
644 /** What a check found, in one sentence, for the page's flash and the terminal's toast. */
645 export function checkedWords(c: Checked): string {
646 switch (c.kind) {
647 case "up_to_date":
648 return "Up to date with the upstream.";
649 case "pending":
650 return `${c.behind} behind; the open proposal lands first.`;
651 case "declined":
652 return `${c.behind} behind; the last proposal was closed.`;
653 case "pull":
654 return `${c.behind === 1 ? "1 new upstream commit merges" : `${c.behind} new upstream commits merge`} cleanly: pull #${c.number} lands through the gate.`;
655 case "conflict":
656 return `${c.behind === 1 ? "1 new upstream commit conflicts" : `${c.behind} new upstream commits conflict`} in ${c.files.join(", ")}: issue #${c.number}${c.builder === undefined ? " waits for a builder" : ` is with @${c.builder}`}.`;
657 }
658 }
src/core/event_audience.ts +3
@@ -48,6 +48,9 @@ export function eventAudience(kind: string): EventAudience {
4848 // theirs to see, never the readers' (`actions/reports.ts`).
4949 kind.startsWith("report.") ||
5050 kind === "repo.settings_updated" ||
51 // Where a repository follows is its admins' to read (`followShown`),
52 // off or on: the address is often a private repository's.
53 kind === "repo.upstream_follow" ||
5154 // Which of a person's connected accounts a mirror now syncs through is
5255 // the repository's configuration, as a webhook's URL is.
5356 kind === "origin.mirror_reattached" ||
src/core/migrations/20261020200000-repo-upstream.ts added +21
@@ -0,0 +1,21 @@
1 // A repository follows an outside upstream (#3442): the git URL and branch
2 // it takes new commits from, whether it is on, who it acts as, the origin
3 // whose credential opens a private one, and what the last check read.
4 export default `
5 CREATE TABLE IF NOT EXISTS repo_upstream (
6 repo_id TEXT PRIMARY KEY REFERENCES repo(id) ON DELETE CASCADE,
7 url TEXT NOT NULL,
8 branch TEXT NOT NULL,
9 enabled INTEGER NOT NULL DEFAULT 0,
10 by_id TEXT NOT NULL,
11 origin_id TEXT NOT NULL DEFAULT '',
12 parent_url TEXT NOT NULL DEFAULT '',
13 checked_at TEXT,
14 tip TEXT NOT NULL DEFAULT '',
15 behind INTEGER NOT NULL DEFAULT 0,
16 error TEXT NOT NULL DEFAULT '',
17 pending_id TEXT,
18 opened INTEGER NOT NULL DEFAULT 0,
19 updated_at TEXT NOT NULL
20 );
21 `;
src/core/upstream_follow.ts added +157
@@ -0,0 +1,157 @@
1 /**
2 * A repository following an outside upstream (#3442): the git URL and
3 * branch new commits come from, whether it is on, who the forge acts as
4 * when it proposes them, and what the last check read. The commits
5 * themselves are git's (`refs/upstream/<branch>` in the repository); this
6 * row is the setting and the last reading, rebuilt by the next check.
7 *
8 * Pure data, no authz, no events (`actions/upstream_follow.ts`).
9 */
10
11 import type { Database } from "bun:sqlite";
12
13 export interface UpstreamFollow {
14 readonly repoId: string;
15 /** A git URL git may be handed (`migrateUrl`). */
16 readonly url: string;
17 readonly branch: string;
18 readonly enabled: boolean;
19 /** The person the forge acts as: who turned it on. */
20 readonly byId: string;
21 /** The connected origin whose credential opens a private upstream; "" for none. */
22 readonly originId: string;
23 /** The upstream's own parent, when its host said it is a fork: the second choice. */
24 readonly parentUrl: string;
25 readonly checkedAt: string | null;
26 /** The upstream tip the last check read; "" before the first. */
27 readonly tip: string;
28 /** Commits on the upstream branch the default branch does not hold. */
29 readonly behind: number;
30 /** Why the last check could not finish; "" when it did. */
31 readonly error: string;
32 /** The pull or issue carrying the last proposal, while it is open. */
33 readonly pendingId: string | null;
34 /** How many proposals the forge has opened for this repository. */
35 readonly opened: number;
36 }
37
38 interface Row {
39 repo_id: string;
40 url: string;
41 branch: string;
42 enabled: number;
43 by_id: string;
44 origin_id: string;
45 parent_url: string;
46 checked_at: string | null;
47 tip: string;
48 behind: number;
49 error: string;
50 pending_id: string | null;
51 opened: number;
52 }
53
54 const fromRow = (r: Row): UpstreamFollow => ({
55 repoId: r.repo_id,
56 url: r.url,
57 branch: r.branch,
58 enabled: r.enabled === 1,
59 byId: r.by_id,
60 originId: r.origin_id,
61 parentUrl: r.parent_url,
62 checkedAt: r.checked_at,
63 tip: r.tip,
64 behind: r.behind,
65 error: r.error,
66 pendingId: r.pending_id,
67 opened: r.opened,
68 });
69
70 export function getFollow(db: Database, repoId: string): UpstreamFollow | undefined {
71 const row = db
72 .query<Row, [string]>("SELECT * FROM repo_upstream WHERE repo_id = ?1")
73 .get(repoId);
74 return row ? fromRow(row) : undefined;
75 }
76
77 /** Every repository whose following is on. */
78 export function listFollowing(db: Database): UpstreamFollow[] {
79 return db
80 .query<Row, []>("SELECT * FROM repo_upstream WHERE enabled = 1 ORDER BY repo_id")
81 .all()
82 .map(fromRow);
83 }
84
85 /**
86 * Set where a repository follows and whether it does. A new URL or branch
87 * forgets the last reading — it was of another upstream.
88 */
89 export function putFollow(
90 db: Database,
91 input: {
92 readonly repoId: string;
93 readonly url: string;
94 readonly branch: string;
95 readonly enabled: boolean;
96 readonly byId: string;
97 readonly originId: string;
98 readonly parentUrl?: string;
99 },
100 ): UpstreamFollow {
101 const now = new Date().toISOString();
102 const was = getFollow(db, input.repoId);
103 const moved = was !== undefined && (was.url !== input.url || was.branch !== input.branch);
104 db.query(
105 `INSERT INTO repo_upstream (repo_id, url, branch, enabled, by_id, origin_id, parent_url, updated_at)
106 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
107 ON CONFLICT(repo_id) DO UPDATE SET url = ?2, branch = ?3, enabled = ?4,
108 by_id = ?5, origin_id = ?6, parent_url = CASE WHEN ?7 = '' THEN parent_url ELSE ?7 END,
109 updated_at = ?8`,
110 ).run(
111 input.repoId,
112 input.url,
113 input.branch,
114 input.enabled ? 1 : 0,
115 input.byId,
116 input.originId,
117 input.parentUrl ?? "",
118 now,
119 );
120 if (moved)
121 db.query(
122 "UPDATE repo_upstream SET checked_at = NULL, tip = '', behind = 0, error = '' WHERE repo_id = ?1",
123 ).run(input.repoId);
124 return getFollow(db, input.repoId)!;
125 }
126
127 /** What one check read. `pendingId` is left alone when absent. */
128 export function noteCheck(
129 db: Database,
130 repoId: string,
131 reading: {
132 readonly at: string;
133 readonly tip?: string;
134 readonly behind?: number;
135 readonly error: string;
136 readonly pendingId?: string | null;
137 /** A proposal was opened by this check. */
138 readonly opened?: boolean;
139 },
140 ): void {
141 db.query(
142 `UPDATE repo_upstream SET checked_at = ?2,
143 tip = COALESCE(?3, tip), behind = COALESCE(?4, behind), error = ?5,
144 pending_id = CASE WHEN ?6 = 1 THEN ?7 ELSE pending_id END,
145 opened = opened + ?8
146 WHERE repo_id = ?1`,
147 ).run(
148 repoId,
149 reading.at,
150 reading.tip ?? null,
151 reading.behind ?? null,
152 reading.error,
153 reading.pendingId === undefined ? 0 : 1,
154 reading.pendingId ?? null,
155 reading.opened === true ? 1 : 0,
156 );
157 }
src/crew/autonomy.ts +27 −1
@@ -28,6 +28,11 @@ import { mergeable, resolveOid, treeOf } from "../git/merge.ts";
2828 import { repoDir } from "../git/repos.ts";
2929 import { CLOSED_NOTE } from "../core/done_on_main.ts";
3030 import { mergePull } from "../actions/pulls.ts";
31 import {
32 carriesUpstream,
33 followTick,
34 followWords,
35 } from "../actions/upstream_follow.ts";
3136 import {
3237 listCrewRoles,
3338 type Agent,
@@ -1164,6 +1169,7 @@ export async function autonomyTick(
11641169 // never a mystery: the numbers behind "idle" are on the line.
11651170 const status = autonomyStatus(app, current, now);
11661171 const approved = waitWords(lastWaits(current.id));
1172 const upstream = followWords(app, current.id);
11671173 const ready = readyNow(repoGraph(app.db, current.id, { sealed: true }));
11681174 const held = heldBy(
11691175 app,
@@ -1193,6 +1199,8 @@ export async function autonomyTick(
11931199 // The approved pulls the last green sweep saw, and why each waits (#3055).
11941200 ...(approved === undefined ? {} : { approved }),
11951201 spent: `${status.spentTodayUsd.toFixed(2)}/${status.ceilingUsd}`,
1202 // A repository following its upstream: how far behind, how many proposed (#3442).
1203 ...(upstream === undefined ? {} : { upstream }),
11961204 ...(status.paused === null ? {} : { paused: status.paused }),
11971205 });
11981206 } catch (error) {
@@ -1214,6 +1222,13 @@ export async function autonomyTick(
12141222 } catch (error) {
12151223 log.error("sentinel failed", { error: String(error) });
12161224 }
1225 // Every following repository is checked on its own clock (#3442), beside
1226 // the tick: a slow upstream holds nothing up.
1227 try {
1228 followTick(app, now.getTime());
1229 } catch (error) {
1230 log.error("upstream follow failed", { error: String(error) });
1231 }
12171232 // Review is not autonomy's alone: an agent's green pull is read by the
12181233 // crew's reviewer in every repository that has one.
12191234 try {
@@ -1894,7 +1909,18 @@ async function landGated(
18941909 by: "rule",
18951910 ms: 0,
18961911 });
1897 const merged = await mergePull(app, by, repo, pull, "squash", expect);
1912 // A pull carrying upstream's commits lands as a merge: squashed, their
1913 // history would never be ours and the next check would count it again.
1914 const strategy = (await carriesUpstream(
1915 app,
1916 repo,
1917 await pullDir(app.db, app.reposRoot, repo, pull),
1918 pull.headOid,
1919 expect.baseOid,
1920 ))
1921 ? "merge"
1922 : "squash";
1923 const merged = await mergePull(app, by, repo, pull, strategy, expect);
18981924 if (!merged.ok) {
18991925 const why = mergeWhy(merged.error);
19001926 log.info("green but not landed", {
src/crew/brief.ts +26 −3
@@ -192,7 +192,14 @@ export interface TaskInput extends BriefInput {
192192 readonly resolution?: string | undefined;
193193 /** For `converge`: the parent this repository follows, and its branch. */
194194 readonly following?:
195 | { readonly parent: string; readonly branch: string }
195 | {
196 readonly parent: string;
197 readonly branch: string;
198 /** Where it is staged, when not `refs/following/<branch>`. */
199 readonly ref?: string;
200 /** An outside upstream this repository follows (#3442), not a forge parent. */
201 readonly upstream?: boolean;
202 }
196203 | undefined;
197204 /** For `review`: the pull's diff against its base, capped. */
198205 readonly reviewDiff?: string | undefined;
@@ -447,13 +454,29 @@ function taskBody(input: TaskInput): string {
447454 const parent = input.following?.parent ?? "its parent";
448455 const pbranch = input.following?.branch ?? "main";
449456 const direction = input.repo.autonomyDirection.trim();
457 const staged = input.following?.ref ?? `refs/following/${pbranch}`;
458 if (input.following?.upstream === true) {
459 out.push(
460 `This repository follows its upstream ${parent} (\`${pbranch}\`), and new upstream commits do not merge cleanly. Issue #${issue.number}: ${issue.title}`,
461 "",
462 ...told(),
463 "",
464 `The upstream tip is staged here at \`${staged}\`. On the branch \`${input.branch}\`:`,
465 `1. \`git fetch origin ${staged} && git merge FETCH_HEAD\` — a real merge: never rebase, squash or cherry-pick, so upstream's history stays an ancestor of ours.`,
466 `2. Resolve each conflict${files.length > 0 ? ` (${files.join(", ")})` : ""}: keep upstream's fixes, and keep this repository's own work. Where they cannot both be kept, this repository's direction decides${direction === "" ? "" : `: ${direction}`}. Never take an upstream deletion of a file this repository changed unless you say why.`,
467 "3. Make sure the tests pass, then push. Never force-push.",
468 "",
469 `The forge opens the pull on your first push and lands it as a merge. Your report becomes its description: explain each resolution, file by file, and end it with \`Closes #${issue.number}\`.`,
470 );
471 return out.join("\n");
472 }
450473 out.push(
451474 `This repository follows ${parent}, and both have moved. Issue #${issue.number}: ${issue.title}`,
452475 "",
453476 ...told(),
454477 "",
455 `The parent's \`${pbranch}\` is staged here at \`refs/following/${pbranch}\`. On the branch \`${input.branch}\`:`,
456 `1. \`git fetch origin refs/following/${pbranch} && git merge FETCH_HEAD\``,
478 `The parent's \`${pbranch}\` is staged here at \`${staged}\`. On the branch \`${input.branch}\`:`,
479 `1. \`git fetch origin ${staged} && git merge FETCH_HEAD\``,
457480 `2. Resolve each conflict${files.length > 0 ? ` (${files.join(", ")})` : ""} keeping what both sides meant. Where they cannot both be kept, this repository's direction decides${direction === "" ? "" : `: ${direction}`}. Never drop this repository's own work to make a merge easy.`,
458481 "3. Make sure the tests pass, then push.",
459482 "",
src/crew/runner.ts +7 −1
@@ -41,6 +41,7 @@ import {
4141 type Issue,
4242 } from "../core/issues.ts";
4343 import { refreshPullHead } from "../core/following.ts";
44 import { UPSTREAM_TITLE, upstreamFollowing } from "../actions/upstream_follow.ts";
4445 import { getPull, listPulls, type Pull } from "../core/pulls.ts";
4546 import {
4647 canWrite,
@@ -976,13 +977,18 @@ async function work(
976977 conflictFiles:
977978 reason === "conflict" || reason === "converge"
978979 ? run.summary
979 .replace(/^(main|parent) moved: /, "")
980 .replace(/^(main|parent|upstream) moved: /, "")
980981 .split(", ")
981982 .filter((f) => f !== "")
982983 : undefined,
983984 following:
984985 reason === "converge"
985986 ? (() => {
987 // An outside upstream's new commits, staged here (#3442).
988 if (issue.title.startsWith(UPSTREAM_TITLE)) {
989 const upstream = upstreamFollowing(app, repo.id);
990 if (upstream !== undefined) return upstream;
991 }
986992 // Only a parent the agent may read is put in its brief.
987993 const parent = forkParentFor(app.db, repo, agent.user);
988994 return parent === undefined
src/http/api.ts +53
@@ -8,6 +8,13 @@
88 * back to continue); errors are `{ error, message }`.
99 */
1010
11 import {
12 checkUpstreamNow,
13 FOLLOW_REFUSALS,
14 followJson,
15 followShown,
16 setFollowUpstream,
17 } from "../actions/upstream_follow.ts";
1118 import { upstreamPayload } from "../spawn/upstream.ts";
1219 import { setRole } from "../actions/roles.ts";
1320 import { listPeople, NOT_A_MEMBER } from "../core/roles.ts";
@@ -2277,6 +2284,52 @@ export function apiRoutes(router: Router<Handler>): void {
22772284 : notFound();
22782285 });
22792286
2287 // Following an outside upstream (#3442): read, set, and check now.
2288 router.add("GET", "/api/v1/repos/:owner/:name/upstream", (ctx) => {
2289 const repo = loadRepo(ctx);
2290 if (!repo) return notFound();
2291 const follow = followShown(ctx.app, repo, ctx.auth.user);
2292 if (follow === undefined) return json({ following: null });
2293 // Why a check failed is the remote's own stderr: a writer's to read.
2294 const shown = followJson(follow);
2295 return json({
2296 following: canWrite(ctx.app.db, repo, ctx.auth.user) ? shown : { ...shown, error: null },
2297 });
2298 });
2299
2300 router.add("PUT", "/api/v1/repos/:owner/:name/upstream", async (ctx) => {
2301 const denied = requireScope(ctx, "admin");
2302 if (denied) return denied;
2303 const repo = loadRepo(ctx);
2304 if (!repo) return notFound();
2305 const input = await body(ctx.request);
2306 if (typeof input.enabled !== "boolean")
2307 return apiError("bad_enabled", 422, "enabled is true or false");
2308 const saved = await setFollowUpstream(ctx.app, ctx.auth.user, repo, {
2309 url: str(input.url),
2310 branch: str(input.branch),
2311 enabled: input.enabled,
2312 });
2313 if (!saved.ok)
2314 return saved.error === "unauthorized" || saved.error === "forbidden" || saved.error === "not_found"
2315 ? respondAccess(saved.error, 422)
2316 : apiError(saved.error, 422, FOLLOW_REFUSALS[saved.error]);
2317 return json({ following: followJson(saved.value) });
2318 });
2319
2320 router.add("POST", "/api/v1/repos/:owner/:name/upstream/check", async (ctx) => {
2321 const denied = requireScope(ctx, "rw");
2322 if (denied) return denied;
2323 const repo = loadRepo(ctx);
2324 if (!repo) return notFound();
2325 const checked = await checkUpstreamNow(ctx.app, ctx.auth.user, repo);
2326 if (!checked.ok)
2327 return checked.error === "unauthorized" || checked.error === "forbidden" || checked.error === "not_found"
2328 ? respondAccess(checked.error, 422)
2329 : apiError(checked.error, checked.error === "busy" ? 409 : 422, FOLLOW_REFUSALS[checked.error]);
2330 return json(checked.value);
2331 });
2332
22802333 router.add("PATCH", "/api/v1/repos/:owner/:name", async (ctx) => {
22812334 const denied = requireScope(ctx, "admin");
22822335 if (denied) return denied;
src/http/server.ts +6
@@ -5,6 +5,10 @@
55 * verdict. Auth is resolved once per request and handed to handlers as data.
66 */
77
8 import {
9 followUpstreamCheck,
10 followUpstreamUpdate,
11 } from "../web/pages/upstream-follow.ts";
812 import { refusedByDatabase, shownRefusal } from "./refusal.ts";
913 import { NOT_A_MEMBER } from "../core/roles.ts";
1014 import { signupOptions, signupPasskey } from "../web/pages/signup-passkey.ts";
@@ -1388,6 +1392,8 @@ export function buildRouter(): Router<Handler> {
13881392 );
13891393 router.add("GET", "/:owner/:name/settings/autonomy", autonomySettingsPage);
13901394 router.add("POST", "/:owner/:name/settings/autonomy", autonomySettingsUpdate);
1395 router.add("POST", "/:owner/:name/settings/upstream", followUpstreamUpdate);
1396 router.add("POST", "/:owner/:name/settings/upstream/check", followUpstreamCheck);
13911397 router.add("GET", "/:owner/:name/settings/labels", labelsPage);
13921398 router.add("POST", "/:owner/:name/settings/labels", labelCreate);
13931399 router.add("POST", "/:owner/:name/settings/labels/:id", labelUpdate);
src/origins/git-mirror.ts +9 −3
@@ -57,17 +57,23 @@ export const MIRROR_UNRESOLVED = "the remote's host could not be resolved";
5757 * Vet the clone URL's host and return git's environment pinned to the
5858 * address that passed — or the one sentence that ends the sync.
5959 */
60 async function vettedEnv(
60 export async function vettedEnv(
6161 url: string,
6262 authEnv: Record<string, string>,
63 protocols?: string,
64 /** The host may resolve inside the network: the caller's own rule let it. */
65 allowPrivate = false,
6366 ): Promise<Result<Record<string, string>, GitMirrorError>> {
6467 const host = new URL(url).hostname;
65 const vetted = await vetHost(host, { ...outbound, trusted: trustedHosts() });
68 const vetted = await vetHost(host, {
69 ...outbound,
70 trusted: allowPrivate ? [...trustedHosts(), host] : trustedHosts(),
71 });
6672 if (!vetted.ok)
6773 return err({
6874 message: vetted.error === "refused" ? MIRROR_REFUSED : MIRROR_UNRESOLVED,
6975 });
70 return ok(remoteGitEnv(authEnv, pinFor(url, vetted.value[0]!)));
76 return ok(remoteGitEnv(authEnv, pinFor(url, vetted.value[0]!), protocols));
7177 }
7278
7379 export interface RefSnapshot {
src/tui/screens/about.ts +124 −3
@@ -23,7 +23,18 @@ import { checkMemoryAt } from "../../apps/check-memory.ts";
2323 import { repoDir } from "../../git/repos.ts";
2424 import { listRefs } from "../../git/read.ts";
2525 import { updateRepoSettings } from "../../actions/repos.ts";
26 import { canAdmin, getRepoById, type Repo } from "../../core/repos.ts";
26 import { canAdmin, canWrite, getRepoById, type Repo } from "../../core/repos.ts";
27 import {
28 checkedWords,
29 checkUpstreamNow,
30 clockWords,
31 FOLLOW_REFUSALS,
32 followShown,
33 setFollowUpstream,
34 standing,
35 upstreamLabel,
36 } from "../../actions/upstream_follow.ts";
37 import { getFollow } from "../../core/upstream_follow.ts";
2738 import type { RepoFacts, RepoSource } from "../../view/source.ts";
2839 import type { Ctx, Screen } from "../app/app.ts";
2940 import { binding } from "../app/keys.ts";
@@ -31,7 +42,7 @@ import { style } from "../term/style.ts";
3142 import { truncate, wrap } from "../term/width.ts";
3243 import { badge, card } from "../ui/widgets.ts";
3344 import type { Session } from "../session.ts";
34 import { PIN_MARK, ago, drawFacts, plural } from "./common.ts";
45 import { PIN_MARK, ago, drawFacts, later, live, plural, promptScreen } from "./common.ts";
3546 import { forkOf, hostOf, liveOrigin, localRepo, sourceName } from "./where.ts";
3647
3748 /**
@@ -52,10 +63,17 @@ export function aboutScreen(
5263 let repo = localRepo(src);
5364 const may = (): boolean =>
5465 repo !== undefined && f.user !== undefined && canAdmin(f.db, repo, f.user);
66 // A writer may ask the upstream now, when following is on (#3442).
67 const mayCheck = (): boolean =>
68 repo !== undefined &&
69 f.user !== undefined &&
70 canWrite(f.db, repo, f.user) &&
71 followShown(f.app, repo, f.user)?.enabled === true;
5572 let cell: [string, string][] = [];
5673 const factRows = (): [string, string][] => [
5774 ...archivedRow(repo),
5875 ...aboutFacts(f, src, facts, ref),
76 ...followRow(f, repo),
5977 ...cell,
6078 ];
6179 let rows = factRows();
@@ -81,8 +99,58 @@ export function aboutScreen(
8199 });
82100 }
83101 const cloneUrl = rows.find(([label]) => label.startsWith("clone"))?.[1] ?? "";
84 return {
102 // An admin turns following on or off, or points it elsewhere (#3442):
103 // the page's `setFollowUpstream`, with the page's refusals.
104 const saveFollow = async (url: string, branch: string, enabled: boolean): Promise<void> => {
105 if (repo === undefined) return;
106 const saved = await setFollowUpstream(f.app, f.user, repo, { url, branch, enabled });

This write emits repo.upstream_follow, and the web client doesn't subscribe to it (see src/web/live.ts). Turning following on or off here doesn't update an open About card or settings page in a browser.

107 rows = factRows();
108 if (saved.ok)
109 ctx.toast(
110 saved.value.enabled
111 ? `following ${upstreamLabel(saved.value.url)} ${saved.value.branch}`
112 : "following the upstream is off",
113 "success",
114 );
115 else ctx.toast(FOLLOW_REFUSALS[saved.error], "danger");
116 ctx.invalidate();
117 };
118 const pointFollow = (enabled: boolean): void => {
119 const now = repo === undefined ? undefined : getFollow(f.db, repo.id);
120 ctx.push(
121 promptScreen(ctx, screen, {
122 title: "Follow an upstream",
123 label: "git address: https:// or http://",
124 value: now?.url ?? "",
125 onSubmit: (url) =>
126 url === ""
127 ? "An address to follow."
128 : later(ctx, () =>
129 promptScreen(ctx, screen, {
130 title: "Follow an upstream",
131 label: "its branch",
132 value: now?.branch ?? "main",
133 onSubmit: (branch) => saveFollow(url, branch, enabled),
134 }),
135 ),
136 }),
137 );
138 };
139 const screen: Screen = {
85140 title: "About",
141 // A check finishing, or following changing, redraws the row in place.
142 async load(signal) {
143 if (repo === undefined) return;
144 live(
145 f,
146 signal,
147 { repoId: repo.id, kinds: ["repo.upstream_checked", "repo.upstream_follow"] },
148 () => {
149 rows = factRows();
150 ctx.invalidate();
151 },
152 );
153 },
86154 get keys() {
87155 return [
88156 binding(["y"], "copy the clone URL", { disabled: cloneUrl === "" }),
@@ -95,6 +163,18 @@ export function aboutScreen(
95163 ),
96164 ]
97165 : []),
166 ...(mayCheck() ? [binding(["u"], "check upstream now")] : []),
167 ...(may()
168 ? [
169 binding(
170 ["f"],
171 repo !== undefined && getFollow(f.db, repo.id)?.enabled === true
172 ? "stop following upstream"
173 : "follow upstream",
174 ),
175 binding(["F"], "point following elsewhere"),
176 ]
177 : []),
98178 binding(["esc"], "close"),
99179 ];
100180 },
@@ -200,6 +280,26 @@ export function aboutScreen(
200280 });
201281 return true;
202282 }
283 if (e.key === "u" && repo !== undefined && mayCheck()) {
284 ctx.toast("checking the upstream…");
285 void checkUpstreamNow(f.app, f.user, repo).then((checked) => {
286 rows = factRows();
287 if (checked.ok) ctx.toast(checkedWords(checked.value), "success");
288 else ctx.toast(FOLLOW_REFUSALS[checked.error], "danger");
289 ctx.invalidate();
290 });
291 return true;
292 }
293 if (e.key === "f" && repo !== undefined && may()) {
294 const now = getFollow(f.db, repo.id);
295 if (now === undefined) pointFollow(true);
296 else void saveFollow(now.url, now.branch, !now.enabled);
297 return true;
298 }
299 if (e.key === "F" && repo !== undefined && may()) {
300 pointFollow(getFollow(f.db, repo.id)?.enabled ?? true);
301 return true;
302 }
203303 if (e.key === "esc" || e.key === "q" || e.key === "I") {
204304 ctx.pop();
205305 return true;
@@ -207,6 +307,27 @@ export function aboutScreen(
207307 return true;
208308 },
209309 };
310 return screen;
311 }
312
313 /**
314 * What the repository follows, the About line's words (`followingLine`):
315 * shown when on, or to an admin when off.
316 */
317 function followRow(f: Session, repo: Repo | undefined): [string, string][] {
318 if (repo === undefined) return [];
319 const follow = followShown(f.app, repo, f.user);
320 if (follow === undefined) return [];
321 // Two rows: the card is at most 72 wide, and an address plus where it
322 // stands is more than one row of it holds.
323 const where = [
324 standing(follow, f.user !== undefined && canWrite(f.db, repo, f.user)),
325 ...(follow.checkedAt === null ? [] : [`last checked ${clockWords(follow.checkedAt)}`]),
326 ];
327 return [
328 ["following", `${upstreamLabel(follow.url)} ${follow.branch}`],
329 ...wrap(where.join(" · "), 50).map((line): [string, string] => ["", line]),
330 ];
210331 }
211332
212333 /** One line when an admin has put the repository away. */
src/web/live.ts +1
@@ -303,6 +303,7 @@ export const liveClientJs = /* js */ `
303303 'run.queued', 'run.started', 'run.finished', 'app.serving',
304304 'app.created', 'app.updated', 'app.deleted', 'app.stopped',
305305 'limb.moved', 'limb.replan', 'limb.replan_taken_back', 'issue.assigned', 'pull.assigned', 'crew.added', 'crew.removed',
306 'repo.upstream_checked',

Only repo.upstream_checked is heard. repo.upstream_follow (a save from the terminal's f/F, or from another tab) never reaches an open web page. Add it here, and give readers a reader-audience event when enabled flips, since repo.upstream_follow is admins-only.

306307 ];
307308 var extra = (cfg.getAttribute('data-repos') || '').split(' ').filter(Boolean);
308309 var watching = [repo].concat(extra).filter(function (r, i, all) {
src/web/pages/repo.ts +2
@@ -8,6 +8,7 @@
88 * path segment and can never smuggle a path of its own.
99 */
1010
11 import { followingLine } from "./upstream-follow.ts";
1112 import { NOT_A_MEMBER } from "../../core/roles.ts";
1213 import { storageLimitMessage } from "../../core/storage.ts";
1314 import { canRead, listForks, type Repo } from "../../core/repos.ts";
@@ -631,6 +632,7 @@ function aboutCard(
631632 </dd>`,
632633 )}
633634 </dl>
635 ${followingLine(ctx, repo)}
634636 ${whereItLives}
635637 ${when(
636638 repo.visibility === "public" && repo.origin === null,
src/web/pages/settings.ts +2 −1
@@ -109,6 +109,7 @@ import { proposalTokensSection } from "./proposal-tokens.ts";
109109 import { secretsSection } from "./secrets.ts";
110110 import { checkMemoryAt } from "../../apps/check-memory.ts";
111111 import { saveGrants } from "./subscriptions.ts";
112 import { followUpstreamCard } from "./upstream-follow.ts";
112113
113114 type Section =
114115 | "general"
@@ -363,7 +364,7 @@ export async function settingsPage(ctx: Ctx): Promise<Response> {
363364 repo,
364365 "general",
365366 "Settings",
366 html`${lead}<div class="mt">${body}</div><div class="mt">${wave}</div><div class="mt">${archive}</div>${proposals
367 html`${lead}<div class="mt">${body}</div><div class="mt">${followUpstreamCard(ctx, repo)}</div><div class="mt">${wave}</div><div class="mt">${archive}</div>${proposals
367368 ? html`<div class="mt">${proposals}</div>`
368369 : null}${secrets
369370 ? html`<div class="mt">${secrets}</div>`
src/web/pages/upstream-follow.ts added +167
@@ -0,0 +1,167 @@
1 /**
2 * Following an upstream (#3442), on the page: the settings card that turns
3 * it on, points it and checks now; and the one line the repository's About
4 * card shows — "Following <upstream> · last checked HH:MM · N behind".
5 * Every mutation is a same-origin POST through `readForm`; the doors only
6 * word what `actions/upstream_follow.ts` answers.
7 */
8
9 import {
10 checkedWords,
11 checkUpstreamNow,
12 clockWords,
13 FOLLOW_REFUSALS,
14 followShown,
15 setFollowUpstream,
16 standing,
17 upstreamLabel,
18 } from "../../actions/upstream_follow.ts";
19 import { canAdmin, canWrite, type Repo } from "../../core/repos.ts";
20 import { getFollow } from "../../core/upstream_follow.ts";
21 import { getIssueById } from "../../core/issues.ts";
22 import type { Ctx } from "../../http/context.ts";
23 import { loadRepo, repoBase, repoNotFound } from "../chrome.ts";
24 import { field, readForm } from "../form.ts";
25 import { html, when, type Html } from "../html.ts";
26 import { icon } from "../icons.ts";
27 import { flashTo } from "../layout.ts";
28 import { btn, card, field as formField } from "../ui.ts";
29
30 /** HH:MM in UTC, with the instant for machines and the title for people. */
31 function clock(iso: string): Html {
32 const at = new Date(iso);
33 if (Number.isNaN(at.getTime())) return html``;
34 const exact = `${at.toISOString().slice(0, 16).replace("T", " ")} UTC`;
35 return html`<time datetime="${at.toISOString()}" title="${exact}"
36 >${clockWords(iso)}</time
37 >`;
38 }
39
40 /**
41 * The About card's line: an enabled following for every reader, an off one
42 * for admins (`followShown`). Only a web address is a link; a `git://`
43 * upstream is named, not linked — no browser opens it.
44 */
45 export function followingLine(ctx: Ctx, repo: Repo): Html | null {
46 const follow = followShown(ctx.app, repo, ctx.auth.user);
47 if (follow === undefined) return null;
48 const writer = canWrite(ctx.app.db, repo, ctx.auth.user);
49 const pending =
50 follow.pendingId === null ? undefined : getIssueById(ctx.app.db, follow.pendingId);
51 const open = pending !== undefined && pending.state === "open" ? pending : undefined;
52 const label = upstreamLabel(follow.url);
53 return html`<p class="mt small muted" data-following-upstream>
54 ${icon("sync")} Following
55 ${/^https?:\/\//i.test(follow.url)

upstreamUrl refuses anything but http(s), so this test is always true and the <span class="mono"> branch below is dead. The doc comment's git:// sentence is stale too. Drop both.

56 ? html`<a href="${follow.url}" rel="noreferrer noopener">${label}</a>`
57 : html`<span class="mono">${label}</span>`}
58 <span class="mono">${follow.branch}</span>
59 ${follow.checkedAt === null ? null : html`· last checked ${clock(follow.checkedAt)}`}
60 · ${standing(follow, writer)}${when(
61 open,
62 (i) =>
63 html` · <a href="${repoBase(repo)}/${i.kind === "pull" ? "pulls" : "issues"}/${i.number}"
64 >#${i.number}</a
65 >`,
66 )}
67 </p>`;
68 }
69
70 /** The settings card: on or off, the URL and branch, and "Check upstream now". */
71 export function followUpstreamCard(ctx: Ctx, repo: Repo): Html {
72 const follow = getFollow(ctx.app.db, repo.id);
73 const base = repoBase(repo);
74 const parent = follow?.parentUrl ?? "";
75 return card(
76 html`<form method="post" action="${base}/settings/upstream">
77 <p class="muted">
78 New commits on the upstream's branch land here by themselves: a
79 fast-forward or a clean <code>git merge</code> opens a pull that
80 lands through the landing gate; a conflict goes to the crew, whose
81 pull is reviewed and lands like any other. Never a push to
82 <span class="mono">${repo.defaultBranch}</span>, never a force-push.
83 Checked every 30 minutes.
84 </p>
85 ${formField({
86 label: "Upstream git URL",
87 name: "url",
88 value: follow?.url ?? "",
89 placeholder: "https://github.com/owner/name.git",
90 mono: true,
91 spellcheck: false,
92 hint:
93 parent === ""
94 ? "A public upstream needs no credential; a private one uses your connected origin on its host."
95 : `Its own upstream is ${upstreamLabel(parent)} — paste ${parent} to follow that instead.`,
96 })}
97 ${formField({
98 label: "Branch",
99 name: "branch",
100 value: follow?.branch ?? "main",
101 mono: true,
102 spellcheck: false,
103 })}
104 <div class="field">
105 <label class="check">
106 <input type="checkbox" name="enabled" ${follow?.enabled === true ? html`checked` : null} />
107 <span>Follow upstream</span>
108 </label>
109 </div>
110 ${when(
111 follow,
112 (f) => html`<p class="hint" data-following-standing>${standing(f, true)}${
113 f.checkedAt === null ? "" : html` · last checked ${clock(f.checkedAt)}`
114 } · ${f.opened} proposed so far</p>`,
115 )}
116 <div class="form-actions">${btn("Save", { variant: "primary" })}</div>
117 </form>
118 ${when(
119 follow?.enabled === true,
120 () => html`<form method="post" action="${base}/settings/upstream/check" class="mt">
121 ${btn("Check upstream now", { size: "sm", icon: "sync" })}
122 </form>`,
123 )}`,
124 { head: html`${icon("sync")}<h2 id="upstream">Follow upstream</h2>` },
125 );
126 }
127
128 // POST /:owner/:name/settings/upstream
129 export async function followUpstreamUpdate(ctx: Ctx): Promise<Response> {
130 const repo = loadRepo(ctx);
131 if (!repo || !canAdmin(ctx.app.db, repo, ctx.auth.user)) return repoNotFound(ctx);
132 const form = await readForm(ctx, "admin");
133 if (form instanceof Response) return form;
134 const to = `${repoBase(repo)}/settings#upstream`;
135 const saved = await setFollowUpstream(ctx.app, ctx.auth.user, repo, {
136 url: field(form, "url"),
137 branch: field(form, "branch"),
138 enabled: form.get("enabled") !== null,
139 });
140 return flashTo(
141 ctx,
142 to,
143 saved.ok
144 ? {
145 message: saved.value.enabled
146 ? `Following ${upstreamLabel(saved.value.url)} ${saved.value.branch}. The first check runs within a minute.`
147 : "Following the upstream is off. Nothing is checked or proposed.",
148 }
149 : { tone: "danger", message: FOLLOW_REFUSALS[saved.error] },
150 );
151 }
152
153 // POST /:owner/:name/settings/upstream/check
154 export async function followUpstreamCheck(ctx: Ctx): Promise<Response> {
155 const repo = loadRepo(ctx);
156 if (!repo || !canWrite(ctx.app.db, repo, ctx.auth.user)) return repoNotFound(ctx);
157 const form = await readForm(ctx, "rw");
158 if (form instanceof Response) return form;
159 const checked = await checkUpstreamNow(ctx.app, ctx.auth.user, repo);
160 return flashTo(
161 ctx,
162 `${repoBase(repo)}/settings#upstream`,
163 checked.ok
164 ? { message: checkedWords(checked.value) }
165 : { tone: "danger", message: FOLLOW_REFUSALS[checked.error] },
166 );
167 }
test/migrate.test.ts +4
@@ -45,6 +45,7 @@ import { serve, type Servers } from "../src/http/server.ts";
4545 import { createToken } from "../src/core/tokens.ts";
4646 import { createSession } from "../src/core/sessions.ts";
4747 import { advance, createJob, settled } from "../src/origins/jobs.ts";
48 import { getFollow } from "../src/core/upstream_follow.ts";
4849 import { forgetProviders } from "../src/origins/providers/index.ts";
4950 import {
5051 newFakeOAuth,
@@ -463,6 +464,9 @@ describe("migrate", () => {
463464 ]);
464465 expect(getAppByRepo(app.db, repo.id)).toBeDefined();
465466 expect(repo.autonomy).toBe(autonomous ? "autonomous" : "off");
467 // The source is the upstream it follows: on when autonomous (#3442).
468 const follow = getFollow(app.db, repo.id)!;
469 expect([follow.url, follow.branch, follow.enabled]).toEqual([fixtureUrl, "trunk", autonomous]);
466470
467471 const issues = listIssues(app.db, repo.id, {
468472 kind: "issue",
test/tui-upstream-follow.test.ts added +239
@@ -0,0 +1,239 @@
1 /**
2 * Following an upstream in the terminal (#3442): About shows what the
3 * repository follows, how far behind and when it last looked — on for
4 * everyone, off for its admins only — and a writer's `u` checks now. An
5 * admin's `f` turns it on or off and `F` points it elsewhere, through the
6 * page's refusals; a check finishing anywhere redraws the row.
7 */
8
9 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
10 import { mkdtemp, rm } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
14 import { checkUpstream, setFollowUpstream } from "../src/actions/upstream_follow.ts";
15 import { createApp, type App as Forge } from "../src/app.ts";
16 import { listPulls } from "../src/core/pulls.ts";
17 import { getRepoById, type Repo } from "../src/core/repos.ts";
18 import { getFollow } from "../src/core/upstream_follow.ts";
19 import type { User } from "../src/core/users.ts";
20 import { runGit } from "../src/git/env.ts";
21 import { repoDir } from "../src/git/repos.ts";
22 import { serve, type Servers } from "../src/http/server.ts";
23 import { createForgeApp } from "../src/tui/forge.ts";
24 import type { TuiIdentity } from "../src/tui/session.ts";
25 import { headlessTerminal } from "../src/tui/term/terminal.ts";
26 import { seedAdmin } from "./helpers/admin.ts";
27 import { quietLogs } from "./helpers/globals.ts";
28 import { settleApp, settleUntil } from "./helpers/tui.ts";
29
30 quietLogs();
31
32 describe("following an upstream in the terminal", () => {
33 let dataDir: string;
34 let forge: Forge;
35 let servers: Servers;
36 let alice: User;
37 let up: Repo;
38 let beacon: Repo;
39 let upUrl: string;
40 const fresh = () => getRepoById(forge.db, beacon.id)!;
41 const commit = async (repo: Repo, path: string) => {
42 const done = await commitToBranch(forge, alice, repo, {
43 branch: "main",
44 message: path,
45 files: [{ path, content: `${path}\n` }],
46 });
47 if (!done.ok) throw new Error(JSON.stringify(done.error));
48 };
49 const asAlice = (): TuiIdentity => ({
50 sshUsername: "alice",
51 remoteAddress: "127.0.0.1",
52 fingerprint: "SHA256:test",
53 user: alice,
54 });
55 const asGuest: TuiIdentity = {
56 sshUsername: "git",
57 remoteAddress: "127.0.0.1",
58 fingerprint: "SHA256:unknown",
59 };
60
61 function boot(identity: TuiIdentity) {
62 const terminal = headlessTerminal(140, 40);
63 const { app } = createForgeApp(forge, identity, { terminal, exitHooks: false });
64 app.start();
65 const press = async (...keys: string[]): Promise<void> => {
66 for (const key of keys)
67 app.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false });
68 await settleApp(app);
69 };
70 return { app, press, text: () => app.screen.toText() };
71 }
72
73 async function openAbout(h: ReturnType<typeof boot>): Promise<void> {
74 await settleApp(h.app);
75 await h.press("/");
76 for (const ch of "beacon") await h.press(ch);
77 await h.press("enter");
78 await h.press("enter");
79 await settleUntil(h.app, "alice/beacon");
80 await h.press("I");
81 await settleUntil(h.app, "clone (http)");
82 }
83
84 beforeAll(async () => {
85 dataDir = await mkdtemp(join(tmpdir(), "forge-tui-upstream-"));
86 forge = createApp({ dataDir, port: 0, migrateFromPrivateHosts: true });
87 servers = await serve(forge);
88 const a = await seedAdmin(forge, {
89 username: "alice",
90 email: "[email protected]",
91 password: "a-long-passphrase",
92 });
93 if (!a.ok) throw new Error("signup failed");
94 alice = a.value;
95 const u = await createRepo(forge, alice, { name: "up", visibility: "public" });
96 if (!u.ok) throw new Error("repo failed");
97 up = u.value;
98 await commit(up, "README.md");
99 upUrl = `http://127.0.0.1:${servers.port}/alice/up.git`;
100 const b = await createRepo(forge, alice, { name: "beacon", visibility: "public" });
101 if (!b.ok) throw new Error("repo failed");
102 beacon = b.value;
103 const fetched = await runGit(
104 ["fetch", "--quiet", repoDir(forge.reposRoot, "alice", "up"), "main:main"],
105 { cwd: repoDir(forge.reposRoot, "alice", "beacon") },
106 );
107 expect(fetched.ok).toBe(true);
108 });
109
110 afterAll(async () => {
111 servers.stop();
112 await rm(dataDir, { recursive: true, force: true });
113 });
114
115 test("off: an admin sees the row and no check key; a guest sees nothing", async () => {
116 const off = await setFollowUpstream(forge, alice, fresh(), { url: upUrl, branch: "main", enabled: false });
117 expect(off.ok).toBe(true);
118 const admin = boot(asAlice());
119 try {
120 await openAbout(admin);
121 expect(admin.text()).toMatch(/following +127\.0\.0\.1:\d+\/alice\/up main\s.*\n.*\boff\b/);
122 expect(admin.text()).not.toContain("check upstream now");
123 } finally {
124 admin.app.stop();
125 }
126 const guest = boot(asGuest);
127 try {
128 await openAbout(guest);
129 expect(guest.text()).not.toMatch(/following +127/);
130 } finally {
131 guest.app.stop();
132 }
133 });
134
135 test("on: a writer's `u` checks now, proposes, and the row says how far behind and when", async () => {
136 const on = await setFollowUpstream(forge, alice, fresh(), { url: upUrl, branch: "main", enabled: true });
137 expect(on.ok).toBe(true);
138 await commit(up, "new.txt");
139 const h = boot(asAlice());
140 try {
141 await openAbout(h);
142 expect(h.text()).toMatch(/following +127\.0\.0\.1:\d+\/alice\/up main\s.*\n.*not checked yet/);
143 expect(h.text()).toContain("check upstream now");
144 await h.press("u");
145 await settleUntil(h.app, "1 behind");
146 expect(h.text()).toMatch(/1 behind · last checked \d\d:\d\d UTC/);
147 expect(listPulls(forge.db, beacon.id, { state: "open" }).map((p) => p.title)).toEqual([
148 expect.stringMatching(/^Upstream: 1 commit from /),
149 ]);
150 } finally {
151 h.app.stop();
152 }
153 });
154
155 test("a guest sees the row of an enabled following, but not why a check failed, and `u` does nothing", async () => {
156 forge.db
157 .query("UPDATE repo_upstream SET error = 'fatal: secret-ish remote words' WHERE repo_id = ?1")
158 .run(beacon.id);
159 const checkedAt = getFollow(forge.db, beacon.id)!.checkedAt;
160 const h = boot(asGuest);
161 try {
162 await openAbout(h);
163 expect(h.text()).toMatch(/following +127\.0\.0\.1:\d+\/alice\/up main\s.*\n.*the last check did not finish/);
164 expect(h.text()).not.toContain("secret-ish");
165 expect(h.text()).not.toContain("check upstream now");
166 await h.press("u");
167 expect(getFollow(forge.db, beacon.id)!.checkedAt).toBe(checkedAt);
168 } finally {
169 h.app.stop();
170 }
171 });
172
173 test("a check finished elsewhere redraws the row in place", async () => {
174 await commit(up, "more.txt");
175 const h = boot(asAlice());
176 try {
177 await openAbout(h);
178 expect(h.text()).not.toContain("2 behind");
179 expect((await checkUpstream(forge, fresh())).ok).toBe(true);
180 await settleUntil(h.app, "2 behind");
181 expect(h.text()).toMatch(/2 behind · last checked \d\d:\d\d UTC/);
182 } finally {
183 h.app.stop();
184 }
185 });
186
187 test("an admin's `f` turns following off and on; `F` points it elsewhere, with the page's refusals", async () => {
188 const h = boot(asAlice());
189 try {
190 await openAbout(h);
191 expect(h.text()).toContain("stop following upstream");
192 await h.press("f");
193 await settleUntil(h.app, "following the upstream is off");
194 expect(getFollow(forge.db, beacon.id)!.enabled).toBe(false);
195 await h.press("f");
196 await settleUntil(h.app, "following 127.0.0.1");
197 expect(getFollow(forge.db, beacon.id)!.enabled).toBe(true);
198
199 // An address git must never be handed: refused, nothing changes.
200 const clear = Array.from({ length: upUrl.length + 5 }, () => "backspace");
201 await h.press("F");
202 await settleUntil(h.app, "git address");
203 await h.press(...clear, ..."file:///etc", "enter");
204 await settleUntil(h.app, "its branch");
205 await h.press("enter");
206 await settleUntil(h.app, "That is not a git address");
207 expect(getFollow(forge.db, beacon.id)!.url).toBe(upUrl);
208
209 // Elsewhere: the same address, another branch.
210 await h.press("F");
211 await settleUntil(h.app, "git address");
212 await h.press("enter");
213 await settleUntil(h.app, "its branch");
214 await h.press("backspace", "backspace", "backspace", "backspace", ..."dev", "enter");
215 await settleUntil(h.app, "following 127.0.0.1");
216 const now = getFollow(forge.db, beacon.id)!;
217 expect([now.url, now.branch, now.enabled]).toEqual([upUrl, "dev", true]);
218 } finally {
219 h.app.stop();
220 }
221 });
222
223 test("a guest is not offered `f` or `F`, and pressing them changes nothing", async () => {
224 const before = getFollow(forge.db, beacon.id)!;
225 const h = boot(asGuest);
226 try {
227 await openAbout(h);
228 expect(h.text()).not.toContain("following upstream");
229 expect(h.text()).not.toContain("point following elsewhere");
230 await h.press("f");
231 await h.press("F");
232 expect(h.text()).not.toContain("git address");
233 const after = getFollow(forge.db, beacon.id)!;
234 expect([after.enabled, after.url, after.branch]).toEqual([before.enabled, before.url, before.branch]);
235 } finally {
236 h.app.stop();
237 }
238 });
239 });
test/upstream_follow.test.ts added +584
@@ -0,0 +1,584 @@
1 /**
2 * A repository follows its upstream (#3442). The upstream is a public
3 * repository on this same forge, over HTTP on loopback (a private host, so
4 * the forge says that is fine). It gains two commits that merge cleanly:
5 * a pull opens and lands as a merge, and the next check is up to date. It
6 * gains a conflicting commit: an issue goes to the builder as a converge
7 * run, the crew's merge lands, up to date again. Turned off: nothing
8 * happens. And the doors: the About card's line, the settings card, the
9 * same-origin floor, the API.
10 */
11 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
12 import { mkdtemp, rm } from "node:fs/promises";
13 import { tmpdir } from "node:os";
14 import { join } from "node:path";
15 import { createApp, type App } from "../src/app.ts";
16 import { addToCrew, createAgent } from "../src/actions/crew.ts";
17 import { openPull } from "../src/actions/pulls.ts";
18 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
19 import {
20 carriesUpstream,
21 checkUpstream,
22 checkUpstreamNow,
23 followTick,
24 followWords,
25 setFollowUpstream,
26 stagedRef,
27 upstreamFollowing,
28 } from "../src/actions/upstream_follow.ts";
29 import { getIssueById } from "../src/core/issues.ts";
30 import { getPull, listPulls } from "../src/core/pulls.ts";
31 import { getRepoById, type Repo } from "../src/core/repos.ts";
32 import { claimRun, createRun, finishRun, listRuns } from "../src/core/runs.ts";
33 import { sweepGreen } from "../src/crew/autonomy.ts";
34 import { createSession } from "../src/core/sessions.ts";
35 import { createToken } from "../src/core/tokens.ts";
36 import { audienceFilter } from "../src/core/event_audience.ts";
37 import { createOrigin } from "../src/core/origins.ts";
38 import { getFollow, putFollow } from "../src/core/upstream_follow.ts";
39 import { provideMirrorOutboundForTest, vettedEnv } from "../src/origins/git-mirror.ts";
40 import { createUser, type User } from "../src/core/users.ts";
41 import { taskPrompt, type TaskInput } from "../src/crew/brief.ts";
42 import { runGit } from "../src/git/env.ts";
43 import { aheadCount, resolveOid } from "../src/git/merge.ts";
44 import { repoDir } from "../src/git/repos.ts";
45 import { serve, type Servers } from "../src/http/server.ts";
46 import { promote } from "./helpers/members.ts";
47
48 let dataDir: string;
49 let app: App;
50 let servers: Servers;
51 let alice: User;
52 let bob: User;
53 let up: Repo;
54 let ours: Repo;
55 let upUrl: string;
56
57 const fresh = () => getRepoById(app.db, ours.id)!;
58 const ourDir = () => repoDir(app.reposRoot, "alice", "ours");
59 const must = <T>(r: { ok: true; value: T } | { ok: false; error: unknown }): T => {
60 if (!r.ok) throw new Error(JSON.stringify(r.error));
61 return r.value;
62 };
63 const commit = async (repo: Repo, path: string, content: string, message = path) =>
64 must(
65 await commitToBranch(app, alice, repo, {
66 branch: "main",
67 message,
68 files: [{ path, content }],
69 }),
70 );
71 const behind = async () => {
72 const main = (await resolveOid(ourDir(), "refs/heads/main"))!;
73 const staged = (await resolveOid(ourDir(), stagedRef("main")))!;
74 return aheadCount(ourDir(), main, staged);
75 };
76 /**
77 * The landing gate lands it, as it would on its own: the repository runs
78 * autonomous, the head's check is green, the sweep picks the strategy.
79 * Upstream's tip is an ancestor of main afterwards — a squash would leave
80 * it out, and the next check would count the same commits again.
81 */
82 const landThroughGate = async (number: number) => {
83 app.db
84 .query("UPDATE repo SET autonomy = 'autonomous', autonomy_by = ?2 WHERE id = ?1")
85 .run(ours.id, alice.id);
86 const pull = getPull(app.db, ours.id, number)!;
87 const check = createRun(app.db, {
88 repoId: ours.id,
89 kind: "check",
90 issueId: pull.id,
91 env: `pull-${pull.number}`,
92 commitOid: pull.headOid,
93 reason: "pull",
94 });
95 claimRun(app.db, check.id);
96 finishRun(app.db, check.id, { state: "ok", summary: "check passed" });
97 expect(await sweepGreen(app, fresh())).toBe(1);
98 const landed = getPull(app.db, ours.id, number)!;
99 expect(landed.mergedOid).not.toBeNull();
100 const main = (await resolveOid(ourDir(), "refs/heads/main"))!;
101 expect(landed.mergedOid).toBe(main);
102 const staged = (await resolveOid(ourDir(), stagedRef("main")))!;
103 expect((await runGit(["merge-base", "--is-ancestor", staged, main], { cwd: ourDir() })).ok).toBe(true);
104 expect(await behind()).toBe(0);
105 };
106 const cookie = (u: User) => `forge_session=${createSession(app.db, u.id).token}`;
107
108 beforeAll(async () => {
109 dataDir = await mkdtemp(join(tmpdir(), "forge-upstream-follow-"));
110 app = createApp({ dataDir, port: 0, migrateFromPrivateHosts: true });
111 servers = await serve(app);
112 const person = async (username: string, adminIfFirst = false) =>
113 must(
114 await createUser(app.db, {
115 origin: "seed",
116 trusted: true,
117 username,
118 email: `${username}@forge.test`,
119 adminIfFirst,
120 }),
121 );
122 alice = await person("alice", true);
123 bob = await person("bob");
124 up = must(await createRepo(app, alice, { name: "up", visibility: "public" }));
125 await commit(up, "README.md", "upstream\n");
126 await commit(up, "a.txt", "one\ntwo\nthree\n");
127 upUrl = `http://127.0.0.1:${servers.port}/alice/up.git`;
128
129 // Ours starts as upstream's history, then does its own work.
130 ours = must(await createRepo(app, alice, { name: "ours", visibility: "private" }));
131 const upDir = repoDir(app.reposRoot, "alice", "up");
132 expect((await runGit(["fetch", "--quiet", upDir, "main:main"], { cwd: ourDir() })).ok).toBe(true);
133 await commit(fresh(), "ours.txt", "our own work\n");
134
135 must(await createAgent(app, alice, { username: "mason" }));
136 expect(addToCrew(app, alice, fresh(), "mason").ok).toBe(true);
137 });
138
139 afterAll(async () => {
140 servers.stop();
141 app.db.close();
142 await rm(dataDir, { recursive: true, force: true });
143 });
144
145 describe("the setting", () => {
146 test("an address git must never be handed, or a branch that is not one, is refused", async () => {
147 for (const url of ["file:///etc", "-uhoh", "ext::sh -c id", "https://u:[email protected]/x.git"]) {
148 const r = await setFollowUpstream(app, alice, fresh(), { url, branch: "main", enabled: true });
149 expect(r.ok ? "saved" : r.error).toBe("invalid_url");
150 }
151 const r = await setFollowUpstream(app, alice, fresh(), { url: upUrl, branch: "-x", enabled: true });
152 expect(r.ok ? "saved" : r.error).toBe("invalid_branch");
153 expect(getFollow(app.db, ours.id)).toBeUndefined();
154 });
155
156 test("a host inside the network is refused unless the forge says it is fine", async () => {
157 const config = app.config as { migrateFromPrivateHosts?: boolean };
158 config.migrateFromPrivateHosts = false;
159 try {
160 // bob is no forge admin: the check is his, on his own repository.
161 promote(app.db, bob);
162 const bobs = must(await createRepo(app, bob, { name: "bobs", visibility: "private" }));
163 const r = await setFollowUpstream(app, bob, bobs, { url: upUrl, branch: "main", enabled: true });
164 expect(r.ok ? "saved" : r.error).toBe("private_host");
165 expect(getFollow(app.db, bobs.id)).toBeUndefined();
166 } finally {
167 config.migrateFromPrivateHosts = true;
168 }
169 });
170
171 test("only an admin turns it on", async () => {
172 const r = await setFollowUpstream(app, bob, fresh(), { url: upUrl, branch: "main", enabled: true });
173 expect(r.ok ? "saved" : r.error).toBe("not_found");
174 });
175 });
176
177 describe("following", () => {
178 test("off: nothing is checked and nothing is proposed", async () => {
179 must(await setFollowUpstream(app, alice, fresh(), { url: upUrl, branch: "main", enabled: false }));
180 await commit(up, "b.txt", "b\n");
181 const r = await checkUpstream(app, fresh());
182 expect(r.ok ? r.value.kind : r.error).toBe("off");
183 expect(followTick(app)).toBe(0);
184 expect(listPulls(app.db, ours.id, { state: "open" })).toHaveLength(0);
185 expect(await resolveOid(ourDir(), stagedRef("main"))).toBeUndefined();
186 });
187
188 test("two clean upstream commits open one pull, which lands as a merge; the next check is up to date", async () => {
189 await commit(up, "c.txt", "c\n");
190 must(await setFollowUpstream(app, alice, fresh(), { url: upUrl, branch: "main", enabled: true }));
191 const r = must(await checkUpstream(app, fresh()));
192 expect(r.kind).toBe("pull");
193 if (r.kind !== "pull") return;
194 expect(r.behind).toBe(2);
195 const pull = getPull(app.db, ours.id, r.number)!;
196 expect(pull.title).toMatch(
197 new RegExp(`^Upstream: 2 commits from 127\\.0\\.0\\.1:${servers.port}/alice/up \\([0-9a-f]{7}\\.\\.[0-9a-f]{7}\\)$`),
198 );
199 expect(pull.authorId).toBe(alice.id);
200 expect(pull.headBranch).toMatch(/^upstream\/[0-9a-f]{7}$/);
201 // Our own work stays: the head is a merge on top of main, not upstream alone.
202 const head = await runGit(["show", "--format=%P", "--no-patch", pull.headOid], { cwd: ourDir() });
203 expect(head.ok && head.value.trim().split(" ")).toHaveLength(2);
204 expect(followWords(app, ours.id)).toBe(`2 behind, 1 opened, #${pull.number} open`);
205
206 // While it is open, a second check opens nothing more.
207 const again = must(await checkUpstream(app, fresh()));
208 expect(again.kind).toBe("pending");
209 expect(listPulls(app.db, ours.id, { state: "open" })).toHaveLength(1);
210
211 // The gate's choice: it carries upstream, so it lands as a merge.
212 const main = (await resolveOid(ourDir(), "refs/heads/main"))!;
213 expect(await carriesUpstream(app, fresh(), ourDir(), pull.headOid, main)).toBe(true);
214 await landThroughGate(pull.number);
215 const done = must(await checkUpstream(app, fresh()));
216 expect(done.kind).toBe("up_to_date");
217 expect(getFollow(app.db, ours.id)!.behind).toBe(0);
218 // A pull with nothing of upstream's is squashed as ever.
219 const newMain = (await resolveOid(ourDir(), "refs/heads/main"))!;
220 expect(await carriesUpstream(app, fresh(), ourDir(), newMain, newMain)).toBe(false);
221 });
222
223 test("a conflicting upstream commit goes to the builder as a converge run; the crew's merge lands", async () => {
224 await commit(fresh(), "a.txt", "one\nours\nthree\n");
225 await commit(up, "a.txt", "one\ntheirs\nthree\n");
226 const r = must(await checkUpstream(app, fresh()));
227 expect(r.kind).toBe("conflict");
228 if (r.kind !== "conflict") return;
229 expect(r.files).toEqual(["a.txt"]);
230 expect(r.builder).toBe("mason");
231 const issue = getIssueById(app.db, getFollow(app.db, ours.id)!.pendingId!)!;
232 expect(issue.kind).toBe("issue");
233 expect(issue.title).toMatch(/^Upstream: 1 commit from /);
234 expect(issue.body).toContain("`a.txt`");
235 expect(issue.body).toContain("refs/upstream/main");
236 const runs = listRuns(app.db, ours.id, { kind: "agent" }).filter((x) => x.issueId === issue.id);
237 expect(runs.map((x) => [x.reason, x.summary])).toEqual([["converge", "upstream moved: a.txt"]]);
238
239 // The brief the builder reads: merge the staged tip, keep both, explain.
240 const following = upstreamFollowing(app, ours.id)!;
241 expect(following.ref).toBe("refs/upstream/main");
242 const brief = taskPrompt({
243 agent: { user: { username: "mason" } },
244 repo: fresh(),
245 issue,
246 branch: "mason/1",
247 forgeUrl: servers.url,
248 isApp: false,
249 resuming: false,
250 reason: "converge",
251 comments: [],
252 reviews: [],
253 reviewComments: [],
254 since: "1",
255 conflictFiles: ["a.txt"],
256 following,
257 } as unknown as TaskInput);
258 expect(brief).toContain("git fetch origin refs/upstream/main && git merge FETCH_HEAD");
259 expect(brief).toContain("keep upstream's fixes, and keep this repository's own work");
260 expect(brief).toContain("explain each resolution");
261
262 // A second check while the crew works opens nothing more.
263 expect(must(await checkUpstream(app, fresh())).kind).toBe("pending");
264
265 // The crew's resolution: a real merge of the staged tip, kept both.
266 const work = await mkdtemp(join(tmpdir(), "forge-upstream-work-"));
267 try {
268 const g = (args: string[]) =>
269 runGit(args, {
270 cwd: work,
271 env: {
272 GIT_AUTHOR_NAME: "mason",
273 GIT_AUTHOR_EMAIL: "[email protected]",
274 GIT_COMMITTER_NAME: "mason",
275 GIT_COMMITTER_EMAIL: "[email protected]",
276 },
277 });
278 expect((await g(["clone", "--quiet", ourDir(), "."])).ok).toBe(true);
279 expect((await g(["fetch", "--quiet", "origin", "refs/upstream/main"])).ok).toBe(true);
280 expect((await g(["merge", "--no-edit", "FETCH_HEAD"])).ok).toBe(false);
281 await Bun.write(join(work, "a.txt"), "one\nours\ntheirs\nthree\n");
282 expect((await g(["commit", "--quiet", "-am", "Merge upstream, both lines kept"])).ok).toBe(true);
283 // As the agent's push would, without a hook: the branch arrives.
284 expect(
285 (await runGit(["fetch", "--quiet", work, "HEAD:refs/heads/mason/resolve"], { cwd: ourDir() })).ok,
286 ).toBe(true);
287 } finally {
288 await rm(work, { recursive: true, force: true });
289 }
290 const pull = must(
291 await openPull(app, alice, fresh(), {
292 title: "Take upstream",
293 body: `Closes #${issue.number}`,
294 baseBranch: "main",
295 headBranch: "mason/resolve",
296 }),
297 );
298 const main = (await resolveOid(ourDir(), "refs/heads/main"))!;
299 expect(await carriesUpstream(app, fresh(), ourDir(), pull.headOid, main)).toBe(true);
300 await landThroughGate(pull.number);
301 expect(must(await checkUpstream(app, fresh())).kind).toBe("up_to_date");
302 });
303
304 test("a proposal closed unlanded is not opened again until upstream moves, unless a person asks", async () => {
305 await commit(up, "d.txt", "d\n");
306 const r = must(await checkUpstream(app, fresh()));
307 expect(r.kind).toBe("pull");
308 if (r.kind !== "pull") return;
309 app.db.query("UPDATE issue SET state = 'closed' WHERE id = ?1").run(getPull(app.db, ours.id, r.number)!.id);
310 expect(must(await checkUpstream(app, fresh())).kind).toBe("declined");
311 const asked = must(await checkUpstream(app, fresh(), true));
312 expect(asked.kind).toBe("pull");
313 });
314 });
315
316 describe("the doors", () => {
317 test("the About card says what it follows, how far behind, and when it last looked", async () => {
318 const page = await (await fetch(`${servers.url}/alice/ours`, { headers: { cookie: cookie(alice) } })).text();
319 expect(page).toContain("data-following-upstream");
320 expect(page).toMatch(/Following\s*<a href="http:\/\/127\.0\.0\.1:\d+\/alice\/up\.git"/);
321 expect(page).toMatch(/last checked\s*<time[^>]*>\d\d:\d\d UTC<\/time/);
322 expect(page).toContain("1 behind");
323 });
324
325 test("the settings card shows it; a cross-origin save is refused and changes nothing", async () => {
326 const settings = await (await fetch(`${servers.url}/alice/ours/settings`, { headers: { cookie: cookie(alice) } })).text();
327 expect(settings).toContain("Follow upstream");
328 expect(settings).toContain("Check upstream now");
329 const res = await fetch(`${servers.url}/alice/ours/settings/upstream`, {
330 method: "POST",
331 redirect: "manual",
332 headers: {
333 cookie: cookie(alice),
334 origin: "https://evil.example",
335 "content-type": "application/x-www-form-urlencoded",
336 },
337 body: new URLSearchParams({ url: upUrl, branch: "main" }),
338 });
339 expect(res.status).toBeGreaterThanOrEqual(400);
340 expect(getFollow(app.db, ours.id)!.enabled).toBe(true);
341 });
342
343 test("the settings form turns it off, same-origin", async () => {
344 const res = await fetch(`${servers.url}/alice/ours/settings/upstream`, {
345 method: "POST",
346 redirect: "manual",
347 headers: {
348 cookie: cookie(alice),
349 origin: servers.url,
350 "content-type": "application/x-www-form-urlencoded",
351 },
352 body: new URLSearchParams({ url: upUrl, branch: "main" }),
353 });
354 expect(res.status).toBe(303);
355 expect(getFollow(app.db, ours.id)!.enabled).toBe(false);
356 const r = await checkUpstream(app, fresh());
357 expect(r.ok ? r.value.kind : r.error).toBe("off");
358 });
359
360 test("the API reads it, an admin sets it, and a reader sees nothing of an off one", async () => {
361 const admin = createToken(app.db, alice.id, "t", "admin").token;
362 const put = await fetch(`${servers.url}/api/v1/repos/alice/ours/upstream`, {
363 method: "PUT",
364 headers: { authorization: `Bearer ${admin}`, "content-type": "application/json" },
365 body: JSON.stringify({ url: upUrl, branch: "main", enabled: true }),
366 });
367 expect(put.status).toBe(200);
368 const got = (await (
369 await fetch(`${servers.url}/api/v1/repos/alice/ours/upstream`, { headers: { authorization: `Bearer ${admin}` } })
370 ).json()) as { following: { url: string; enabled: boolean; originId?: string } };
371 expect(got.following.url).toBe(upUrl);
372 expect(got.following.enabled).toBe(true);
373 expect("originId" in got.following).toBe(false);
374 const bad = await fetch(`${servers.url}/api/v1/repos/alice/ours/upstream`, {
375 method: "PUT",
376 headers: { authorization: `Bearer ${admin}`, "content-type": "application/json" },
377 body: JSON.stringify({ url: "file:///etc/passwd", branch: "main", enabled: true }),
378 });
379 expect(bad.status).toBe(422);
380 expect(((await bad.json()) as { error: string }).error).toBe("invalid_url");
381 const ro = createToken(app.db, alice.id, "r", "ro").token;
382 const refused = await fetch(`${servers.url}/api/v1/repos/alice/ours/upstream/check`, {
383 method: "POST",
384 headers: { authorization: `Bearer ${ro}` },
385 });
386 expect(refused.status).toBe(403);
387 });
388
389 test("a git:// upstream cannot be saved, by an admin or anyone: its transport escapes the pin", async () => {
390 for (const who of [alice, bob]) {
391 const r = await setFollowUpstream(app, who, who === alice ? fresh() : must(await createRepo(app, bob, { name: `g${who.id.slice(-4)}`, visibility: "private" })), {
392 url: "git://rebind.example:6379/x.git",
393 branch: "main",
394 enabled: true,
395 });
396 expect(r.ok ? "saved" : r.error).toBe("invalid_url");
397 }
398 });
399
400 test("an upstream is named, not linked, when it is not a web address; why a check failed is a writer's to read", async () => {
401 const pub = must(await createRepo(app, alice, { name: "pub", visibility: "public" }));
402 await commit(pub, "README.md", "pub\n");
403 must(
404 await setFollowUpstream(app, alice, pub, {
405 url: upUrl,
406 branch: "main",
407 enabled: true,
408 }),
409 );
410 app.db
411 .query("UPDATE repo_upstream SET checked_at = ?2, error = 'fatal: remote words' WHERE repo_id = ?1")
412 .run(pub.id, new Date().toISOString());
413 const page = await (await fetch(`${servers.url}/alice/pub`)).text();
414 expect(page).toContain("data-following-upstream");
415 expect(page).toContain("the last check did not finish");
416 expect(page).not.toContain("remote words");
417 const anon = (await (await fetch(`${servers.url}/api/v1/repos/alice/pub/upstream`)).json()) as {
418 following: { error: string | null };
419 };
420 expect(anon.following.error).toBeNull();
421 const ro = createToken(app.db, alice.id, "ro2", "ro").token;
422 const own = (await (
423 await fetch(`${servers.url}/api/v1/repos/alice/pub/upstream`, { headers: { authorization: `Bearer ${ro}` } })
424 ).json()) as { following: { error: string | null } };
425 expect(own.following.error).toBe("fatal: remote words");
426 });
427 });
428
429 describe("one check at a time", () => {
430 test("two checks at once open exactly one pull: the second is refused busy, and only the first is heard", async () => {
431 const twice = must(await createRepo(app, alice, { name: "twice", visibility: "private" }));
432 const dir = repoDir(app.reposRoot, "alice", "twice");
433 const upDir = repoDir(app.reposRoot, "alice", "up");
434 expect((await runGit(["fetch", "--quiet", upDir, "main:main"], { cwd: dir })).ok).toBe(true);
435 const at = getRepoById(app.db, twice.id)!;
436 await commit(at, "twice.txt", "our own work\n");
437 must(await setFollowUpstream(app, alice, at, { url: upUrl, branch: "main", enabled: true }));
438 await commit(up, "e.txt", "e\n");
439 const heard: string[] = [];
440 const off = app.bus.subscribe((e) => {
441 if (e.repoId === twice.id) heard.push(e.kind);
442 });
443 try {
444 // A double click: both start before either has read "no proposal open".
445 const both = await Promise.all([
446 checkUpstreamNow(app, alice, at),
447 checkUpstreamNow(app, alice, at),
448 ]);
449 expect(both.map((r) => (r.ok ? r.value.kind : r.error)).sort()).toEqual(["busy", "pull"]);
450 expect(
451 listPulls(app.db, twice.id, { state: "open" }).filter((p) => p.title.startsWith("Upstream: ")),
452 ).toHaveLength(1);
453 expect(heard.filter((k) => k === "repo.upstream_checked")).toHaveLength(1);
454 // The claim is let go: the next check answers, and opens nothing more.
455 expect(must(await checkUpstreamNow(app, alice, at)).kind).toBe("pending");
456 expect(listPulls(app.db, twice.id, { state: "open" })).toHaveLength(1);
457 } finally {
458 off();
459 }
460 });
461
462 test("the API answers a check already running with 409 busy", async () => {
463 const at = getRepoById(app.db, ours.id)!;
464 const rw = createToken(app.db, alice.id, "rw-busy", "rw").token;
465 const post = () =>
466 fetch(`${servers.url}/api/v1/repos/alice/ours/upstream/check`, {
467 method: "POST",
468 headers: { authorization: `Bearer ${rw}` },
469 });
470 const running = checkUpstream(app, at);
471 const res = await post();
472 await running;
473 expect(res.status).toBe(409);
474 expect(((await res.json()) as { error: string }).error).toBe("busy");
475 });
476 });
477
478 describe("a credential goes only to its exact https origin", () => {
479 const connect = (webUrl: string, login: string) =>
480 must(
481 createOrigin(app.db, app.config.dataDir, {
482 userId: alice.id,
483 kind: "forgejo",
484 apiUrl: `${webUrl}/api/v1`,
485 webUrl,
486 login,
487 token: "s3cret-token",
488 }),
489 );
490
491 test("the setting remembers an origin only for the same https scheme, host and port", async () => {
492 const o = connect("https://git.example.test", "cred-a");
493 const save = async (url: string) => {
494 must(await setFollowUpstream(app, alice, fresh(), { url, branch: "main", enabled: false }));
495 return getFollow(app.db, ours.id)!.originId;
496 };
497 expect(await save("https://git.example.test/a/b.git")).toBe(o.id);
498 expect(await save("http://git.example.test/a/b.git")).toBe("");
499 expect(await save("https://git.example.test:8443/a/b.git")).toBe("");
500 expect(await save("https://other.example.test/a/b.git")).toBe("");
501 });
502
503 test("an http upstream on a connected host is fetched with no Authorization", async () => {
504 const seen: (string | null)[] = [];
505 const server = Bun.serve({
506 port: 0,
507 hostname: "127.0.0.1",
508 fetch(req) {
509 seen.push(req.headers.get("authorization"));
510 return new Response("no", { status: 404 });
511 },
512 });
513 try {
514 const url = `http://127.0.0.1:${server.port}/x/y.git`;
515 const o = connect(`http://127.0.0.1:${server.port}`, "cred-b");
516 // A row migrate wrote, naming the origin for an http upstream.
517 putFollow(app.db, {
518 repoId: ours.id,
519 url,
520 branch: "main",
521 enabled: true,
522 byId: alice.id,
523 originId: o.id,
524 });
525 const r = await checkUpstreamNow(app, alice, fresh());
526 expect(r.ok ? r.value.kind : r.error).toBe("unreadable");
527 expect(seen.length).toBeGreaterThan(0);
528 expect(seen.every((h) => h === null)).toBe(true);
529 } finally {
530 server.stop(true);
531 }
532 });
533
534 test("the fetch is pinned to the address the vet resolved", async () => {
535 provideMirrorOutboundForTest({ resolve: async () => ["93.184.216.34"] });
536 try {
537 const env = must(await vettedEnv("https://git.example.test/a/b.git", {}, "https:http:git"));
538 const config = Object.entries(env).filter(([k]) => k.startsWith("GIT_CONFIG_VALUE_")).map(([, v]) => v);
539 expect(config).toContain("git.example.test:443:93.184.216.34");
540 expect(env["GIT_ALLOW_PROTOCOL"]).toBe("https:http:git");
541 } finally {
542 provideMirrorOutboundForTest({ allow: ["127.0.0.1", "::1"] });
543 }
544 });
545 });
546
547 describe("what a following leaks or lets through", () => {
548 test("the address of a following goes to the repository's admins, not to readers", () => {
549 const event = {
550 id: 1,
551 kind: "repo.upstream_follow",
552 repoId: ours.id,
553 actorId: alice.id,
554 payload: { url: "https://private.example/x.git", branch: "main", enabled: false },
555 createdAt: new Date().toISOString(),
556 };
557 expect(audienceFilter(app.db, undefined)(event as any)).toBe(false);
558 expect(audienceFilter(app.db, alice)(event as any)).toBe(true);
559 });
560
561 test("a branch squatted at the proposal's name is never the proposal", async () => {
562 const sq = must(await createRepo(app, alice, { name: "squat", visibility: "private" }));
563 const dir = repoDir(app.reposRoot, "alice", "squat");
564 const upDir = repoDir(app.reposRoot, "alice", "up");
565 expect((await runGit(["fetch", "--quiet", upDir, "main:main"], { cwd: dir })).ok).toBe(true);
566 const at = getRepoById(app.db, sq.id)!;
567 must(await setFollowUpstream(app, alice, at, { url: upUrl, branch: "main", enabled: true }));
568 await commit(up, "squat.txt", "s\n");
569 const tip = (await resolveOid(upDir, "refs/heads/main"))!;
570 // Someone with write access pushes other content under the proposal's name.
571 expect(
572 (await runGit(["branch", `upstream/${tip.slice(0, 7)}`, "main"], { cwd: dir })).ok,
573 ).toBe(true);
574 await commit(at, "evil.txt", "evil\n", "evil");
575 const squatted = (await resolveOid(dir, "refs/heads/main"))!;
576 expect((await runGit(["branch", "-f", `upstream/${tip.slice(0, 7)}`, squatted], { cwd: dir })).ok).toBe(true);
577 const r = must(await checkUpstreamNow(app, alice, getRepoById(app.db, sq.id)!));
578 expect(r.kind === "pull" || r.kind === "conflict").toBe(true);
579 const pull = listPulls(app.db, sq.id, { state: "open" }).find((p) => p.title.startsWith("Upstream: "));
580 expect(pull).toBeDefined();
581 expect(pull!.headBranch).not.toBe(`upstream/${tip.slice(0, 7)}`);
582 expect(await resolveOid(dir, `refs/heads/${pull!.headBranch}`)).not.toBe(squatted);
583 });
584 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs