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

Every hosted forge holds a proposal credential, and a refusal says when it does not #13725

Merged opened this in answer to

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

Merged

torque/forge:torque/13706-every-hosted-forge-holds-a-proposal-cred → main 6 commits fork 3 threads · 3 unresolved

  • Merged. torque/13706-every-hosted-forge-holds-a-proposal-cred was merged into main as 2f4eb9c.

Review

Sign in to review this change.
16 files changed +563 −52
docs/features/README.md +1
@@ -18,6 +18,7 @@ Read with the guide page [What a forge is](../guide-what-a-forge-is.md).
1818
1919 - [A forge made from a template says so on its home](started-from.md)
2020 - [First week: three steps on a new forge's home](first-week.md)
21 - [A hosted forge proposes to its parent once the parent has handed it a credential](propose-to-parent.md)
2122 - [How long the last forge from a template took, at /templates/<name>](template-timing.md)
2223 - [A look in the feed](feed-look.md)
2324 - [Open pulls red for over a day are named in one issue](red-pulls.md)
docs/features/propose-to-parent.md added +21
@@ -0,0 +1,21 @@
1 # Proposing to the parent forge
2
3 A hosted forge that follows its parent's code can offer a change up as a pull on the parent. That needs a **proposal credential**: a token that may read the parent repository, push `child/<name>/…` branches there and open a pull from one, and nothing else.
4
5 ## When a forge holds one
6
7 The parent hands every finished child with a live chain a credential on its own pass, which runs every 5 minutes, and renews it a week before it ends (it lives 30 days). A child that keeps reporting never lapses; one that stops ends by itself. A forge that severed its code link is handed nothing.
8
9 The parent mints it as the person who spawned the child, and only while that person may write to the parent repository. If they cannot, or the child has no https address, the child is skipped and holds none.
10
11 ## When it does not
12
13 Proposing before the credential arrives is refused on every door with the same words, `this forge holds no proposal credential: its parent hands one over on its next pass (every 5 minutes), so wait for that or ask the parent's admin to check the forge is reporting`:
14
15 - **API:** `POST /api/v1/repos/:owner/:name/following/propose-parent` answers `409` with `no_credential`.
16 - **MCP:** `propose_to_parent_forge` answers `no_credential: …`.
17 - **Web:** the Offer this change button flashes the sentence on the following page.
18
19 Wait one pass and press again. If it still refuses, the parent's admin should check the forge is reporting and that its spawner still writes to the parent repository.
20
21 The words live in `src/actions/family_words.ts`; the interval there is the one `src/spawn/proposal_handout.ts` runs on.
src/actions/family_words.ts +9
@@ -3,11 +3,20 @@
33 * rules is told, typed once so the API, MCP and the contract read the same
44 * sentence from one place.
55 */
6 /**
7 * How often a parent looks over its children's proposal credentials; the refusal below types the
8 * same number.
9 */
10 export const HANDOUT_EVERY_MINUTES = 5;
11
612 export const FAMILY_WORDS = {
713 /** Proposing to the parent forge with no commit ahead of it. */
outdated

Says 'every ten minutes'; the handout pass runs every 5 minutes (HANDOUT_EVERY_MS). Make them agree.

814 nothing_to_propose: "nothing here is ahead of the parent forge",
915 /** Taking, severing or changing the mode of a repository with no chain across forges. */
1016 not_following: "this repository follows nothing across forges",
17 /** Proposing from a forge whose parent has not yet handed it a proposal credential. */
18 no_credential:
19 "this forge holds no proposal credential: its parent hands one over on its next pass (every 5 minutes), so wait for that or ask the parent's admin to check the forge is reporting",
1120 /** Showing or hiding a migration trail on a repository that was never migrated. */
1221 no_provenance: "this repository was not migrated here",
1322 } as const;
src/actions/upstream.ts +4 −2
@@ -145,6 +145,7 @@ export interface ForgeProposal {
145145 export type ProposeForgeError =
146146 | AccessError
147147 | "no_parent_forge"
148 | "no_credential"
148149 | "nothing_to_propose"
149150 | { readonly kind: "refused"; readonly reason: string }
150151 | { readonly kind: "unreachable" };
@@ -206,8 +207,9 @@ export async function proposeToParentForge(
206207 if (!writer.ok) return writer;
207208 const link = await forgeLinkOf(app);
208209 const cred = await parentCredential(app);
209 if (link === undefined || cred === undefined || link.repo !== `${repo.ownerName}/${repo.name}`)
210 return err("no_parent_forge");
210 if (link === undefined || link.repo !== `${repo.ownerName}/${repo.name}`) return err("no_parent_forge");
211 // A forge with a live chain but no handed credential says so, rather than that it has no parent.
212 if (cred === undefined) return err("no_credential");
211213
212214 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
213215 const tip = await resolveOid(dir, `refs/heads/${repo.defaultBranch}`);
src/contract/openapi/routes/postApiV1ReposOwnerNameFollowingProposeParent.ts +1
@@ -9,6 +9,7 @@ export const route: Route = {
99 role: "member",
1010 refusals: {
1111 no_parent_forge: "404: this repository has no parent forge to propose to",
12 no_credential: `409: ${FAMILY_WORDS.no_credential}`,
1213 nothing_to_propose: `409: ${FAMILY_WORDS.nothing_to_propose}`,
1314 parent_unreachable: "502: the parent forge did not answer",
1415 refused: "409: the parent forge refused, with the reason",
src/core/proposal_token.ts +19 −2
@@ -123,7 +123,21 @@ export function renewFollowTokens(db: Database, repoId: string, child: string, n
123123 .all(repoId, child, new Date(now + FOLLOW_TTL_MS).toISOString()).length;
124124 }
125125
126 /** End every follow token minted for a child, whatever the repository: the child is gone. How many ended. */
126 /** End the proposal tokens a child holds for one repository, except `keep`; how many ended. */
127 export function revokeProposalTokens(db: Database, repoId: string, child: string, keep: string): number {
128 return db
129 .query<{ id: string }, [string, string, string]>(
130 `DELETE FROM token WHERE id IN
131 (SELECT token_id FROM proposal_token WHERE repo_id = ?1 AND child = ?2 AND read_only = 0 AND token_id != ?3)
132 RETURNING id`,
133 )
134 .all(repoId, child, keep).length;
135 }
136
137 /**
138 * End every follow token minted for a child, whatever the repository: the child is gone. How many
139 * ended.
140 */
127141 export function revokeChildFollowTokens(db: Database, child: string): number {
128142 return db
129143 .query<{ id: string }, [string]>(
@@ -246,7 +260,10 @@ export function listProposalTokens(
246260 }));
247261 }
248262
249 /** End one proposal token of this person's for this repository; with `follows`, also a follow token anyone's. */
263 /**
264 * End one proposal token of this person's for this repository; with `follows`, also a follow token
265 * anyone's.
266 */
250267 export function deleteProposalToken(
251268 db: Database,
252269 userId: string,
src/http/api/following.ts +3 −2
@@ -24,8 +24,8 @@ import { apiError, body, json, notFound, requireScope, respondAccess, tryAgain,
2424 import type { Router } from "../router.ts";
2525
2626 /**
27 * A body tagged by its own bytes (the standing, or the proposals to the parent): a push to the fork or to the parent's
28 * default branch, or a severed chain, changes them, and a viewer who cannot see
27 * A body tagged by its own bytes (the standing, or the proposals to the parent): a push to the fork
28 * or to the parent's default branch, or a severed chain, changes them, and a viewer who cannot see
2929 * the parent is rendered a different body, so never shares a tag with one who can.
3030 */
3131 function tagged(request: Request, payload: unknown): Response {
@@ -197,6 +197,7 @@ export function followingRoutes(router: Router<Handler>): void {
197197 const e = made.error;
198198 if (e === "no_parent_forge")
199199 return apiError("no_parent_forge", 404, "this repository has no parent forge to propose to");
200 if (e === "no_credential") return apiError("no_credential", 409, FAMILY_WORDS.no_credential);
200201 if (e === "nothing_to_propose")
201202 return apiError("nothing_to_propose", 409, FAMILY_WORDS.nothing_to_propose);
202203 if (typeof e === "string") return respondAccess(e, 403);
src/http/mcp/tools/propose_to_parent_forge.ts +1
@@ -44,6 +44,7 @@ export const tool: Tool = {
4444 });
4545 const e = made.error;
4646 if (e === "no_parent_forge") return bad(e, "this forge has no parent forge to propose to");
47 if (e === "no_credential") return bad(e, FAMILY_WORDS.no_credential);
4748 if (e === "nothing_to_propose") return bad(e, FAMILY_WORDS.nothing_to_propose);
4849 if (typeof e === "string") return bad(e, "you need write access to propose from here");
4950 return e.kind === "unreachable"
src/spawn/app_follow.ts +19 −6
@@ -23,6 +23,7 @@ import { applyAppLinks, entriesOf, reasonOf, reconcileAppLinks } from "./app_lin
2323 import { noticeOwners } from "./archive.ts";
2424 import { refreshServed } from "./clients.ts";
2525 import { hostedChildOpen, openChildren } from "./host.ts";
26 import { handProposalCredentials } from "./proposal_handout.ts";
2627
2728 /** Look at every app this forge follows from its parent, now, whatever the clock says. */
2829 export async function followParentNow(app: App, label = "this forge"): Promise<number> {
@@ -35,7 +36,8 @@ export async function followParentNow(app: App, label = "this forge"): Promise<n
3536 const result = await checkUpstream(app, repo);
3637 if (result.ok) {
3738 checked++;
38 // What taking it did, said when it did something: moved the branch, or (the app has commits of its own) proposed a pull.
39 // What taking it did, said when it did something: moved the branch, or (the app has commits
40 // of its own) proposed a pull.
3941 if (result.value.outcome !== "none")
4042 app.log.info("app followed", {
4143 forge: label,
@@ -70,7 +72,9 @@ export async function followTick(app: App, boot = false): Promise<void> {
7072 const applied = await applyAppLinks(app);
7173 if (applied.linked.length > 0) await followParentNow(app);
7274 await reconcileAppLinks(app);
73 // One child that cannot be opened or linked is that child's trouble: the rest are looked at all the same.
75 await handProposalCredentials(app);
76 // One child that cannot be opened or linked is that child's trouble: the rest are looked at all
77 // the same.
7478 for (const { name, app: child } of openChildren(app)) {
7579 try {
7680 if (!hostedChildOpen(app, child)) continue;
@@ -81,7 +85,8 @@ export async function followTick(app: App, boot = false): Promise<void> {
8185 app.log.warn("a hosted child's follow pass failed", { forge: name, reason: reasonOf(error) });
8286 }
8387 }
84 // The list /forges serves is read here, off any request: with a question to each child at a start, never after.
88 // The list /forges serves is read here, off any request: with a question to each child at a
89 // start, never after.
8590 const rows = await refreshServed(app, { probe: boot }).catch((error) => {
8691 app.log.warn("the forges list was not read", { reason: reasonOf(error) });
8792 return [];
@@ -111,7 +116,9 @@ export function watchLandings(parent: App): () => void {
111116 });
112117 }
113118
114 /** A hosted child's `parent.json` as its parent reads it: the child's own regular file, or nothing. */
119 /**
120 * A hosted child's `parent.json` as its parent reads it: the child's own regular file, or nothing.
121 */
115122 function readParentDoc(dir: string): Record<string, unknown> | undefined {
116123 try {
117124 const doc: unknown = JSON.parse(readPrivate(join(dir, "parent.json")) ?? "");
@@ -138,7 +145,10 @@ async function landed(parent: App, child: App, ref: string): Promise<void> {
138145 const OID = /^[0-9a-f]{40,64}$/;
139146 const REPO = /^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/;
140147
141 /** What the parent's heartbeat answer carries, as the child reads it: bounded, shaped, never trusted for more than "look now". */
148 /**
149 * What the parent's heartbeat answer carries, as the child reads it: bounded, shaped, never trusted
150 * for more than "look now".
151 */
142152 export function parseHints(v: unknown): Record<string, string> {
143153 const out: Record<string, string> = {};
144154 if (typeof v !== "object" || v === null || Array.isArray(v)) return out;
@@ -147,7 +157,10 @@ export function parseHints(v: unknown): Record<string, string> {
147157 return out;
148158 }
149159
150 /** The parent said these apps now stand at these tips: look at each whose tip this forge has not fetched. */
160 /**
161 * The parent said these apps now stand at these tips: look at each whose tip this forge has not
162 * fetched.
163 */
151164 export async function hearLandings(app: App, hints: Record<string, string>): Promise<void> {
152165 for (const [name, tip] of Object.entries(hints)) {
153166 const [o, n] = name.split("/") as [string, string];
src/spawn/parent_credential.ts +30 −6
@@ -9,7 +9,7 @@
99 import { join } from "node:path";
1010 import type { App } from "../app.ts";
1111 import { isChildName } from "../core/proposal_token.ts";
12 import { writePrivate } from "../kernel/file_modes.ts";
12 import { readPrivate, writePrivate } from "../kernel/file_modes.ts";
1313 import { err, ok, type Result } from "../kernel/result.ts";
1414 import { forgeLinkOf, originOf } from "./chain.ts";
1515
@@ -49,14 +49,38 @@ export async function parentCredential(app: App): Promise<ParentCredential | und
4949 return { url, repo: link.upstream, child, token };
5050 }
5151
52 const TOKEN = /^[\x21-\x7e]{8,200}$/;
53
54 /**
55 * Write the proposal block into the `parent.json` of the data directory `dataDir`, keeping the
56 * rest. The parent calls this on a child's directory from outside its cell (what it keeps is what
57 * `readPrivate` read, never a file a link there names); the child calls it on its own. `expiresAt`
58 * (ms) is the parent's note of when to mint a fresh one; the child never reads it.
59 */
60 export function storeProposal(
61 dataDir: string,
62 input: { child: string; token: string; expiresAt?: number },
63 ): Result<void, "invalid" | "no_parent"> {
64 if (!isChildName(input.child) || !TOKEN.test(input.token)) return err("invalid");
65 let doc: unknown;
66 try {
67 doc = JSON.parse(readPrivate(join(dataDir, "parent.json")) ?? "");
68 } catch {
69 return err("no_parent");
70 }
71 if (typeof doc !== "object" || doc === null || Array.isArray(doc)) return err("no_parent");
72 const { child, token, expiresAt } = input;
73 writePrivate(
74 join(dataDir, "parent.json"),
75 JSON.stringify({ ...doc, proposal: { child, token, ...(expiresAt === undefined ? {} : { expiresAt }) } }),
76 );
77 return ok();
78 }
79
5280 /** Keep the token a parent minted for this child. The rest of `parent.json` stays as it is. */
5381 export async function keepParentCredential(
5482 app: App,
5583 input: { child: string; token: string },
5684 ): Promise<Result<void, "invalid" | "no_parent">> {
57 if (!isChildName(input.child) || !/^[\x21-\x7e]{8,200}$/.test(input.token)) return err("invalid");
58 const doc = await readDoc(app);
59 if (doc === undefined) return err("no_parent");
60 writePrivate(path(app), JSON.stringify({ ...doc, proposal: { child: input.child, token: input.token } }));
61 return ok();
85 return storeProposal(app.config.dataDir, input);
6286 }
src/spawn/proposal_handout.ts added +92
@@ -0,0 +1,92 @@
1 /**
2 * Every forge this one made holds its proposal credential: a token that may read the child's
3 * parent repository, push `child/<name>/…` branches there and open a pull from one, and nothing
4 * else (`http/proposal_gate.ts`). The parent mints it and writes it into the child's `parent.json`
5 * beside the heartbeat key (`storeProposal`), the way it already hands over the lent credit
6 * (`funding.ts`). The token lives `PROPOSAL_TTL_MS`; the parent's pass looks every few minutes and
7 * mints a fresh one when the child has none or its token is within `RENEW_BEFORE_MS` of its end, so
8 * a child that keeps reporting never lapses and one that stops ends by itself. A child that severed
9 * its code link is handed nothing, and its token is not renewed.
10 */
11
12 import type { App } from "../app.ts";
13 import { HANDOUT_EVERY_MINUTES } from "../actions/family_words.ts";
14 import { childDirOf, listChildren, type Child } from "../actions/spawn.ts";
15 import { mintProposalToken, parseOrigin, PROPOSAL_TTL_MS, revokeProposalTokens } from "../core/proposal_token.ts";
16 import { getRepo } from "../core/repos.ts";
17 import { proposalUser, readDoc } from "./app_links.ts";
18 import { storeProposal } from "./parent_credential.ts";
19
20 /** A token this near its end is replaced. */
21 export const RENEW_BEFORE_MS = 7 * 24 * 3600_000;
22 /** How often the parent looks over its children's credentials. */
23 export const HANDOUT_EVERY_MS = HANDOUT_EVERY_MINUTES * 60_000;
24
outdated

This constant is 5 minutes while the user-facing refusal promises 10. Reconcile.

25 type Handed = "handed" | "kept" | "skipped";
26
27 /** Give one child a proposal credential when it has none or its own is nearly spent. Idempotent. */
28 export function handProposalCredential(app: App, child: Child, now: number = Date.now()): Handed {
29 const dir = childDirOf(app, child.bodyId);
30 const doc = readDoc(dir);
31 const code = doc?.["forgeCode"];
32 if (doc === undefined || typeof code !== "object" || code === null) return "skipped";
33 const link = code as Record<string, unknown>;
34 if (link["severedAt"] !== undefined || typeof link["upstream"] !== "string") return "skipped";
35 const [owner, name, ...rest] = link["upstream"].split("/");
36 const parent = owner && name && rest.length === 0 ? getRepo(app.db, owner, name) : undefined;
37 if (parent === undefined) return "skipped";
38 const have = doc["proposal"];
39 const expiresAt = typeof have === "object" && have !== null ? (have as Record<string, unknown>)["expiresAt"] : undefined;
40 if (typeof expiresAt === "number" && expiresAt - now > RENEW_BEFORE_MS) return "kept";
41 // Only the spawner, and only while they may write to the parent; and only for an origin that
42 // parses.
43 const as = proposalUser(app, parent, child.ownerId);
44 const origin = parseOrigin(child.url);
45 if (as === undefined || origin === undefined) return "skipped";
46 const minted = mintProposalToken(
47 app.db,
48 as.id,
49 parent.id,
50 { child: child.name, origin },
51 now,
52 );
53 if (!minted.ok) return "skipped";
54 // A token the child never received is not left standing, whether the write refused or threw.
55 const unminted = (): void => void app.db.query("DELETE FROM token WHERE id = ?1").run(minted.value.id);
56 let stored: ReturnType<typeof storeProposal>;
outdated

Fallback origin https://<name>.invalid/ mints a token bound to a made-up host. Skip the child when the origin does not parse.

57 try {
58 stored = storeProposal(dir, { child: child.name, token: minted.value.token, expiresAt: now + PROPOSAL_TTL_MS });
59 } catch (error) {
60 unminted();
61 throw error;
62 }
63 if (!stored.ok) {
64 unminted();
65 return "skipped";
66 }
67 // Only once the child holds the new one does the old one end.
68 revokeProposalTokens(app.db, parent.id, child.name, minted.value.id);
69 return "handed";
70 }
71
72 let lastPass = 0;
73
74 /** The parent's pass over every finished child; the names handed a credential. Never throws. */
75 export async function handProposalCredentials(app: App, force = false, now: number = Date.now()): Promise<string[]> {
76 if (!force && now - lastPass < HANDOUT_EVERY_MS) return [];
77 lastPass = now;
78 const handed: string[] = [];
79 try {
80 for (const child of await listChildren(app)) {
81 if (!child.done) continue;
82 try {
83 if (handProposalCredential(app, child, now) === "handed") handed.push(child.name);
84 } catch (error) {
85 app.log.warn("proposal credential not handed", { forge: child.name, reason: String(error) });
86 }
87 }
88 } catch (error) {
89 app.log.warn("proposal credential pass failed", { error: String(error) });
90 }
91 return handed;
92 }
src/web/pages/chain.ts +11 −2
@@ -5,6 +5,7 @@
55 * sever. A severed forge says so with the date and nothing is deleted.
66 */
77
8 import { FAMILY_WORDS } from "../../actions/family_words.ts";
89 import { FOLLOW_MODE_REFUSALS, followModeSaid, setFollowMode, severForge, takeForgeCode, takeForgeWords } from "../../actions/follow.ts";
910 import { FOLLOWS_NOTHING, PROPOSE_NEEDS_WRITE } from "../../actions/follow_words.ts";
1011 import { forgeProposals, proposeToParentForge, type ForgeProposal } from "../../actions/upstream.ts";
@@ -228,7 +229,10 @@ export async function takeSubmit(ctx: Ctx): Promise<Response> {
228229 return flashOrJson(ctx, to, takeForgeWords(took.value));
229230 }
230231
231 /** POST /:owner/:name/following/mode {mode} or /following/mode/:mode (what the confirm step posts); the owner only. */
232 /**
233 * POST /:owner/:name/following/mode {mode} or /following/mode/:mode (what the confirm step posts);
234 * the owner only.
235 */
232236 export async function modeSubmit(ctx: Ctx): Promise<Response> {
233237 const repo = loadRepo(ctx);
234238 if (!repo) return notFoundPage(ctx);
@@ -241,7 +245,10 @@ export async function modeSubmit(ctx: Ctx): Promise<Response> {
241245 return flashOrJson(ctx, to, { message: followModeSaid(forkParentFor(ctx.app.db, repo, ctx.auth.user), set.value) });
242246 }
243247
244 /** POST /:owner/:name/following/propose: push to the parent forge and open the pull there; a writer only. */
248 /**
249 * POST /:owner/:name/following/propose: push to the parent forge and open the pull there; a writer
250 * only.
251 */
245252 export async function proposeParentSubmit(ctx: Ctx): Promise<Response> {
246253 const repo = loadRepo(ctx);
247254 if (!repo) return notFoundPage(ctx);
@@ -257,6 +264,8 @@ export async function proposeParentSubmit(ctx: Ctx): Promise<Response> {
257264 message:
258265 e === "no_parent_forge"
259266 ? "This forge has no parent forge to propose to."
267 : e === "no_credential"
268 ? `${FAMILY_WORDS.no_credential[0]!.toUpperCase()}${FAMILY_WORDS.no_credential.slice(1)}.`
260269 : e === "nothing_to_propose"
261270 ? "Nothing here is ahead of the parent forge."
262271 : typeof e === "string"
test/parent-forge-refusals.test.ts +4 −4
@@ -77,10 +77,10 @@ describe("proposing to a parent forge that is not there for this repository", ()
7777 forgeCode: { repo, upstream: "alice/app", mode: "tell-me", tip: "", chain: [] },
7878 });
7979
80 const refused = async (c: { app: App; user: User; repo: Repo }) => {
80 const refused = async (c: { app: App; user: User; repo: Repo }, why = "no_parent_forge") => {
8181 seen = [];
8282 const r = await proposeToParentForge(c.app, c.user, c.repo);
83 expect(r.ok ? "ok" : r.error).toBe("no_parent_forge");
83 expect(r.ok ? "ok" : r.error).toBe(why);
8484 expect(seen).toEqual([]);
8585 };
8686
@@ -95,8 +95,8 @@ describe("proposing to a parent forge that is not there for this repository", ()
9595 await refused(c);
9696 });
9797
98 test("a link with no stored credential is refused", async () => {
99 await refused(await child("alice", "app", () => doc("alice/app")));
98 test("a link with no stored credential is refused as holding none", async () => {
99 await refused(await child("alice", "app", () => doc("alice/app")), "no_credential");
100100 });
101101
102102 test("the same link with a credential gets past the refusal", async () => {
test/proposal-handout.test.ts added +188
@@ -0,0 +1,188 @@
1 /**
2 * Every hosted forge holds a proposal credential (#13725): the parent hands one to each finished
3 * child with a live chain, renews it before it ends, and the child's refusal says when it has none.
4 */
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
6 import { chmodSync, readFileSync, writeFileSync } from "node:fs";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { proposeToParentForge } from "../src/actions/upstream.ts";
11 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
12 import { childDirOf, listChildren, spawnForge } from "../src/actions/spawn.ts";
13 import { createApp, type App } from "../src/app.ts";
14 import { FAMILY_WORDS, HANDOUT_EVERY_MINUTES } from "../src/actions/family_words.ts";
15 import { PROPOSAL_TTL_MS } from "../src/core/proposal_token.ts";
16 import { getRepo, type Repo } from "../src/core/repos.ts";
17 import { verifyToken } from "../src/core/tokens.ts";
18 import { createUser, type User } from "../src/core/users.ts";
19 import { hostedPlacement } from "../src/spawn/placement.ts";
20 import { parentCredential } from "../src/spawn/parent_credential.ts";
21 import { handProposalCredential, handProposalCredentials, HANDOUT_EVERY_MS, RENEW_BEFORE_MS } from "../src/spawn/proposal_handout.ts";
22 import { quietLogs } from "./helpers/globals.ts";
23
24 quietLogs();
25
26 describe("the proposal credential a parent hands each child", () => {
27 let dir = "";
28 let parent: App;
29 let alice: User;
30 let forge: Repo;
31 let child: App;
32 let dataDir = "";
33
34 beforeAll(async () => {
35 dir = await mkdtemp(join(tmpdir(), "forge-handout-"));
36 parent = createApp({ dataDir: join(dir, "parent"), port: 0, host: "root.test", url: "https://root.test" });
37 const u = await createUser(parent.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-long-handout-passphrase", adminIfFirst: true });
38 if (!u.ok) throw new Error(String(u.error));
39 alice = u.value;
40 const made = await createRepo(parent, alice, { name: "forge", visibility: "public" });
41 if (!made.ok) throw new Error(String(made.error));
42 forge = made.value;
43 const c = await commitToBranch(parent, alice, forge, {
44 branch: "main",
45 message: "Start",
46 files: [{ path: "README.md", content: "hi\n" }],
47 });
48 if (!c.ok) throw new Error(JSON.stringify(c.error));
49 const r = await spawnForge(
50 parent,
51 alice,
52 { name: "kid", org: "kid", apps: [], carryBriefs: false, carrySubscriptions: false },
53 { catalog: [], briefs: [], subscriptions: [] },
54 {
55 placement: hostedPlacement({ host: "root.test" }),
56 request: new Request("https://root.test/x", { method: "POST", headers: { origin: "https://root.test" } }),
57 url: new URL("https://root.test/x"),
58 },
59 );
60 if (!r.ok) throw new Error(JSON.stringify(r.error));
61 dataDir = childDirOf(parent, r.value.bodyId);
62 child = createApp({ dataDir, port: 0 });
63 // A live chain: the child's code is a fork of alice/forge.
64 const file = join(dataDir, "parent.json");
65 const doc = JSON.parse(readFileSync(file, "utf8"));
66 writeFileSync(
67 file,
68 JSON.stringify({
69 ...doc,
70 upstream: "http://127.0.0.1:1",
71 forgeCode: { repo: "kid/forge", upstream: "alice/forge", mode: "tell-me", tip: "", chain: [] },
72 }),
73 );
74 });
75
76 afterAll(async () => {
77 child.db.close();
78 parent.db.close();
79 await rm(dir, { recursive: true, force: true });
80 });
81
82 const kid = async () => (await listChildren(parent)).find((c) => c.name === "kid")!;
83 const docOf = () => JSON.parse(readFileSync(join(dataDir, "parent.json"), "utf8"));
84
85 test("a child with a live chain and no credential is refused in words that say so", async () => {
86 expect(await parentCredential(child)).toBeUndefined();
87 const solo = createApp({ dataDir: join(dir, "solo"), port: 0, host: "kid.test" });
88 const owner = await createUser(solo.db, { origin: "seed", trusted: true, username: "kidowner", email: "[email protected]", password: "a-long-handout-passphrase", adminIfFirst: true });
89 if (!owner.ok) throw new Error(String(owner.error));
90 const mine = await createRepo(solo, owner.value, { name: "forge", visibility: "public" });
91 if (!mine.ok) throw new Error(String(mine.error));
92 writeFileSync(
93 join(dir, "solo", "parent.json"),
94 JSON.stringify({ upstream: "http://127.0.0.1:1", name: "kid", forgeCode: { repo: "kidowner/forge", upstream: "alice/forge", mode: "tell-me", tip: "", chain: [] } }),
95 );
96 const r = await proposeToParentForge(solo, owner.value, mine.value);
97 expect(r.ok ? "ok" : r.error).toBe("no_credential");
98 });
99
100 test("the parent hands one over, and the child reads it as its own", async () => {
101 expect(handProposalCredential(parent, await kid())).toBe("handed");
102 const cred = await parentCredential(child);
103 expect(cred?.child).toBe("kid");
104 expect(cred?.repo).toBe("alice/forge");
105 const known = verifyToken(parent.db, cred!.token);
106 expect(known.ok).toBe(true);
107 const p = known.ok ? known.value.proposal : undefined;
108 expect(p?.repoId).toBe(forge.id);
109 expect(p?.child).toBe("kid");
110 expect(p?.readOnly).toBeFalsy();
111 });
112
113 test("while it has time left, nothing is minted again", async () => {
114 const before = docOf().proposal.token;
115 expect(handProposalCredential(parent, await kid())).toBe("kept");
116 expect(docOf().proposal.token).toBe(before);
117 });
118
119 test("near its end a fresh one replaces it and the old one stops working", async () => {
120 const old = docOf().proposal.token;
121 const at = Date.now() + PROPOSAL_TTL_MS - RENEW_BEFORE_MS + 1000;
122 expect(handProposalCredential(parent, await kid(), at)).toBe("handed");
123 const now = docOf().proposal.token;
124 expect(now).not.toBe(old);
125 expect(verifyToken(parent.db, old).ok).toBe(false);
126 expect(verifyToken(parent.db, now).ok).toBe(true);
127 });
128
129 const tokens = () => parent.db.query<{ n: number }, []>("SELECT count(*) AS n FROM token").get()!.n;
130
131 test("the refusal's wait is the pass's own interval", () => {
132 expect(HANDOUT_EVERY_MS).toBe(HANDOUT_EVERY_MINUTES * 60_000);
133 expect(FAMILY_WORDS.no_credential).toContain(`every ${HANDOUT_EVERY_MINUTES} minutes`);
134 });
135
136 test("a spawner who cannot write to the parent repository gets nothing, and the owner is not stood in", async () => {
137 const bob = await createUser(parent.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-long-handout-passphrase" });
138 if (!bob.ok) throw new Error(String(bob.error));
139 const before = tokens();
140 const old = docOf().proposal?.token;
141 const at = Date.now() + 4 * PROPOSAL_TTL_MS;
142 expect(handProposalCredential(parent, { ...(await kid()), ownerId: bob.value.id }, at)).toBe("skipped");
143 expect(handProposalCredential(parent, (({ ownerId: _gone, ...rest }) => rest)(await kid()), at)).toBe("skipped");
144 expect(tokens()).toBe(before);
145 expect(docOf().proposal?.token).toBe(old);
146 });
147
148 test("a child with no parseable origin is skipped, not given a token bound to a made-up host", async () => {
149 const before = tokens();
150 const at = Date.now() + 4 * PROPOSAL_TTL_MS;
151 expect(handProposalCredential(parent, { ...(await kid()), url: "not a url" }, at)).toBe("skipped");
152 expect(tokens()).toBe(before);
153 });
154
155 test("a credential the child could not be given is not left minted", async () => {
156 const before = tokens();
157 const at = Date.now() + 4 * PROPOSAL_TTL_MS;
158 chmodSync(dataDir, 0o500);
159 try {
160 let threw = false;
161 let result = "";
162 try {
163 result = handProposalCredential(parent, await kid(), at);
164 } catch {
165 threw = true;
166 }
167 if (!threw && result === "handed") return; // a user who ignores the mode (root): nothing to prove
168 expect(threw || result === "skipped").toBe(true);
169 } finally {
170 chmodSync(dataDir, 0o700);
171 }
172 expect(tokens()).toBe(before);
173 });
174
175 test("the pass hands to every finished child and a severed chain gets nothing", async () => {
176 const file = join(dataDir, "parent.json");
177 const doc = docOf();
178 delete doc.proposal;
179 doc.forgeCode.severedAt = new Date().toISOString();
180 writeFileSync(file, JSON.stringify(doc));
181 expect(await handProposalCredentials(parent, true)).toEqual([]);
182 expect(docOf().proposal).toBeUndefined();
183 delete doc.forgeCode.severedAt;
184 writeFileSync(file, JSON.stringify(doc));
185 expect(await handProposalCredentials(parent, true)).toEqual(["kid"]);
186 expect(getRepo(parent.db, "alice", "forge")).toBeDefined();
187 });
188 });
test/propose-no-credential.test.ts added +77
@@ -0,0 +1,77 @@
1 /**
2 * A forge with a live chain and no proposal credential (#13725) says so on every door: the API
3 * answers 409 `no_credential`, the MCP tool and the page say the same words, and nothing is sent.
4 */
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { FAMILY_WORDS } from "../src/actions/family_words.ts";
10 import { createRepo } from "../src/actions/repos.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { createSession } from "../src/core/sessions.ts";
13 import { createToken } from "../src/core/tokens.ts";
14 import { createUser, type User } from "../src/core/users.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16 import { quietLogs } from "./helpers/globals.ts";
17
18 quietLogs();
19
20 describe("a forge whose parent has not yet handed it a credential", () => {
21 let dir = "";
22 let app: App;
23 let server: Servers;
24 let user: User;
25
26 beforeAll(async () => {
27 dir = await mkdtemp(join(tmpdir(), "forge-nocred-"));
28 app = createApp({ dataDir: join(dir, "kid"), port: 0, host: "kid.test", url: "https://kid.example.com" });
29 server = await serve(app);
30 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "kid", email: "[email protected]", password: "a-long-nocred-passphrase", adminIfFirst: true });
31 if (!made.ok) throw new Error(String(made.error));
32 user = made.value;
33 const repo = await createRepo(app, user, { name: "forge", visibility: "public" });
34 if (!repo.ok) throw new Error(String(repo.error));
35 await Bun.write(
36 join(dir, "kid", "parent.json"),
37 JSON.stringify({ upstream: "http://127.0.0.1:1", name: "kid", forgeCode: { repo: "kid/forge", upstream: "alice/forge", mode: "tell-me", tip: "", chain: [] } }),
38 );
39 });
40
41 afterAll(async () => {
42 await server.stop();
43 await rm(dir, { recursive: true, force: true });
44 });
45
46 test("the API answers 409 no_credential with the words", async () => {
47 const token = createToken(app.db, user.id, "api", "rw").token;
48 const res = await fetch(`${server.url}/api/v1/repos/kid/forge/following/propose-parent`, { method: "POST", headers: { authorization: `Bearer ${token}` } });
49 expect(res.status).toBe(409);
50 const body = (await res.json()) as { error: { code?: string; message?: string } | string; code?: string; message?: string };
51 expect(JSON.stringify(body)).toContain("no_credential");
52 expect(JSON.stringify(body)).toContain(FAMILY_WORDS.no_credential);
53 });
54
55 test("the MCP tool says the same", async () => {
56 const token = createToken(app.db, user.id, "mcp", "rw").token;
57 const res = await fetch(`${server.url}/mcp`, {
58 method: "POST",
59 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` },
60 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "propose_to_parent_forge", arguments: { repo: "kid/forge" } } }),
61 });
62 const body = (await res.json()) as any;
63 expect(body.result.isError).toBe(true);
64 expect(body.result.content[0].text).toStartWith(`no_credential: ${FAMILY_WORDS.no_credential}`);
65 });
66
67 test("the page says it, capitalised and ended", async () => {
68 const cookie = `forge_session=${createSession(app.db, user.id).token}`;
69 const res = await fetch(`${server.url}/kid/forge/following/propose`, {
70 method: "POST",
71 redirect: "manual",
72 headers: { cookie, origin: "https://kid.example.com", accept: "application/json" },
73 });
74 const said = (await res.json()) as { error: string };
75 expect(said.error).toBe(`${FAMILY_WORDS.no_credential[0]!.toUpperCase()}${FAMILY_WORDS.no_credential.slice(1)}.`);
76 });
77 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs