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

A repository brought from another forge follows its source with one action, and new commits there show here as drift #16085

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

mason/forge:mason/16069-a-repository-brought-from-another-forge → main 0 commits fork 4 threads · 4 unresolved

  • Merged. mason/16069-a-repository-brought-from-another-forge was merged into main as 40a8949.

Review

Sign in to review this change.
15 files changed +613 −9
docs/features/forge-origin.md +7 −1
@@ -22,10 +22,16 @@ Type the friend's address at `/settings/origins` and press "Sign in there". If t
2222 - **Registration is per callback address:** if this forge's public URL changes, forget the app and connect again.
2323 - Test: `test/forge-origin-oauth.test.ts` runs two forges through the whole flow.
2424
25 Not yet: review and check state coming back live, guest rules for a crew on the receiving side, following upstream with one action.
25 Not yet: review and check state coming back live, guest rules for a crew on the receiving side.
2626
2727 Not yet, in order: migrate an app whole with its run and build, follow upstream between forges with a pull back, and the one-page paste-a-link path. Test: `test/forge-origin.test.ts` runs two forges against each other.
2828
29 ## Follow the forge it came from (#16069)
30
31 A repository brought across with a connected origin (`migrate`) keeps the address it came from and the origin whose credential reads it. Under its head an admin sees the state ("Brought from <host>/<owner>/<name>; new commits there are not shown here") and one **Follow** button that opens a question and, answered, turns the upstream follow on (`src/origins/follow.ts`, `src/web/pages/origin-follow.ts`, `POST /:owner/:name/follow-origin`, which needs the confirming field); the same place says **Stop following** once it is on. The terminal's About screen (`src/tui/screens/about.ts`) has the same press on `g`, behind a confirm, through the same `setOriginFollow`, so a web viewer sees it live. A new commit on the source's default branch then shows as "N commits behind" at the next check (every 30 minutes, or "Check upstream now"), as a pack's follow does. The credential is the origin's, handed to git through the environment at check time, never argv or config; it is sent only to the origin's own https address (a test may allow a loopback address over http with `credentialOverLoopback`; production never does).
32
33 Both presses write a `repo.origin_follow` event for the admins' history. An origin that needs signing in again (or was disconnected) stops the follow at its next check and says so on the repository and in the check history; the offer then points to Origins until it is signed in. A mirror (a repository that syncs with its origin) is not offered this: its sweep already takes what is new. Test: `test/forge-origin-follow.test.ts`, two forges.
34
2935 ## Issues and comments both ways (#8967)
3036
3137 On a brought repository an issue or comment opened here is written to the origin as the connected account (`src/origins/write-through.ts`), then reflected here under the origin's own number and id.
src/actions/upstream_follow.ts +16 −6
@@ -81,6 +81,7 @@ import {
8181 type FollowSource,
8282 } from "../core/follow_sources.ts";
8383 import { err, ok, type Result } from "../kernel/result.ts";
84 import { REAUTH_STOPPED_WORDS, stopForReauth } from "../origins/follow.ts";
8485 import { providerForOrigin } from "../origins/credential.ts";
8586 import { basicHeader, gitAuthEnv, redact, secretsIn } from "../origins/credentials.ts";
8687 import { vettedEnv } from "../origins/git-mirror.ts";
@@ -114,7 +115,7 @@ export function mayCarryFollowCredential(url: string): boolean {
114115 }
115116 }
116117
117 export type CheckError = "off" | "nobody" | "unreadable" | "no_branch" | "git" | "busy" | "squatted";
118 export type CheckError = "off" | "nobody" | "unreadable" | "no_branch" | "git" | "busy" | "squatted" | "reauth";
118119
119120 /** What each refusal says, at every door. */
120121 export const CHECK_REFUSALS: Record<CheckError, string> = {
@@ -124,6 +125,7 @@ export const CHECK_REFUSALS: Record<CheckError, string> = {
124125 no_branch: "The upstream has no such branch.",
125126 git: "Git could not read the staged upstream.",
126127 busy: "Already checking this upstream",
128 reauth: REAUTH_STOPPED_WORDS,
127129 squatted: "A branch of the proposal's name already exists and is not the upstream's head.",
128130 };
129131
@@ -145,13 +147,14 @@ export const proposalBranch = (tip: string): string => `upstream/${tip.slice(0,
145147
146148 /**
147149 * Whether an origin's token may travel to this upstream: only to the exact
148 * https origin (scheme, host and port) the person connected. An `http://`
149 * upstream on the same host is fetched anonymously.
150 * https origin (scheme, host and port) the person connected. An `http://` upstream is fetched
151 * anonymously, unless `loopback` (a test's two forges on one machine) allows a loopback address.
150152 */
151 export function mayCarryCredential(upstreamUrl: string, webUrl: string): boolean {
153 export function mayCarryCredential(upstreamUrl: string, webUrl: string, loopback = false): boolean {
152154 try {
153155 const up = new URL(upstreamUrl);
154 return up.protocol === "https:" && up.origin === new URL(webUrl).origin;
156 const secure = up.protocol === "https:" || (loopback && mayCarryFollowCredential(upstreamUrl));
157 return secure && up.origin === new URL(webUrl).origin;
outdated

Production now carries the credential over http to loopback origins for a test's sake. Keep https-only here and have the test opt in, and test that other http hosts stay anonymous.

155158 } catch {
156159 return false;
157160 }
@@ -546,6 +549,13 @@ export async function stageTarget(app: App, repo: Repo, follow: Target): Promise
546549 if ((by === undefined || !canWrite(app.db, repo, by)) && follow.via === "parent") by = followsAs(app, repo, follow.byId);
547550 if (by === undefined || !canWrite(app.db, repo, by)) return failed("nobody");
548551
552 // A follow that rides a connected origin's sign-in stops, and says so, when that sign-in is gone
553 // (#16069).
554 if (follow.sourceId === undefined && follow.originId !== "") {
555 const row = getFollow(app.db, repo.id);
556 if (row !== undefined && stopForReauth(app, repo, row)) return failed("reauth", REAUTH_STOPPED_WORDS);
557 }
558
549559 // The credential of a private upstream: the connected origin's, scoped to
550560 // this one git invocation, and only when the upstream is that origin's https origin.
551561 let authEnv: Record<string, string> = {};
@@ -562,7 +572,7 @@ export async function stageTarget(app: App, repo: Repo, follow: Target): Promise
562572 if (follow.originId !== "") {
563573 const origin = getOriginFor(app.db, by.id, follow.originId);
564574 const provider = origin === undefined ? undefined : providerForOrigin(app, origin);
565 if (origin !== undefined && provider?.ok && mayCarryCredential(follow.url, origin.webUrl))
575 if (origin !== undefined && provider?.ok && mayCarryCredential(follow.url, origin.webUrl, app.config.credentialOverLoopback === true))
566576 authEnv = await provider.value.gitAuthEnv(follow.url);
567577 }
568578 // Vetted as the mirror fetch is, and pinned to the address that passed.
src/app.ts +5
@@ -41,6 +41,11 @@ export interface ForgeConfig {
4141 engine?: { mode: string; why: string };
4242 /** Everything lives here: index db, bare repos, the internal socket. */
4343 dataDir: string;
44 /**
45 * Whether a connected origin's credential may travel over plain http to that same origin when it
46 * is a loopback address (two forges on one machine). Off unless a test turns it on.
47 */
48 credentialOverLoopback?: boolean;
4449 /**
4550 * A database made by this call starts with signup = invite (`seedSignup`);
4651 * one that already exists is left as it is. Off by default so a test's
src/core/event_audience.ts +1
@@ -315,6 +315,7 @@ export function classifiedAudience(kind: string): EventAudience | undefined {
315315 // Where a repository follows is its admins' to read, off or on: the
316316 // address is often a private repository's.
317317 kind === "repo.upstream_follow" ||
318 kind === "repo.origin_follow" ||
318319 kind === "repo.upstream_checked" ||
319320 kind === "repo.source_added" ||
320321 kind === "repo.source_removed" ||
src/design/activity.ts +1
@@ -210,6 +210,7 @@ const WORDS: Record<string, string> = {
210210 "repo.upstream_follow": "changed which upstream the repository follows",
211211 "repo.source_added": "followed another source",
212212 "repo.source_removed": "stopped following a source",
213 "repo.origin_follow": "followed, or stopped following, the forge a repository was brought from",
213214 "repo.following": "turned following an upstream on or off",
214215 "repo.crew_outsiders": "changed who may trigger the crew",
215216 "repo.mirrored": "mirrored a repository",
src/engine/crossing.ts +1
@@ -29,6 +29,7 @@ export const CROSSES = [
2929 "edgeToken",
3030 "previewIdentityKey",
3131 "migrateFromPrivateHosts",
32 "credentialOverLoopback",
3233 "edgeName",
3334 "sshHostKey",
3435 "crewCeilingUsd",
src/http/server.ts +2
@@ -23,6 +23,7 @@ import {
2323 followUpstreamSever,
2424 followUpstreamUpdate,
2525 } from "../web/pages/upstream-follow.ts";
26 import { originFollowUpdate } from "../web/pages/origin-follow.ts";
2627 import { secureFor } from "./cookie_secure.ts";
2728 import { noteRenewal, withRenewal } from "./session_renewal.ts";
2829 import { refusedByDatabase, shownRefusal } from "./refusal.ts";
@@ -1895,6 +1896,7 @@ export function buildRouter(): Router<Handler> {
18951896 router.add("POST", "/:owner/:name/settings/holds", fileHoldUpdate);
18961897 router.add("POST", "/:owner/:name/settings/upstream", followUpstreamUpdate);
18971898 router.add("POST", "/:owner/:name/settings/upstream/check", followUpstreamCheck);
1899 router.add("POST", "/:owner/:name/follow-origin", originFollowUpdate);
18981900 router.add("POST", "/:owner/:name/settings/upstream/sever", followUpstreamSever);
18991901 router.add("POST", "/:owner/:name/settings/sources", followSourcesAdd);
19001902 router.add("POST", "/:owner/:name/settings/sources/check", followSourcesCheck);
src/origins/follow.ts added +142
@@ -0,0 +1,142 @@
1 /**
2 * Following the forge a repository was brought from, in one action (#16069).
3 *
4 * A repository brought across (`actions/migrate.ts`) keeps a follow row naming the address it came
5 * from and the connected origin whose credential reads it; it is left off unless the crew runs the
6 * repository by itself. This module turns that row on and off for an admin, as its own words
7 * ("Follow host/owner/name"), and ends it, saying so, when the origin needs signing in again. The
8 * checking, the drift and the pull are the upstream follow's (`actions/upstream_follow.ts`): a
9 * new commit on the source's default branch shows as "N commits behind" at the next check.
10 *
11 * The credential is the origin's, read at check time and handed to git through the environment; it
12 * is never copied onto the row, argv or a git config.
13 */
14
15 import type { App } from "../app.ts";
16 import { getOriginFor, getOriginById } from "../core/origins.ts";
17 import { canAdmin, type Repo } from "../core/repos.ts";
18 import type { User } from "../core/users.ts";
19 import { getFollow, noteCheck, putFollow, type UpstreamFollow } from "../core/upstream_follow.ts";
20 import { err, ok, type Result } from "../kernel/result.ts";
21
22 /** Said when a press arrives without the confirming step. */
23 export const ORIGIN_FOLLOW_UNCONFIRMED = "Confirm first: the press follows or stops following the source.";
24
25 export type OriginFollowError = "not_found" | "not_brought" | "reauth";
26
27 /** What each refusal says, at every door. */
28 export const ORIGIN_FOLLOW_REFUSALS: Record<OriginFollowError, string> = {
29 not_found: "No such repository.",
30 not_brought: "This repository was not brought from a forge you are connected to.",
31 reauth: "The connection to that forge needs you to sign in again (Settings, Origins) before this can follow it.",
32 };
33
34 /** Said when a follow stopped because the origin lost its sign-in; also the check's own error. */
35 export const REAUTH_STOPPED_WORDS =
36 "Stopped following: the connection to that forge needs you to sign in again. Reconnect it in Settings, then follow again.";
37
38 /** What a confirmed press says back, at every door. */
39 export function originFollowReceipt(on: boolean, label: string): string {
40 return on
41 ? `Following ${label}. It is checked every 30 minutes; Check upstream now checks at once.`
42 : `Stopped following ${label}. It is not checked any more.`;
43 }
44
45 /** The question before a press, at every door. */
46 export function originFollowAsk(on: boolean, label: string): string {
47 return on
48 ? `Check ${label} every 30 minutes, with the sign-in you brought it with?`
49 : `Stop checking ${label}?`;
50 }
51
52 /** `host/owner/name` of the address a repository was brought from. */
53 export function sourceLabel(url: string): string {
54 const parsed = URL.parse(url);
55 if (parsed === null) return url;
56 return `${parsed.host}${parsed.pathname}`.replace(/\.git$/, "").replace(/\/$/, "");
57 }
58
59 export interface OriginFollowOffer {
60 /** What the button says after "Follow" / "Stop following". */
61 readonly label: string;
62 readonly following: boolean;
63 /** The origin needs signing in again, so following cannot start. */
64 readonly reauth: boolean;
65 }
66
67 /**
68 * The offer for this repository to this person, or undefined when there is none: not an admin,
69 * not brought across, or brought with a credential that is not theirs.
70 */
71 export function originFollowOffer(app: App, repo: Repo, actor: User | undefined): OriginFollowOffer | undefined {
72 if (actor === undefined || repo.origin !== null || !canAdmin(app.db, repo, actor)) return undefined;
73 const follow = getFollow(app.db, repo.id);
74 if (follow === undefined || follow.originId === "") return undefined;
75 const origin = getOriginFor(app.db, actor.id, follow.originId);
76 if (origin === undefined) return undefined;
77 return { label: sourceLabel(follow.url), following: follow.enabled, reauth: origin.needsReauth };
78 }
79
80 function record(app: App, repo: Repo, actor: User, follow: UpstreamFollow, extra: Record<string, unknown> = {}): void {
81 app.bus.append({
82 kind: "repo.origin_follow",
83 repoId: repo.id,
84 actorId: actor.id,
85 payload: { enabled: follow.enabled, branch: follow.branch, ...extra },
86 });
87 // The readers' event, as the upstream follow's: on or off and nothing that says where.
88 app.bus.append({ kind: "repo.following", repoId: repo.id, actorId: actor.id, payload: { enabled: follow.enabled } });
89 }
90
91 /** Turn following the source on (`enabled`) or off, as an admin whose credential brought it. */
92 export function setOriginFollow(
93 app: App,
94 actor: User | undefined,
95 repo: Repo,
96 enabled: boolean,
97 ): Result<UpstreamFollow, OriginFollowError> {
98 if (actor === undefined || repo.origin !== null || !canAdmin(app.db, repo, actor)) return err("not_found");
99 const was = getFollow(app.db, repo.id);
100 if (was === undefined || was.originId === "") return err("not_brought");
101 const origin = getOriginFor(app.db, actor.id, was.originId);
102 if (origin === undefined) return err("not_brought");
103 if (enabled && origin.needsReauth) return err("reauth");
104 if (was.enabled === enabled) return ok(was);
105 const saved = putFollow(app.db, {
106 repoId: repo.id,
107 url: was.url,
108 branch: was.branch,
109 enabled,
110 byId: enabled ? actor.id : was.byId,
111 originId: was.originId,
112 });
113 record(app, repo, actor, saved);
114 return ok(saved);
115 }
116
117 /**
118 * A check of a follow that rides an origin's credential: when that origin needs signing in again
119 * (or was disconnected) following stops, and the repository says why. Never a silent failure and
120 * never a retry with a credential known to be dead. True when it stopped here.
121 */
122 export function stopForReauth(app: App, repo: Repo, follow: UpstreamFollow): boolean {
123 if (follow.originId === "") return false;
124 const origin = getOriginById(app.db, follow.originId);
125 if (origin !== undefined && !origin.needsReauth) return false;
126 putFollow(app.db, {
127 repoId: repo.id,
128 url: follow.url,
129 branch: follow.branch,
130 enabled: false,
131 byId: follow.byId,
132 originId: follow.originId,
133 });
134 noteCheck(app.db, repo.id, { at: new Date().toISOString(), error: REAUTH_STOPPED_WORDS });
135 app.bus.append({
136 kind: "repo.origin_follow",
137 repoId: repo.id,
138 payload: { enabled: false, branch: follow.branch, reauth: true },
139 });
140 app.bus.append({ kind: "repo.following", repoId: repo.id, payload: { enabled: false } });
141 return true;
142 }
src/tui/screens/about.ts +32
@@ -60,6 +60,13 @@ import {
6060 standing,
6161 upstreamLabel,
6262 } from "../../actions/upstream_follow.ts";
63 import {
64 originFollowAsk,
65 originFollowOffer,
66 originFollowReceipt,
67 ORIGIN_FOLLOW_REFUSALS,
68 setOriginFollow,
69 } from "../../origins/follow.ts";
6370 import { getFollow, listChecks } from "../../core/upstream_follow.ts";
6471 import {
6572 getProvenance,
@@ -120,6 +127,8 @@ export function aboutScreen(
120127 // The following card's rule: an admin's, and only while it is on or to be turned on.
121128 const mayFollow = (): boolean =>
122129 may() && repo !== undefined && repo.origin === null;
130 // The offer to follow the forge this was brought from: the page's rule, read at use.
131 const brought = () => (repo === undefined ? undefined : originFollowOffer(f.app, repo, f.user));
123132 // Outsiders is the same person-and-admin gate; `d` (direct) never clashes
124133 // with `o`, the fork's upstream offer.
125134 const mayOutsiders = (): boolean => mayPerson();
@@ -258,6 +267,9 @@ export function aboutScreen(
258267 binding(["f"], checking() ? "stop following upstream" : "follow upstream"),
259268 ]
260269 : []),
270 ...(brought() !== undefined
271 ? [binding(["g"], brought()?.following ? "stop following where it came from" : "follow where it came from")]
272 : []),
261273 ...(may() && repo?.origin === null ? [binding(["s"], "followed sources")] : []),
262274 // Who can read it is a person's, an admin's call (#8008).
263275 ...(mayPerson()
@@ -678,6 +690,26 @@ export function aboutScreen(
678690 .finally(() => ctx.invalidate());
679691 return true;
680692 }
693 const offer = brought();
694 if (e.key === "g" && repo !== undefined && offer !== undefined) {
695 const at = repo;
696 const on = !offer.following;
697 ctx.push(
698 confirmScreen(ctx, screen, {
699 title: on ? "Follow where it came from" : "Stop following",
700 body: [originFollowAsk(on, offer.label)],
701 actions: [{ label: "Cancel", variant: "ghost" }, { label: on ? "Follow" : "Stop following", variant: "default" }],
702 onChoose: (i) => {
703 if (i !== 1) return;
704 const done = setOriginFollow(f.app, f.user, at, on);
705 ctx.toast(done.ok ? originFollowReceipt(on, offer.label) : ORIGIN_FOLLOW_REFUSALS[done.error], done.ok ? "success" : "danger");
706 rows = factRows();
707 ctx.invalidate();
708 },
709 }),
710 );
711 return true;
712 }
681713 if (e.key === "s" && repo !== undefined && may()) {
682714 ctx.push(sourcesScreen(f, ctx, repo));
683715 return true;
src/web/live.ts +1 −1
@@ -496,7 +496,7 @@ export const liveClientJs = /* js */ `
496496 'label.created', 'label.updated', 'label.deleted',
497497 'run.queued', 'run.started', 'run.finished', 'app.serving',
498498 'schedule.steered', 'app.created', 'app.updated', 'app.deleted', 'app.stopped', 'app.cache.cleared',
499 'repo.upstream_checked', 'repo.links_probed', 'repo.source_added', 'repo.source_removed', 'repo.upstream_follow', 'repo.following', 'limb.moved', 'limb.replan', 'limb.replan_taken_back', 'issue.assigned', 'pull.assigned', 'crew.added', 'crew.removed',
499 'repo.upstream_checked', 'repo.links_probed', 'repo.source_added', 'repo.source_removed', 'repo.upstream_follow', 'repo.origin_follow', 'repo.following', 'limb.moved', 'limb.replan', 'limb.replan_taken_back', 'issue.assigned', 'pull.assigned', 'crew.added', 'crew.removed',
500500 ];
501501 var extra = (cfg.getAttribute('data-repos') || '').split(' ').filter(Boolean);
502502 var watching = [repo].concat(extra).filter(function (r, i, all) {
src/web/pages/fork-standing.ts +2 −1
@@ -25,6 +25,7 @@ import { loadRepo, repoBase } from "../chrome.ts";
2525 import { html, type Html } from "../html.ts";
2626 import { icon } from "../icons.ts";
2727 import { fragment, missingFragment } from "../layout.ts";
28 import { originFollowLine } from "./origin-follow.ts";
2829 import { behindLine, originAheadLine } from "./upstream-follow.ts";
2930
3031 /**
@@ -85,7 +86,7 @@ async function lines(ctx: Ctx, repo: Repo): Promise<Html> {
8586 // it is silent.
8687 const counts = words === undefined ? await upstreamCounts(ctx.app, repo, ctx.auth.user) : undefined;
8788 const countLine = counts === undefined ? null : html`<div class="small" data-upstream-counts>${icon("sync")} ${counts}</div>`;
88 return html`${failedLine(repo)}${countLine}${behind}${ahead}${behind === null && ahead === null ? plain : null}${followedLine(ctx, repo)}`;
89 return html`${failedLine(repo)}${countLine}${behind}${ahead}${originFollowLine(ctx, repo)}${behind === null && ahead === null ? plain : null}${followedLine(ctx, repo)}`;
8990 }
9091
9192 /** The region as the page paints it first; null for a repository that stands against nothing. */
src/web/pages/origin-follow.ts added +67
@@ -0,0 +1,67 @@
1 /**
2 * Following the forge a repository was brought from (#16069), on the page: one line under the
3 * head with one button, and the POST behind it. The words and rules are `origins/follow.ts`; the
4 * drift it leads to is the upstream follow's line (`behindLine`).
5 */
6
7 import {
8 ORIGIN_FOLLOW_REFUSALS,
9 ORIGIN_FOLLOW_UNCONFIRMED,
10 originFollowAsk,
11 originFollowOffer,
12 originFollowReceipt,
13 setOriginFollow,
14 } from "../../origins/follow.ts";
15 import type { Repo } from "../../core/repos.ts";
16 import type { Ctx } from "../../http/context.ts";
17 import { loadRepo, repoBase, repoNotFound } from "../chrome.ts";
18 import { field, readForm } from "../form.ts";
19 import { html, type Html } from "../html.ts";
20 import { icon } from "../icons.ts";
21 import { flashTo } from "../layout.ts";
22 import { btn } from "../ui.ts";
23
24 /** The offer to an admin of a brought repository; null for anyone else. */
25 export function originFollowLine(ctx: Ctx, repo: Repo): Html | null {
26 const offer = originFollowOffer(ctx.app, repo, ctx.auth.user);
27 if (offer === undefined) return null;
28 const base = repoBase(repo);
29 if (offer.reauth && !offer.following)
30 return html`<div class="small muted" data-origin-follow>${icon("sync")}
31 ${ORIGIN_FOLLOW_REFUSALS.reauth} <a href="/settings/origins">Origins</a></div>`;
32 const on = !offer.following;
outdated

Principle 1: the sentence repeats what the button says. State it once. Also no confirm step (issue box 1: one confirmed tap).

33 // The sentence is the state; the button is the action, and opens its own question, so the press
34 // is confirmed with JavaScript off.
35 return html`<div class="small muted" data-origin-follow>${icon("sync")}
36 ${offer.following ? `Following ${offer.label}: new commits there show here as drift.` : `Brought from ${offer.label}; new commits there are not shown here.`}
37 <details>
38 <summary class="btn" data-variant="outline" data-size="sm">${offer.following ? "Stop following" : "Follow"}</summary>
39 <form method="post" action="${base}/follow-origin">
40 <p>${originFollowAsk(on, offer.label)}</p>
41 <input type="hidden" name="enabled" value="${on ? "1" : "0"}" />
42 <input type="hidden" name="confirmed" value="1" />
43 ${btn(on ? "Yes, follow" : "Yes, stop", { size: "sm", variant: "outline" })}
44 </form>
45 </details></div>`;
46 }
47
48 // POST /:owner/:name/follow-origin
49 export async function originFollowUpdate(ctx: Ctx): Promise<Response> {
50 const repo = loadRepo(ctx);
51 if (!repo) return repoNotFound(ctx);
52 const form = await readForm(ctx, "admin");
outdated

'Within a minute' contradicts the 30-minute check in the docs; 'Nothing was checked or proposed from now on' breaks principle 8 (plain words).

53 if (form instanceof Response) return form;
54 const on = field(form, "enabled") === "1";
55 if (field(form, "confirmed") !== "1")
56 return flashTo(ctx, repoBase(repo), { tone: "danger", message: ORIGIN_FOLLOW_UNCONFIRMED });
57 const saved = setOriginFollow(ctx.app, ctx.auth.user, repo, on);
58 const offer = originFollowOffer(ctx.app, repo, ctx.auth.user);
59 const label = offer?.label ?? "the source";
60 return flashTo(
61 ctx,
62 repoBase(repo),
63 saved.ok
64 ? { message: originFollowReceipt(on, label) }
65 : { tone: "danger", message: ORIGIN_FOLLOW_REFUSALS[saved.error] },
66 );
67 }
test/engine-crossing.test.ts +1
@@ -203,6 +203,7 @@ const whole = (dataDir: string): Required<ForgeConfig> => ({
203203 engine: { mode: "worker", why: "FORGE_ENGINE=worker is set" },
204204 dataDir,
205205 seedSignup: true,
206 credentialOverLoopback: false,
206207 disk: () => ({ freeBytes: 1, totalBytes: 2 }),
207208 hostFree: () => 1,
208209 memoryWatch: { grown: () => undefined },
test/forge-origin-follow.test.ts added +230
@@ -0,0 +1,230 @@
1 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2 import { mkdtemp, rm } from "node:fs/promises";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { createApp, type App } from "../src/app.ts";
6 import { migrateRepo } from "../src/actions/migrate.ts";
7 import { behindFor, checkUpstreamNow, mayCarryCredential } from "../src/actions/upstream_follow.ts";
8 import { createToken } from "../src/core/tokens.ts";
9 import { createUser, getUserByName } from "../src/core/users.ts";
10 import { listOrigins, markNeedsReauth } from "../src/core/origins.ts";
11 import { getRepo } from "../src/core/repos.ts";
12 import { getFollow } from "../src/core/upstream_follow.ts";
13 import { listEvents } from "../src/core/events.ts";
14 import { serve, type Servers } from "../src/http/server.ts";
15 import { originFollowOffer, setOriginFollow } from "../src/origins/follow.ts";
16 import { settled } from "../src/origins/jobs.ts";
17 import { syncsSettled } from "../src/origins/sync.ts";
18 import { seedAdmin } from "./helpers/admin.ts";
19 import { proveAll } from "./helpers/verified.ts";
20
21 /**
22 * A repository brought from another forge follows its source with one action (#16069): two real
23 * forges, the source private so that only the stored origin credential reads it, and a push there
24 * that shows here as drift at the next check.
25 */
26
27 const ALICE = "alice-login-secret";
28 const BOB = "bob-login-secret";
29 const basic = (user: string, secret: string): string => `Basic ${Buffer.from(`${user}:${secret}`).toString("base64")}`;
30
31 describe("following the forge a repository was brought from", () => {
32 const dirs: string[] = [];
33 let mine: App;
34 let friend: App;
35 let mineServers: Servers;
36 let friendServers: Servers;
37 let originId = "";
38
39 const bob = (path: string, body: object) =>
40 fetch(`${friendServers.url}${path}`, {
41 method: "POST",
42 headers: { "content-type": "application/json", authorization: basic("bob", BOB) },
43 body: JSON.stringify(body),
44 });
45 const commit = async (file: string) => {
46 const wrote = await bob("/api/v1/repos/bob/notes/contents", {
47 branch: "main",
48 message: `add ${file}`,
49 files: [{ path: file, content: `${file}\n` }],
50 });
51 expect(wrote.status).toBeLessThan(300);
52 };
53 const press = (enabled: boolean) =>
54 fetch(`${mineServers.url}/alice/notes/follow-origin`, {
55 method: "POST",
56 redirect: "manual",
57 headers: {
58 authorization: basic("alice", ALICE),
59 origin: mineServers.url,
60 "content-type": "application/x-www-form-urlencoded",
61 },
62 body: `enabled=${enabled ? "1" : "0"}&confirmed=1`,
63 });
64 const page = async () =>
65 (await fetch(`${mineServers.url}/alice/notes`, { headers: { authorization: basic("alice", ALICE) } })).text();
66 const repo = () => getRepo(mine.db, "alice", "notes")!;
67 const alice = () => getUserByName(mine.db, "alice")!;
68
69 beforeAll(async () => {
70 const make = async () => {
71 const dir = await mkdtemp(join(tmpdir(), "forge-origin-follow-"));
72 dirs.push(dir);
73 return dir;
74 };
75 friend = createApp({ dataDir: await make(), port: 0 });
76 friendServers = await serve(friend);
77 await seedAdmin(friend, { username: "bob", email: "[email protected]", password: BOB });
78 proveAll(friend);
79 const token = createToken(friend.db, getUserByName(friend.db, "bob")!.id, "alice", "rw").token;
80 expect(
81 (await bob("/api/v1/repos", { name: "notes", visibility: "private" })).status,
82 ).toBe(201);
83 await commit("README.md");
84
85 mine = createApp({ dataDir: await make(), port: 0, credentialOverLoopback: true });
86 mineServers = await serve(mine);
87 await seedAdmin(mine, { username: "alice", email: "[email protected]", password: ALICE });
88 proveAll(mine);
89 const connected = await fetch(`${mineServers.url}/api/v1/user/origins`, {
90 method: "POST",
91 headers: { "content-type": "application/json", authorization: basic("alice", ALICE) },
92 body: JSON.stringify({ host: friendServers.url, token }),
93 });
94 expect(connected.status).toBe(201);
95 originId = listOrigins(mine.db, alice().id)[0]!.id;
96
97 const started = await migrateRepo(mine, alice(), { source: { originId, fullName: "bob/notes" }, name: "notes" });
98 expect(started.ok).toBe(true);
99 if (started.ok) expect((await settled(started.value.job.id))?.stage).toBe("done");
100 });
101
102 afterAll(async () => {
103 await syncsSettled();
104 mineServers.stop();
105 friendServers.stop();
106 mine.close();
107 friend.close();
108 for (const dir of dirs) await rm(dir, { recursive: true, force: true, maxRetries: 5 });
109 });
110
111 test("the brought repository offers to follow its source, and starts off", async () => {
112 expect(getFollow(mine.db, repo().id)).toMatchObject({ enabled: false, originId });
113 const html = (await page()).replace(/\s+/g, " ");
114 expect(html).toContain("data-origin-follow");
115 expect(html).toContain("Brought from ");
116 expect(html).toContain("/bob/notes");
117 // The sentence says the state and the button the action: the word is not said twice.
118 expect(html).toContain("<summary");
119 expect(html).not.toMatch(/Follow [^<]*bob\/notes[^<]*<\/summary>/);
120 });
121
122 test("a stranger is offered nothing and cannot press it", async () => {
123 const anon = await fetch(`${mineServers.url}/alice/notes/follow-origin`, {
124 method: "POST",
125 redirect: "manual",
126 headers: { origin: mineServers.url, "content-type": "application/x-www-form-urlencoded" },
127 body: "enabled=1",
128 });
129
130 expect(anon.status).toBe(404);
131 expect(getFollow(mine.db, repo().id)?.enabled).toBe(false);
132 expect(await (await fetch(`${mineServers.url}/alice/notes`)).text()).not.toContain("data-origin-follow");
133 });
134
135 test("a signed-in person who is not an admin of it is refused and offered nothing", async () => {
136 const made = await createUser(mine.db, { username: "carol", email: "[email protected]", password: "carol-login-secret", origin: "seed", trusted: true });
137 expect(made.ok).toBe(true);
138 proveAll(mine);
139 const carol = basic("carol", "carol-login-secret");
140 const refused = await fetch(`${mineServers.url}/alice/notes/follow-origin`, {
141 method: "POST",
142 redirect: "manual",
143 headers: { authorization: carol, origin: mineServers.url, "content-type": "application/x-www-form-urlencoded" },
144 body: "enabled=1&confirmed=1",
145 });
146 expect([403, 404]).toContain(refused.status);
147 expect(getFollow(mine.db, repo().id)?.enabled).toBe(false);
148 const seen = await (await fetch(`${mineServers.url}/alice/notes`, { headers: { authorization: carol } })).text();
149 expect(seen).not.toContain("data-origin-follow");
150 });
151
152 test("a mirror is not offered it, and cannot be set", () => {
153 const mirror = { ...repo(), origin: { originId, fullName: "bob/notes" } } as unknown as ReturnType<typeof repo>;
154 expect(originFollowOffer(mine, mirror, alice())).toBeUndefined();
155 expect(setOriginFollow(mine, alice(), mirror, true)).toEqual({ ok: false, error: "not_found" });
156 });
157
158 test("a press without the confirming step changes nothing", async () => {
159 const bare = await fetch(`${mineServers.url}/alice/notes/follow-origin`, {
160 method: "POST",
161 redirect: "manual",
162 headers: { authorization: basic("alice", ALICE), origin: mineServers.url, "content-type": "application/x-www-form-urlencoded" },
163 body: "enabled=1",
164 });
165 expect(bare.status).toBe(303);
166 expect(getFollow(mine.db, repo().id)?.enabled).toBe(false);
167 });
168
169 test("the credential goes only to the origin's own https address, and loopback http only when a test allows it", () => {
170 const web = "https://git.example.com";
171 expect(mayCarryCredential("http://git.example.com/a/b.git", web, true)).toBe(false);
172 expect(mayCarryCredential("http://127.0.0.1:9/a/b.git", "https://127.0.0.1:9", true)).toBe(false);
173 expect(mayCarryCredential("http://127.0.0.1:9/a/b.git", "http://127.0.0.1:9")).toBe(false);
174 expect(mayCarryCredential("http://127.0.0.1:9/a/b.git", "http://127.0.0.1:9", true)).toBe(true);
175 expect(mayCarryCredential("http://127.0.0.1:9/a/b.git", "http://127.0.0.1:10", true)).toBe(false);
176 });
177
178 test("a press from another site is refused", async () => {
179 const forged = await fetch(`${mineServers.url}/alice/notes/follow-origin`, {
180 method: "POST",
181 redirect: "manual",
182 headers: {
183 authorization: basic("alice", ALICE),
184 origin: "https://evil.example",
185 "content-type": "application/x-www-form-urlencoded",
186 },
187 body: "enabled=1&confirmed=1",
188 });
189 expect(forged.status).toBe(403);
190 expect(getFollow(mine.db, repo().id)?.enabled).toBe(false);
191 });
192
193 test("one press follows; a push there shows here as drift at the next check", async () => {
194 expect((await press(true)).status).toBe(303);
195 expect(getFollow(mine.db, repo().id)?.enabled).toBe(true);
196
197 const level = await checkUpstreamNow(mine, alice(), repo());
198 expect(level).toEqual({ ok: true, value: expect.anything() });
199 expect(behindFor(mine.db, repo(), alice())?.text).toBe("up to date");
200
201 await commit("CHANGES.md");
202 const moved = await checkUpstreamNow(mine, alice(), repo());
203 expect(moved.ok).toBe(true);
204 expect(behindFor(mine.db, repo(), alice())?.text).toContain("1 commit behind");
205 expect((await page()).replace(/\s+/g, " ")).toContain("1 commit behind");
206 });
207
208 test("stopping is one press with the same words, and both are in the history", async () => {
209 expect((await press(false)).status).toBe(303);
210 expect(getFollow(mine.db, repo().id)?.enabled).toBe(false);
211 const events = listEvents(mine.db, { repoId: repo().id }).filter((e) => e.kind === "repo.origin_follow");
212 expect(events.map((e) => e.payload.enabled).sort()).toEqual([false, true]);
213 // The credential is never in what the history holds.
214 expect(JSON.stringify(events)).not.toContain("forge_");
215 });
216
217 test("an origin that needs signing in again stops the follow and says so", async () => {
218 expect((await press(true)).status).toBe(303);
219 markNeedsReauth(mine.db, originId, "invalid_grant");
220 const checked = await checkUpstreamNow(mine, alice(), repo());
221 expect(checked.ok).toBe(false);
222 const row = getFollow(mine.db, repo().id)!;
223 expect(row.enabled).toBe(false);
224 expect(row.error).toContain("sign in again");
225 // Starting again is refused in words until it is signed in.
226 await press(true);
227 expect(getFollow(mine.db, repo().id)?.enabled).toBe(false);
228 expect((await page()).replace(/\s+/g, " ")).toContain("sign in again");
229 });
230 });
test/tui-origin-follow.test.ts added +105
@@ -0,0 +1,105 @@
1 /**
2 * Following the forge a repository was brought from, at the terminal's door (#16069): on About, an
3 * admin whose sign-in brought the repository presses `g`, and only the confirm turns the follow on
4 * (or off); the press goes through the page's `setOriginFollow`. Anyone else is offered nothing.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { createOrigin } from "../src/core/origins.ts";
12 import { createRepo, getRepoById, type Repo } from "../src/core/repos.ts";
13 import { createUser, type User } from "../src/core/users.ts";
14 import { getFollow, putFollow } from "../src/core/upstream_follow.ts";
15 import type { Ctx, Screen } from "../src/tui/app/app.ts";
16 import { aboutScreen } from "../src/tui/screens/about.ts";
17 import type { Session } from "../src/tui/session.ts";
18 import { theme } from "../src/tui/ui/theme.ts";
19 import type { KeyEvent } from "../src/tui/term/input.ts";
20 import { localSource } from "../src/view/local.ts";
21 import { quietLogs } from "./helpers/globals.ts";
22
23 quietLogs();
24
25 const pressed = (key: string): KeyEvent => ({ type: "key", key, ctrl: false, alt: false, shift: false });
26
27 let dir: string;
28 let app: App;
29 let alice: User;
30 let carol: User;
31 let repo: Repo;
32
33 const ok = <T>(r: { ok: true; value: T } | { ok: false; error: unknown }): T => {
34 if (!r.ok) throw new Error(JSON.stringify(r.error));
35 return r.value;
36 };
37
38 function card(user: User) {
39 const pushed: Screen[] = [];
40 const ctx = {
41 theme: theme("dark"),
42 invalidate() {},
43 toast() {},
44 push: (s: Screen) => pushed.push(s),
45 pop() {},
46 copy() {},
47 } as unknown as Ctx;
48 const f = { app, db: app.db, user } as unknown as Session;
49 const src = localSource(app, getRepoById(app.db, repo.id)!, user);
50 const screen = aboutScreen(f, ctx, { render() {} } as unknown as Screen, src, undefined, "main");
51 return {
52 pushed,
53 offered: (key: string) => screen.keys.some((b) => b.keys.includes(key)),
54 press: (key: string) => screen.key!(pressed(key)),
55 };
56 }
57
58 beforeAll(async () => {
59 dir = await mkdtemp(join(tmpdir(), "forge-tui-origin-follow-"));
60 app = createApp({ dataDir: dir, port: 0 });
61 const make = async (username: string) =>
62 ok(await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase" }));
63 alice = await make("alice");
64 carol = await make("carol");
65 repo = ok(await createRepo(app.db, app.reposRoot, { ownerId: alice.id, name: "notes", visibility: "public" }));
66 const origin = ok(
67 createOrigin(app.db, dir, {
68 userId: alice.id,
69 kind: "forgejo",
70 apiUrl: "https://far.example/api/v1",
71 webUrl: "https://far.example",
72 login: "bob",
73 token: "far-token",
74 }),
75 );
76 putFollow(app.db, { repoId: repo.id, url: "https://far.example/bob/notes.git", branch: "main", enabled: false, byId: alice.id, originId: origin.id });
77 });
78
79 afterAll(async () => {
80 app.close();
81 await rm(dir, { recursive: true, force: true, maxRetries: 5 });
82 });
83
84 test("the admin who brought it is offered `g`, and only the confirm follows", () => {
85 const c = card(alice);
86 expect(c.offered("g")).toBe(true);
87 expect(c.press("g")).toBe(true);
88 expect(getFollow(app.db, repo.id)?.enabled).toBe(false);
89 const confirm = c.pushed[0]!;
90 expect(confirm.title).toBe("Follow where it came from");
91 // Cancel (index 0) changes nothing; the second action follows.
92 confirm.key!(pressed("enter"));
93 expect(getFollow(app.db, repo.id)?.enabled).toBe(false);
94 confirm.key!(pressed("right"));
95 confirm.key!(pressed("enter"));
96 expect(getFollow(app.db, repo.id)?.enabled).toBe(true);
97 expect(card(alice).offered("g")).toBe(true);
98 });
99
100 test("someone who did not bring it is offered nothing", () => {
101 const c = card(carol);
102 expect(c.offered("g")).toBe(false);
103 c.press("g");
104 expect(c.pushed).toEqual([]);
105 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs