Public: anyone can read this; the crew can change it.
Cross-forge following: a child reads its parent's releases over HTTPS and takes updates #1023
scout/forge:scout/423-cross-forge-following-a-child-reads-its → main 2 commits fork
14 files
changed +921
−29
docs/FOLLOWING.md +11
| @@ -143,3 +143,14 @@ the fork owner's name, `trevato/main` proposing into `main`. Landing it | ||
| 143 | 143 | there is landing it upstream. |
| 144 | 144 | `POST /api/v1/repos/:owner/:name/following/propose` is the same press over |
| 145 | 145 | the API. |
| 146 | ||
| 147 | ## Across forges | |
| 148 | ||
| 149 | A child spawned on another forge holds an `upstream`: the parent's URL plus a | |
| 150 | read-only token the parent minted at spawn, scoped to the shared apps and | |
| 151 | revocable by the parent. The child stores the token as a secret. Standing | |
| 152 | (synced, behind, ahead, diverged) is computed against the parent's releases | |
| 153 | over HTTPS git, and Take updates reuses `takeUpdates`; a conflict is reported | |
| 154 | as a decision, as in a local fork. Standing is cached and refreshed in the | |
| 155 | background, so an unreachable parent says so, leaves the child untouched and | |
| 156 | never blocks a page. |
scripts/gate.ts +1
| @@ -73,6 +73,7 @@ export const GATE: readonly string[] = [ | ||
| 73 | 73 | "test/studio.test.ts", |
| 74 | 74 | "test/studio-words.test.ts", |
| 75 | 75 | "test/following.test.ts", |
| 76 | "test/remote-following.test.ts", | |
| 76 | 77 | "test/forks.test.ts", |
| 77 | 78 | "test/front.test.ts", |
| 78 | 79 | "test/fork-counts.test.ts", |
src/actions/forks.ts +41
| @@ -26,6 +26,14 @@ import { divergence } from "../git/branches.ts"; | ||
| 26 | 26 | import { resolveOid } from "../git/merge.ts"; |
| 27 | 27 | import { repoDir } from "../git/repos.ts"; |
| 28 | 28 | import { err, type Result } from "../kernel/result.ts"; |
| 29 | import { | |
| 30 | standingNow, | |
| 31 | takeRemote, | |
| 32 | upstreamOf, | |
| 33 | type RemoteStanding, | |
| 34 | type RemoteTakeError, | |
| 35 | type Upstream, | |
| 36 | } from "../core/remote_following.ts"; | |
| 29 | 37 | import { requireWriter, type AccessError } from "./access.ts"; |
| 30 | 38 | |
| 31 | 39 | export type { ForkRelation, ForkSync, TakeError } from "../core/following.ts"; |
| @@ -120,3 +128,36 @@ export async function forkDrift( | ||
| 120 | 128 | return { ahead: null, behind: null }; |
| 121 | 129 | return divergence(forkDir, base, head); |
| 122 | 130 | } |
| 131 | ||
| 132 | /** | |
| 133 | * Where a repository stands against a parent on another forge, for anyone | |
| 134 | * who may read it: the last answer (undefined until the first arrives) and | |
| 135 | * the upstream it came from. Never waits on the parent. | |
| 136 | */ | |
| 137 | export async function remoteStandingOf( | |
| 138 | app: App, | |
| 139 | actor: User | undefined, | |
| 140 | repo: Repo, | |
| 141 | ): Promise<{ upstream: Upstream; standing: RemoteStanding | undefined } | undefined> { | |
| 142 | if (!canRead(app.db, repo, actor)) return undefined; | |
| 143 | const upstream = await upstreamOf(app, repo); | |
| 144 | if (upstream === undefined) return undefined; | |
| 145 | return { upstream, standing: standingNow(app, repo, upstream) }; | |
| 146 | } | |
| 147 | ||
| 148 | /** `takeUpdates` for a parent on another forge. */ | |
| 149 | export async function takeRemoteUpdates( | |
| 150 | app: App, | |
| 151 | actor: User | undefined, | |
| 152 | repo: Repo, | |
| 153 | ): Promise<Result<ForkSync & { merged: boolean }, AccessError | "not_a_fork" | RemoteTakeError>> { | |
| 154 | const writer = requireWriter(app, actor, repo); | |
| 155 | if (!writer.ok) return writer; | |
| 156 | const upstream = await upstreamOf(app, repo); | |
| 157 | if (upstream === undefined) return err("not_a_fork"); | |
| 158 | const who = writer.value; | |
| 159 | return takeRemote(app, repo, upstream, { | |
| 160 | id: who.id, | |
| 161 | ...commitIdentity(app.config, who), | |
| 162 | }); | |
| 163 | } |
src/actions/spawn.ts +47
| @@ -53,6 +53,9 @@ import { claimLink, hasAdmin, mintClaim, spawnedOrg } from "../spawn/claim.ts"; | ||
| 53 | 53 | import type { Placement } from "../spawn/placement.ts"; |
| 54 | 54 | import { planSpawn, type SpawnInput, type SpawnPlan, type SpawnSource } from "../spawn/plan.ts"; |
| 55 | 55 | import { requireUser } from "./access.ts"; |
| 56 | import { UPSTREAM_SECRET } from "../core/remote_following.ts"; | |
| 57 | import { setSecret } from "../core/secret_store.ts"; | |
| 58 | import { mintUpstream, revokeUpstream } from "../spawn/upstream.ts"; | |
| 56 | 59 | |
| 57 | 60 | export interface Spawned { |
| 58 | 61 | readonly name: string; |
| @@ -379,11 +382,34 @@ async function copyInto( | ||
| 379 | 382 | return err("could not set the key's budget"); |
| 380 | 383 | } |
| 381 | 384 | |
| 385 | // What the child follows the parent with: a read-only token for these | |
| 386 | // apps alone, kept by the child as a sealed secret and never shown. A | |
| 387 | // child that already holds one keeps it. | |
| 388 | const holds = child.db | |
| 389 | .query( | |
| 390 | "SELECT 1 FROM secret WHERE name = ?1 AND scope = 'forge' AND scope_id = ''", | |
| 391 | ) | |
| 392 | .get(UPSTREAM_SECRET); | |
| 393 | if (!holds) { | |
| 394 | const token = mintUpstream( | |
| 395 | app.db, | |
| 396 | owner.id, | |
| 397 | plan.name, | |
| 398 | copiedRepos.map((r) => r.parent.id), | |
| 399 | ); | |
| 400 | const kept = setSecret(child.db, dir, "forge", "", UPSTREAM_SECRET, token); | |
| 401 | if (!kept.ok) return err("could not keep the child's upstream token"); | |
| 402 | } | |
| 403 | ||
| 382 | 404 | const upstream = app.config.url ?? `http://${app.config.host ?? "localhost"}`; |
| 383 | 405 | await Bun.write( |
| 384 | 406 | join(dir, "parent.json"), |
| 385 | 407 | JSON.stringify({ |
| 386 | 408 | upstream, |
| 409 | // Which parent app each of the child's repositories follows. | |
| 410 | apps: Object.fromEntries( | |
| 411 | copiedRepos.map((r) => [r.child.name, `${r.parent.ownerName}/${r.parent.name}`]), | |
| 412 | ), | |
| 387 | 413 | name: plan.name, |
| 388 | 414 | org: plan.org, |
| 389 | 415 | // The child's own address, from the placement: <name>.<parent's host>. |
| @@ -428,6 +454,27 @@ function heldKey(dir: string): string | undefined { | ||
| 428 | 454 | * child keeps one claim row, so minting replaces it and the old link dies |
| 429 | 455 | * at once. A claimed child (one with a person as admin) is refused. |
| 430 | 456 | */ |
| 457 | /** | |
| 458 | * Stop a child following this forge: its upstream token dies, and its next | |
| 459 | * fetch is refused. Admin only. Answers whether it held one. | |
| 460 | */ | |
| 461 | export async function revokeUpstreamAccess( | |
| 462 | app: App, | |
| 463 | actor: User | undefined, | |
| 464 | name: string, | |
| 465 | deps: { readonly request: Request; readonly url: URL }, | |
| 466 | ): Promise<Result<{ readonly name: string; readonly revoked: boolean }, SpawnError | { readonly kind: "not_found" }>> { | |
| 467 | if (crossOrigin(deps.request, deps.url, app.log)) return err({ kind: "cross_origin" }); | |
| 468 | const user = requireUser(actor); | |
| 469 | if (!user.ok) return err({ kind: "unauthorized" }); | |
| 470 | if (!user.value.isAdmin) return err({ kind: "forbidden" }); | |
| 471 | const ledger = /^[a-z0-9-]{1,39}$/.test(name) ? await readLedger(app, name) : undefined; | |
| 472 | if (!ledger || !ledger.done) return err({ kind: "not_found" }); | |
| 473 | const revoked = revokeUpstream(app.db, name); | |
| 474 | app.bus.append({ kind: "forge.upstream_revoked", actorId: user.value.id, payload: { name } }); | |
| 475 | return ok({ name, revoked }); | |
| 476 | } | |
| 477 | ||
| 431 | 478 | export async function reissueClaim( |
| 432 | 479 | app: App, |
| 433 | 480 | actor: User | undefined, |
src/core/following.ts +59 −17
| @@ -165,27 +165,45 @@ export async function forkRelation( | ||
| 165 | 165 | resolveOid(parentDir, `refs/heads/${p.defaultBranch}`), |
| 166 | 166 | resolveOid(forkDir, `refs/heads/${fork.defaultBranch}`), |
| 167 | 167 | ]); |
| 168 | // The parent's objects reach the fork through its alternates, so every | |
| 169 | // question is answered inside the fork without a fetch. | |
| 170 | return { | |
| 171 | parent: p, | |
| 172 | ...(await standingBetween(forkDir, forkTip, parentTip)), | |
| 173 | forkTip: forkTip ?? "", | |
| 174 | parentTip: parentTip ?? "", | |
| 175 | }; | |
| 176 | } | |
| 177 | ||
| 178 | /** The four-state answer alone: what two tips say, asked inside `forkDir`. */ | |
| 179 | export interface Standing { | |
| 180 | readonly state: RelationState; | |
| 181 | readonly behind: number; | |
| 182 | readonly ahead: number; | |
| 183 | readonly clean: boolean; | |
| 184 | readonly conflicts: readonly string[]; | |
| 185 | } | |
| 186 | ||
| 187 | /** | |
| 188 | * Where a copy stands against what it follows, given both tips and a | |
| 189 | * repository that holds both sets of objects — through alternates for a | |
| 190 | * fork on this forge, through a fetch for a parent on another. | |
| 191 | */ | |
| 192 | export async function standingBetween( | |
| 193 | forkDir: string, | |
| 194 | forkTip: string | undefined, | |
| 195 | parentTip: string | undefined, | |
| 196 | ): Promise<Standing> { | |
| 168 | 197 | const at = ( |
| 169 | 198 | state: RelationState, |
| 170 | 199 | behind: number, |
| 171 | 200 | ahead: number, |
| 172 | 201 | clean = true, |
| 173 | 202 | conflicts: readonly string[] = [], |
| 174 | ): ForkRelation => ({ | |
| 175 | parent: p, | |
| 176 | state, | |
| 177 | behind, | |
| 178 | ahead, | |
| 179 | clean, | |
| 180 | conflicts, | |
| 181 | forkTip: forkTip ?? "", | |
| 182 | parentTip: parentTip ?? "", | |
| 183 | }); | |
| 203 | ): Standing => ({ state, behind, ahead, clean, conflicts }); | |
| 184 | 204 | // An empty side has nothing to follow or to differ by. |
| 185 | 205 | if (parentTip === undefined || forkTip === undefined || parentTip === forkTip) |
| 186 | 206 | return at("synced", 0, 0); |
| 187 | // The parent's objects reach the fork through its alternates, so every | |
| 188 | // question here is answered inside the fork without a fetch. | |
| 189 | 207 | const base = await mergeBase(forkDir, forkTip, parentTip); |
| 190 | 208 | if (base === undefined) return at("diverged", 0, 0, false); |
| 191 | 209 | const [behind, ahead] = await Promise.all([ |
| @@ -251,13 +269,37 @@ export async function takeUpdates( | ||
| 251 | 269 | `refs/heads/${parent.defaultBranch}`, |
| 252 | 270 | ); |
| 253 | 271 | if (tip === undefined) return err({ kind: "git", message: "fetch failed" }); |
| 272 | return mergeTip( | |
| 273 | forge, | |
| 274 | fork, | |
| 275 | again.forkTip, | |
| 276 | tip, | |
| 277 | `${parent.ownerName}/${parent.name}`, | |
| 278 | author, | |
| 279 | ); | |
| 280 | } | |
| 281 | ||
| 282 | /** | |
| 283 | * The merge commit of a diverged fork and a tip its repository already | |
| 284 | * holds, if git merges them without a conflict. Lands only if the fork's tip | |
| 285 | * is still `forkTip`; the result is a push like any other. | |
| 286 | */ | |
| 287 | export async function mergeTip( | |
| 288 | forge: Pick<Following, "bus" | "reposRoot">, | |
| 289 | fork: Repo, | |
| 290 | forkTip: string, | |
| 291 | tip: string, | |
| 292 | label: string, | |
| 293 | author: MergeIdentity & { readonly id: string }, | |
| 294 | ): Promise<Result<ForkSync & { merged: boolean }, TakeError>> { | |
| 295 | const forkDir = repoDir(forge.reposRoot, fork.ownerName, fork.name); | |
| 254 | 296 | const ref = `refs/heads/${fork.defaultBranch}`; |
| 255 | 297 | const landed = await merge(forkDir, { |
| 256 | 298 | baseBranch: fork.defaultBranch, |
| 257 | baseOid: again.forkTip, | |
| 299 | baseOid: forkTip, | |
| 258 | 300 | headOid: tip, |
| 259 | 301 | strategy: "merge", |
| 260 | message: `Take updates from ${parent.ownerName}/${parent.name}`, | |
| 302 | message: `Take updates from ${label}`, | |
| 261 | 303 | author, |
| 262 | 304 | }); |
| 263 | 305 | if (!landed.ok) { |
| @@ -274,15 +316,15 @@ export async function takeUpdates( | ||
| 274 | 316 | repoId: fork.id, |
| 275 | 317 | actorId: author.id, |
| 276 | 318 | payload: { |
| 277 | updates: [{ ref, oldOid: again.forkTip, newOid: landed.value.mergeOid }], | |
| 278 | followed: `${parent.ownerName}/${parent.name}`, | |
| 319 | updates: [{ ref, oldOid: forkTip, newOid: landed.value.mergeOid }], | |
| 320 | followed: label, | |
| 279 | 321 | merged: true, |
| 280 | 322 | }, |
| 281 | 323 | }); |
| 282 | 324 | return ok({ |
| 283 | 325 | updated: true, |
| 284 | 326 | merged: true, |
| 285 | from: again.forkTip, | |
| 327 | from: forkTip, | |
| 286 | 328 | to: landed.value.mergeOid, |
| 287 | 329 | }); |
| 288 | 330 | } |
src/core/remote_following.ts added +247
| @@ -0,0 +1,247 @@ | ||
| 1 | /** | |
| 2 | * Following a parent on another forge (#423). The child holds an upstream — | |
| 3 | * the parent's address and a read-only token, sealed as a secret — and reads | |
| 4 | * the parent's default branch over HTTPS git into `refs/upstream/<branch>` | |
| 5 | * of its own repository. From there the standing is the same four-state | |
| 6 | * answer a local fork gets (`standingBetween`) and taking updates is the | |
| 7 | * same step (`mergeTip`). | |
| 8 | * | |
| 9 | * A parent is another machine, so it is never waited on: the standing is | |
| 10 | * cached and refreshed in the background, an unreachable parent is a cached | |
| 11 | * fact that says so, and a read that fails leaves the child as it was. | |
| 12 | */ | |
| 13 | ||
| 14 | import { join } from "node:path"; | |
| 15 | import type { App } from "../app.ts"; | |
| 16 | import { runGit } from "../git/env.ts"; | |
| 17 | import { isSafeRef } from "../git/guard.ts"; | |
| 18 | import { resolveOid } from "../git/merge.ts"; | |
| 19 | import { repoDir } from "../git/repos.ts"; | |
| 20 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 21 | import { | |
| 22 | mergeTip, | |
| 23 | standingBetween, | |
| 24 | type ForkSync, | |
| 25 | type Standing, | |
| 26 | type TakeError, | |
| 27 | } from "./following.ts"; | |
| 28 | import type { MergeIdentity } from "../git/merge.ts"; | |
| 29 | import type { Repo } from "./repos.ts"; | |
| 30 | import { resolveSecrets } from "./secret_store.ts"; | |
| 31 | ||
| 32 | /** The name the parent's token goes by in the child's secrets. */ | |
| 33 | export const UPSTREAM_SECRET = "UPSTREAM_TOKEN"; | |
| 34 | ||
| 35 | /** How long a standing is trusted before a read starts a refresh. */ | |
| 36 | export const STALE_MS = 60_000; | |
| 37 | const FETCH_MS = 15_000; | |
| 38 | const ZERO = "0".repeat(40); | |
| 39 | ||
| 40 | export interface Upstream { | |
| 41 | /** The parent forge's address, no trailing slash. */ | |
| 42 | readonly url: string; | |
| 43 | /** The parent's app, `owner/name`. */ | |
| 44 | readonly parent: string; | |
| 45 | } | |
| 46 | ||
| 47 | /** Where this repository's parent is, from `parent.json`; undefined when it follows nothing remote. */ | |
| 48 | export async function upstreamOf( | |
| 49 | app: App, | |
| 50 | repo: Repo, | |
| 51 | ): Promise<Upstream | undefined> { | |
| 52 | const file = Bun.file(join(app.config.dataDir, "parent.json")); | |
| 53 | if (!(await file.exists())) return undefined; | |
| 54 | try { | |
| 55 | const parsed = (await file.json()) as { | |
| 56 | upstream?: unknown; | |
| 57 | org?: unknown; | |
| 58 | apps?: Record<string, unknown>; | |
| 59 | }; | |
| 60 | if (parsed.org !== repo.ownerName) return undefined; | |
| 61 | const parent = parsed.apps?.[repo.name]; | |
| 62 | if (typeof parsed.upstream !== "string" || typeof parent !== "string") | |
| 63 | return undefined; | |
| 64 | if (!/^https?:\/\/[^\s/]+$/.test(parsed.upstream.replace(/\/+$/, ""))) | |
| 65 | return undefined; | |
| 66 | if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(parent)) return undefined; | |
| 67 | return { url: parsed.upstream.replace(/\/+$/, ""), parent }; | |
| 68 | } catch { | |
| 69 | return undefined; | |
| 70 | } | |
| 71 | } | |
| 72 | ||
| 73 | export type RemoteStanding = | |
| 74 | | { | |
| 75 | readonly ok: true; | |
| 76 | readonly parent: string; | |
| 77 | readonly checkedAt: number; | |
| 78 | readonly standing: Standing; | |
| 79 | readonly forkTip: string; | |
| 80 | readonly parentTip: string; | |
| 81 | } | |
| 82 | | { | |
| 83 | readonly ok: false; | |
| 84 | readonly parent: string; | |
| 85 | readonly checkedAt: number; | |
| 86 | readonly reason: "unreachable"; | |
| 87 | }; | |
| 88 | ||
| 89 | /** Fetch the parent's default branch into the child; the tip, or undefined. */ | |
| 90 | async function fetchParent( | |
| 91 | app: App, | |
| 92 | repo: Repo, | |
| 93 | up: Upstream, | |
| 94 | ): Promise<string | undefined> { | |
| 95 | const token = resolveSecrets(app.db, app.config.dataDir, app.bus, [ | |
| 96 | UPSTREAM_SECRET, | |
| 97 | ])[UPSTREAM_SECRET]; | |
| 98 | if (token === undefined || !isSafeRef(`refs/heads/${repo.defaultBranch}`)) | |
| 99 | return undefined; | |
| 100 | const dir = repoDir(app.reposRoot, repo.ownerName, repo.name); | |
| 101 | const local = `refs/upstream/${repo.defaultBranch}`; | |
| 102 | const fetched = await runGit( | |
| 103 | [ | |
| 104 | "fetch", | |
| 105 | "--no-tags", | |
| 106 | "--quiet", | |
| 107 | "--no-write-fetch-head", | |
| 108 | `${up.url}/${up.parent}.git`, | |
| 109 | `+refs/heads/${repo.defaultBranch}:${local}`, | |
| 110 | ], | |
| 111 | { | |
| 112 | cwd: dir, | |
| 113 | timeoutMs: FETCH_MS, | |
| 114 | // The token rides a header in the environment, never an argument | |
| 115 | // another process could list. | |
| 116 | env: { | |
| 117 | GIT_CONFIG_COUNT: "1", | |
| 118 | GIT_CONFIG_KEY_0: "http.extraHeader", | |
| 119 | GIT_CONFIG_VALUE_0: `Authorization: Basic ${Buffer.from(`upstream:${token}`).toString("base64")}`, | |
| 120 | }, | |
| 121 | }, | |
| 122 | ); | |
| 123 | return fetched.ok ? resolveOid(dir, local) : undefined; | |
| 124 | } | |
| 125 | ||
| 126 | const cache = new WeakMap<App, Map<string, RemoteStanding>>(); | |
| 127 | const inFlight = new WeakMap<App, Map<string, Promise<RemoteStanding>>>(); | |
| 128 | ||
| 129 | const mapOf = <V>(store: WeakMap<App, Map<string, V>>, app: App): Map<string, V> => { | |
| 130 | let m = store.get(app); | |
| 131 | if (m === undefined) store.set(app, (m = new Map())); | |
| 132 | return m; | |
| 133 | }; | |
| 134 | ||
| 135 | /** | |
| 136 | * Ask the parent now and remember the answer. One read per repository at a | |
| 137 | * time; whoever arrives meanwhile shares it. | |
| 138 | */ | |
| 139 | export function refreshStanding( | |
| 140 | app: App, | |
| 141 | repo: Repo, | |
| 142 | up: Upstream, | |
| 143 | ): Promise<RemoteStanding> { | |
| 144 | const running = mapOf(inFlight, app); | |
| 145 | const held = running.get(repo.id); | |
| 146 | if (held !== undefined) return held; | |
| 147 | const read = (async (): Promise<RemoteStanding> => { | |
| 148 | const dir = repoDir(app.reposRoot, repo.ownerName, repo.name); | |
| 149 | const parentTip = await fetchParent(app, repo, up); | |
| 150 | const answer: RemoteStanding = | |
| 151 | parentTip === undefined | |
| 152 | ? { | |
| 153 | ok: false, | |
| 154 | parent: up.parent, | |
| 155 | checkedAt: Date.now(), | |
| 156 | reason: "unreachable", | |
| 157 | } | |
| 158 | : await (async () => { | |
| 159 | const forkTip = await resolveOid( | |
| 160 | dir, | |
| 161 | `refs/heads/${repo.defaultBranch}`, | |
| 162 | ); | |
| 163 | return { | |
| 164 | ok: true as const, | |
| 165 | parent: up.parent, | |
| 166 | checkedAt: Date.now(), | |
| 167 | standing: await standingBetween(dir, forkTip, parentTip), | |
| 168 | forkTip: forkTip ?? "", | |
| 169 | parentTip, | |
| 170 | }; | |
| 171 | })(); | |
| 172 | mapOf(cache, app).set(repo.id, answer); | |
| 173 | return answer; | |
| 174 | })().finally(() => running.delete(repo.id)); | |
| 175 | running.set(repo.id, read); | |
| 176 | return read; | |
| 177 | } | |
| 178 | ||
| 179 | /** | |
| 180 | * What a page may say right now: the last answer, however old, and a | |
| 181 | * refresh started behind it when it is missing or stale. Never waits. | |
| 182 | */ | |
| 183 | export function standingNow( | |
| 184 | app: App, | |
| 185 | repo: Repo, | |
| 186 | up: Upstream, | |
| 187 | ): RemoteStanding | undefined { | |
| 188 | const known = mapOf(cache, app).get(repo.id); | |
| 189 | if (known === undefined || Date.now() - known.checkedAt >= STALE_MS) | |
| 190 | refreshStanding(app, repo, up).catch(() => {}); | |
| 191 | return known; | |
| 192 | } | |
| 193 | ||
| 194 | export type RemoteTakeError = TakeError | { kind: "unreachable" }; | |
| 195 | ||
| 196 | /** | |
| 197 | * Take the parent's updates from the parent's own forge: read it afresh, | |
| 198 | * then fast-forward, merge cleanly, or refuse a conflict with its files. A | |
| 199 | * parent that does not answer changes nothing. | |
| 200 | */ | |
| 201 | export async function takeRemote( | |
| 202 | app: App, | |
| 203 | repo: Repo, | |
| 204 | up: Upstream, | |
| 205 | author: MergeIdentity & { readonly id: string }, | |
| 206 | ): Promise<Result<ForkSync & { merged: boolean }, RemoteTakeError>> { | |
| 207 | const read = await refreshStanding(app, repo, up); | |
| 208 | if (!read.ok) return err({ kind: "unreachable" }); | |
| 209 | const { standing, forkTip, parentTip } = read; | |
| 210 | if (standing.state === "synced" || standing.state === "ahead") | |
| 211 | return ok({ updated: false, merged: false, from: forkTip, to: forkTip }); | |
| 212 | const ref = `refs/heads/${repo.defaultBranch}`; | |
| 213 | const dir = repoDir(app.reposRoot, repo.ownerName, repo.name); | |
| 214 | let result: Result<ForkSync & { merged: boolean }, RemoteTakeError>; | |
| 215 | if (standing.state === "behind") { | |
| 216 | // Compare-and-swap: lands only if the tip is still where it was read. | |
| 217 | const moved = await runGit( | |
| 218 | ["update-ref", ref, parentTip, forkTip === "" ? ZERO : forkTip], | |
| 219 | { cwd: dir }, | |
| 220 | ); | |
| 221 | if (!moved.ok) return err({ kind: "moved" }); | |
| 222 | app.bus.append({ | |
| 223 | kind: "push", | |
| 224 | repoId: repo.id, | |
| 225 | actorId: author.id, | |
| 226 | payload: { | |
| 227 | updates: [{ ref, oldOid: forkTip || ZERO, newOid: parentTip }], | |
| 228 | followed: `${up.url}/${up.parent}`, | |
| 229 | }, | |
| 230 | }); | |
| 231 | result = ok({ updated: true, merged: false, from: forkTip, to: parentTip }); | |
| 232 | } else if (!standing.clean) { | |
| 233 | return err({ kind: "conflict", files: standing.conflicts }); | |
| 234 | } else { | |
| 235 | result = await mergeTip( | |
| 236 | app, | |
| 237 | repo, | |
| 238 | forkTip, | |
| 239 | parentTip, | |
| 240 | `${up.url}/${up.parent}`, | |
| 241 | author, | |
| 242 | ); | |
| 243 | } | |
| 244 | // The card should not keep saying "behind" for a minute. | |
| 245 | if (result.ok) await refreshStanding(app, repo, up); | |
| 246 | return result; | |
| 247 | } |
src/http/api.ts +38 −5
| @@ -36,10 +36,10 @@ import { emailVerified } from "../core/verify.ts"; | ||
| 36 | 36 | import { readHealth } from "../actions/health.ts"; |
| 37 | 37 | import { listChildren } from "../actions/spawn.ts"; |
| 38 | 38 | import { forgeState, PARENT_HEADER } from "../spawn/clients.ts"; |
| 39 | import { reissueDoor, spawnDoor } from "../spawn/door.ts"; | |
| 39 | import { reissueDoor, revokeUpstreamDoor, spawnDoor } from "../spawn/door.ts"; | |
| 40 | 40 | import { listSecrets, putSecret, removeSecret } from "../actions/secrets.ts"; |
| 41 | 41 | import { proposeUpstream } from "../actions/upstream.ts"; |
| 42 | import { relationOf, syncFork, takeUpdates } from "../actions/forks.ts"; | |
| 42 | import { relationOf, remoteStandingOf, syncFork, takeRemoteUpdates, takeUpdates } from "../actions/forks.ts"; | |
| 43 | 43 | import { convergeFork, convergeState } from "../crew/converge.ts"; |
| 44 | 44 | import { markReaders, mayDirectCrew } from "../crew/direct.ts"; |
| 45 | 45 | import { |
| @@ -1670,8 +1670,24 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 1670 | 1670 | const repo = loadRepo(ctx); |
| 1671 | 1671 | if (!repo) return notFound(); |
| 1672 | 1672 | const relation = await relationOf(ctx.app, ctx.auth.user, repo); |
| 1673 | if (relation === undefined) | |
| 1674 | return apiError("not_a_fork", 404, "this repository follows nothing"); | |
| 1673 | if (relation === undefined) { | |
| 1674 | const remote = await remoteStandingOf(ctx.app, ctx.auth.user, repo); | |
| 1675 | if (remote === undefined) | |
| 1676 | return apiError("not_a_fork", 404, "this repository follows nothing"); | |
| 1677 | const s = remote.standing; | |
| 1678 | return json({ | |
| 1679 | parent: `${remote.upstream.url}/${remote.upstream.parent}`, | |
| 1680 | branch: repo.defaultBranch, | |
| 1681 | remote: true, | |
| 1682 | // Cached and refreshed behind the answer: null until the first read. | |
| 1683 | checking: s === undefined, | |
| 1684 | reachable: s === undefined ? null : s.ok, | |
| 1685 | checkedAt: s === undefined ? null : new Date(s.checkedAt).toISOString(), | |
| 1686 | ...(s?.ok === true | |
| 1687 | ? { ...s.standing, forkTip: s.forkTip, parentTip: s.parentTip } | |
| 1688 | : {}), | |
| 1689 | }); | |
| 1690 | } | |
| 1675 | 1691 | const converge = |
| 1676 | 1692 | relation.state === "diverged" && !relation.clean |
| 1677 | 1693 | ? convergeState(ctx.app, repo, relation.parent) |
| @@ -1710,9 +1726,18 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 1710 | 1726 | if (denied) return denied; |
| 1711 | 1727 | const repo = loadRepo(ctx); |
| 1712 | 1728 | if (!repo) return notFound(); |
| 1713 | const took = await takeUpdates(ctx.app, ctx.auth.user, repo); | |
| 1729 | let took: Awaited<ReturnType<typeof takeUpdates>> | Awaited<ReturnType<typeof takeRemoteUpdates>> = | |
| 1730 | await takeUpdates(ctx.app, ctx.auth.user, repo); | |
| 1731 | if (!took.ok && took.error === "not_a_fork") | |
| 1732 | took = await takeRemoteUpdates(ctx.app, ctx.auth.user, repo); | |
| 1714 | 1733 | if (!took.ok) { |
| 1715 | 1734 | const e = took.error; |
| 1735 | if (typeof e === "object" && e.kind === "unreachable") | |
| 1736 | return apiError( | |
| 1737 | "unreachable", | |
| 1738 | 502, | |
| 1739 | "the parent forge did not answer; nothing here changed", | |
| 1740 | ); | |
| 1716 | 1741 | if (typeof e === "string") |
| 1717 | 1742 | return e === "not_a_fork" |
| 1718 | 1743 | ? apiError("not_a_fork", 404, "this repository follows nothing") |
| @@ -3781,6 +3806,14 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 3781 | 3806 | return json(door.body, door.status); |
| 3782 | 3807 | }); |
| 3783 | 3808 | |
| 3809 | // The parent takes back a child's read-only token (#423). | |
| 3810 | router.add("DELETE", "/api/v1/forges/:name/upstream", async (ctx) => { | |
| 3811 | const denied = requireScope(ctx, "rw"); | |
| 3812 | if (denied) return denied; | |
| 3813 | const door = await revokeUpstreamDoor(ctx, ctx.auth.user!, ctx.params["name"] ?? ""); | |
| 3814 | return json(door.body, door.status); | |
| 3815 | }); | |
| 3816 | ||
| 3784 | 3817 | router.add("GET", "/api/v1/apps", (ctx) => { |
| 3785 | 3818 | const records = listApps(ctx.app.db); |
| 3786 | 3819 | const repos = getReposByIds( |
src/http/server.ts +13
| @@ -35,6 +35,7 @@ import { trackPullHead } from "../core/pulls.ts"; | ||
| 35 | 35 | import { createRepo } from "../actions/repos.ts"; |
| 36 | 36 | import { sessionOf } from "../core/sessions.ts"; |
| 37 | 37 | import { scopeAllows, verifyToken } from "../core/tokens.ts"; |
| 38 | import { gateUpstream } from "../spawn/upstream.ts"; | |
| 38 | 39 | import { forgeHost } from "../core/commit_identity.ts"; |
| 39 | 40 | import { |
| 40 | 41 | ensureEdgeUser, |
| @@ -438,8 +439,19 @@ async function resolveAuth(app: App, request: Request): Promise<Auth> { | ||
| 438 | 439 | const header = request.headers.get("authorization"); |
| 439 | 440 | if (!header) return NO_AUTH; |
| 440 | 441 | |
| 442 | // A child's token reaches only a fetch of the apps it was granted | |
| 443 | // (`spawn/upstream.ts`); anywhere else it is no credential at all. | |
| 444 | const upstreamRefused = (secret: string): boolean => | |
| 445 | gateUpstream( | |
| 446 | app.db, | |
| 447 | secret, | |
| 448 | request.method, | |
| 449 | new URL(request.url).pathname, | |
| 450 | ) === "refused"; | |
| 451 | ||
| 441 | 452 | // Bearer is always a token. |
| 442 | 453 | if (header.startsWith("Bearer ")) { |
| 454 | if (upstreamRefused(header.slice(7))) return NO_AUTH; | |
| 443 | 455 | const verified = verifyToken(app.db, header.slice(7)); |
| 444 | 456 | if (verified.ok) { |
| 445 | 457 | return { |
| @@ -462,6 +474,7 @@ async function resolveAuth(app: App, request: Request): Promise<Auth> { | ||
| 462 | 474 | const secret = decoded.slice(colon + 1); |
| 463 | 475 | |
| 464 | 476 | if (secret.startsWith("forge_")) { |
| 477 | if (upstreamRefused(secret)) return NO_AUTH; | |
| 465 | 478 | const verified = verifyToken(app.db, secret); |
| 466 | 479 | if (verified.ok) { |
| 467 | 480 | return { |
src/spawn/door.ts +10 −1
| @@ -6,7 +6,7 @@ | ||
| 6 | 6 | * the caller says `false` — returns the plan and changes nothing. |
| 7 | 7 | */ |
| 8 | 8 | |
| 9 | import { listChildren, reissueClaim, spawnForge, type SpawnError } from "../actions/spawn.ts"; | |
| 9 | import { listChildren, reissueClaim, revokeUpstreamAccess, spawnForge, type SpawnError } from "../actions/spawn.ts"; | |
| 10 | 10 | import type { App } from "../app.ts"; |
| 11 | 11 | import { getAgentByName } from "../core/agents.ts"; |
| 12 | 12 | import { canRead, getRepo } from "../core/repos.ts"; |
| @@ -184,3 +184,12 @@ export async function reissueDoor(ctx: Ctx, user: User, name: string): Promise<D | ||
| 184 | 184 | return { status: 404, body: { error: "not_found", message: `no child forge named ${name}` } }; |
| 185 | 185 | return spawnWords(made.error); |
| 186 | 186 | } |
| 187 | ||
| 188 | /** The parent takes back a child's right to follow it (#423). */ | |
| 189 | export async function revokeUpstreamDoor(ctx: Ctx, user: User, name: string): Promise<Door> { | |
| 190 | const done = await revokeUpstreamAccess(ctx.app, user, name, { request: ctx.request, url: ctx.url }); | |
| 191 | if (done.ok) return { status: 200, body: { ...done.value } }; | |
| 192 | if (done.error.kind === "not_found") | |
| 193 | return { status: 404, body: { error: "not_found", message: `no child forge named ${name}` } }; | |
| 194 | return spawnWords(done.error); | |
| 195 | } |
src/spawn/upstream.ts added +86
| @@ -0,0 +1,86 @@ | ||
| 1 | /** | |
| 2 | * What a child is handed to follow its parent over HTTPS: one token, read-only, | |
| 3 | * good for `git fetch` of the shared apps and nothing else, which the parent can | |
| 4 | * revoke. The token is the spawner's own identity narrowed to a list of | |
| 5 | * repositories, so the narrowing lives here and is applied before any handler | |
| 6 | * sees the request (`gateUpstream`, called by the server's auth): a | |
| 7 | * grant that is missing, or a path outside it, is no credential at all. | |
| 8 | * | |
| 9 | * The table is made on first use; it is this module's alone. | |
| 10 | */ | |
| 11 | ||
| 12 | import type { Database } from "bun:sqlite"; | |
| 13 | import { getRepo } from "../core/repos.ts"; | |
| 14 | import { createToken, revokeToken } from "../core/tokens.ts"; | |
| 15 | import { sha256 } from "../kernel/hash.ts"; | |
| 16 | ||
| 17 | const made = new WeakSet<Database>(); | |
| 18 | function table(db: Database): void { | |
| 19 | if (made.has(db)) return; | |
| 20 | db.run(`CREATE TABLE IF NOT EXISTS upstream_grant ( | |
| 21 | child TEXT NOT NULL, | |
| 22 | token_id TEXT NOT NULL, | |
| 23 | token_hash TEXT NOT NULL, | |
| 24 | repo_id TEXT NOT NULL, | |
| 25 | PRIMARY KEY (token_hash, repo_id) | |
| 26 | )`); | |
| 27 | made.add(db); | |
| 28 | } | |
| 29 | ||
| 30 | /** Mint the child's token for these repositories, replacing any it had. */ | |
| 31 | export function mintUpstream( | |
| 32 | db: Database, | |
| 33 | userId: string, | |
| 34 | child: string, | |
| 35 | repoIds: readonly string[], | |
| 36 | ): string { | |
| 37 | revokeUpstream(db, child); | |
| 38 | const { id, token } = createToken(db, userId, `upstream:${child}`, "ro"); | |
| 39 | for (const repoId of repoIds) | |
| 40 | db.query( | |
| 41 | "INSERT INTO upstream_grant (child, token_id, token_hash, repo_id) VALUES (?1, ?2, ?3, ?4)", | |
| 42 | ).run(child, id, sha256(token), repoId); | |
| 43 | return token; | |
| 44 | } | |
| 45 | ||
| 46 | /** Stop the child's token working. True when there was one. */ | |
| 47 | export function revokeUpstream(db: Database, child: string): boolean { | |
| 48 | table(db); | |
| 49 | const ids = db | |
| 50 | .query<{ token_id: string }, [string]>( | |
| 51 | "SELECT DISTINCT token_id FROM upstream_grant WHERE child = ?1", | |
| 52 | ) | |
| 53 | .all(child); | |
| 54 | db.query("DELETE FROM upstream_grant WHERE child = ?1").run(child); | |
| 55 | for (const { token_id } of ids) revokeToken(db, token_id); | |
| 56 | return ids.length > 0; | |
| 57 | } | |
| 58 | ||
| 59 | const FETCH_PATH = /^\/([^/]+)\/([^/]+)\.git\/(info\/refs|git-upload-pack)$/; | |
| 60 | ||
| 61 | /** | |
| 62 | * `free` when the secret is no child's token; `allowed` when it is and the | |
| 63 | * request is a fetch of a repository it was granted; `refused` otherwise. | |
| 64 | */ | |
| 65 | export function gateUpstream( | |
| 66 | db: Database, | |
| 67 | secret: string, | |
| 68 | method: string, | |
| 69 | pathname: string, | |
| 70 | ): "free" | "allowed" | "refused" { | |
| 71 | table(db); | |
| 72 | const granted = db | |
| 73 | .query<{ repo_id: string }, [string]>( | |
| 74 | "SELECT repo_id FROM upstream_grant WHERE token_hash = ?1", | |
| 75 | ) | |
| 76 | .all(sha256(secret)); | |
| 77 | if (granted.length === 0) return "free"; | |
| 78 | const m = FETCH_PATH.exec(pathname); | |
| 79 | if (m === null) return "refused"; | |
| 80 | const verb = m[3] === "info/refs" ? "GET" : "POST"; | |
| 81 | if (method !== verb) return "refused"; | |
| 82 | const repo = getRepo(db, m[1]!, m[2]!); | |
| 83 | return repo !== undefined && granted.some((g) => g.repo_id === repo.id) | |
| 84 | ? "allowed" | |
| 85 | : "refused"; | |
| 86 | } |
src/web/pages/following.ts +87 −2
| @@ -13,6 +13,8 @@ | ||
| 13 | 13 | import { DIRECTION_NOTE } from "../../crew/direct.ts"; |
| 14 | 14 | import { |
| 15 | 15 | relationOf, |
| 16 | remoteStandingOf, | |
| 17 | takeRemoteUpdates, | |
| 16 | 18 | takeUpdates, |
| 17 | 19 | type ForkRelation, |
| 18 | 20 | } from "../../actions/forks.ts"; |
| @@ -30,7 +32,7 @@ import { | ||
| 30 | 32 | convergeState, |
| 31 | 33 | type Converge, |
| 32 | 34 | } from "../../crew/converge.ts"; |
| 33 | import type { Lineage, LineageNode } from "../../core/following.ts"; | |
| 35 | import type { Lineage, LineageNode, Standing } from "../../core/following.ts"; | |
| 34 | 36 | import { loadRepo, notFoundPage, repoBase, signInFirst } from "../chrome.ts"; |
| 35 | 37 | import { openProposal, proposeUpstream } from "../../actions/upstream.ts"; |
| 36 | 38 | import { field, readForm } from "../form.ts"; |
| @@ -137,7 +139,13 @@ export function relationBadge(relation: ForkRelation): Html { | ||
| 137 | 139 | |
| 138 | 140 | /** The sentence a person reads first. */ |
| 139 | 141 | export function relationSentence(relation: ForkRelation): string { |
| 140 | const parent = `${relation.parent.ownerName}/${relation.parent.name}`; | |
| 142 | return standingSentence( | |
| 143 | `${relation.parent.ownerName}/${relation.parent.name}`, | |
| 144 | relation, | |
| 145 | ); | |
| 146 | } | |
| 147 | ||
| 148 | function standingSentence(parent: string, relation: Standing): string { | |
| 141 | 149 | switch (relation.state) { |
| 142 | 150 | case "synced": |
| 143 | 151 | return `Everything here is up to date with ${parent}.`; |
| @@ -302,6 +310,57 @@ export function followingCard( | ||
| 302 | 310 | </section>`; |
| 303 | 311 | } |
| 304 | 312 | |
| 313 | /** | |
| 314 | * The card for a copy whose parent is on another forge. It says what the | |
| 315 | * last read said — or that the parent cannot be reached, or that the first | |
| 316 | * read is on its way — and never waits for the parent to answer. | |
| 317 | */ | |
| 318 | export async function remoteCard(ctx: Ctx, repo: Repo): Promise<Html | undefined> { | |
| 319 | const remote = await remoteStandingOf(ctx.app, ctx.auth.user, repo); | |
| 320 | if (remote === undefined) return undefined; | |
| 321 | const { upstream, standing } = remote; | |
| 322 | const base = repoBase(repo); | |
| 323 | const writer = canWrite(ctx.app.db, repo, ctx.auth.user); | |
| 324 | const [sentence, tone, label] = | |
| 325 | standing === undefined | |
| 326 | ? [`Asking ${upstream.url} where ${upstream.parent} stands…`, "default" as Tone, "checking"] | |
| 327 | : !standing.ok | |
| 328 | ? [ | |
| 329 | `${upstream.url} did not answer, so this is as you left it. Showing nothing until it does.`, | |
| 330 | "attn" as Tone, | |
| 331 | "unreachable", | |
| 332 | ] | |
| 333 | : [ | |
| 334 | standingSentence(upstream.parent, standing.standing), | |
| 335 | standing.standing.state === "synced" ? ("success" as Tone) : ("default" as Tone), | |
| 336 | standing.standing.state, | |
| 337 | ]; | |
| 338 | const canTake = | |
| 339 | standing?.ok === true && | |
| 340 | (standing.standing.state === "behind" || | |
| 341 | (standing.standing.state === "diverged" && standing.standing.clean)); | |
| 342 | return html`<section class="card following" id="following"> | |
| 343 | <div class="card-body"> | |
| 344 | <div class="following-head"> | |
| 345 | <span class="following-eyebrow" | |
| 346 | >${icon("fork")} following ${upstream.parent} on ${upstream.url}</span | |
| 347 | > | |
| 348 | ${badge(label, { tone })} | |
| 349 | </div> | |
| 350 | <p class="following-sentence">${sentence}</p> | |
| 351 | ${when( | |
| 352 | writer && canTake, | |
| 353 | () => html`<div class="following-actions"> | |
| 354 | <form method="post" action="${base}/following"> | |
| 355 | <input type="hidden" name="do" value="take" /> | |
| 356 | ${btn("Take updates", { size: "sm", type: "submit", variant: "primary" })} | |
| 357 | </form> | |
| 358 | </div>`, | |
| 359 | )} | |
| 360 | </div> | |
| 361 | </section>`; | |
| 362 | } | |
| 363 | ||
| 305 | 364 | /** |
| 306 | 365 | * POST /:owner/:name/following { do: take | converge } |
| 307 | 366 | * One form, two verbs: take what git can take, or hand the rest to the crew. |
| @@ -314,6 +373,32 @@ export async function followingSubmit(ctx: Ctx): Promise<Response> { | ||
| 314 | 373 | if (form instanceof Response) return form; |
| 315 | 374 | const base = repoBase(repo); |
| 316 | 375 | const parent = forkParentFor(ctx.app.db, repo, ctx.auth.user); |
| 376 | if (parent === undefined && field(form, "do") !== "converge") { | |
| 377 | const took = await takeRemoteUpdates(ctx.app, ctx.auth.user, repo); | |
| 378 | if (!(!took.ok && took.error === "not_a_fork")) { | |
| 379 | if (!took.ok) { | |
| 380 | const e = took.error; | |
| 381 | return flashOrJson(ctx, base, { | |
| 382 | tone: "danger", | |
| 383 | message: | |
| 384 | typeof e === "string" | |
| 385 | ? "You need write access to take updates here." | |
| 386 | : e.kind === "unreachable" | |
| 387 | ? "The parent forge did not answer; nothing here changed." | |
| 388 | : e.kind === "conflict" | |
| 389 | ? `${e.files.length === 1 ? "One file needs" : `${e.files.length} files need`} a decision (${e.files.join(", ")}).` | |
| 390 | : e.kind === "moved" | |
| 391 | ? "Something moved while this was read; try again." | |
| 392 | : `Git could not take the updates: ${e.message}`, | |
| 393 | }); | |
| 394 | } | |
| 395 | return flashOrJson(ctx, base, { | |
| 396 | message: took.value.updated | |
| 397 | ? `Took updates: ${repo.defaultBranch} is at ${took.value.to.slice(0, 7)}.` | |
| 398 | : "Already up to date.", | |
| 399 | }); | |
| 400 | } | |
| 401 | } | |
| 317 | 402 | if (parent === undefined) |
| 318 | 403 | return flashOrJson(ctx, base, { |
| 319 | 404 | tone: "danger", |
src/web/pages/repo.ts +4 −4
| @@ -12,7 +12,7 @@ import { canRead, listForks, type Repo } from "../../core/repos.ts"; | ||
| 12 | 12 | import { FORKS_PER_DAY, forkRepo } from "../../actions/repos.ts"; |
| 13 | 13 | import { forkDrift, takeUpdates, type ForkDrift } from "../../actions/forks.ts"; |
| 14 | 14 | import { lineageOf } from "../../core/following.ts"; |
| 15 | import { followingCard, followingOf, lineageCard } from "./following.ts"; | |
| 15 | import { followingCard, followingOf, lineageCard, remoteCard } from "./following.ts"; | |
| 16 | 16 | import { pinRepo, syncRepoNow, unpinRepo } from "../../actions/origins.ts"; |
| 17 | 17 | import { |
| 18 | 18 | canAdmin, |
| @@ -980,9 +980,9 @@ async function codeHome(ctx: Ctx, repo: Repo): Promise<Response> { | ||
| 980 | 980 | branchCount: refs.branches.length, |
| 981 | 981 | })}${noApp} |
| 982 | 982 | ${appStrip(ctx, repo)} |
| 983 | ${following === undefined | |
| 984 | ? forkBar(ctx, repo) | |
| 985 | : followingCard(ctx, repo, following)} | |
| 983 | ${following !== undefined | |
| 984 | ? followingCard(ctx, repo, following) | |
| 985 | : (await remoteCard(ctx, repo)) ?? forkBar(ctx, repo)} | |
| 986 | 986 | ${await renderCode(scope, { |
| 987 | 987 | refs, |
| 988 | 988 | ref, |
test/remote-following.test.ts added +276
| @@ -0,0 +1,276 @@ | ||
| 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 { createRepo } from "../src/actions/repos.ts"; | |
| 6 | import { childDirOf, spawnForge } from "../src/actions/spawn.ts"; | |
| 7 | import { createApp, type App } from "../src/app.ts"; | |
| 8 | import { | |
| 9 | refreshStanding, | |
| 10 | standingNow, | |
| 11 | UPSTREAM_SECRET, | |
| 12 | upstreamOf, | |
| 13 | } from "../src/core/remote_following.ts"; | |
| 14 | import { getRepo, type Repo } from "../src/core/repos.ts"; | |
| 15 | import { resolveSecrets } from "../src/core/secret_store.ts"; | |
| 16 | import { createToken } from "../src/core/tokens.ts"; | |
| 17 | import { createUser, getUserByName, type User } from "../src/core/users.ts"; | |
| 18 | import { runGit } from "../src/git/env.ts"; | |
| 19 | import { repoDir } from "../src/git/repos.ts"; | |
| 20 | import { commitFiles } from "../src/git/write.ts"; | |
| 21 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 22 | import { hostedPlacement } from "../src/spawn/placement.ts"; | |
| 23 | import { revokeUpstream } from "../src/spawn/upstream.ts"; | |
| 24 | import { takeRemoteUpdates } from "../src/actions/forks.ts"; | |
| 25 | import { gitClientEnv } from "./helpers/git-client.ts"; | |
| 26 | ||
| 27 | const author = { name: "a", email: "[email protected]" }; | |
| 28 | ||
| 29 | let root: string; | |
| 30 | let parent: App; | |
| 31 | let parentServers: Servers; | |
| 32 | let child: App; | |
| 33 | let childServers: Servers; | |
| 34 | let alice: User; | |
| 35 | let childAlice: User; | |
| 36 | let token: string; | |
| 37 | ||
| 38 | const put = (app: App, owner: string, name: string, path: string, content: string) => | |
| 39 | commitFiles(repoDir(app.reposRoot, owner, name), { | |
| 40 | branch: "main", | |
| 41 | message: `edit ${path}`, | |
| 42 | files: [{ path, content }], | |
| 43 | author, | |
| 44 | }); | |
| 45 | const kid = (): Repo => getRepo(child.db, "kids", "notes")!; | |
| 46 | const tip = async (app: App, owner: string, name: string) => { | |
| 47 | const r = await runGit(["rev-parse", "refs/heads/main"], { | |
| 48 | cwd: repoDir(app.reposRoot, owner, name), | |
| 49 | }); | |
| 50 | return r.ok ? r.value : ""; | |
| 51 | }; | |
| 52 | const lsRemote = async (url: string, secret: string) => { | |
| 53 | const proc = Bun.spawn(["git", "ls-remote", url], { | |
| 54 | env: gitClientEnv({ | |
| 55 | GIT_CONFIG_COUNT: "1", | |
| 56 | GIT_CONFIG_KEY_0: "http.extraHeader", | |
| 57 | GIT_CONFIG_VALUE_0: `Authorization: Basic ${Buffer.from(`u:${secret}`).toString("base64")}`, | |
| 58 | }), | |
| 59 | stdout: "pipe", | |
| 60 | stderr: "pipe", | |
| 61 | }); | |
| 62 | return { code: await proc.exited, out: await new Response(proc.stdout).text() }; | |
| 63 | }; | |
| 64 | ||
| 65 | beforeAll(async () => { | |
| 66 | root = await mkdtemp(join(tmpdir(), "forge-remote-")); | |
| 67 | parent = createApp({ dataDir: join(root, "parent"), port: 0 }); | |
| 68 | parentServers = await serve(parent); | |
| 69 | const made = await createUser(parent.db, { | |
| 70 | trusted: true, | |
| 71 | username: "alice", | |
| 72 | email: "[email protected]", | |
| 73 | isAdmin: true, | |
| 74 | }); | |
| 75 | if (!made.ok) throw new Error("user"); | |
| 76 | alice = made.value; | |
| 77 | for (const name of ["notes", "vault"]) { | |
| 78 | const r = await createRepo(parent, alice, { name, visibility: "private" }); | |
| 79 | if (!r.ok) throw new Error("repo"); | |
| 80 | await put(parent, "alice", name, "readme.txt", `${name}\n`); | |
| 81 | } | |
| 82 | await put(parent, "alice", "notes", "a.txt", "one\nsame\ntwo\n"); | |
| 83 | const spawned = await spawnForge( | |
| 84 | parent, | |
| 85 | alice, | |
| 86 | { name: "kid", org: "kids", apps: ["alice/notes"], carryBriefs: false, carrySubscriptions: false }, | |
| 87 | { | |
| 88 | catalog: [{ ref: "alice/notes", readable: true, bytes: 10, forgeJsonBytes: 0 }], | |
| 89 | briefs: [], | |
| 90 | subscriptions: [], | |
| 91 | }, | |
| 92 | { | |
| 93 | placement: hostedPlacement({ host: "forge.test" }), | |
| 94 | request: new Request("https://forge.test/spawn", { | |
| 95 | method: "POST", | |
| 96 | headers: { origin: "https://forge.test" }, | |
| 97 | }), | |
| 98 | url: new URL("https://forge.test/spawn"), | |
| 99 | }, | |
| 100 | ); | |
| 101 | if (!spawned.ok) throw new Error(JSON.stringify(spawned.error)); | |
| 102 | const dir = childDirOf(parent, spawned.value.bodyId); | |
| 103 | // The placement is hosted by name only; in this process the parent is here. | |
| 104 | const file = Bun.file(join(dir, "parent.json")); | |
| 105 | await Bun.write(file, JSON.stringify({ ...(await file.json()), upstream: parentServers.url })); | |
| 106 | child = createApp({ dataDir: dir, port: 0 }); | |
| 107 | childServers = await serve(child); | |
| 108 | childAlice = getUserByName(child.db, "alice")!; | |
| 109 | token = resolveSecrets(child.db, child.config.dataDir, child.bus, [UPSTREAM_SECRET])[ | |
| 110 | UPSTREAM_SECRET | |
| 111 | ]!; | |
| 112 | }, 60_000); | |
| 113 | ||
| 114 | afterAll(async () => { | |
| 115 | await childServers.stop(); | |
| 116 | await parentServers.stop(); | |
| 117 | child.close(); | |
| 118 | parent.close(); | |
| 119 | await rm(root, { recursive: true, force: true }); | |
| 120 | }); | |
| 121 | ||
| 122 | const asChild = () => ({ ...kid() }); | |
| 123 | const take = () => takeRemoteUpdates(child, childAlice, asChild()); | |
| 124 | const standing = async () => { | |
| 125 | const up = (await upstreamOf(child, kid()))!; | |
| 126 | return refreshStanding(child, kid(), up); | |
| 127 | }; | |
| 128 | ||
| 129 | describe("the upstream token", () => { | |
| 130 | test("the child holds one, sealed, and the parent never copied it to disk in the open", async () => { | |
| 131 | expect(token).toStartWith("forge_"); | |
| 132 | const row = child.db.query("SELECT value_enc FROM secret WHERE name = ?1").get(UPSTREAM_SECRET) as { | |
| 133 | value_enc: string; | |
| 134 | }; | |
| 135 | expect(row.value_enc).not.toContain(token); | |
| 136 | expect(await Bun.file(join(child.config.dataDir, "parent.json")).text()).not.toContain(token); | |
| 137 | }); | |
| 138 | ||
| 139 | test("it fetches the shared app and nothing else", async () => { | |
| 140 | const granted = await lsRemote(`${parentServers.url}/alice/notes.git`, token); | |
| 141 | expect(granted.code).toBe(0); | |
| 142 | expect(granted.out).toContain("refs/heads/main"); | |
| 143 | const other = await lsRemote(`${parentServers.url}/alice/vault.git`, token); | |
| 144 | expect(other.code).not.toBe(0); | |
| 145 | }); | |
| 146 | ||
| 147 | test("it is no credential for the API, and cannot push", async () => { | |
| 148 | const api = await fetch(`${parentServers.url}/api/v1/user`, { | |
| 149 | headers: { authorization: `Bearer ${token}` }, | |
| 150 | }); | |
| 151 | expect(api.status).toBe(401); | |
| 152 | const repo = await fetch(`${parentServers.url}/api/v1/repos/alice/vault`, { | |
| 153 | headers: { authorization: `Bearer ${token}` }, | |
| 154 | }); | |
| 155 | expect(repo.status).toBeGreaterThanOrEqual(401); | |
| 156 | const push = await fetch(`${parentServers.url}/alice/notes.git/info/refs?service=git-receive-pack`, { | |
| 157 | headers: { authorization: `Basic ${Buffer.from(`u:${token}`).toString("base64")}` }, | |
| 158 | }); | |
| 159 | expect(push.status).toBeGreaterThanOrEqual(401); | |
| 160 | }); | |
| 161 | }); | |
| 162 | ||
| 163 | describe("standing and taking updates against another forge", () => { | |
| 164 | test("in step, then behind, and the first read never waits", async () => { | |
| 165 | const up = (await upstreamOf(child, kid()))!; | |
| 166 | expect(up.parent).toBe("alice/notes"); | |
| 167 | // A page's read answers at once; the answer arrives behind it. | |
| 168 | expect(standingNow(child, kid(), up)).toBeUndefined(); | |
| 169 | const first = await standing(); | |
| 170 | expect(first.ok && first.standing.state).toBe("synced"); | |
| 171 | expect(standingNow(child, kid(), up)).toBeDefined(); | |
| 172 | ||
| 173 | await put(parent, "alice", "notes", "b.txt", "new\n"); | |
| 174 | const behind = await standing(); | |
| 175 | expect(behind.ok && behind.standing).toMatchObject({ state: "behind", behind: 1, ahead: 0 }); | |
| 176 | }); | |
| 177 | ||
| 178 | test("the card and the API say the same", async () => { | |
| 179 | const t = createToken(child.db, childAlice.id, "t", "rw").token; | |
| 180 | const res = await fetch(`${childServers.url}/api/v1/repos/kids/notes/following`, { | |
| 181 | headers: { authorization: `Bearer ${t}` }, | |
| 182 | }); | |
| 183 | const body = (await res.json()) as Record<string, unknown>; | |
| 184 | expect(body).toMatchObject({ remote: true, reachable: true, state: "behind", behind: 1 }); | |
| 185 | const page = await ( | |
| 186 | await fetch(`${childServers.url}/kids/notes`, { headers: { authorization: `Bearer ${t}` } }) | |
| 187 | ).text(); | |
| 188 | expect(page).not.toContain("did not answer"); | |
| 189 | expect(page).toContain("Take updates"); | |
| 190 | }); | |
| 191 | ||
| 192 | test("take updates fast-forwards", async () => { | |
| 193 | const took = await take(); | |
| 194 | if (!took.ok) throw new Error(JSON.stringify(took.error)); | |
| 195 | expect(took.value).toMatchObject({ updated: true, merged: false }); | |
| 196 | expect(await tip(child, "kids", "notes")).toBe(await tip(parent, "alice", "notes")); | |
| 197 | const after = await standing(); | |
| 198 | expect(after.ok && after.standing.state).toBe("synced"); | |
| 199 | }); | |
| 200 | ||
| 201 | test("ahead, then diverged and clean merges", async () => { | |
| 202 | await put(child, "kids", "notes", "mine.txt", "mine\n"); | |
| 203 | const ahead = await standing(); | |
| 204 | expect(ahead.ok && ahead.standing).toMatchObject({ state: "ahead", ahead: 1 }); | |
| 205 | expect(await take()).toMatchObject({ ok: true, value: { updated: false } }); | |
| 206 | ||
| 207 | await put(parent, "alice", "notes", "theirs.txt", "theirs\n"); | |
| 208 | const both = await standing(); | |
| 209 | expect(both.ok && both.standing).toMatchObject({ state: "diverged", clean: true }); | |
| 210 | const took = await take(); | |
| 211 | if (!took.ok) throw new Error(JSON.stringify(took.error)); | |
| 212 | expect(took.value.merged).toBe(true); | |
| 213 | const files = await runGit(["ls-tree", "--name-only", "refs/heads/main"], { | |
| 214 | cwd: repoDir(child.reposRoot, "kids", "notes"), | |
| 215 | }); | |
| 216 | expect(files.ok && files.value).toContain("theirs.txt"); | |
| 217 | expect(files.ok && files.value).toContain("mine.txt"); | |
| 218 | }); | |
| 219 | ||
| 220 | test("a conflict is a decision with its files, and changes nothing", async () => { | |
| 221 | await put(parent, "alice", "notes", "a.txt", "one\ntheirs\ntwo\n"); | |
| 222 | await put(child, "kids", "notes", "a.txt", "one\nmine\ntwo\n"); | |
| 223 | const before = await tip(child, "kids", "notes"); | |
| 224 | const both = await standing(); | |
| 225 | expect(both.ok && both.standing).toMatchObject({ | |
| 226 | state: "diverged", | |
| 227 | clean: false, | |
| 228 | conflicts: ["a.txt"], | |
| 229 | }); | |
| 230 | const took = await take(); | |
| 231 | expect(took).toMatchObject({ ok: false, error: { kind: "conflict", files: ["a.txt"] } }); | |
| 232 | expect(await tip(child, "kids", "notes")).toBe(before); | |
| 233 | ||
| 234 | const t = createToken(child.db, childAlice.id, "t2", "rw").token; | |
| 235 | const res = await fetch(`${childServers.url}/api/v1/repos/kids/notes/following/take`, { | |
| 236 | method: "POST", | |
| 237 | headers: { authorization: `Bearer ${t}` }, | |
| 238 | }); | |
| 239 | expect(res.status).toBe(409); | |
| 240 | expect(((await res.json()) as { files: string[] }).files).toEqual(["a.txt"]); | |
| 241 | }); | |
| 242 | }); | |
| 243 | ||
| 244 | describe("a parent that cannot be reached", () => { | |
| 245 | test("says so, keeps the last word, and leaves the child alone", async () => { | |
| 246 | const before = await tip(child, "kids", "notes"); | |
| 247 | // The parent takes the token back. | |
| 248 | expect(revokeUpstream(parent.db, "kid")).toBe(true); | |
| 249 | const lost = await standing(); | |
| 250 | expect(lost).toMatchObject({ ok: false, reason: "unreachable" }); | |
| 251 | const took = await take(); | |
| 252 | expect(took).toMatchObject({ ok: false, error: { kind: "unreachable" } }); | |
| 253 | expect(await tip(child, "kids", "notes")).toBe(before); | |
| 254 | ||
| 255 | // The revoked token is no credential anywhere. | |
| 256 | expect((await lsRemote(`${parentServers.url}/alice/notes.git`, token)).code).not.toBe(0); | |
| 257 | ||
| 258 | const t = createToken(child.db, childAlice.id, "t3", "rw").token; | |
| 259 | const res = await fetch(`${childServers.url}/api/v1/repos/kids/notes/following`, { | |
| 260 | headers: { authorization: `Bearer ${t}` }, | |
| 261 | }); | |
| 262 | expect(await res.json()).toMatchObject({ remote: true, reachable: false }); | |
| 263 | const post = await fetch(`${childServers.url}/api/v1/repos/kids/notes/following/take`, { | |
| 264 | method: "POST", | |
| 265 | headers: { authorization: `Bearer ${t}` }, | |
| 266 | }); | |
| 267 | expect(post.status).toBe(502); | |
| 268 | }); | |
| 269 | ||
| 270 | test("a parent that is gone entirely answers the same", async () => { | |
| 271 | const file = Bun.file(join(child.config.dataDir, "parent.json")); | |
| 272 | await Bun.write(file, JSON.stringify({ ...(await file.json()), upstream: "http://127.0.0.1:1" })); | |
| 273 | const lost = await standing(); | |
| 274 | expect(lost).toMatchObject({ ok: false, reason: "unreachable" }); | |
| 275 | }); | |
| 276 | }); |
test/spawn.test.ts +1
| @@ -80,6 +80,7 @@ describe("spawnForge", () => { | ||
| 80 | 80 | db.close(); |
| 81 | 81 | expect(JSON.parse(await Bun.file(join(child, "parent.json")).text())).toEqual({ |
| 82 | 82 | upstream: "https://forge.test", |
| 83 | apps: { notes: "alice/notes" }, | |
| 83 | 84 | name: "kid", |
| 84 | 85 | org: "kids", |
| 85 | 86 | url: "https://kid.forge.test", |
new above
offline