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

A spawned forge can be claimed through the API, and a pull with no check says why #16413

Merged opened this in answer to

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

Merged

sold/f2f-claim-and-why → main 0 commits

  • Merged. sold/f2f-claim-and-why was merged into main as b9db131.

Review

Sign in to review this change.
7 files changed +109 −11
docs/REFERENCE.md +4
@@ -265,6 +265,10 @@ token always expires: in a day (86400 seconds) unless `expiresIn` asks for
265265 whole seconds from 60 to 2592000 (30 days); anything else is 422
266266 `invalid_expiry` and spends nothing. The account has no password or passkey and
267267 a token cannot mint tokens, so once its token lapses it cannot sign in.
268 On a spawned forge the same door takes the claim link's code (the part after
269 the `#` in `<child>/claim#<code>`): the claim's single spend, once, within its
270 24 hours, with the same handover as the claim page. Its username must be new
271 (the page's takeover of the spawner's name is the page's only).
268272
269273 If that leaves no admin with a working credential (no password, passkey,
270274 unexpired token, live session, SSH key or sign-in with the parent), running
src/actions/first_admin.ts +17 −7
@@ -29,7 +29,7 @@ import { createUser, discardFreshUser, getUserById, getUserByName, type User } f
2929 import { bucketOf } from "../http/peer.ts";
3030 import { err, ok, type Result } from "../kernel/result.ts";
3131 import { limitValue } from "../settings/limits.ts";
32 import { handOver, spawnedOrg } from "../spawn/claim.ts";
32 import { burnClaim, handOver, readClaim, spawnedOrg, unburnClaim } from "../spawn/claim.ts";
3333 import { moveOwnForge } from "../spawn/own_forge.ts";
3434 import { EMAIL_TAKEN_MESSAGE, EMAIL_WANTED, INVALID_USERNAME_MESSAGE, NAME_RESERVED, USERNAME_TAKEN } from "./signup_words.ts";
3535
@@ -109,8 +109,11 @@ function attempt(app: App, address: string): boolean {
109109 function problemOf(
110110 app: App,
111111 input: { code: string; username: string; email: string },
112 claimOrg?: string,
112113 ): FirstAdminError | undefined {
113 if (readFirstAdmin(app.db, input.code) !== "ok") return "refused";
114 // A spawned forge's claim code works here too (`spawn/claim.ts` judges it).
115 const claim = claimOrg !== undefined && readClaim(app.db, claimOrg, input.code).state === "ok";
116 if (readFirstAdmin(app.db, input.code) !== "ok" && !claim) return "refused";
114117 if (!USERNAME.test(input.username)) return "invalid_username";
115118 if (getUserByName(app.db, input.username)) return "username_taken";
116119 if (!input.email.includes("@")) return "invalid_email";
@@ -137,10 +140,18 @@ export async function redeemFirstAdmin<T>(
137140 finish: (user: User) => T | undefined,
138141 ): Promise<Result<{ user: User; finished: T }, FirstAdminError>> {
139142 if (!attempt(app, input.address)) return err("rate_limited");
140 const problem = problemOf(app, input);
143 const spawned = await spawnedOrg(app);
144 const problem = problemOf(app, input, spawned?.org.id);
141145 if (problem !== undefined) return err(problem);
142146 // Spent first, in one statement: of two redemptions on one code, one wins.
143 if (burnFirstAdmin(app.db, input.code) !== "ok") return err("refused");
147 // A code that is no first-admin code is the spawn claim's, spent by its own single-spend.
148 const byClaim = burnFirstAdmin(app.db, input.code) !== "ok";
149 if (byClaim && (spawned === undefined || burnClaim(app.db, spawned.org.id, input.code).state !== "ok"))
150 return err("refused");
151 const putBack = (): void => {
152 if (byClaim && spawned !== undefined) unburnClaim(app.db, spawned.org.id, input.code);
153 else unburnFirstAdmin(app.db, input.code);
154 };
144155 // Origin: the operator's first admin, an exemption from the signup policy
145156 // (the operator vouches by minting the code), as a claim is.
146157 const made = await createUser(app.db, {
@@ -152,7 +163,7 @@ export async function redeemFirstAdmin<T>(
152163 trusted: true,
153164 });
154165 if (!made.ok) {
155 unburnFirstAdmin(app.db, input.code);
166 putBack();
156167 return err(
157168 made.error === "email_taken" || made.error === "username_reserved" || made.error === "username_taken"
158169 ? made.error
@@ -162,10 +173,9 @@ export async function redeemFirstAdmin<T>(
162173 const finished = finish(made.value);
163174 if (finished === undefined) {
164175 discardFreshUser(app.db, made.value.id);
165 unburnFirstAdmin(app.db, input.code);
176 putBack();
166177 return err("unfinished");
167178 }
168 const spawned = await spawnedOrg(app);
169179 if (spawned !== undefined) handOver(app.db, spawned, made.value.id);
170180 // A deployed forge's own code becomes the new admin's, under their name (#16361).
171181 const own = await moveOwnForge(app, made.value);
src/checks/no_check.ts added +30
@@ -0,0 +1,30 @@
1 /**
2 * Why a pull has no check: the words behind a bare "none". A forge that was
3 * started with no checks lane, a head a writer has not yet approved, and a
4 * repository that declares no `check` each leave a pull with no run, and
5 * each has a different next step (`checks/request.ts` is what decides).
6 */
7
8 import type { App } from "../app.ts";
9 import { readFileAt } from "../apps/checkout.ts";
10 import { parseCheck } from "../apps/manifest.ts";
11 import { runDir, type Pull } from "../core/pulls.ts";
12 import { pullMayRun } from "../core/pull_trust.ts";
13 import type { Repo } from "../core/repos.ts";
14 import { checksFor } from "./service.ts";
15
16 export async function whyNoCheck(app: App, repo: Repo, pull: Pull, head: string): Promise<string> {
17 if (checksFor(app) === undefined)
18 return "this forge runs no checks: its checks lane is not running here, so nothing on it is checked";
19 if (!pullMayRun(app.db, repo, pull, head))
20 return "the check waits for a writer to approve this head: nothing from an unapproved pull runs";
21 const bare = await runDir(app.db, app.reposRoot, repo, pull.id);
22 const [forgeJson, packageJson] = await Promise.all([
23 readFileAt(bare, head, "forge.json"),
24 readFileAt(bare, head, "package.json"),
25 ]);
26 const declared = parseCheck(forgeJson, packageJson);
27 if (declared.ok && declared.value === undefined)
28 return 'this repository declares no check: add a "check" command to forge.json and the next push runs it';
29 return "no check has run on this head yet";
30 }
src/contract/openapi/routes/getApiV1ReposOwnerNamePullsNumberChecks.ts +1 −1
@@ -4,7 +4,7 @@ export const route: Route = {
44 method: "get",
55 path: `${REPO}/pulls/{number}/checks`,
66 summary: "A pull's checks at its current head",
7 detail: "A pull's checks at its current head; answers { head, state, required, run, runs } with state `none` when no run exists; `?format=text` answers three plain-text lines (`state:`, `head:`, `required:`) instead",
7 detail: "A pull's checks at its current head; answers { head, state, required, run, runs } with state `none` when no run exists, and `why`; `?format=text` answers plain-text lines (`state:`, `head:`, `required:`, and `why:` when there is no run) instead",
88 auth: false,
99 role: "anonymous",
1010 query: { format: "string" },
src/contract/openapi/routes/postApiV1FirstAdmin.ts +1 −1
@@ -6,7 +6,7 @@ export const route: Route = {
66 summary:
77 "Make the forge's first admin with the operator's one-time code, no session or password",
88 detail:
9 "Make the forge's first admin with the operator's one-time code, no session or password: answers 201 with { user, scope, id, token, expiresAt, expiresIn }, the token shown once; scope is ro, rw or admin; expiresIn is whole seconds from 60 to a month (default a day); refused from another origin with 403 forbidden",
9 "Make the forge's first admin with the operator's one-time code (a spawned forge: its claim link's code), no session or password: answers 201 with { user, scope, id, token, expiresAt, expiresIn }, the token shown once; scope is ro, rw or admin; expiresIn is whole seconds from 60 to a month (default a day); refused from another origin with 403 forbidden",
1010 auth: false,
1111 role: "anonymous",
1212 status: 201,
src/http/api.ts +14 −2
@@ -65,6 +65,8 @@ import { healthAnswer } from "../actions/health.ts";
6565 import { isProbe } from "../kernel/probe.ts";
6666 import { PRIVATE_ADDRESS_REFUSED } from "../kernel/address_words.ts";
6767 import { forgeState, PARENT_HEADER } from "../spawn/clients.ts";
68 import { spawnedOrg } from "../spawn/claim.ts";
69 import { whyNoCheck } from "../checks/no_check.ts";
6870 import { familyView } from "../spawn/family.ts";
6971 import { HOOK_BODY_MAX, receiveOriginHook, signatureOf } from "../origins/hook.ts";
7072 import { receiveMirrorHook } from "../origins/mirror-pulls.ts";
@@ -1455,7 +1457,13 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
14551457 if (!made.ok && made.error === "rate_limited")
14561458 return tryAgain(made.error, 429, FIRST_ADMIN_WORDS[made.error], 60);
14571459 if (!made.ok)
1458 return apiError(made.error, made.error === "refused" ? 403 : 422, FIRST_ADMIN_WORDS[made.error]);
1460 return apiError(
1461 made.error,
1462 made.error === "refused" ? 403 : 422,
1463 made.error === "refused" && (await spawnedOrg(ctx.app)) !== undefined
1464 ? `${FIRST_ADMIN_WORDS.refused} On a spawned forge the code is the claim link's, the part after the #; it works here once, within 24 hours.`
1465 : FIRST_ADMIN_WORDS[made.error],
1466 );
14591467 return json(
14601468 { user: publicUser(made.value.user), scope, ...made.value.finished, expiresAt, expiresIn },
14611469 201,
@@ -3572,9 +3580,12 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
35723580 return { head: oid, runs: checksForHead(ctx.app.db, found.pull.id, oid) };
35733581 });
35743582 const latest = runs[0];
3583 // With no run, the reason: a bare "none" does not say whether to wait, approve or add a
3584 // check.
3585 const why = latest === undefined ? await whyNoCheck(ctx.app, found.repo, found.pull, head) : undefined;
35753586 // `?format=text`: three plain lines, the URL a contribute push prints.
35763587 if (ctx.url.searchParams.get("format") === "text")
3577 return new Response(`state: ${latest?.state ?? "none"}\nhead: ${head}\nrequired: ${found.repo.requireChecks ? "yes" : "no"}\n`, {
3588 return new Response(`state: ${latest?.state ?? "none"}\nhead: ${head}\nrequired: ${found.repo.requireChecks ? "yes" : "no"}\n${why === undefined ? "" : `why: ${why}\n`}`, {
35783589 headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" },
35793590 });
35803591 return timePhase(ctx.request, "render", () =>
@@ -3582,6 +3593,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
35823593 head,
35833594 state: latest?.state ?? "none",
35843595 required: found.repo.requireChecks,
3596 ...(why === undefined ? {} : { why }),
35853597 run: latest ?? null,
35863598 looks: latest
35873599 ? looksOfCheck(ctx.app, ctx.auth.user, found.repo, { id: latest.id, commitOid: latest.commitOid })
test/spawn-claim-api.test.ts added +42
@@ -0,0 +1,42 @@
1 /**
2 * A spawned forge is claimed headlessly: its claim code at `POST /api/v1/first-admin`
3 * makes the admin and answers with an expiring token, once. The page's single spend is the
4 * only one (`spawn/claim.ts`).
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { startedForge, type StartedForge } from "./helpers/claimed-forge.ts";
8 import { quietLogs } from "./helpers/globals.ts";
9
10 quietLogs();
11
12 describe("a spawned forge claimed through the API", () => {
13 let forge: StartedForge;
14 const redeem = (code: string, username = "maker") =>
15 fetch(`${forge.base}/api/v1/first-admin`, {
16 method: "POST",
17 headers: { origin: forge.base, "content-type": "application/json" },
18 body: JSON.stringify({ code, username, email: `${username}@x.test`, scope: "admin" }),
19 });
20
21 beforeAll(async () => {
22 forge = await startedForge("forge-claim-api-");
23 }, 60_000);
24 afterAll(async () => forge.stop());
25
26 test("a wrong code is refused and names the claim code", async () => {
27 const res = await redeem("A".repeat(43));
28 expect(res.status).toBe(403);
29 expect(((await res.json()) as { message: string }).message).toContain("claim link");
30 });
31
32 test("the claim code makes the admin once", async () => {
33 const res = await redeem(forge.token);
34 expect(res.status).toBe(201);
35 const body = (await res.json()) as { token: string; user: { username: string } };
36 expect(body.user.username).toBe("maker");
37 expect(body.token.length).toBeGreaterThan(10);
38 expect((await redeem(forge.token, "second")).status).toBe(403);
39 const page = await fetch(`${forge.base}/claim`, { method: "POST", headers: { origin: forge.base }, body: new URLSearchParams({ token: forge.token }) });
40 expect(page.status).not.toBe(302);
41 });
42 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs