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 #1225
scout/forge:scout/1052-cross-forge-following-a-child-reads-its → main 3 commits fork
10 files
changed +919
−33
docs/FOLLOWING.md +41
| @@ -165,3 +165,44 @@ the fork owner's name, `trevato/main` proposing into `main`. Landing it | ||
| 165 | 165 | there is landing it upstream. |
| 166 | 166 | `POST /api/v1/repos/:owner/:name/following/propose` is the same press over |
| 167 | 167 | the API. |
| 168 | ||
| 169 | ## Across forges | |
| 170 | ||
| 171 | A child spawned on another forge follows its parent over HTTPS git — no SSH, | |
| 172 | so it works hosted — and shows the same four states against the parent's | |
| 173 | default branch. Taking updates is the same `takeFrom` a local fork uses | |
| 174 | (`core/following.ts`); only the source differs. | |
| 175 | ||
| 176 | **The parent shares.** `POST /api/v1/repos/:owner/:name/share` (admin token, | |
| 177 | repository admin) mints a token and answers `{ id, token, url }` once. The | |
| 178 | token is read-only and held to that repository (`token_repo`): it is a | |
| 179 | credential for `info/refs` and `git-upload-pack` of the repositories it names | |
| 180 | and for nothing else — not the API, not another repository, not a push | |
| 181 | (`heldTo`, `http/server.ts`). The flag sits on the token, so one whose | |
| 182 | repositories are deleted opens nothing rather than everything. The parent | |
| 183 | revokes with `POST …/share/revoke` `{ token: id }`; the next fetch fails. | |
| 184 | ||
| 185 | **The child follows.** `PUT /api/v1/repos/:owner/:name/upstream` | |
| 186 | `{ url, token, branch? }` stores the parent's URL (https; http only on | |
| 187 | loopback; no credentials in it) and keeps the token as a repository secret, | |
| 188 | `UPSTREAM_TOKEN`, sealed like any other and never in a row or an answer. The | |
| 189 | token reaches git through its environment, never argv or the URL, with | |
| 190 | redirects off and only http(s) allowed. `DELETE` unfollows and forgets it. | |
| 191 | ||
| 192 | **Reading never waits.** `GET …/upstream` answers from the last standing, | |
| 193 | cached on the row (`state`, `behind`, `ahead`, `clean`, `conflicts`, | |
| 194 | `checkedAt`) and, when it is older than half a minute, starts one refresh in | |
| 195 | the background for the next reader. A refresh fetches the parent's branch | |
| 196 | into `refs/upstream/<branch>` inside the child and stands against that ref. | |
| 197 | ||
| 198 | **Unreachable is a fact, not a failure.** When the parent cannot be reached | |
| 199 | (token revoked, parent down, branch gone) the row records `unreachable` | |
| 200 | beside the last standing it had; no branch of the child moves. | |
| 201 | ||
| 202 | **Taking updates.** `POST …/upstream/take` refreshes, then fast-forwards or | |
| 203 | merges as a local fork does; a conflict is 409 with the files and nothing | |
| 204 | applied; an unreachable parent is 502 and nothing applied. | |
| 205 | ||
| 206 | Left out: no page card yet (the JSON is the surface), no push-triggered | |
| 207 | refresh from the parent, and converging a conflict with the crew is not wired | |
| 208 | to a remote parent. |
scripts/gate.ts +1
| @@ -83,6 +83,7 @@ export const GATE: readonly string[] = [ | ||
| 83 | 83 | "test/studio.test.ts", |
| 84 | 84 | "test/studio-words.test.ts", |
| 85 | 85 | "test/following.test.ts", |
| 86 | "test/upstream.test.ts", | |
| 86 | 87 | "test/forks.test.ts", |
| 87 | 88 | "test/front.test.ts", |
| 88 | 89 | "test/fork-counts.test.ts", |
src/actions/upstream_follow.ts added +185
| @@ -0,0 +1,185 @@ | ||
| 1 | /** | |
| 2 | * Following a parent on another forge, as people do it: the parent shares | |
| 3 | * (`grantUpstream`), the child follows (`followUpstream`), a page reads the | |
| 4 | * cached standing (`readUpstream`, never waiting on the network), and the | |
| 5 | * one button takes what git can take (`takeUpstream`). The git is | |
| 6 | * `core/following.ts`, shared with a fork on this forge; the fetch and the | |
| 7 | * row are `core/upstream.ts`. | |
| 8 | */ | |
| 9 | ||
| 10 | import type { App } from "../app.ts"; | |
| 11 | import { commitIdentity } from "../core/commit_identity.ts"; | |
| 12 | import { standingFrom, takeFrom, type TakeError } from "../core/following.ts"; | |
| 13 | import { canAdmin, type Repo } from "../core/repos.ts"; | |
| 14 | import { createToken, revokeToken } from "../core/tokens.ts"; | |
| 15 | import type { User } from "../core/users.ts"; | |
| 16 | import { | |
| 17 | clearUpstream, | |
| 18 | fetchUpstream, | |
| 19 | getUpstream, | |
| 20 | recordUpstream, | |
| 21 | setUpstream, | |
| 22 | upstreamSource, | |
| 23 | type Upstream, | |
| 24 | type UpstreamError, | |
| 25 | } from "../core/upstream.ts"; | |
| 26 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 27 | import { requireWriter, type AccessError } from "./access.ts"; | |
| 28 | import type { ForkSync } from "./forks.ts"; | |
| 29 | ||
| 30 | /** | |
| 31 | * Mint what a child needs to follow `repo`: a read-only token held to this | |
| 32 | * repository alone, and the URL to fetch it at. The token is shown once; the | |
| 33 | * parent revokes it with `revokeUpstream`. | |
| 34 | */ | |
| 35 | export function grantUpstream( | |
| 36 | app: App, | |
| 37 | actor: User | undefined, | |
| 38 | repo: Repo, | |
| 39 | origin: string, | |
| 40 | ): Result<{ id: string; token: string; url: string }, "not_found"> { | |
| 41 | if (!actor || !canAdmin(app.db, repo, actor)) return err("not_found"); | |
| 42 | const made = createToken( | |
| 43 | app.db, | |
| 44 | actor.id, | |
| 45 | `upstream ${repo.ownerName}/${repo.name}`, | |
| 46 | "ro", | |
| 47 | { repoIds: [repo.id] }, | |
| 48 | ); | |
| 49 | app.bus.append({ | |
| 50 | kind: "upstream.granted", | |
| 51 | repoId: repo.id, | |
| 52 | actorId: actor.id, | |
| 53 | payload: { token: made.id }, | |
| 54 | }); | |
| 55 | return ok({ | |
| 56 | id: made.id, | |
| 57 | token: made.token, | |
| 58 | url: `${origin}/${repo.ownerName}/${repo.name}.git`, | |
| 59 | }); | |
| 60 | } | |
| 61 | ||
| 62 | export function revokeUpstream( | |
| 63 | app: App, | |
| 64 | actor: User | undefined, | |
| 65 | repo: Repo, | |
| 66 | tokenId: string, | |
| 67 | ): boolean { | |
| 68 | if (!actor || !canAdmin(app.db, repo, actor)) return false; | |
| 69 | const held = app.db | |
| 70 | .query("SELECT 1 FROM token_repo WHERE token_id = ?1 AND repo_id = ?2") | |
| 71 | .get(tokenId, repo.id); | |
| 72 | if (!held) return false; | |
| 73 | app.bus.append({ | |
| 74 | kind: "upstream.revoked", | |
| 75 | repoId: repo.id, | |
| 76 | actorId: actor.id, | |
| 77 | payload: { token: tokenId }, | |
| 78 | }); | |
| 79 | return revokeToken(app.db, tokenId); | |
| 80 | } | |
| 81 | ||
| 82 | export type FollowUpstreamError = AccessError | UpstreamError; | |
| 83 | ||
| 84 | export function followUpstream( | |
| 85 | app: App, | |
| 86 | actor: User | undefined, | |
| 87 | repo: Repo, | |
| 88 | input: { url: string; branch: string; token: string }, | |
| 89 | ): Result<Upstream, FollowUpstreamError> { | |
| 90 | const writer = requireWriter(app, actor, repo); | |
| 91 | if (!writer.ok) return writer; | |
| 92 | return setUpstream(app.db, app.config.dataDir, repo, input); | |
| 93 | } | |
| 94 | ||
| 95 | export function unfollowUpstream( | |
| 96 | app: App, | |
| 97 | actor: User | undefined, | |
| 98 | repo: Repo, | |
| 99 | ): Result<boolean, AccessError> { | |
| 100 | const writer = requireWriter(app, actor, repo); | |
| 101 | if (!writer.ok) return writer; | |
| 102 | return ok(clearUpstream(app.db, repo)); | |
| 103 | } | |
| 104 | ||
| 105 | /** One refresh per repository at a time, however many pages ask. */ | |
| 106 | const refreshing = new Map<string, Promise<Upstream | undefined>>(); | |
| 107 | const STALE_MS = 30_000; | |
| 108 | ||
| 109 | /** | |
| 110 | * Read the parent's standing now and cache it. An unreachable parent is | |
| 111 | * recorded and nothing else changes: the child's branches are not touched. | |
| 112 | */ | |
| 113 | export function refreshUpstream( | |
| 114 | app: App, | |
| 115 | repo: Repo, | |
| 116 | ): Promise<Upstream | undefined> { | |
| 117 | const running = refreshing.get(repo.id); | |
| 118 | if (running) return running; | |
| 119 | const run = (async () => { | |
| 120 | const up = getUpstream(app.db, repo.id); | |
| 121 | if (up === undefined) return undefined; | |
| 122 | const fetched = await fetchUpstream( | |
| 123 | app.db, | |
| 124 | app.config.dataDir, | |
| 125 | app.bus, | |
| 126 | app.reposRoot, | |
| 127 | repo, | |
| 128 | up, | |
| 129 | ); | |
| 130 | if (!fetched.ok) recordUpstream(app.db, repo.id, { error: fetched.error }); | |
| 131 | else | |
| 132 | recordUpstream(app.db, repo.id, { | |
| 133 | standing: await standingFrom( | |
| 134 | app, | |
| 135 | repo, | |
| 136 | upstreamSource(app.reposRoot, repo, up), | |
| 137 | ), | |
| 138 | }); | |
| 139 | return getUpstream(app.db, repo.id); | |
| 140 | })().finally(() => refreshing.delete(repo.id)); | |
| 141 | refreshing.set(repo.id, run); | |
| 142 | return run; | |
| 143 | } | |
| 144 | ||
| 145 | /** | |
| 146 | * The cached standing, immediately. A standing older than half a minute (or | |
| 147 | * never read) starts a refresh in the background for the next reader. | |
| 148 | */ | |
| 149 | export function readUpstream(app: App, repo: Repo): Upstream | undefined { | |
| 150 | const up = getUpstream(app.db, repo.id); | |
| 151 | if (up === undefined) return undefined; | |
| 152 | const age = up.checkedAt === undefined ? Infinity : Date.now() - Date.parse(up.checkedAt); | |
| 153 | if (age > STALE_MS) void refreshUpstream(app, repo).catch(() => undefined); | |
| 154 | return up; | |
| 155 | } | |
| 156 | ||
| 157 | export type TakeUpstreamError = | |
| 158 | | AccessError | |
| 159 | | "not_following" | |
| 160 | | { kind: "unreachable"; message: string } | |
| 161 | | TakeError; | |
| 162 | ||
| 163 | /** | |
| 164 | * Take the parent's updates: fetch first (an unreachable parent says so and | |
| 165 | * leaves the child untouched), then the same step a local fork takes. | |
| 166 | */ | |
| 167 | export async function takeUpstream( | |
| 168 | app: App, | |
| 169 | actor: User | undefined, | |
| 170 | repo: Repo, | |
| 171 | ): Promise<Result<ForkSync & { merged: boolean }, TakeUpstreamError>> { | |
| 172 | const writer = requireWriter(app, actor, repo); | |
| 173 | if (!writer.ok) return writer; | |
| 174 | const refreshed = await refreshUpstream(app, repo); | |
| 175 | if (refreshed === undefined) return err("not_following"); | |
| 176 | if (refreshed.error !== undefined) | |
| 177 | return err({ kind: "unreachable", message: refreshed.error }); | |
| 178 | const who = writer.value; | |
| 179 | const taken = await takeFrom(app, repo, upstreamSource(app.reposRoot, repo, refreshed), { | |
| 180 | id: who.id, | |
| 181 | ...commitIdentity(app.config, who), | |
| 182 | }); | |
| 183 | if (taken.ok && taken.value.updated) await refreshUpstream(app, repo); | |
| 184 | return taken; | |
| 185 | } |
src/core/following.ts +69 −28
| @@ -159,10 +159,44 @@ export async function forkRelation( | ||
| 159 | 159 | ? undefined |
| 160 | 160 | : getRepoById(forge.db, fork.forkParentId)); |
| 161 | 161 | if (p === undefined) return undefined; |
| 162 | const parentDir = repoDir(forge.reposRoot, p.ownerName, p.name); | |
| 162 | return { parent: p, ...(await standingFrom(forge, fork, sourceOf(forge, p))) }; | |
| 163 | } | |
| 164 | ||
| 165 | /** | |
| 166 | * Where a fork's default branch is read against: a directory holding the | |
| 167 | * objects, and the ref in it. A parent on this forge is its own repository; | |
| 168 | * a parent on another forge is a ref fetched into the child itself | |
| 169 | * (`core/upstream.ts`), so both answer the same questions the same way. | |
| 170 | */ | |
| 171 | export interface Source { | |
| 172 | readonly dir: string; | |
| 173 | readonly ref: string; | |
| 174 | /** What the merge commit and the push event call it. */ | |
| 175 | readonly label: string; | |
| 176 | } | |
| 177 | ||
| 178 | export function sourceOf( | |
| 179 | forge: Pick<Following, "reposRoot">, | |
| 180 | parent: Repo, | |
| 181 | ): Source { | |
| 182 | return { | |
| 183 | dir: repoDir(forge.reposRoot, parent.ownerName, parent.name), | |
| 184 | ref: `refs/heads/${parent.defaultBranch}`, | |
| 185 | label: `${parent.ownerName}/${parent.name}`, | |
| 186 | }; | |
| 187 | } | |
| 188 | ||
| 189 | /** A fork's standing without naming the parent: what both kinds share. */ | |
| 190 | export type Standing = Omit<ForkRelation, "parent">; | |
| 191 | ||
| 192 | export async function standingFrom( | |
| 193 | forge: Pick<Following, "reposRoot">, | |
| 194 | fork: Repo, | |
| 195 | source: Source, | |
| 196 | ): Promise<Standing> { | |
| 163 | 197 | const forkDir = repoDir(forge.reposRoot, fork.ownerName, fork.name); |
| 164 | 198 | const [parentTip, forkTip] = await Promise.all([ |
| 165 | resolveOid(parentDir, `refs/heads/${p.defaultBranch}`), | |
| 199 | resolveOid(source.dir, source.ref), | |
| 166 | 200 | resolveOid(forkDir, `refs/heads/${fork.defaultBranch}`), |
| 167 | 201 | ]); |
| 168 | 202 | const at = ( |
| @@ -171,8 +205,7 @@ export async function forkRelation( | ||
| 171 | 205 | ahead: number, |
| 172 | 206 | clean = true, |
| 173 | 207 | conflicts: readonly string[] = [], |
| 174 | ): ForkRelation => ({ | |
| 175 | parent: p, | |
| 208 | ): Standing => ({ | |
| 176 | 209 | state, |
| 177 | 210 | behind, |
| 178 | 211 | ahead, |
| @@ -184,8 +217,9 @@ export async function forkRelation( | ||
| 184 | 217 | // An empty side has nothing to follow or to differ by. |
| 185 | 218 | if (parentTip === undefined || forkTip === undefined || parentTip === forkTip) |
| 186 | 219 | 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. | |
| 220 | // The parent's objects reach the fork through its alternates (or, for a | |
| 221 | // remote parent, were fetched into it), so every question here is answered | |
| 222 | // inside the fork without a fetch. | |
| 189 | 223 | const base = await mergeBase(forkDir, forkTip, parentTip); |
| 190 | 224 | if (base === undefined) return at("diverged", 0, 0, false); |
| 191 | 225 | const [behind, ahead] = await Promise.all([ |
| @@ -223,8 +257,17 @@ export async function takeUpdates( | ||
| 223 | 257 | parent: Repo, |
| 224 | 258 | author: MergeIdentity & { readonly id: string }, |
| 225 | 259 | ): Promise<Result<ForkSync & { merged: boolean }, TakeError>> { |
| 226 | const relation = await forkRelation(forge, fork, parent); | |
| 227 | if (relation === undefined) return err({ kind: "git", message: "no parent" }); | |
| 260 | return takeFrom(forge, fork, sourceOf(forge, parent), author); | |
| 261 | } | |
| 262 | ||
| 263 | /** `takeUpdates` from any source: a parent here, or a ref fetched from afar. */ | |
| 264 | export async function takeFrom( | |
| 265 | forge: Following, | |
| 266 | fork: Repo, | |
| 267 | source: Source, | |
| 268 | author: MergeIdentity & { readonly id: string }, | |
| 269 | ): Promise<Result<ForkSync & { merged: boolean }, TakeError>> { | |
| 270 | const relation = await standingFrom(forge, fork, source); | |
| 228 | 271 | if (relation.state === "synced" || relation.state === "ahead") |
| 229 | 272 | return ok({ |
| 230 | 273 | updated: false, |
| @@ -233,23 +276,17 @@ export async function takeUpdates( | ||
| 233 | 276 | to: relation.forkTip, |
| 234 | 277 | }); |
| 235 | 278 | if (relation.state === "behind") { |
| 236 | const moved = await fastForwardFork(forge, fork, parent, author.id); | |
| 279 | const moved = await fastForwardFrom(forge, fork, source, author.id); | |
| 237 | 280 | if (moved.ok) return ok({ ...moved.value, merged: false }); |
| 238 | 281 | // Diverged between the read and the move: fall through to the merge. |
| 239 | 282 | } |
| 240 | const again = await forkRelation(forge, fork, parent); | |
| 241 | if (again === undefined || again.state !== "diverged") | |
| 242 | return err({ kind: "moved" }); | |
| 283 | const again = await standingFrom(forge, fork, source); | |
| 284 | if (again.state !== "diverged") return err({ kind: "moved" }); | |
| 243 | 285 | if (!again.clean) return err({ kind: "conflict", files: again.conflicts }); |
| 244 | const parentDir = repoDir(forge.reposRoot, parent.ownerName, parent.name); | |
| 245 | 286 | const forkDir = repoDir(forge.reposRoot, fork.ownerName, fork.name); |
| 246 | 287 | // The parent's objects are visible through the alternates already; the |
| 247 | 288 | // fetch makes the fork own what its new commit points at. |
| 248 | const tip = await fetchInto( | |
| 249 | forkDir, | |
| 250 | parentDir, | |
| 251 | `refs/heads/${parent.defaultBranch}`, | |
| 252 | ); | |
| 289 | const tip = await fetchInto(forkDir, source.dir, source.ref); | |
| 253 | 290 | if (tip === undefined) return err({ kind: "git", message: "fetch failed" }); |
| 254 | 291 | const ref = `refs/heads/${fork.defaultBranch}`; |
| 255 | 292 | const landed = await merge(forkDir, { |
| @@ -257,7 +294,7 @@ export async function takeUpdates( | ||
| 257 | 294 | baseOid: again.forkTip, |
| 258 | 295 | headOid: tip, |
| 259 | 296 | strategy: "merge", |
| 260 | message: `Take updates from ${parent.ownerName}/${parent.name}`, | |
| 297 | message: `Take updates from ${source.label}`, | |
| 261 | 298 | author, |
| 262 | 299 | }); |
| 263 | 300 | if (!landed.ok) { |
| @@ -275,7 +312,7 @@ export async function takeUpdates( | ||
| 275 | 312 | actorId: author.id, |
| 276 | 313 | payload: { |
| 277 | 314 | updates: [{ ref, oldOid: again.forkTip, newOid: landed.value.mergeOid }], |
| 278 | followed: `${parent.ownerName}/${parent.name}`, | |
| 315 | followed: source.label, | |
| 279 | 316 | merged: true, |
| 280 | 317 | }, |
| 281 | 318 | }); |
| @@ -393,10 +430,18 @@ export async function fastForwardFork( | ||
| 393 | 430 | parent: Repo, |
| 394 | 431 | actorId: string | undefined, |
| 395 | 432 | ): Promise<Result<ForkSync, "diverged">> { |
| 396 | const parentDir = repoDir(forge.reposRoot, parent.ownerName, parent.name); | |
| 433 | return fastForwardFrom(forge, fork, sourceOf(forge, parent), actorId); | |
| 434 | } | |
| 435 | ||
| 436 | export async function fastForwardFrom( | |
| 437 | forge: Following, | |
| 438 | fork: Repo, | |
| 439 | source: Source, | |
| 440 | actorId: string | undefined, | |
| 441 | ): Promise<Result<ForkSync, "diverged">> { | |
| 397 | 442 | const forkDir = repoDir(forge.reposRoot, fork.ownerName, fork.name); |
| 398 | 443 | const ref = `refs/heads/${fork.defaultBranch}`; |
| 399 | const to = await resolveOid(parentDir, `refs/heads/${parent.defaultBranch}`); | |
| 444 | const to = await resolveOid(source.dir, source.ref); | |
| 400 | 445 | const from = await resolveOid(forkDir, ref); |
| 401 | 446 | if (to === undefined || from === to) |
| 402 | 447 | return ok({ updated: false, from: from ?? "", to: to ?? "" }); |
| @@ -404,11 +449,7 @@ export async function fastForwardFork( | ||
| 404 | 449 | // ancestry question is answerable before anything is fetched. |
| 405 | 450 | if (from !== undefined && (await mergeBase(forkDir, from, to)) !== from) |
| 406 | 451 | return err("diverged"); |
| 407 | const tip = await fetchInto( | |
| 408 | forkDir, | |
| 409 | parentDir, | |
| 410 | `refs/heads/${parent.defaultBranch}`, | |
| 411 | ); | |
| 452 | const tip = await fetchInto(forkDir, source.dir, source.ref); | |
| 412 | 453 | if (tip === undefined || !(await writeRef(forkDir, ref, tip))) |
| 413 | 454 | return ok({ updated: false, from: from ?? "", to }); |
| 414 | 455 | forge.bus.append({ |
| @@ -417,7 +458,7 @@ export async function fastForwardFork( | ||
| 417 | 458 | actorId, |
| 418 | 459 | payload: { |
| 419 | 460 | updates: [{ ref, oldOid: from ?? ZERO, newOid: tip }], |
| 420 | followed: `${parent.ownerName}/${parent.name}`, | |
| 461 | followed: source.label, | |
| 421 | 462 | }, |
| 422 | 463 | }); |
| 423 | 464 | return ok({ updated: true, from: from ?? "", to: tip }); |
src/core/schema.ts +22
| @@ -1578,6 +1578,28 @@ export const migrations: readonly string[] = [ | ||
| 1578 | 1578 | expires_at TEXT NOT NULL |
| 1579 | 1579 | ); |
| 1580 | 1580 | `, |
| 1581 | // 74 — following across forges (#1052). On the parent, a token may be | |
| 1582 | // held to named repositories (`token_repo`): it opens nothing else, and | |
| 1583 | // deleting the token ends it. On the child, `upstream` is the parent it | |
| 1584 | // follows — URL and branch — and the last standing read from it, so a page | |
| 1585 | // answers from the row and a background refresh keeps it. The token itself | |
| 1586 | // is a repository secret (`UPSTREAM_TOKEN`), never a column. | |
| 1587 | ` | |
| 1588 | ALTER TABLE token ADD COLUMN restricted INTEGER NOT NULL DEFAULT 0; | |
| 1589 | CREATE TABLE token_repo ( | |
| 1590 | token_id TEXT NOT NULL REFERENCES token(id) ON DELETE CASCADE, | |
| 1591 | repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE, | |
| 1592 | PRIMARY KEY (token_id, repo_id) | |
| 1593 | ); | |
| 1594 | CREATE TABLE upstream ( | |
| 1595 | repo_id TEXT PRIMARY KEY REFERENCES repo(id) ON DELETE CASCADE, | |
| 1596 | url TEXT NOT NULL, | |
| 1597 | branch TEXT NOT NULL, | |
| 1598 | standing TEXT, | |
| 1599 | checked_at TEXT, | |
| 1600 | error TEXT | |
| 1601 | ); | |
| 1602 | `, | |
| 1581 | 1603 | ]; |
| 1582 | 1604 | |
| 1583 | 1605 | /** |
src/core/tokens.ts +39 −3
| @@ -38,13 +38,23 @@ export function createToken( | ||
| 38 | 38 | userId: string, |
| 39 | 39 | name: string, |
| 40 | 40 | scope: TokenScope, |
| 41 | options: { expiresAt?: string } = {}, | |
| 41 | options: { expiresAt?: string; repoIds?: readonly string[] } = {}, | |
| 42 | 42 | ): { id: string; token: string } { |
| 43 | 43 | const tokenId = id(); |
| 44 | 44 | const token = `forge_${secret()}`; |
| 45 | 45 | db.query( |
| 46 | 46 | "INSERT INTO token (id, token_hash, user_id, name, scope, expires_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", |
| 47 | 47 | ).run(tokenId, sha256(token), userId, name, scope, options.expiresAt ?? null); |
| 48 | // A token held to repositories opens only those (`restrictedTo`). The flag | |
| 49 | // lives on the token, so a token whose repositories are all deleted opens | |
| 50 | // nothing instead of everything. | |
| 51 | if (options.repoIds !== undefined) | |
| 52 | db.query("UPDATE token SET restricted = 1 WHERE id = ?1").run(tokenId); | |
| 53 | for (const repoId of options.repoIds ?? []) | |
| 54 | db.query("INSERT INTO token_repo (token_id, repo_id) VALUES (?1, ?2)").run( | |
| 55 | tokenId, | |
| 56 | repoId, | |
| 57 | ); | |
| 48 | 58 | return { id: tokenId, token }; |
| 49 | 59 | } |
| 50 | 60 | |
| @@ -65,7 +75,10 @@ const TOUCH_EVERY_MS = 60_000; | ||
| 65 | 75 | export function verifyToken( |
| 66 | 76 | db: Database, |
| 67 | 77 | presented: string, |
| 68 | ): Result<{ user: User; scope: TokenScope }, "invalid_token"> { | |
| 78 | ): Result< | |
| 79 | { user: User; scope: TokenScope; only: readonly string[] | undefined }, | |
| 80 | "invalid_token" | |
| 81 | > { | |
| 69 | 82 | const row = db |
| 70 | 83 | .query< |
| 71 | 84 | { |
| @@ -96,7 +109,30 @@ export function verifyToken( | ||
| 96 | 109 | row.id, |
| 97 | 110 | ); |
| 98 | 111 | } |
| 99 | return ok({ user, scope: row.scope }); | |
| 112 | return ok({ user, scope: row.scope, only: restrictedTo(db, row.id) }); | |
| 113 | } | |
| 114 | ||
| 115 | /** | |
| 116 | * The repositories a token is held to, or nothing for a token that is not. | |
| 117 | * A held token reads those repositories over git and nothing else | |
| 118 | * (`resolveAuth`): the credential a parent hands a child to follow it. | |
| 119 | */ | |
| 120 | export function restrictedTo( | |
| 121 | db: Database, | |
| 122 | tokenId: string, | |
| 123 | ): readonly string[] | undefined { | |
| 124 | const held = db | |
| 125 | .query<{ restricted: number }, [string]>( | |
| 126 | "SELECT restricted FROM token WHERE id = ?1", | |
| 127 | ) | |
| 128 | .get(tokenId); | |
| 129 | if (held?.restricted !== 1) return undefined; | |
| 130 | return db | |
| 131 | .query<{ repo_id: string }, [string]>( | |
| 132 | "SELECT repo_id FROM token_repo WHERE token_id = ?1", | |
| 133 | ) | |
| 134 | .all(tokenId) | |
| 135 | .map((r) => r.repo_id); | |
| 100 | 136 | } |
| 101 | 137 | |
| 102 | 138 | export function listTokens(db: Database, userId: string): TokenInfo[] { |
src/core/upstream.ts added +206
| @@ -0,0 +1,206 @@ | ||
| 1 | /** | |
| 2 | * Following a parent on another forge. | |
| 3 | * | |
| 4 | * A fork on this forge reads its parent through alternates; a child spawned | |
| 5 | * elsewhere reads its parent over HTTPS git. The child holds an `upstream` | |
| 6 | * row — URL and branch — and a read-only token the parent minted for the | |
| 7 | * shared repositories, kept as a repository secret. A read fetches the | |
| 8 | * parent's branch into `refs/upstream/<branch>` inside the child, after | |
| 9 | * which the child stands against that ref exactly as a fork stands against | |
| 10 | * its parent (`standingFrom`): synced, behind, ahead, diverged. | |
| 11 | * | |
| 12 | * The standing is cached on the row. A page reads the row and never waits | |
| 13 | * on the network; `refreshUpstream` is the background half, and an | |
| 14 | * unreachable parent is recorded as an `error` beside the last standing it | |
| 15 | * had, with the child's own branches left exactly as they were. | |
| 16 | */ | |
| 17 | ||
| 18 | import type { Database } from "bun:sqlite"; | |
| 19 | import type { Source, Standing } from "./following.ts"; | |
| 20 | import type { Repo } from "./repos.ts"; | |
| 21 | import { deleteSecret, resolveSecrets, setSecret } from "./secret_store.ts"; | |
| 22 | import type { EventBus } from "./events.ts"; | |
| 23 | import { runGit } from "../git/env.ts"; | |
| 24 | import { isSafeRef } from "../git/guard.ts"; | |
| 25 | import { repoDir } from "../git/repos.ts"; | |
| 26 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 27 | ||
| 28 | export const UPSTREAM_SECRET = "UPSTREAM_TOKEN"; | |
| 29 | ||
| 30 | export interface Upstream { | |
| 31 | readonly url: string; | |
| 32 | readonly branch: string; | |
| 33 | /** The last standing read, or nothing before the first refresh. */ | |
| 34 | readonly standing: Standing | undefined; | |
| 35 | readonly checkedAt: string | undefined; | |
| 36 | /** Why the last refresh failed; cleared by the next that works. */ | |
| 37 | readonly error: string | undefined; | |
| 38 | } | |
| 39 | ||
| 40 | export type UpstreamError = "invalid_url" | "invalid_branch" | "invalid_token"; | |
| 41 | ||
| 42 | interface Row { | |
| 43 | url: string; | |
| 44 | branch: string; | |
| 45 | standing: string | null; | |
| 46 | checked_at: string | null; | |
| 47 | error: string | null; | |
| 48 | } | |
| 49 | ||
| 50 | const TOKEN = /^forge_[A-Za-z0-9_-]{8,200}$/; | |
| 51 | ||
| 52 | /** `https://host/owner/name.git`; plain http only for a loopback host. */ | |
| 53 | export function parseUpstreamUrl(raw: string): URL | undefined { | |
| 54 | let url: URL; | |
| 55 | try { | |
| 56 | url = new URL(raw); | |
| 57 | } catch { | |
| 58 | return undefined; | |
| 59 | } | |
| 60 | const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname); | |
| 61 | if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) | |
| 62 | return undefined; | |
| 63 | if (url.username !== "" || url.password !== "") return undefined; | |
| 64 | if (url.search !== "" || url.hash !== "") return undefined; | |
| 65 | if (!/^\/[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+\.git$/.test(url.pathname)) | |
| 66 | return undefined; | |
| 67 | return url; | |
| 68 | } | |
| 69 | ||
| 70 | export function getUpstream(db: Database, repoId: string): Upstream | undefined { | |
| 71 | const row = db | |
| 72 | .query<Row, [string]>( | |
| 73 | "SELECT url, branch, standing, checked_at, error FROM upstream WHERE repo_id = ?1", | |
| 74 | ) | |
| 75 | .get(repoId); | |
| 76 | if (!row) return undefined; | |
| 77 | let standing: Standing | undefined; | |
| 78 | try { | |
| 79 | standing = row.standing === null ? undefined : JSON.parse(row.standing); | |
| 80 | } catch { | |
| 81 | standing = undefined; | |
| 82 | } | |
| 83 | return { | |
| 84 | url: row.url, | |
| 85 | branch: row.branch, | |
| 86 | standing, | |
| 87 | checkedAt: row.checked_at ?? undefined, | |
| 88 | error: row.error ?? undefined, | |
| 89 | }; | |
| 90 | } | |
| 91 | ||
| 92 | /** Follow `url`'s `branch`, holding `token` as the repository's secret. */ | |
| 93 | export function setUpstream( | |
| 94 | db: Database, | |
| 95 | dataDir: string, | |
| 96 | repo: Repo, | |
| 97 | input: { url: string; branch: string; token: string }, | |
| 98 | ): Result<Upstream, UpstreamError> { | |
| 99 | const url = parseUpstreamUrl(input.url); | |
| 100 | if (url === undefined) return err("invalid_url"); | |
| 101 | if (!isSafeRef(`refs/heads/${input.branch}`)) return err("invalid_branch"); | |
| 102 | if (!TOKEN.test(input.token)) return err("invalid_token"); | |
| 103 | const stored = setSecret( | |
| 104 | db, | |
| 105 | dataDir, | |
| 106 | "repo", | |
| 107 | repo.id, | |
| 108 | UPSTREAM_SECRET, | |
| 109 | input.token, | |
| 110 | ); | |
| 111 | if (!stored.ok) return err("invalid_token"); | |
| 112 | db.query( | |
| 113 | `INSERT INTO upstream (repo_id, url, branch) VALUES (?1, ?2, ?3) | |
| 114 | ON CONFLICT(repo_id) DO UPDATE SET url = ?2, branch = ?3, | |
| 115 | standing = NULL, checked_at = NULL, error = NULL`, | |
| 116 | ).run(repo.id, url.href, input.branch); | |
| 117 | return ok(getUpstream(db, repo.id)!); | |
| 118 | } | |
| 119 | ||
| 120 | export function clearUpstream(db: Database, repo: Repo): boolean { | |
| 121 | deleteSecret(db, "repo", repo.id, UPSTREAM_SECRET); | |
| 122 | return db.query("DELETE FROM upstream WHERE repo_id = ?1").run(repo.id).changes > 0; | |
| 123 | } | |
| 124 | ||
| 125 | /** Where the fetched parent lives inside the child. */ | |
| 126 | export const upstreamRef = (branch: string): string => `refs/upstream/${branch}`; | |
| 127 | ||
| 128 | /** The parent as a source for `takeFrom`: a ref in the child itself. */ | |
| 129 | export function upstreamSource( | |
| 130 | reposRoot: string, | |
| 131 | repo: Repo, | |
| 132 | up: Upstream, | |
| 133 | ): Source { | |
| 134 | return { | |
| 135 | dir: repoDir(reposRoot, repo.ownerName, repo.name), | |
| 136 | ref: upstreamRef(up.branch), | |
| 137 | label: `${new URL(up.url).host}${new URL(up.url).pathname.replace(/\.git$/, "")}`, | |
| 138 | }; | |
| 139 | } | |
| 140 | ||
| 141 | /** | |
| 142 | * Fetch the parent's branch into the child. Hardened: only http(s), no | |
| 143 | * redirects, the token in the environment (never argv, never the URL), a | |
| 144 | * wall-clock limit. Answers the fetched tip or why not. | |
| 145 | */ | |
| 146 | export async function fetchUpstream( | |
| 147 | db: Database, | |
| 148 | dataDir: string, | |
| 149 | bus: EventBus, | |
| 150 | reposRoot: string, | |
| 151 | repo: Repo, | |
| 152 | up: Upstream, | |
| 153 | ): Promise<Result<string, string>> { | |
| 154 | const token = resolveSecrets(db, dataDir, bus, [UPSTREAM_SECRET], { | |
| 155 | repo: repo.id, | |
| 156 | })[UPSTREAM_SECRET]; | |
| 157 | if (token === undefined) return err("no token is held for the parent"); | |
| 158 | const auth = Buffer.from(`upstream:${token}`).toString("base64"); | |
| 159 | const dir = repoDir(reposRoot, repo.ownerName, repo.name); | |
| 160 | const ref = upstreamRef(up.branch); | |
| 161 | const fetched = await runGit( | |
| 162 | [ | |
| 163 | "-c", "protocol.allow=never", | |
| 164 | "-c", "protocol.http.allow=always", | |
| 165 | "-c", "protocol.https.allow=always", | |
| 166 | "-c", "http.followRedirects=false", | |
| 167 | "-c", "http.lowSpeedLimit=1000", | |
| 168 | "-c", "http.lowSpeedTime=15", | |
| 169 | "fetch", "--no-tags", "--quiet", "--force", | |
| 170 | up.url, | |
| 171 | `refs/heads/${up.branch}:${ref}`, | |
| 172 | ], | |
| 173 | { | |
| 174 | cwd: dir, | |
| 175 | timeoutMs: 30_000, | |
| 176 | env: { | |
| 177 | GIT_CONFIG_COUNT: "1", | |
| 178 | GIT_CONFIG_KEY_0: "http.extraHeader", | |
| 179 | GIT_CONFIG_VALUE_0: `Authorization: Basic ${auth}`, | |
| 180 | }, | |
| 181 | }, | |
| 182 | ); | |
| 183 | if (!fetched.ok) return err("the parent could not be reached"); | |
| 184 | const tip = await runGit(["rev-parse", "--verify", ref], { cwd: dir }); | |
| 185 | return tip.ok ? ok(tip.value.trim()) : err("the parent has no such branch"); | |
| 186 | } | |
| 187 | ||
| 188 | /** Record a refresh: the standing it found, or why it found none. */ | |
| 189 | export function recordUpstream( | |
| 190 | db: Database, | |
| 191 | repoId: string, | |
| 192 | outcome: { standing: Standing } | { error: string }, | |
| 193 | ): void { | |
| 194 | const now = new Date().toISOString(); | |
| 195 | if ("standing" in outcome) | |
| 196 | db.query( | |
| 197 | "UPDATE upstream SET standing = ?2, checked_at = ?3, error = NULL WHERE repo_id = ?1", | |
| 198 | ).run(repoId, JSON.stringify(outcome.standing), now); | |
| 199 | else | |
| 200 | db.query("UPDATE upstream SET error = ?2, checked_at = ?3 WHERE repo_id = ?1").run( | |
| 201 | repoId, | |
| 202 | outcome.error, | |
| 203 | now, | |
| 204 | ); | |
| 205 | } | |
| 206 |
src/http/api.ts +111
| @@ -38,7 +38,16 @@ import { listChildren } from "../actions/spawn.ts"; | ||
| 38 | 38 | import { forgeState, PARENT_HEADER } from "../spawn/clients.ts"; |
| 39 | 39 | import { reissueDoor, spawnDoor } from "../spawn/door.ts"; |
| 40 | 40 | import { listSecrets, putSecret, removeSecret } from "../actions/secrets.ts"; |
| 41 | import type { Upstream } from "../core/upstream.ts"; | |
| 41 | 42 | import { proposeUpstream } from "../actions/upstream.ts"; |
| 43 | import { | |
| 44 | followUpstream, | |
| 45 | grantUpstream, | |
| 46 | readUpstream, | |
| 47 | revokeUpstream, | |
| 48 | takeUpstream, | |
| 49 | unfollowUpstream, | |
| 50 | } from "../actions/upstream_follow.ts"; | |
| 42 | 51 | import { relationOf, syncFork, takeUpdates } from "../actions/forks.ts"; |
| 43 | 52 | import { convergeFork, convergeState } from "../crew/converge.ts"; |
| 44 | 53 | import { markReaders, mayDirectCrew } from "../crew/direct.ts"; |
| @@ -1004,6 +1013,23 @@ function loadRepo(ctx: Ctx): Repo | undefined { | ||
| 1004 | 1013 | return repo && canRead(ctx.app.db, repo, ctx.auth.user) ? repo : undefined; |
| 1005 | 1014 | } |
| 1006 | 1015 | |
| 1016 | /** The cached standing of a parent on another forge, as JSON. */ | |
| 1017 | function upstreamJson(up: Upstream) { | |
| 1018 | return { | |
| 1019 | url: up.url, | |
| 1020 | branch: up.branch, | |
| 1021 | state: up.standing?.state ?? null, | |
| 1022 | behind: up.standing?.behind ?? null, | |
| 1023 | ahead: up.standing?.ahead ?? null, | |
| 1024 | clean: up.standing?.clean ?? null, | |
| 1025 | conflicts: up.standing?.conflicts ?? [], | |
| 1026 | checkedAt: up.checkedAt ?? null, | |
| 1027 | // Set while the parent cannot be reached; the standing above is the last | |
| 1028 | // one read, and the child is as it was. | |
| 1029 | unreachable: up.error ?? null, | |
| 1030 | }; | |
| 1031 | } | |
| 1032 | ||
| 1007 | 1033 | function dirOf(ctx: Ctx, repo: Repo): string { |
| 1008 | 1034 | return repoDir(ctx.app.reposRoot, repo.ownerName, repo.name); |
| 1009 | 1035 | } |
| @@ -1780,6 +1806,91 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 1780 | 1806 | }, |
| 1781 | 1807 | ); |
| 1782 | 1808 | |
| 1809 | // ── a parent on another forge (docs/FOLLOWING.md, "Across forges"). The | |
| 1810 | // parent shares and revokes; the child follows, reads its cached standing | |
| 1811 | // and takes updates. Reading never waits on the parent. | |
| 1812 | router.add("POST", "/api/v1/repos/:owner/:name/share", async (ctx) => { | |
| 1813 | const denied = requireScope(ctx, "admin"); | |
| 1814 | if (denied) return denied; | |
| 1815 | const repo = loadRepo(ctx); | |
| 1816 | if (!repo) return notFound(); | |
| 1817 | const granted = grantUpstream(ctx.app, ctx.auth.user, repo, ctx.url.origin); | |
| 1818 | return granted.ok ? json(granted.value, 201) : notFound(); | |
| 1819 | }); | |
| 1820 | ||
| 1821 | router.add("POST", "/api/v1/repos/:owner/:name/share/revoke", async (ctx) => { | |
| 1822 | const denied = requireScope(ctx, "admin"); | |
| 1823 | if (denied) return denied; | |
| 1824 | const repo = loadRepo(ctx); | |
| 1825 | if (!repo) return notFound(); | |
| 1826 | const input = await body(ctx.request); | |
| 1827 | return revokeUpstream(ctx.app, ctx.auth.user, repo, str(input.token)) | |
| 1828 | ? json({ revoked: true }) | |
| 1829 | : notFound(); | |
| 1830 | }); | |
| 1831 | ||
| 1832 | router.add("PUT", "/api/v1/repos/:owner/:name/upstream", async (ctx) => { | |
| 1833 | const denied = requireScope(ctx, "rw"); | |
| 1834 | if (denied) return denied; | |
| 1835 | const repo = loadRepo(ctx); | |
| 1836 | if (!repo) return notFound(); | |
| 1837 | const input = await body(ctx.request); | |
| 1838 | const followed = followUpstream(ctx.app, ctx.auth.user, repo, { | |
| 1839 | url: str(input.url), | |
| 1840 | branch: str(input.branch) || repo.defaultBranch, | |
| 1841 | token: str(input.token), | |
| 1842 | }); | |
| 1843 | if (!followed.ok) return respondAccess(followed.error, 422); | |
| 1844 | return json(upstreamJson(followed.value), 201); | |
| 1845 | }); | |
| 1846 | ||
| 1847 | router.add("DELETE", "/api/v1/repos/:owner/:name/upstream", (ctx) => { | |
| 1848 | const denied = requireScope(ctx, "rw"); | |
| 1849 | if (denied) return denied; | |
| 1850 | const repo = loadRepo(ctx); | |
| 1851 | if (!repo) return notFound(); | |
| 1852 | const left = unfollowUpstream(ctx.app, ctx.auth.user, repo); | |
| 1853 | return left.ok ? json({ unfollowed: left.value }) : respondAccess(left.error, 403); | |
| 1854 | }); | |
| 1855 | ||
| 1856 | router.add("GET", "/api/v1/repos/:owner/:name/upstream", (ctx) => { | |
| 1857 | const repo = loadRepo(ctx); | |
| 1858 | if (!repo) return notFound(); | |
| 1859 | const up = readUpstream(ctx.app, repo); | |
| 1860 | return up === undefined | |
| 1861 | ? apiError("not_following", 404, "this repository follows no other forge") | |
| 1862 | : json(upstreamJson(up)); | |
| 1863 | }); | |
| 1864 | ||
| 1865 | router.add("POST", "/api/v1/repos/:owner/:name/upstream/take", async (ctx) => { | |
| 1866 | const denied = requireScope(ctx, "rw"); | |
| 1867 | if (denied) return denied; | |
| 1868 | const repo = loadRepo(ctx); | |
| 1869 | if (!repo) return notFound(); | |
| 1870 | const took = await takeUpstream(ctx.app, ctx.auth.user, repo); | |
| 1871 | if (took.ok) return json(took.value); | |
| 1872 | const e = took.error; | |
| 1873 | if (e === "not_following") | |
| 1874 | return apiError(e, 404, "this repository follows no other forge"); | |
| 1875 | if (typeof e === "string") return respondAccess(e, 403); | |
| 1876 | if (e.kind === "unreachable") | |
| 1877 | return apiError("unreachable", 502, `${e.message}; nothing here was changed`); | |
| 1878 | if (e.kind === "conflict") | |
| 1879 | return json( | |
| 1880 | { | |
| 1881 | error: "conflict", | |
| 1882 | message: "both sides changed these files; the crew can converge", | |
| 1883 | files: e.files, | |
| 1884 | }, | |
| 1885 | 409, | |
| 1886 | ); | |
| 1887 | return apiError( | |
| 1888 | e.kind, | |
| 1889 | 409, | |
| 1890 | e.kind === "moved" ? "something moved while this was read; try again" : e.message, | |
| 1891 | ); | |
| 1892 | }); | |
| 1893 | ||
| 1783 | 1894 | router.add( |
| 1784 | 1895 | "POST", |
| 1785 | 1896 | "/api/v1/repos/:owner/:name/following/propose", |
src/http/server.ts +27 −2
| @@ -412,6 +412,31 @@ import { getVerifiedDomain } from "../core/domains.ts"; | ||
| 412 | 412 | |
| 413 | 413 | const NO_AUTH: Auth = { user: undefined, scope: undefined, via: "none" }; |
| 414 | 414 | |
| 415 | /** | |
| 416 | * A token held to repositories (`token_repo`) is good for one thing: reading | |
| 417 | * those repositories over git. Anywhere else it is no credential at all, so | |
| 418 | * what a parent hands a child to follow it opens nothing but what was shared. | |
| 419 | */ | |
| 420 | function heldTo( | |
| 421 | app: App, | |
| 422 | request: Request, | |
| 423 | only: readonly string[] | undefined, | |
| 424 | ): boolean { | |
| 425 | if (only === undefined) return true; | |
| 426 | const path = new URL(request.url).pathname; | |
| 427 | const m = /^\/([^/]+)\/([^/]+)\.git\/(?:info\/refs|git-upload-pack)$/.exec( | |
| 428 | path, | |
| 429 | ); | |
| 430 | if (m === null || request.method === "PUT") return false; | |
| 431 | let repo; | |
| 432 | try { | |
| 433 | repo = getRepo(app.db, decodeURIComponent(m[1]!), decodeURIComponent(m[2]!)); | |
| 434 | } catch { | |
| 435 | return false; | |
| 436 | } | |
| 437 | return repo !== undefined && only.includes(repo.id); | |
| 438 | } | |
| 439 | ||
| 415 | 440 | async function resolveAuth(app: App, request: Request): Promise<Auth> { |
| 416 | 441 | // The platform edge, when there is one, has already signed this person |
| 417 | 442 | // in; its word outranks a cookie of ours. |
| @@ -450,7 +475,7 @@ async function resolveAuth(app: App, request: Request): Promise<Auth> { | ||
| 450 | 475 | // Bearer is always a token. |
| 451 | 476 | if (header.startsWith("Bearer ")) { |
| 452 | 477 | const verified = verifyToken(app.db, header.slice(7)); |
| 453 | if (verified.ok) { | |
| 478 | if (verified.ok && heldTo(app, request, verified.value.only)) { | |
| 454 | 479 | return { |
| 455 | 480 | user: verified.value.user, |
| 456 | 481 | scope: verified.value.scope, |
| @@ -472,7 +497,7 @@ async function resolveAuth(app: App, request: Request): Promise<Auth> { | ||
| 472 | 497 | |
| 473 | 498 | if (secret.startsWith("forge_")) { |
| 474 | 499 | const verified = verifyToken(app.db, secret); |
| 475 | if (verified.ok) { | |
| 500 | if (verified.ok && heldTo(app, request, verified.value.only)) { | |
| 476 | 501 | return { |
| 477 | 502 | user: verified.value.user, |
| 478 | 503 | scope: verified.value.scope, |
test/upstream.test.ts added +218
| @@ -0,0 +1,218 @@ | ||
| 1 | /** | |
| 2 | * Following a parent on another forge: two forges in one process, the child | |
| 3 | * reading the parent's branch over HTTPS git (plain http on loopback here) | |
| 4 | * with a read-only token the parent minted for the shared repository alone. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, describe, 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 { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 12 | import { refreshUpstream } from "../src/actions/upstream_follow.ts"; | |
| 13 | import type { Repo } from "../src/core/repos.ts"; | |
| 14 | import { createToken } from "../src/core/tokens.ts"; | |
| 15 | import { createUser, type User } from "../src/core/users.ts"; | |
| 16 | import { getUpstream, parseUpstreamUrl } from "../src/core/upstream.ts"; | |
| 17 | import { resolveSecrets } from "../src/core/secret_store.ts"; | |
| 18 | import { runGit } from "../src/git/env.ts"; | |
| 19 | import { resolveOid } from "../src/git/merge.ts"; | |
| 20 | import { repoDir } from "../src/git/repos.ts"; | |
| 21 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 22 | ||
| 23 | describe("following a parent on another forge", () => { | |
| 24 | let dirs: string[] = []; | |
| 25 | let parentApp: App; | |
| 26 | let childApp: App; | |
| 27 | let parentServer: Servers; | |
| 28 | let childServer: Servers; | |
| 29 | let alice: User; | |
| 30 | let carol: User; | |
| 31 | let notes: Repo; | |
| 32 | let secret: Repo; | |
| 33 | let kid: Repo; | |
| 34 | let aliceAdmin: string; | |
| 35 | let carolRw: string; | |
| 36 | let grant: { id: string; token: string; url: string }; | |
| 37 | ||
| 38 | const mk = async (name: string) => { | |
| 39 | const dir = await mkdtemp(join(tmpdir(), `forge-up-${name}-`)); | |
| 40 | dirs.push(dir); | |
| 41 | return dir; | |
| 42 | }; | |
| 43 | const child = (path: string, init: RequestInit = {}) => | |
| 44 | fetch(`${childServer.url}/api/v1/repos/carol/kid${path}`, { | |
| 45 | ...init, | |
| 46 | headers: { authorization: `Bearer ${carolRw}`, "content-type": "application/json" }, | |
| 47 | }); | |
| 48 | const parentCommit = (path: string, content: string, message = path) => | |
| 49 | commitToBranch(parentApp, alice, notes, { message, files: [{ path, content }] }); | |
| 50 | const childCommit = (path: string, content: string) => | |
| 51 | commitToBranch(childApp, carol, kid, { message: path, files: [{ path, content }] }); | |
| 52 | const tip = (app: App, repo: Repo) => | |
| 53 | resolveOid(repoDir(app.reposRoot, repo.ownerName, repo.name), "refs/heads/main"); | |
| 54 | const standing = async () => { | |
| 55 | await refreshUpstream(childApp, kid); | |
| 56 | return (await (await child("/upstream")).json()) as any; | |
| 57 | }; | |
| 58 | ||
| 59 | beforeAll(async () => { | |
| 60 | parentApp = createApp({ dataDir: await mk("parent"), port: 0 }); | |
| 61 | childApp = createApp({ dataDir: await mk("child"), port: 0 }); | |
| 62 | parentServer = await serve(parentApp); | |
| 63 | childServer = await serve(childApp); | |
| 64 | const a = await createUser(parentApp.db, { trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 65 | const c = await createUser(childApp.db, { trusted: true, username: "carol", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 66 | if (!a.ok || !c.ok) throw new Error("users"); | |
| 67 | alice = a.value; | |
| 68 | carol = c.value; | |
| 69 | aliceAdmin = createToken(parentApp.db, alice.id, "admin", "admin").token; | |
| 70 | carolRw = createToken(childApp.db, carol.id, "rw", "rw").token; | |
| 71 | const n = await createRepo(parentApp, alice, { name: "notes" }); | |
| 72 | const s = await createRepo(parentApp, alice, { name: "secret" }); | |
| 73 | const k = await createRepo(childApp, carol, { name: "kid" }); | |
| 74 | if (!n.ok || !s.ok || !k.ok) throw new Error("repos"); | |
| 75 | notes = n.value; | |
| 76 | secret = s.value; | |
| 77 | kid = k.value; | |
| 78 | await parentCommit("a.txt", "one\n", "seed"); | |
| 79 | await commitToBranch(parentApp, alice, secret, { message: "s", files: [{ path: "s.txt", content: "s" }] }); | |
| 80 | // The child is spawned holding the parent's history so far. | |
| 81 | const kidDir = repoDir(childApp.reposRoot, "carol", "kid"); | |
| 82 | await runGit(["fetch", "--quiet", repoDir(parentApp.reposRoot, "alice", "notes"), "main"], { cwd: kidDir }); | |
| 83 | await runGit(["update-ref", "refs/heads/main", "FETCH_HEAD"], { cwd: kidDir }); | |
| 84 | const res = await fetch(`${parentServer.url}/api/v1/repos/alice/notes/share`, { | |
| 85 | method: "POST", | |
| 86 | headers: { authorization: `Bearer ${aliceAdmin}` }, | |
| 87 | }); | |
| 88 | expect(res.status).toBe(201); | |
| 89 | grant = (await res.json()) as any; | |
| 90 | }, 30_000); | |
| 91 | ||
| 92 | afterAll(async () => { | |
| 93 | parentServer.stop(); | |
| 94 | childServer.stop(); | |
| 95 | parentApp.close(); | |
| 96 | childApp.close(); | |
| 97 | for (const d of dirs) await rm(d, { recursive: true, force: true }); | |
| 98 | }); | |
| 99 | ||
| 100 | test("the token reads the shared repository over git and nothing else", async () => { | |
| 101 | const basic = `Basic ${Buffer.from(`up:${grant.token}`).toString("base64")}`; | |
| 102 | const refs = (repo: string) => | |
| 103 | fetch(`${parentServer.url}/alice/${repo}.git/info/refs?service=git-upload-pack`, { headers: { authorization: basic } }); | |
| 104 | expect((await refs("notes")).status).toBe(200); | |
| 105 | // Alice could read `secret`; her held token cannot. | |
| 106 | expect((await refs("secret")).status).not.toBe(200); | |
| 107 | // Not the API, even for the shared repository. | |
| 108 | const api = await fetch(`${parentServer.url}/api/v1/repos/alice/notes`, { headers: { authorization: `Bearer ${grant.token}` } }); | |
| 109 | expect(api.status).not.toBe(200); | |
| 110 | // Read-only: no push, whatever the path. | |
| 111 | const push = await fetch(`${parentServer.url}/alice/notes.git/info/refs?service=git-receive-pack`, { headers: { authorization: basic } }); | |
| 112 | expect(push.status).not.toBe(200); | |
| 113 | }); | |
| 114 | ||
| 115 | test("a stranger cannot mint a token for the repository", async () => { | |
| 116 | const bob = await createUser(parentApp.db, { trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" }); | |
| 117 | if (!bob.ok) throw new Error("bob"); | |
| 118 | const t = createToken(parentApp.db, bob.value.id, "admin", "admin").token; | |
| 119 | const res = await fetch(`${parentServer.url}/api/v1/repos/alice/notes/share`, { method: "POST", headers: { authorization: `Bearer ${t}` } }); | |
| 120 | expect(res.status).toBe(404); | |
| 121 | }); | |
| 122 | ||
| 123 | test("the boundary refuses a bad url and a bad token; the token is stored as a secret", async () => { | |
| 124 | for (const bad of [ | |
| 125 | { url: "ftp://x/y/z.git", token: grant.token }, | |
| 126 | { url: "http://evil.example/a/b.git", token: grant.token }, | |
| 127 | { url: "https://user:[email protected]/a/b.git", token: grant.token }, | |
| 128 | { url: grant.url, token: "nope" }, | |
| 129 | { url: grant.url, token: grant.token, branch: "a..b" }, | |
| 130 | ]) | |
| 131 | expect((await child("/upstream", { method: "PUT", body: JSON.stringify(bad) })).status).toBe(422); | |
| 132 | expect(parseUpstreamUrl("https://forge.example/a/b.git")?.host).toBe("forge.example"); | |
| 133 | const ok = await child("/upstream", { method: "PUT", body: JSON.stringify({ url: grant.url, token: grant.token }) }); | |
| 134 | expect(ok.status).toBe(201); | |
| 135 | // Not in the row, not in the answer; sealed in the secret store. | |
| 136 | expect(JSON.stringify(await ok.json())).not.toContain(grant.token); | |
| 137 | expect(JSON.stringify(getUpstream(childApp.db, kid.id))).not.toContain(grant.token); | |
| 138 | const held = resolveSecrets(childApp.db, childApp.config.dataDir, childApp.bus, ["UPSTREAM_TOKEN"], { repo: kid.id }); | |
| 139 | expect(held["UPSTREAM_TOKEN"]).toBe(grant.token); | |
| 140 | }); | |
| 141 | ||
| 142 | test("a read answers from the cache and never waits on the parent", async () => { | |
| 143 | const first = (await (await child("/upstream")).json()) as any; | |
| 144 | expect(first.state).toBeNull(); | |
| 145 | expect(first.checkedAt).toBeNull(); | |
| 146 | expect((await standing()).state).toBe("synced"); | |
| 147 | }); | |
| 148 | ||
| 149 | test("behind, then taking updates fast-forwards the child", async () => { | |
| 150 | await parentCommit("b.txt", "two\n"); | |
| 151 | const s = await standing(); | |
| 152 | expect([s.state, s.behind, s.ahead]).toEqual(["behind", 1, 0]); | |
| 153 | const took = await child("/upstream/take", { method: "POST" }); | |
| 154 | expect(took.status).toBe(200); | |
| 155 | expect(((await took.json()) as any).updated).toBe(true); | |
| 156 | expect(await tip(childApp, kid)).toBe(await tip(parentApp, notes)); | |
| 157 | expect((await standing()).state).toBe("synced"); | |
| 158 | }); | |
| 159 | ||
| 160 | test("ahead, then diverged and clean merges", async () => { | |
| 161 | await childCommit("c.txt", "mine\n"); | |
| 162 | const ahead = await standing(); | |
| 163 | expect([ahead.state, ahead.behind, ahead.ahead]).toEqual(["ahead", 0, 1]); | |
| 164 | await parentCommit("d.txt", "theirs\n"); | |
| 165 | const div = await standing(); | |
| 166 | expect([div.state, div.behind, div.ahead, div.clean]).toEqual(["diverged", 1, 1, true]); | |
| 167 | const took = (await (await child("/upstream/take", { method: "POST" })).json()) as any; | |
| 168 | expect(took.merged).toBe(true); | |
| 169 | const files = await runGit(["ls-tree", "--name-only", "refs/heads/main"], { cwd: repoDir(childApp.reposRoot, "carol", "kid") }); | |
| 170 | expect(files.ok && files.value.split("\n").sort()).toEqual(["a.txt", "b.txt", "c.txt", "d.txt"]); | |
| 171 | }); | |
| 172 | ||
| 173 | test("a conflict is a decision: reported with the files, nothing half-applied", async () => { | |
| 174 | await parentCommit("a.txt", "parent says\n"); | |
| 175 | await childCommit("a.txt", "child says\n"); | |
| 176 | const s = await standing(); | |
| 177 | expect([s.state, s.clean, s.conflicts]).toEqual(["diverged", false, ["a.txt"]]); | |
| 178 | const before = await tip(childApp, kid); | |
| 179 | const took = await child("/upstream/take", { method: "POST" }); | |
| 180 | expect(took.status).toBe(409); | |
| 181 | expect(((await took.json()) as any).files).toEqual(["a.txt"]); | |
| 182 | expect(await tip(childApp, kid)).toBe(before); | |
| 183 | }); | |
| 184 | ||
| 185 | test("revoking the token makes the parent unreachable: said so, child untouched, pages still answer", async () => { | |
| 186 | const before = await tip(childApp, kid); | |
| 187 | const revoke = await fetch(`${parentServer.url}/api/v1/repos/alice/notes/share/revoke`, { | |
| 188 | method: "POST", | |
| 189 | headers: { authorization: `Bearer ${aliceAdmin}`, "content-type": "application/json" }, | |
| 190 | body: JSON.stringify({ token: grant.id }), | |
| 191 | }); | |
| 192 | expect(revoke.status).toBe(200); | |
| 193 | const s = await standing(); | |
| 194 | expect(s.unreachable).toContain("could not be reached"); | |
| 195 | // The last standing survives the failure. | |
| 196 | expect(s.state).toBe("diverged"); | |
| 197 | const took = await child("/upstream/take", { method: "POST" }); | |
| 198 | expect(took.status).toBe(502); | |
| 199 | expect(await tip(childApp, kid)).toBe(before); | |
| 200 | }); | |
| 201 | ||
| 202 | test("a parent that is gone is unreachable too, and a read stays instant", async () => { | |
| 203 | parentServer.stop(); | |
| 204 | const t0 = performance.now(); | |
| 205 | const read = await child("/upstream"); | |
| 206 | expect(read.status).toBe(200); | |
| 207 | expect(performance.now() - t0).toBeLessThan(1000); | |
| 208 | expect(((await standing()) as any).unreachable).not.toBeNull(); | |
| 209 | }); | |
| 210 | ||
| 211 | test("unfollowing removes the row and the secret", async () => { | |
| 212 | const res = await child("/upstream", { method: "DELETE" }); | |
| 213 | expect(res.status).toBe(200); | |
| 214 | expect((await child("/upstream")).status).toBe(404); | |
| 215 | const held = resolveSecrets(childApp.db, childApp.config.dataDir, childApp.bus, ["UPSTREAM_TOKEN"], { repo: kid.id }); | |
| 216 | expect(held["UPSTREAM_TOKEN"]).toBeUndefined(); | |
| 217 | }); | |
| 218 | }); |
new above
offline