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

Connect a cloud in a minute: the provider token page, the exact scopes, paste, verified at once #16702

Merged opened this

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

Merged

sold/connect → main 0 commits 6 threads · 6 unresolved

  • Merged. sold/connect was merged into main as 72be5fd.

Review

Sign in to review this change.
14 files changed +534 −13
docs/design/audit.md +1
@@ -148,6 +148,7 @@ Machine routes are not pages and have no entry: `/audit.csv`,
148148 - `/settings/model` — `pages/model.ts` · which model the crew runs on · `/settings/crew` · none seen.
149149 - `/settings/cloud` — `pages/cloud.ts` · cloud provider connection · none · none seen.
150150 - `/settings/cloud/audit` — `pages/cloud.ts` · what the cloud connection did · `/audit` (different subject, same word) · none seen.
151 - `/cloud/connect` — `pages/cloud.ts` · connect a cloud in a minute, guided, one provider at a time · `/settings/cloud` (every key; this is the front door) · none seen.
151152 - `/settings/access` — `pages/access.ts` · who may reach the forge · `/settings/people`, `/settings/accounts` · none seen.
152153 - `/settings/captain` — `pages/captain.ts` · what Talk remembers and the check-ins it posts · `/talk` · none seen.
153154
docs/features/cloud.md +8
@@ -6,6 +6,14 @@ row: Cloud accounts
66
77 The forge keeps the provider tokens (a cloud vendor's API token) its repositories use, sealed. Four doors show them, all a forge admin's alone; anyone else finds no such page, screen, tool or route. No door ever returns a secret: a token is typed once, checked, sealed, and never drawn, kept in a note or sent back.
88
9 ## Connect a cloud (#16696)
10
11 The quickest way in is `/cloud/connect` (`src/web/pages/cloud.ts`). It lists the clouds the forge builds on (DigitalOcean, Hetzner Cloud, OVHcloud US, Cloudflare), each with one line on what the forge does there. Picking one shows the provider's own token page as a link, the two to four things to tick there (read-only first, and what building adds), and one masked, focused field for the key; OVHcloud's four parts are asked one by one.
12
13 The key is verified at once with read-only calls and sealed as `<provider>/main` (then `main_2`), so there is no name to invent. The page then says what it sees, whether building is on, and the next step: **Switch on building** (the account's write switch) and then **Build something** (`/infra`). A key the provider refused, a missing part or a project the key cannot see says so in plain words with a link to make a good key, and what the key cannot see or write is named before you build. The key is never shown again, never put in a URL, an event or a log line (`test/cloud-connect.test.ts`).
14
15 In the terminal, `C` on the Cloud accounts screen (`src/tui/screens/cloud.ts`) asks which cloud, shows its token page and steps, and takes the key masked. Talk and the MCP send people to `/cloud/connect` to paste: a key never goes through a chat.
16
917 - **Page**: Settings → Cloud accounts, `/settings/cloud`. Each account with what it is used for, when it was verified and last used, and today's vendor calls. Attach, verify, allow writes, rename, rotate, audit and remove are forms on the page.
1018 - **Terminal**: the "Cloud accounts" screen (`src/tui/screens/cloud.ts`), opened from the palette. `a` attaches (token typed masked), `v` re-verifies, `r` rotates, `n` renames, `x` removes, `P` sets the project its forges are filed in. The checks are the page's (`src/actions/cloud.ts`).
1119 - **MCP**: `cloud_accounts` takes no arguments and returns the accounts with each token's use, verification, write permission and today's calls. It counts as a write, so a `ro` token never lists them.
src/actions/cloud.ts +21
@@ -68,6 +68,27 @@ export async function addAccount(
6868 return ok(v.value.summary);
6969 }
7070
71 /**
72 * Connect a cloud (#16696): the guided add. The person picks a provider and pastes a key; the
73 * account is named for them (`main`, then `main_2` and on), so nothing is asked that the forge
74 * can decide. The same verify-then-seal as `addAccount`, writes off until switched on.
75 */
76 export async function connectAccount(
77 app: App,
78 actor: User | undefined,
79 provider: string,
80 value: string,
81 ): Promise<Result<{ name: string; summary: string }, string>> {
82 const who = admin(actor);
83 if (!who.ok) return who;
84 if (!isProvider(provider)) return err("That is not a provider the forge knows.");
85 if (value.trim() === "") return err("Paste the key first.");
86 let name = "main";
87 for (let i = 2; getCloudAccount(app.db, provider, name) !== undefined; i++) name = `main_${i}`;
88 const added = await addAccount(app, who.value, provider, name, value.trim());
89 return added.ok ? ok({ name, summary: added.value }) : added;
90 }
91
7192 /** Open the sealed value for one named purpose, which the read event records. */
7293 function open(app: App, actor: User, secret: string, run: string): string | undefined {
7394 return resolveSecrets(app.db, app.config.dataDir, app.bus, [secret], {
src/cloud/providers.ts +68 −3
@@ -99,6 +99,69 @@ export const shape: Record<Provider, string> = {
9999 vercel: "an access token scoped to one team",
100100 };
101101
102 /**
103 * Connect a cloud in a minute (#16696, phase 1d): for each provider the forge can build on, what
104 * it does with a key, the page that makes one, the 2 to 4 things to tick, and what building needs
105 * beyond reading. The links are each provider's own token page as its documentation names it:
106 * DigitalOcean docs.digitalocean.com/reference/api/create-personal-access-token, Hetzner
107 * docs.hetzner.com/cloud/api/getting-started/generating-api-token, Cloudflare
108 * developers.cloudflare.com/fundamentals/api/get-started/create-token, OVHcloud US
109 * help.ovhcloud.com (first steps with the OVHcloud US API, api.us.ovhcloud.com/createToken).
110 * Hetzner has no link into a project's tokens, so its first step names the way there.
111 */
112 export interface ConnectGuide {
113 readonly provider: "digitalocean" | "hetzner" | "ovh" | "cloudflare";
114 /** What the forge can do with it, one plain line. */
115 readonly can: string;
116 /** The provider's page that makes a key. */
117 readonly link: string;
118 /** What to do there, short numbered lines; read-only first. */
119 readonly steps: readonly string[];
120 /** What building (writes) needs on top. */
121 readonly build: string;
122 /** The parts pasted, when a key is more than one string (joined with `:`). */
123 readonly parts?: readonly string[];
124 }
125
126 export const CONNECT: readonly ConnectGuide[] = [
127 {
128 provider: "digitalocean",
129 can: "Machines and disks for your forges",
130 link: "https://cloud.digitalocean.com/account/api/tokens/new",
131 steps: [
132 "Name it forge and pick Custom Scopes.",
133 "Tick read on account, project, droplet, volume and regions; to build, add create and delete on droplet, volume, ssh_key and project.",
134 "Or pick Full Access: simpler, but it can do anything in the account.",
135 "Generate, then copy the token.",
outdated

Least privilege: telling people to pick Full Access hands the forge more than it needs. Lead with the custom scopes already listed in build, and offer Full Access only as the simple fallback.

136 ],
137 build: "custom scopes with create and delete on droplet, volume, ssh_key and project (or Full Access)",
138 },
139 {
140 provider: "hetzner",
141 can: "Machines and disks in one Hetzner project",
142 link: "https://console.hetzner.com/projects",
143 steps: ["Open your project, then Security, then API tokens.", "Generate an API token named forge.", "Pick Read, or Read & Write to build.", "Copy the token."],
144 build: "a Read & Write token: Hetzner has nothing narrower",
145 },
146 {
147 provider: "ovh",
148 can: "Instances and volumes in one Public Cloud project",
149 link: "https://api.us.ovhcloud.com/createToken/",
150 steps: ["Name the application forge.", "Add GET on /cloud/project/PROJECT_ID/* and on /auth/currentCredential.", "To build, add POST and DELETE on /cloud/project/PROJECT_ID/*.", "Create keys, then copy all three and your project id."],
151 build: "POST and DELETE on /cloud/project/PROJECT_ID/* for the consumer key",
152 parts: ["Application key", "Application secret", "Consumer key", "Project id"],
153 },
154 {
155 provider: "cloudflare",
156 can: "DNS for your domains",
157 link: "https://dash.cloudflare.com/profile/api-tokens",
158 steps: ["Create Token, then Create Custom Token named forge.", "Permissions: Zone, Zone, Read and Zone, DNS, Read; Edit to build.", "Zone resources: the zones the forge may name.", "Continue, create, then copy the token."],
159 build: "Zone, DNS, Edit on the zones its forges are named under",
160 },
161 ];
162
163 export const guideOf = (provider: string): ConnectGuide | undefined => CONNECT.find((g) => g.provider === provider);
164
102165 export type Fetch = (url: string, init?: RequestInit) => Promise<Response>;
103166
104167 export interface Verified {
@@ -115,7 +178,8 @@ export interface Finding {
115178 readonly saving: number;
116179 }
117180
118 const FAIL = "The provider did not accept that credential.";
181 /** The refusals `verify` answers with, exported so a door matches the phrase and not its wording. */
182 export const FAIL = "The provider did not accept that credential.";
119183
120184 async function json(f: Fetch, url: string, init: RequestInit = {}): Promise<any> {
121185 const res = await f(url, { ...init, signal: AbortSignal.timeout(10_000) });
@@ -228,7 +292,8 @@ function parts(value: string, n: number): string[] | undefined {
228292
229293 // ---- OVHcloud US ----
230294
231 const OVH_SHAPE = "An OVHcloud US credential is APPLICATION_KEY:APPLICATION_SECRET:CONSUMER_KEY:PROJECT_ID.";
295 export const OVH_SHAPE = "An OVHcloud US credential is APPLICATION_KEY:APPLICATION_SECRET:CONSUMER_KEY:PROJECT_ID.";
296 export const OVH_NO_PROJECT = "That project id was not found for this key.";
232297
233298 export function ovhParts(value: string): { keys: OvhKeys; project: string } | undefined {
234299 const p = parts(value, 4);
@@ -379,7 +444,7 @@ export async function verify(
379444 try {
380445 inst = await ovhCall(f, o.keys, "GET", `/cloud/project/${o.project}/instance`);
381446 } catch (e) {
382 if (e instanceof Error && /answered 404/.test(e.message)) return err("That project id was not found for this key.");
447 if (e instanceof Error && /answered 404/.test(e.message)) return err(OVH_NO_PROJECT);
383448 throw e;
384449 }
385450 const writes = ovhCanWrite(c.rules, o.project);
src/core/reserved.ts +1
@@ -80,6 +80,7 @@ export const SYSTEM_NAMES: readonly string[] = [
8080 "csp-report",
8181 "deploy-to",
8282 "pinned",
83 "cloud",
8384 "pipeline",
8485 "events",
8586 "bring",
src/http/marks/cloud.json added +4
@@ -0,0 +1,4 @@
1 {
2 "head": "/cloud",
3 "mark": "admin"
4 }
src/http/server.ts +6
@@ -6,6 +6,7 @@
66 */
77
88 import { allocationMove, allocationPage, allocationWeekly } from "../web/pages/allocation.ts";
9 import { cloudConnectBuild, cloudConnectPage, cloudConnectProvider, cloudConnectSubmit } from "../web/pages/cloud.ts";
910 import { runOwnToken } from "../web/own_token.ts";
1011 import { togetherFragment, togetherLine, togethernessOf } from "../web/together.ts";
1112 import { outsiderStatusPage } from "./offer_routes.ts";
@@ -1199,6 +1200,11 @@ export function buildRouter(): Router<Handler> {
11991200 // Every /settings… page, in its own module (settings_routes.ts); literal, above /:owner.
12001201 // The usage page is handed the pattern list, so settings_routes.ts never imports server.ts.
12011202 settingsRoutes(router, knownPatterns);
1203 // Connect a cloud (#16696): the guided front door to building on a cloud; /infra links here.
1204 router.add("GET", "/cloud/connect", cloudConnectPage);
1205 router.add("GET", "/cloud/connect/:provider", cloudConnectProvider);
1206 router.add("POST", "/cloud/connect/:provider", cloudConnectSubmit);
1207 router.add("POST", "/cloud/connect/:provider/build", cloudConnectBuild);
12021208 // The OpenCode plugin file (#10198); literal, above /:owner.
12031209 pluginRoutes(router);
12041210 // The Deploy to… page for a pinned forge (#8744); literal, above /:owner.
src/tui/screens/cloud.ts +32 −4
@@ -2,18 +2,19 @@
22 * Cloud accounts in the terminal, a forge admin's (#2199): each account with
33 * what it is used for, when it was verified and last used, and today's vendor
44 * calls, as Settings → Cloud accounts shows them. `a` attaches (verified, then
5 * sealed), `v` re-verifies, `r` rotates, `n` renames, `x` removes — all through
5 * sealed), `C` connects a cloud the guided way (/cloud/connect: which cloud, where its key is
6 * made and what to tick, then the key; named for you), `v` re-verifies, `r` rotates, `n` renames, `x` removes — all through
67 * `actions/cloud.ts`, so the checks are the page's. A token is typed masked and
78 * is never drawn, kept or put in a note. Anyone else sees nothing and does nothing.
89 */
910
1011 import { acknowledgeWatch } from "../../actions/cloud_ceiling.ts";
11 import { addAccount, allowWrite, auditAccount, removeAccount, renameAccount, reverify, rotateAccount } from "../../actions/cloud.ts";
12 import { addAccount, allowWrite, connectAccount, auditAccount, removeAccount, renameAccount, reverify, rotateAccount } from "../../actions/cloud.ts";
1213 import { setProject } from "../../actions/cloud_ceiling.ts";
1314 import { usesByVendor, type VendorUse } from "../../cloud/declared.ts";
1415 import { cloudOverview } from "../../cloud/overview.ts";
1516 import { dollars } from "../../cloud/prices.ts";
16 import { LABEL, PROVIDERS } from "../../cloud/providers.ts";
17 import { CONNECT, LABEL, PROVIDERS, guideOf } from "../../cloud/providers.ts";
1718 import type { Ctx, Screen } from "../app/app.ts";
1819 import { binding } from "../app/keys.ts";
1920 import { style } from "../term/style.ts";
@@ -112,11 +113,34 @@ export function cloudScreen(f: Session, ctx: Ctx): Screen {
112113 },
113114 });
114115
116 /** `C`: the guided connect, as /cloud/connect walks it: which cloud, how to make its key, the key. */
117 const connect = (parent: Screen): Screen =>
118 promptScreen(ctx, parent, {
119 title: "Connect a cloud",
120 label: CONNECT.map((g) => `${g.provider} (${g.can.toLowerCase()})`).join(", "),
121 placeholder: "digitalocean",
122 onSubmit: (raw) => {
123 const g = guideOf(raw.trim().toLowerCase());
124 if (g === undefined) return `Pick one of ${CONNECT.map((x) => x.provider).join(", ")}.`;
125 return later(ctx, () =>
126 promptScreen(ctx, parent, {
127 title: `Connect ${LABEL[g.provider]}: open ${g.link}`,
128 label: g.parts ? `the key as ${g.parts.join(":")} (checked, then sealed, never shown)` : "the key (checked, then sealed, never shown)",
129 hint: g.steps.map((step, i) => `${i + 1}. ${step}`).join(" "),
130 mask: true,
131 onSubmit: (value) =>
132 settle(connectAccount(f.app, f.user, g.provider, value), (v) => `Connected ${g.provider}/${v.name}: ${v.summary} Press w on it to switch on building.`),
133 }),
134 );
135 },
136 });
137
115138 const screen: Screen = {
116139 title: "Cloud accounts",
117140 keys: [
118141 binding(["j", "k"], "move cursor"),
119142 binding(["a"], "attach"),
143 binding(["C"], "connect a cloud, guided"),
120144 binding(["v"], "verify"),
121145 binding(["r"], "rotate"),
122146 binding(["n"], "rename"),
@@ -139,7 +163,7 @@ export function cloudScreen(f: Session, ctx: Ctx): Screen {
139163 ? "Cloud accounts are a forge admin's."
140164 : selected !== undefined
141165 ? `${selected.summary} ${selected.usedFor}`
142 : "No account attached. Press a to attach one.";
166 : "No account attached. Press C to connect a cloud.";
143167 s.text(head!.x, head!.y, truncate(text, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
144168 drawList(s, list!, c, state, rows());
145169 },
@@ -150,6 +174,10 @@ export function cloudScreen(f: Session, ctx: Ctx): Screen {
150174 ctx.push(attach(screen));
151175 return true;
152176 }
177 if (e.key === "C") {
178 ctx.push(connect(screen));
179 return true;
180 }
153181 if (e.key === "c") {
154182 ctx.push(callsScreen(f, ctx));
155183 return true;
src/web/pages/cloud.ts +140 −4
@@ -12,12 +12,13 @@ import {
1212 addAccount,
1313 allowWrite,
1414 auditAccount,
15 connectAccount,
1516 removeAccount,
1617 renameAccount,
1718 reverify,
1819 rotateAccount,
1920 } from "../../actions/cloud.ts";
20 import { LABEL, PROVIDERS, VENDOR_OF, isProvider, shape } from "../../cloud/providers.ts";
21 import { CONNECT, FAIL, LABEL, OVH_NO_PROJECT, OVH_SHAPE, PROVIDERS, VENDOR_OF, guideOf, isProvider, shape, type ConnectGuide } from "../../cloud/providers.ts";
2122 import { HOME, usedFor, usesByVendor, type VendorUse } from "../../cloud/declared.ts";
2223 import { watchLine } from "../../cloud/watch.ts";
2324 import { lastReading } from "../../cloud/watch_read.ts";
@@ -26,6 +27,7 @@ import { warmOf } from "../../cloud/warm_pool.ts";
2627 import { dollars } from "../../cloud/prices.ts";
2728 import { auditToday } from "../../core/cloud_audit.ts";
2829 import {
30 getCloudAccount,
2931 listCloudAccounts,
3032 recentCloudReads,
3133 type CloudAccount,
@@ -33,12 +35,12 @@ import {
3335 } from "../../core/cloud_account.ts";
3436 import { nameFrame, notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts";
3537 import type { Ctx } from "../../http/context.ts";
36 import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts";
38 import { notFoundPage, pageHead, settingsLayout, signInFirst } from "../chrome.ts";
3739 import { field, readForm } from "../form.ts";
3840 import { acknowledgeWatch, setCeiling, setProject } from "../../actions/cloud_ceiling.ts";
3941 import { html, type Html } from "../html.ts";
4042 import { flashTo, page } from "../layout.ts";
41 import { btn, confirmAction, icon, row, time } from "../ui.ts";
43 import { btn, confirmAction, field as input, icon, row, rowList, time } from "../ui.ts";
4244 import { emptyLine } from "../empty_words.ts";
4345 import { accountSections } from "./origins.ts";
4446
@@ -150,7 +152,7 @@ function accountsCard(db: Database, accounts: CloudAccount[], reads: CloudRead[]
150152 return html`<section class="settings-block">
151153 <h2>Cloud accounts</h2>
152154 <p class="muted small">Each account has a monthly spend ceiling, $50 until you change it: the forge refuses to make a machine or volume that would take it past. The cost shown is the forge's own reckoning from list prices; the provider's bill is the truth.</p>
153 <p class="muted small">Paste a credential once; the forge checks it read-only, seals it, and never shows it again.</p>
155 <p class="muted small">Paste a credential once; the forge checks it read-only, seals it, and never shows it again. The quickest way: <a href="/cloud/connect">Connect a cloud</a>.</p>
154156 ${rows.length > 0
155157 ? html`<ul class="list setting-list">${rows}</ul>`
156158 : emptyLine("cloudAccounts")}
@@ -361,3 +363,137 @@ export async function cloudRemove(ctx: Ctx): Promise<Response> {
361363 const r = removeAccount(ctx.app, ctx.auth.user, provider, name);
362364 return said(ctx, r, "Removed.", r.ok ? undefined : r.error);
363365 }
366
367 // ---- Connect a cloud (#16696, phase 1d): the front door of building on a cloud ----
368
369 const CONNECT_HOME = "/cloud/connect";
370
371 /** What a key it could not use means, in plain words, with the page that makes a good one. */
372 function connectError(g: ConnectGuide, error: string): Html {
373 const label = LABEL[g.provider];
374 const why =
375 error === FAIL
376 ? `${label} did not accept that key: it may be mistyped, expired or deleted.`
outdated

Matching on error text owned by another module is brittle. A reworded verifier message falls through to the raw error. Return a code from the verifier, or export the phrases and match on those.

377 : error === OVH_NO_PROJECT
378 ? "That project id is not one this key can see: copy it from your Public Cloud project."
379 : error === OVH_SHAPE
380 ? "All four values are needed: the application key, its secret, the consumer key and the project id."
381 : error;
382 return html`<p role="alert">${why} <a href="${g.link}" rel="noopener noreferrer" target="_blank">Make a new key at ${label}</a>.</p>`;
383 }
384
385 /** What the key could not see or do that building will need, each with where to fix it. */
386 function connectGaps(g: ConnectGuide, summary: string): Html[] {
387 const gaps: Html[] = [];
388 const at = html`<a href="${g.link}" rel="noopener noreferrer" target="_blank">${LABEL[g.provider]}'s token page</a>`;
389 if (/hidden from this token/.test(summary)) gaps.push(html`It cannot see everything the forge reads: give it read access to all of the account at ${at}.`);
390 if (/read-only here/.test(summary)) gaps.push(html`It is read-only: building needs ${g.build}, at ${at}.`);
391 return gaps;
392 }
393
394 const guideRows = (g: ConnectGuide): Html =>
395 rowList([
396 row({ num: 1, title: html`Open <a href="${g.link}" rel="noopener noreferrer" target="_blank">${LABEL[g.provider]}'s token page</a>.` }),
397 ...g.steps.map((step, i) => row({ num: i + 2, title: step })),
398 ]);
399
400 /** What happens to a pasted key, said once, under the last field of the one page that takes it. */
401 const SEALED = "Checked with read-only calls before it is sealed; never shown again.";
402
403 /** The paste: one masked field, focused; a key in parts is asked for part by part. */
outdated

Principle 1: this hint says the same thing as the explanation the connected view gives next ('checked, sealed, never shown'). Say it once, on one page. Drop the hint, or keep it and drop the later copy.

404 function pasteForm(g: ConnectGuide, error?: Html): Html {
405 const labels = g.parts ?? ["Paste the key"];
406 const fields = labels.map((label, i) =>
407 input({
408 name: g.parts ? `part${i}` : "value", label, type: "password", autocomplete: "off", required: true,
409 ...(i === 0 ? { autofocus: true } : {}), ...(i === labels.length - 1 ? { hint: SEALED } : {}),
410 }),
411 );
412 return html`<form method="post" action="${CONNECT_HOME}/${g.provider}" class="stack">
413 ${error ?? null}
414 ${fields}
415 ${btn("Connect", { variant: "primary" })}
416 </form>`;
417 }
outdated

Principles 6 and 7: a settings-block section with its own h2 is a box on a page that is otherwise rows. Use pageHead and rowList, with 'Connected as' as the first row, instead of the settings chrome.

418
419 /** A key the forge holds: what it sees, whether it may build, and the next step. */
420 function connected(g: ConnectGuide, name: string, ctx: Ctx): Html {
421 const a = getCloudAccount(ctx.app.db, g.provider, name);
422 if (a === undefined) return pasteForm(g);
423 const gaps = connectGaps(g, a.summary);
424 const ceiling = `a $${a.ceilingDollars} a month ceiling you can change`;
425 return html`${rowList([
426 row({ title: html`Connected as <span class="mono">${g.provider}/${name}</span>`, data: { connected: `${g.provider}/${name}` } }),
427 row({ title: "What it sees", meta: html`${a.summary}` }),
outdated

Principle 1: the 'Building' row above already says whether building is on and what it means, and this paragraph says it again with the $50 ceiling. Fold the ceiling into that row and delete the paragraph.

428 row({
429 title: "Building",
430 meta: html`${a.writeAllowed ? `on: the forge may make and delete machines and disks here, under ${ceiling}.` : `off: the forge only reads here. Switched on, it may make and delete machines and disks with this key, under ${ceiling}.`}`,
431 }),
432 ...gaps.map((gap) => row({ title: "Before you build", meta: gap })),
433 ])}
434 ${a.writeAllowed
435 ? html`<p>${btn("Build something", { href: "/infra", variant: "primary" })}</p>`
436 : html`<form method="post" action="${CONNECT_HOME}/${g.provider}/build">
437 <input type="hidden" name="name" value="${name}" />
438 ${btn("Switch on building", { variant: "primary" })}
439 </form>`}
440 <p class="muted small"><a href="${BACK}">Every cloud account</a> · <a href="${CONNECT_HOME}">Connect another</a></p>`;
441 }
442
443 // GET /cloud/connect
444 export function cloudConnectPage(ctx: Ctx): Response {
445 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
446 const denied = requireAdmin(ctx);
447 if (denied) return denied;
448 const have = timePhase(ctx.request, "accounts", () => listCloudAccounts(ctx.app.db));
449 return timePhase(ctx.request, "render", () => page({
450 ctx,
451 title: "Connect a cloud",
452 body: html`${pageHead("Connect a cloud", { sub: "Paste one key and the forge can deploy, watch and manage what runs there." })}
453 ${rowList(CONNECT.map((g) => row({ href: `${CONNECT_HOME}/${g.provider}`, title: LABEL[g.provider], meta: html`${g.can}${have.some((a) => a.provider === g.provider) ? " · connected" : ""}` })))}
454 <p class="muted small">Other providers, and every key the forge holds: <a href="${BACK}">cloud accounts</a>.</p>`,
455 }));
456 }
457
458 function connectView(ctx: Ctx, g: ConnectGuide, body: Html, status = 200): Response {
459 return timePhase(ctx.request, "render", () => page({ ctx, title: `Connect ${LABEL[g.provider]}`, body: html`${pageHead(`Connect ${LABEL[g.provider]}`, { sub: g.can })}${body}` }, status));
460 }
461
462 // GET /cloud/connect/:provider (?account=<name> once connected)
463 export function cloudConnectProvider(ctx: Ctx): Response {
464 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
465 const denied = requireAdmin(ctx);
466 if (denied) return denied;
467 const g = guideOf(ctx.params.provider ?? "");
468 if (g === undefined) return notFoundPage(ctx);
469 const name = ctx.url.searchParams.get("account") ?? "";
470 if (name !== "" && getCloudAccount(ctx.app.db, g.provider, name) !== undefined) return connectView(ctx, g, connected(g, name, ctx));
471 return connectView(ctx, g, html`${guideRows(g)}${pasteForm(g)}`);
472 }
473
474 // POST /cloud/connect/:provider: verify at once, seal, and show what the key sees.
475 export async function cloudConnectSubmit(ctx: Ctx): Promise<Response> {
476 const denied = requireAdmin(ctx);
477 if (denied) return denied;
478 const g = guideOf(ctx.params.provider ?? "");
479 if (g === undefined) return notFoundPage(ctx);
480 const form = await readForm(ctx, "admin");
481 if (form instanceof Response) return form;
482 const value = g.parts ? g.parts.map((_, i) => field(form, `part${i}`).trim()).join(":") : field(form, "value");
483 const r = await connectAccount(ctx.app, ctx.auth.user, g.provider, value);
484 if (!r.ok) return connectView(ctx, g, html`${guideRows(g)}${pasteForm(g, connectError(g, r.error))}`, 422);
485 return flashTo(ctx, `${CONNECT_HOME}/${g.provider}?account=${r.value.name}`, { message: `Connected ${LABEL[g.provider]}.` });
486 }
487
488 // POST /cloud/connect/:provider/build: the account's write switch, from where the person stands.
489 export async function cloudConnectBuild(ctx: Ctx): Promise<Response> {
490 const denied = requireAdmin(ctx);
491 if (denied) return denied;
492 const g = guideOf(ctx.params.provider ?? "");
493 if (g === undefined) return notFoundPage(ctx);
494 const form = await readForm(ctx, "admin");
495 if (form instanceof Response) return form;
496 const name = field(form, "name");
497 const r = allowWrite(ctx.app, ctx.auth.user, g.provider, name, true);
498 return flashTo(ctx, `${CONNECT_HOME}/${g.provider}?account=${encodeURIComponent(name)}`, r.ok ? { message: "Building is on." } : { tone: "danger", message: r.error });
499 }
test/cloud-connect.test.ts added +246
@@ -0,0 +1,246 @@
1 /**

Restore cloudNet.fetch and the console spies in afterAll; they leak into every suite that runs after this one in the same process. Also add tests for connectGaps, the project-id error, a non-admin POST and the build failure flash.

2 * Connect a cloud (#16696, phase 1d): /cloud/connect lists the clouds the forge builds on, each
3 * provider's page says where its key is made and what to tick, a pasted key is verified at once
4 * and named for the person, what it sees and whether it may build are shown with the next step,
5 * and a key it cannot use says why with the page that makes a good one. The key never comes back:
6 * not in a page, an event or a log line. In-process (`forgeHttp`), no socket.
7 */
8 import { afterAll, beforeAll, describe, expect, spyOn, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { net as cloudNet } from "../src/actions/cloud.ts";
13 import { createApp, type App } from "../src/app.ts";
14 import { getCloudAccount } from "../src/core/cloud_account.ts";
15 import { createToken } from "../src/core/tokens.ts";
16 import { createUser, getUserByName } from "../src/core/users.ts";
17 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
18 import { createForgeApp } from "../src/tui/forge.ts";
19 import { cloudScreen } from "../src/tui/screens/cloud.ts";
20 import { headlessTerminal } from "../src/tui/term/terminal.ts";
21 import { quietLogs } from "./helpers/globals.ts";
22 import { settleApp } from "./helpers/tui.ts";
23
24 quietLogs();
25
26 const TOKEN = "dop_v1_SECRETsecretSECRET0123456789abcdef";
27 const BAD = "dop_v1_WRONGwrongWRONG0123456789abcdef";
28 const ORIGIN = "http://forge.test";
29
30 describe("connect a cloud", () => {
31 let dataDir = "";
32 let app: App;
33 let http: ForgeHttp;
34 let adminTok = "";
35 let bobTok = "";
36 const pages: string[] = [];
37 const realFetch = cloudNet.fetch;
38 const spies: { mockRestore: () => void }[] = [];
39 /** What the next DigitalOcean key may not see: a token without the project scope. */
40 let hideProjects = false;
41 const logged: string[] = [];
42 const get = async (path: string, tok?: string): Promise<Response> => {
43 const r = await http.handle(new Request(ORIGIN + path, { headers: tok ? { authorization: `Bearer ${tok}` } : {} }));
44 const text = await r.clone().text();
45 pages.push(text);
46 return r;
47 };
48 const post = async (path: string, body: Record<string, string>, tok = adminTok): Promise<Response> => {
49 const r = await http.handle(
50 new Request(ORIGIN + path, {
51 method: "POST",
52 headers: { authorization: `Bearer ${tok}`, origin: ORIGIN, "content-type": "application/x-www-form-urlencoded" },
53 body: new URLSearchParams(body),
54 }),
55 );
56 pages.push(await r.clone().text());
57 pages.push(r.headers.get("location") ?? "");
58 return r;
59 };
60
61 beforeAll(async () => {
62 dataDir = await mkdtemp(join(tmpdir(), "forge-cloud-connect-"));
63 app = createApp({ dataDir, port: 0 });
64 http = forgeHttp(app);
65 for (const [username, adminIfFirst] of [
66 ["alice", true],
67 ["bob", false],
68 ] as const) {
69 const made = await createUser(app.db, {
70 origin: "seed",
71 trusted: true,
72 username,
73 email: `${username}@f.test`,
74 password: "a-good-passphrase",
75 adminIfFirst,
76 });
77 if (!made.ok) throw new Error(made.error);
78 }
79 adminTok = createToken(app.db, getUserByName(app.db, "alice")!.id, "admin", "admin").token;
80 bobTok = createToken(app.db, getUserByName(app.db, "bob")!.id, "admin", "admin").token;
81 // DigitalOcean as verify reads it: the good token sees an account, two projects, no droplets.
82 cloudNet.fetch = async (url, init) => {
83 const auth = new Headers(init?.headers).get("authorization") ?? "";
84 // OVHcloud US, as verify reads it: the clock, a credential with no rules, and no such project.
85 if (url.startsWith("https://api.us.ovhcloud.com/")) {
86 const path = new URL(url).pathname;
87 if (path === "/1.0/auth/time") return new Response(String(Math.floor(Date.now() / 1000)));
88 if (path === "/1.0/auth/currentCredential") return Response.json({ rules: [] });
89 return new Response("{}", { status: 404 });
90 }
91 if (!auth.endsWith(TOKEN)) return new Response("{}", { status: 401 });
92 const path = new URL(url).pathname;
93 if (path === "/v2/account") return Response.json({ account: { email: "[email protected]", status: "active" } });
94 if (path === "/v2/projects") return hideProjects ? new Response("{}", { status: 403 }) : Response.json({ projects: [{}, {}] });
95 return Response.json({ droplets: [], meta: { total: 0 } });
96 };
97 for (const m of ["log", "info", "warn", "error", "debug"] as const)
98 spies.push(spyOn(console, m).mockImplementation((...a: unknown[]) => void logged.push(a.map(String).join(" "))));
99 }, 30_000);
100
101 afterAll(async () => {
102 cloudNet.fetch = realFetch;
103 for (const spy of spies) spy.mockRestore();
104 app.close();
105 await rm(dataDir, { recursive: true, force: true });
106 });
107
108 test("the front door lists the clouds the forge builds on, each with what it can do; an admin's alone", async () => {
109 const r = await get("/cloud/connect", adminTok);
110 expect(r.status, "an admin reads it").toBe(200);
111 const text = await r.text();
112 for (const words of [
113 "DigitalOcean",
114 "Hetzner Cloud",
115 "OVHcloud US",
116 "Cloudflare",
117 "DNS for your domains",
118 'href="/cloud/connect/digitalocean"',
119 ])
120 expect(text, words).toContain(words);
121 expect([403, 404], "a non-admin").toContain((await get("/cloud/connect", bobTok)).status);
122 expect((await get("/cloud/connect")).status, "a guest").toBe(303);
123 });
124
125 test("a provider's page says where the key is made, what to tick, and asks for it masked and focused", async () => {
126 const text = await (await get("/cloud/connect/digitalocean", adminTok)).text();
127 expect(text).toContain('href="https://cloud.digitalocean.com/account/api/tokens/new"');
128 expect(text).toContain("Name it forge and pick Custom Scopes.");
129 expect(text.indexOf("Custom Scopes")).toBeLessThan(text.indexOf("Full Access"));
130 expect(text).toContain('type="password"');
131 expect(text).toContain("autofocus");
132 expect(text).toContain('autocomplete="off"');
133 const ovh = await (await get("/cloud/connect/ovh", adminTok)).text();
134 for (let i = 0; i < 4; i++) expect(ovh, `ovh part ${i}`).toContain(`name="part${i}"`);
135 expect((await get("/cloud/connect/aws", adminTok)).status, "a cloud it does not guide").toBe(404);
136 });
137
138 test("a wrong key says why in plain words, links the page that makes one, and is not kept or shown", async () => {
139 const r = await post("/cloud/connect/digitalocean", { value: BAD });
140 expect(r.status).toBe(422);
141 const text = await r.text();
142 expect(text).toContain("DigitalOcean did not accept that key");
143 expect(text).toContain("Make a new key at DigitalOcean");
144 expect(text).not.toContain(BAD);
145 expect(getCloudAccount(app.db, "digitalocean", "main")).toBeUndefined();
146 const ovh = await (await post("/cloud/connect/ovh", { part0: "only-one" })).text();
147 expect(ovh).toContain("All four values are needed");
148 });
149
150 test("a good key is verified at once, named for you, and shows what it sees and the next step", async () => {
151 const r = await post("/cloud/connect/digitalocean", { value: TOKEN });
152 expect(r.status).toBe(303);
153 expect(r.headers.get("location")).toBe("/cloud/connect/digitalocean?account=main");
154 const text = await (await get("/cloud/connect/digitalocean?account=main", adminTok)).text();
155 expect(text).toContain('Connected as <span class="mono">digitalocean/main</span>');
156 expect(text).toContain('data-connected="digitalocean/main"');
157 expect(text).not.toContain("settings-block");
158 expect(text).toContain("under a $50 a month ceiling you can change");
159 expect(text).not.toContain("Before you build");
160 expect(text).toContain("2 projects");
161 expect(text).toContain("0 droplets");
162 expect(text).toContain("Switch on building");
163 expect(getCloudAccount(app.db, "digitalocean", "main")!.writeAllowed).toBe(false);
164
165 const on = await post("/cloud/connect/digitalocean/build", { name: "main" });
166 expect(on.status).toBe(303);
167 expect(getCloudAccount(app.db, "digitalocean", "main")!.writeAllowed).toBe(true);
168 const after = await (await get("/cloud/connect/digitalocean?account=main", adminTok)).text();
169 expect(after).toContain('href="/infra"');
170 expect(after).toContain("Build something");
171
172 expect((await post("/cloud/connect/digitalocean", { value: TOKEN })).headers.get("location")).toBe(
173 "/cloud/connect/digitalocean?account=main_2",
174 );
175 });
176
177 test("a non-admin's paste is refused and nothing is kept", async () => {
178 const r = await post("/cloud/connect/digitalocean", { value: TOKEN }, bobTok);
179 expect([403, 404], "a non-admin's POST").toContain(r.status);
180 expect(getCloudAccount(app.db, "digitalocean", "main_3"), "no account was made").toBeUndefined();
181 });
182
183 test("OVHcloud's project id it cannot see says so, with where to copy the right one", async () => {
184 const r = await post("/cloud/connect/ovh", { part0: "ak", part1: "as", part2: "ck", part3: "proj123" });
185 expect(r.status).toBe(422);
186 expect(await r.text()).toContain("That project id is not one this key can see");
187 expect(getCloudAccount(app.db, "ovh", "main")).toBeUndefined();
188 });
189
190 test("a key that cannot see the whole account is named before building, with where to fix it", async () => {
191 hideProjects = true;
192 const r = await post("/cloud/connect/digitalocean", { value: TOKEN });
193 hideProjects = false;
194 const at = r.headers.get("location") ?? "";
195 expect(at).toBe("/cloud/connect/digitalocean?account=main_3");
196 const text = await (await get(at, adminTok)).text();
197 expect(text).toContain("Before you build");
198 expect(text).toContain("give it read access to all of the account");
199 expect(text).toContain('href="https://cloud.digitalocean.com/account/api/tokens/new"');
200 });
201
202 test("switching on building for an account that is not there says so", async () => {
203 const r = await post("/cloud/connect/digitalocean/build", { name: "nope" });
204 expect(r.status).toBe(303);
205 expect(r.headers.get("location")).toBe("/cloud/connect/digitalocean?account=nope");
206 const flash = decodeURIComponent(r.headers.get("set-cookie") ?? "");
207 expect(flash).toContain("No such credential.");
208 expect(flash).toContain("danger");
209 });
210
211 test("the terminal connects the same way: which cloud, then the key typed masked", async () => {
212 const user = getUserByName(app.db, "alice")!;
213 const { app: tui, session } = createForgeApp(
214 app,
215 { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user },
216 { terminal: headlessTerminal(160, 30), exitHooks: false },
217 );
218 tui.start();
219 tui.ctx.push(cloudScreen(session, tui.ctx));
220 await settleApp(tui);
221 const press = async (keys: string[]) => {
222 for (const key of keys) tui.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false });
223 await settleApp(tui);
224 };
225 await press(["C", ..."digitalocean", "enter"]);
226 expect(tui.screen.toText()).toContain("cloud.digitalocean.com/account/api/tokens/new");
227 await press([...TOKEN, "enter"]);
228 await settleApp(tui);
229 expect(getCloudAccount(app.db, "digitalocean", "main_4")).toBeDefined();
230 pages.push(tui.screen.toText());
231 tui.stop?.();
232 });
233
234 test("the key never comes back: not in a page, an event or a log line", () => {
235 const events = JSON.stringify(app.db.query("SELECT kind, payload FROM event").all());
236 expect(events.length).toBeGreaterThan(2);
237 for (const where of [
238 ["pages", pages.join("\n")],
239 ["events", events],
240 ["logs", logged.join("\n")],
241 ] as const) {
242 expect(where[1].includes(TOKEN), `the token in ${where[0]}`).toBe(false);
243 expect(where[1].includes(BAD), `the wrong token in ${where[0]}`).toBe(false);
244 }
245 });
246 });
test/egress-literals.test.ts +3
@@ -26,6 +26,9 @@ const LINK = "a link or text rendered for a person; the server never fetches it"
2626 const NOT_CALLED: Record<string, string> = {
2727 "billing.stripe.com": "placeholder in the billing form's portal address hint",
2828 "dashboard.stripe.com": LINK,
29 "cloud.digitalocean.com": LINK,
30 "console.hetzner.com": LINK,
31 "dash.cloudflare.com": LINK,
2932 "bun.sh": "inside a droplet's cloud-init script: the droplet fetches it, not the forge",
3033 "codeberg.org": "placeholder and example text on the bring pages",
3134 "forge.open-platform.sh": "the upstream repository's link (core/upstream.ts) and a link-relation URI (apps/proxy.ts)",
test/no-polling.test.ts +1 −1
@@ -375,7 +375,7 @@ describe("every page the router lists", () => {
375375 if (!seed.ok) throw new Error(String(seed.error));
376376 const issue = createIssue(app.db, { repoId: made.value.id, title: "an issue", body: "b", authorId: admin.value.id });
377377 if (!issue.ok) throw new Error(String(issue.error));
378 Object.assign(fill, { owner: "ada", name: "notes", username: "ada", ref: "main", path: "a.txt", number: String(issue.value.number) });
378 Object.assign(fill, { owner: "ada", name: "notes", username: "ada", ref: "main", path: "a.txt", number: String(issue.value.number), provider: "digitalocean" });
379379 cookie = `forge_session=${createSession(app.db, admin.value.id).token}`;
380380 }, 30_000);
381381
test/pages-budget.test.ts +1
@@ -82,6 +82,7 @@ const NOT_PAGES = new Set([
8282
8383 /** Patterns with an id in them, and the path the fixture fills them with. */
8484 const FIXTURE: Record<string, string> = {
85 "/cloud/connect/:provider": "/cloud/connect/digitalocean",
8586 "/:owner/:name/issues/:number": "/alice/forge/issues/1",
8687 "/api/v1/repos/:owner/:name/issues/:number/estimates": "/api/v1/repos/alice/forge/issues/1/estimates",
8788 "/:owner/:name/pulls/:number": "/alice/forge/pulls/2",
test/security-floor-routes.test.ts +2 −1
@@ -45,7 +45,7 @@ import { pool } from "./helpers/sweep-clock.ts";
4545 quietLogs();
4646
4747 /** Parameters the seed supplies; any other parameter makes a pattern unseeded. */
48 const SEEDED = new Set(["owner", "name", "username", "number", "ref", "oid", "path", "env", "slug", "spec", "machine", "n", "receipt"]);
48 const SEEDED = new Set(["owner", "name", "username", "number", "ref", "oid", "path", "env", "slug", "spec", "machine", "n", "receipt", "provider"]);
4949
5050 const ORIGIN = "needs a connected origin account and a mirror job; the seed connects none";
5151 const MIGRATE = "needs a migration job, which only an import creates";
@@ -203,6 +203,7 @@ beforeAll(async () => {
203203 appDb.exec("CREATE TABLE t (n INTEGER); INSERT INTO t VALUES (1)");
204204 appDb.close();
205205 Object.assign(fill, {
206 provider: "digitalocean",
206207 owner: "ada", name: "notes", username: "ada", ref: "main", oid: pull.value.headOid,
207208 path: "a.txt", env: "prod", slug: "notes", spec: "192", machine: "standard",
208209 receipt: issueReceipt(app.db, pull.value.id),

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs