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

Clouds, step 2: Settings → Cloud accounts attaches GitHub, Cloudflare and Vercel tokens, sealed, each saying what it is used for, with one audit line per vendor call #1776

Closed opened this
Closed without merging

scout/forge:scout/1685-clouds-step-2-settings-cloud-accounts-at → main 4 commits fork 6 threads · 6 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
12 files changed +583 −10
README.md +10
@@ -735,6 +735,16 @@ by declaring it like any secret. **Write allowed** is off by default: a run
735735 that adds `writes: yes` to its front-matter and declares a cloud key whose
736736 switch is off fails with that reason. The switch gates the forge's hand-out,
737737 not the key — a provider key that can write still can, so paste read-only keys.
738 Providers are GitHub, Cloudflare, Vercel, DigitalOcean, AWS, Azure, Fly and
739 Backblaze. GitHub, Cloudflare, Vercel and Fly take **one token per vendor**; a
740 second is a rotation. Each account row has **Rotate** (the new token is
741 verified before it replaces the sealed one), **Rename** (the sealed value and
742 call history move with it) and says what it is used for. The forge's own
743 `cloud.json` (docs/CLOUD.md) gates every call to those vendors, including
744 handing the key to a crew run: with no declaration the call is refused and
745 nothing leaves the machine. Each call, a refused one included, writes one audit
746 row, listed at **/settings/cloud/calls** (account, purpose, bytes out; a run's
747 row is `run:<id>` with 0 bytes, as the forge cannot meter the run's traffic).
738748 **Audit** reads one account and opens one `[audit]` issue per finding (unattached
739749 volumes, powered-off droplets, unassociated IPs, never-active zones) with a
740750 monthly saving estimate, skipping findings already open. It runs in the forge,
docs/CLOUD.md +15
@@ -30,3 +30,18 @@ No file means no uses. A malformed file is refused with one sentence
3030 `mayUse(declared, vendor, use)` in `src/apps/cloud.ts` is the only way a
3131 vendor call is allowed. Later steps call it before every vendor request; it is
3232 false unless that exact vendor and use are declared.
33
34 ## Cloud accounts
35
36 Settings → Cloud accounts (`/settings/cloud`, admins only) holds one sealed
37 token per vendor: GitHub, Cloudflare, Vercel and Fly. An admin attaches,
38 rotates, renames and removes it; the value is never shown again. Each account
39 says in one line what it is used for, read from the forge's own `cloud.json`
40 at the repository root, and names its way back ("bring it home").
41
42 Every call these accounts make, and handing a key to a crew run
outdated

This is not true yet. Crew runs get CLOUD_* secrets through src/crew/grant.ts, which neither asks mayUse nor writes cloud_call. Gate and audit the hand-out to runs, or narrow this sentence. Gating the hand-out is the fix the direction wants.

43 (`src/crew/grant.ts`, audited as `run:<id>`), goes through `mayUse` and writes a row to
44 `cloud_call` — account, purpose, bytes out, when, and whether it was refused.
45 `/settings/cloud/calls` lists today's rows. With no `cloud.json` every call is
46 refused and audited as refused. Providers older than `cloud.json`
47 (DigitalOcean, AWS, Azure, Backblaze) are not covered by the gate yet.
src/actions/cloud.ts +124 −4
@@ -8,10 +8,22 @@
88 */
99
1010 import type { App } from "../app.ts";
11 import { audit, isProvider, verify, type Fetch, type Provider } from "../cloud/providers.ts";
11 import { forgeDeclarations, mayCall } from "../cloud/declared.ts";
12 import {
13 audit,
14 GATE,
15 isProvider,
16 verify,
17 type Fetch,
18 type Provider,
19 } from "../cloud/providers.ts";
20 import { mayUse } from "../apps/cloud.ts";
21 import { recordCall, renameCalls } from "../core/cloud_call.ts";
1222 import {
1323 CLOUD_NAME,
1424 forgetCloudAccount,
25 getCloudAccount,
26 listCloudAccounts,
1527 recordVerified,
1628 secretNameOf,
1729 setWriteAllowed,
@@ -40,6 +52,45 @@ function target(
4052 return ok({ provider, name, secret: secretNameOf(provider, name) });
4153 }
4254
55 const REFUSED = (provider: Provider) =>
56 `cloud.json does not declare ${GATE[provider]?.vendor} ${GATE[provider]?.use}, so the forge will not call it.`;
57
58 const sizeOf = (body: unknown): number =>
59 typeof body === "string" || body instanceof URLSearchParams
60 ? new TextEncoder().encode(String(body)).length
61 : 0;
62
63 /**
64 * The only fetch a vendor call is made with: it asks `mayUse` first, and
65 * writes one audit row either way — account, purpose, bytes out, refused or
66 * not. A call the declarations do not allow never leaves the machine.
67 */
68 function gated(app: App, provider: Provider, name: string, purpose: string): Fetch {
69 return async (url, init) => {
70 const g = GATE[provider];
71 const allowed = g === undefined || mayUse(forgeDeclarations(), g.vendor, g.use);
72 const headers = Object.values((init?.headers as Record<string, string> | undefined) ?? {});
73 const bytes = allowed
74 ? url.length + sizeOf(init?.body) + headers.reduce((n, h) => n + String(h).length, 0)
75 : 0;
76 recordCall(app.db, { provider, name, purpose, bytesOut: bytes, refused: !allowed });
77 if (!allowed) throw new Error(REFUSED(provider));
78 return net.fetch(url, init);
79 };
80 }
81
82 /** Refuse once, up front, with one audit row, when the call is undeclared. */
83 function declaredOr(app: App, provider: Provider, name: string, purpose: string): Result<void, string> {
84 if (mayCall(provider)) return ok();
85 recordCall(app.db, { provider, name, purpose, bytesOut: 0, refused: true });
86 return err(REFUSED(provider));
87 }
88
89 /** One token per vendor that `cloud.json` knows; a second is a rotation. */
90 function taken(app: App, provider: Provider): boolean {
91 return GATE[provider] !== undefined && listCloudAccounts(app.db).some((a) => a.provider === provider);
92 }
93
4394 /** Verify, then seal. Returns the one-sentence summary. */
4495 export async function addAccount(
4596 app: App,
@@ -52,7 +103,11 @@ export async function addAccount(
52103 if (!who.ok) return who;
53104 const t = target(provider, name);
54105 if (!t.ok) return t;
55 const v = await verify(t.value.provider, value, net.fetch);
106 if (taken(app, t.value.provider))
107 return err("That vendor already has a token; rotate it instead.");
108 const gate = declaredOr(app, t.value.provider, t.value.name, "attach");
109 if (!gate.ok) return gate;
110 const v = await verify(t.value.provider, value, gated(app, t.value.provider, t.value.name, "attach"));
56111 if (!v.ok) return v;
57112 const set = putSecret(app, who.value, "forge", "", t.value.secret, value);
58113 if (!set.ok) return err("That credential cannot be stored.");
@@ -80,12 +135,75 @@ export async function reverify(
80135 if (!t.ok) return t;
81136 const value = open(app, who.value, t.value.secret, `verify:${t.value.provider}`);
82137 if (value === undefined) return err("No such credential.");
83 const v = await verify(t.value.provider, value, net.fetch);
138 const gate = declaredOr(app, t.value.provider, t.value.name, "verify");
139 if (!gate.ok) return gate;
140 const v = await verify(t.value.provider, value, gated(app, t.value.provider, t.value.name, "verify"));
84141 if (!v.ok) return v;
85142 recordVerified(app.db, t.value.provider, t.value.name, v.value.summary);
86143 return ok(v.value.summary);
87144 }
88145
146 /** Replace the sealed value of an attached account; the new one is checked first. */
147 export async function rotateAccount(
148 app: App,
149 actor: User | undefined,
150 provider: string,
151 name: string,
152 value: string,
153 ): Promise<Result<string, string>> {
154 const who = admin(actor);
155 if (!who.ok) return who;
156 const t = target(provider, name);
157 if (!t.ok) return t;
158 if (!getCloudAccount(app.db, t.value.provider, t.value.name)) return err("No such credential.");
159 const gate = declaredOr(app, t.value.provider, t.value.name, "rotate");
160 if (!gate.ok) return gate;
161 const v = await verify(t.value.provider, value, gated(app, t.value.provider, t.value.name, "rotate"));
162 if (!v.ok) return v;
163 const set = putSecret(app, who.value, "forge", "", t.value.secret, value);
164 if (!set.ok) return err("That credential cannot be stored.");
165 recordVerified(app.db, t.value.provider, t.value.name, v.value.summary);
166 return ok(v.value.summary);
167 }
168
169 /** Give an account a new name; the sealed value moves with it, no vendor call. */
170 export function renameAccount(
171 app: App,
172 actor: User | undefined,
173 provider: string,
174 from: string,
175 to: string,
176 ): Result<void, string> {
177 const who = admin(actor);
178 if (!who.ok) return who;
179 const a = target(provider, from);
180 if (!a.ok) return a;
181 const b = target(provider, to);
182 if (!b.ok) return b;
183 const old = getCloudAccount(app.db, a.value.provider, a.value.name);
184 if (!old) return err("No such credential.");
185 if (a.value.name === b.value.name) return ok();
186 if (getCloudAccount(app.db, b.value.provider, b.value.name)) return err("That name is taken.");
187 const value = open(app, who.value, a.value.secret, `rename:${a.value.provider}`);
188 if (value === undefined) return err("No such credential.");
189 const set = putSecret(app, who.value, "forge", "", b.value.secret, value);

Rename is six separate writes: put the new secret, record verified, set write, remove the old secret, forget the old account, rename the calls. If any later step fails or throws, you are left with two sealed copies or an account row with no secret. Run the DB steps in one app.db.transaction, and only remove the old secret after the new row is committed.

190 if (!set.ok) return err("That credential cannot be stored.");
191 // The new row is committed whole before the old sealed copy is removed.
192 try {
193 app.db.transaction(() => {
194 recordVerified(app.db, b.value.provider, b.value.name, old.summary);
195 setWriteAllowed(app.db, b.value.provider, b.value.name, old.writeAllowed);
196 forgetCloudAccount(app.db, a.value.provider, a.value.name);
197 renameCalls(app.db, a.value.provider, a.value.name, b.value.name);
198 })();
199 } catch {
200 removeSecret(app, who.value, "forge", "", b.value.secret);
201 return err("That credential could not be renamed.");
202 }
203 removeSecret(app, who.value, "forge", "", a.value.secret);
204 return ok();
205 }
206
89207 export function allowWrite(
90208 app: App,
91209 actor: User | undefined,
@@ -141,7 +259,9 @@ export async function auditAccount(
141259 if (!repo) return err("Name a repository as owner/name to file the findings in.");
142260 const value = open(app, who.value, t.value.secret, `audit:${t.value.provider}:${id()}`);
143261 if (value === undefined) return err("No such credential.");
144 const found = await audit(t.value.provider, value, net.fetch);
262 const gate = declaredOr(app, t.value.provider, t.value.name, "audit");
263 if (!gate.ok) return gate;
264 const found = await audit(t.value.provider, value, gated(app, t.value.provider, t.value.name, "audit"));
145265 if (!found.ok) return found;
146266 let opened = 0;
147267 for (const f of found.value) {
src/apps/manifest.ts +1 −1
@@ -366,7 +366,7 @@ export function parseCheck(
366366 }
367367
368368 /** The vendors a repository may name in `cloud.json`; a closed set. */
369 export const CLOUD_VENDORS = ["cloudflare", "fly", "hetzner", "s3"] as const;
369 export const CLOUD_VENDORS = ["cloudflare", "fly", "github", "hetzner", "s3", "vercel"] as const;
370370 /** What a vendor may be used for; a closed set. */
371371 export const CLOUD_USES = ["compute", "storage", "backup", "dns", "cdn"] as const;
372372 export type CloudVendor = (typeof CLOUD_VENDORS)[number];
src/cloud/declared.ts added +43
@@ -0,0 +1,43 @@
1 /**
2 * What this forge's own `cloud.json` (docs/CLOUD.md) lets it do with each
3 * vendor. Read from beside `package.json`; no file, or a refused one, is no
4 * uses at all. `override` lets a test stand in for the file.
5 */
6
7 import { readFileSync } from "node:fs";
8 import { join } from "node:path";
9 import { mayUse } from "../apps/cloud.ts";
10 import { parseCloud, type CloudDeclaration } from "../apps/manifest.ts";
11 import { GATE, type Provider } from "./providers.ts";
12
13 export const declared: { override: readonly CloudDeclaration[] | undefined } = {
14 override: undefined,
15 };
16
17 export function forgeDeclarations(): readonly CloudDeclaration[] {
18 if (declared.override) return declared.override;
19 let text: string | undefined;
20 try {
21 text = readFileSync(join(import.meta.dir, "..", "..", "cloud.json"), "utf8");
22 } catch {
23 text = undefined;
24 }
25 const r = parseCloud(text);
26 return r.ok ? r.value : [];
27 }
28
29 /** Whether the declarations let the forge make this provider's calls. */
30 export function mayCall(provider: Provider): boolean {
31 const g = GATE[provider];
32 return g === undefined || mayUse(forgeDeclarations(), g.vendor, g.use);
33 }
34
35 /** One line: what the account is used for right now. */
36 export function usedFor(provider: Provider): string {
37 const g = GATE[provider];
38 if (!g) return "Used for read-only checks and audits; not covered by cloud.json.";
39 const d = forgeDeclarations().find((x) => x.vendor === g.vendor && x.use === g.use);
40 return d
41 ? `Used for ${d.use}: ${d.why}`
42 : `Not declared in cloud.json (${g.vendor} ${g.use}): every call is refused.`;
43 }
src/cloud/providers.ts +51
@@ -31,6 +31,8 @@ export const PROVIDERS = [
3131 "azure",
3232 "fly",
3333 "backblaze",
34 "github",
35 "vercel",
3436 ] as const;
3537 export type Provider = (typeof PROVIDERS)[number];
3638
@@ -45,6 +47,8 @@ export const LABEL: Record<Provider, string> = {
4547 azure: "Azure",
4648 fly: "Fly.io",
4749 backblaze: "Backblaze B2",
50 github: "GitHub",
51 vercel: "Vercel",
4852 };
4953
5054 /** What to paste, per provider, in a sentence. */
@@ -55,6 +59,27 @@ export const shape: Record<Provider, string> = {
5559 azure: "TENANT_ID:CLIENT_ID:CLIENT_SECRET of a Reader service principal",
5660 fly: "a deploy or read-only org token",
5761 backblaze: "KEY_ID:APPLICATION_KEY with read-only capabilities",
62 github: "a fine-grained personal access token (read-only repository access is enough)",
63 vercel: "an access token scoped to one team",
64 };
65
66 /**
67 * The `cloud.json` vendor and use a provider's calls belong to. A provider
68 * missing here predates `cloud.json` and is not gated by it (docs/CLOUD.md).
69 */
70 export const GATE: Partial<Record<Provider, { vendor: string; use: string }>> = {
71 cloudflare: { vendor: "cloudflare", use: "dns" },
72 fly: { vendor: "fly", use: "compute" },
73 github: { vendor: "github", use: "storage" },
74 vercel: { vendor: "vercel", use: "compute" },
75 };
76
77 /** The way back from each vendor, in one sentence, shown beside the account. */
78 export const BRING_HOME: Partial<Record<Provider, string>> = {
79 cloudflare: "Bring it home: point the domain's nameservers at your own DNS and remove the token.",
80 fly: "Bring it home: run the app on your own machine with the same forge.json and remove the token.",
81 github: "Bring it home: git clone --mirror the repository into this forge and remove the token.",
82 vercel: "Bring it home: the app deploys from this forge as it is; remove the project at Vercel and the token.",
5883 };
5984
6085 export type Fetch = (url: string, init?: RequestInit) => Promise<Response>;
@@ -187,6 +212,12 @@ async function b2(f: Fetch, value: string) {
187212 return { auth, api: api.origin };
188213 }
189214
215 const gh = (t: string) => ({
216 ...bearer(t),
217 accept: "application/vnd.github+json",
218 "user-agent": "forge",
219 });
220
190221 /** Sign in read-only and say what the credential can see. Never throws. */
191222 export async function verify(
192223 provider: Provider,
@@ -248,6 +279,22 @@ export async function verify(
248279 canWrite: null,
249280 });
250281 }
282 case "github": {
283 const u = await json(f, "https://api.github.com/user", { headers: gh(value) });
284 const r = await json(f, "https://api.github.com/user/repos?per_page=1", { headers: gh(value) }).catch(() => undefined);
285 return ok({
286 summary: `GitHub user ${String(u.login ?? "?")} ${r ? "can list repositories" : "cannot list repositories"}; GitHub does not say what a token may write.`,
287 canWrite: null,
288 });
289 }
290 case "vercel": {
291 const u = await json(f, "https://api.vercel.com/v2/user", { headers: bearer(value) });
292 const p = await json(f, "https://api.vercel.com/v9/projects?limit=20", { headers: bearer(value) }).catch(() => undefined);
293 return ok({
294 summary: `Vercel user ${String(u.user?.username ?? "?")} sees ${p ? plural(p.projects?.length ?? 0, "project") : "no projects"}; Vercel does not say what a token may write.`,
295 canWrite: null,
296 });
297 }
251298 case "backblaze": {
252299 const c = await b2(f, value);
253300 if (!c) return err("A Backblaze credential is KEY_ID:APPLICATION_KEY.");
@@ -347,6 +394,10 @@ export async function audit(
347394 add(`Fly: unattached volume ${v.name} in ${a.name}`, `Volume ${v.name} (${v.sizeGb} GB) of app ${a.name} is attached to no machine.`, v.sizeGb * 0.15);
348395 break;
349396 }
397 case "github":
398 case "vercel":
399 // Nothing here has a price the forge could read.
400 break;
350401 case "backblaze":
351402 // Bucket size needs a file listing per bucket; not attempted.
352403 break;
src/core/cloud_call.ts added +68
@@ -0,0 +1,68 @@
1 /**
2 * One row per vendor call, allowed or refused: which account, for what
3 * purpose, how many bytes went out, when. No credential, no response body.
4 */
5
6 import type { Database } from "bun:sqlite";
7
8 const made = new WeakSet<Database>();
9 function table(db: Database): void {
10 if (made.has(db)) return;
11 db.run(`CREATE TABLE IF NOT EXISTS cloud_call (
12 id INTEGER PRIMARY KEY AUTOINCREMENT,
13 at TEXT NOT NULL,
14 provider TEXT NOT NULL,
15 name TEXT NOT NULL,
16 purpose TEXT NOT NULL,
17 bytes_out INTEGER NOT NULL,
18 refused INTEGER NOT NULL
19 )`);
20 made.add(db);
21 }
22
23 export interface CloudCall {
24 readonly at: string;
25 readonly provider: string;
26 readonly name: string;
27 readonly purpose: string;
28 readonly bytesOut: number;
29 readonly refused: boolean;
30 }
31
32 export function recordCall(

No retention and no index on at: every verify, audit and run hand-out adds a row forever. Prune old rows here and index at.

33 db: Database,
34 c: Omit<CloudCall, "at">,
35 ): void {
36 table(db);
37 db.query(
38 `INSERT INTO cloud_call (at, provider, name, purpose, bytes_out, refused)
39 VALUES (strftime('%Y-%m-%dT%H:%M:%fZ','now'), ?1, ?2, ?3, ?4, ?5)`,
40 ).run(c.provider, c.name, c.purpose.slice(0, 120), c.bytesOut, c.refused ? 1 : 0);
41 }
42
43 /** Today's rows (UTC), newest first. */
44 export function callsToday(db: Database, limit = 200): CloudCall[] {
45 table(db);
46 return db
47 .query<
48 { at: string; provider: string; name: string; purpose: string; bytes_out: number; refused: number },
49 [number]
50 >(
51 `SELECT * FROM cloud_call WHERE date(at) = date('now') ORDER BY id DESC LIMIT ?1`,

date(at) = date('now') can't use an index, and the table is never pruned. Every run that declares a cloud key adds a row, so this page scans all history on every load. Add an index on at, query a range from today's midnight, and prune old rows (e.g. >30 days) in recordCall.

52 )
53 .all(limit)
54 .map((r) => ({
55 at: r.at,
56 provider: r.provider,
57 name: r.name,
58 purpose: r.purpose,
59 bytesOut: r.bytes_out,
60 refused: r.refused === 1,
61 }));
62 }
63
64 /** Rename an account's rows so its history follows it. */
65 export function renameCalls(db: Database, provider: string, from: string, to: string): void {
66 table(db);
67 db.query("UPDATE cloud_call SET name = ?3 WHERE provider = ?1 AND name = ?2").run(provider, from, to);
68 }
src/crew/grant.ts +25 −3
@@ -16,7 +16,9 @@
1616 import type { Database } from "bun:sqlite";
1717 import type { EventBus } from "../core/events.ts";
1818 import { recordGrant, releaseGrant } from "../core/run_secret.ts";
19 import { writeRefused } from "../core/cloud_account.ts";
19 import { mayCall } from "../cloud/declared.ts";
20 import { accountOfSecret, writeRefused } from "../core/cloud_account.ts";
21 import { recordCall } from "../core/cloud_call.ts";
2022 import { isSecretName, resolveScoped } from "../core/secret_store.ts";
2123 import { holdValues, releaseValues } from "../kernel/log.ts";
2224
@@ -87,6 +89,8 @@ export interface Grant {
8789 readonly names: readonly string[];
8890 /** Cloud credentials withheld because the run needs writes and they are not write allowed. */
8991 readonly writeRefused: readonly string[];
92 /** Cloud credentials withheld because cloud.json does not declare the vendor. */
93 readonly gateRefused: readonly string[];
9094 /** Declared but set at no scope. */
9195 readonly missing: readonly string[];
9296 /** Extra egress hosts for this run only. */
@@ -103,10 +107,27 @@ export function grantSecrets(
103107 run: { id: string; repoId: string; ownerId: string; actorId: string },
104108 ): Grant {
105109 // Checked before anything is opened: a refused credential leaves no read.
110 // Handing a cloud key to a run is a use of the vendor: it asks the same
111 // gate as the forge's own calls and leaves one audit row either way (the
112 // forge cannot meter the run's own traffic, so bytes are 0).
113 const gateRefused: string[] = [];
114 for (const n of declared.names) {
115 const acct = accountOfSecret(n);
116 if (!acct) continue;
117 const refused = !mayCall(acct.provider);
118 recordCall(db, {
119 provider: acct.provider,
120 name: acct.name,
121 purpose: `run:${run.id}`,
122 bytesOut: 0,
123 refused,
124 });
125 if (refused) gateRefused.push(n);
126 }
106127 const denied = declared.writes
107 ? declared.names.filter((n) => writeRefused(db, n))
128 ? declared.names.filter((n) => !gateRefused.includes(n) && writeRefused(db, n))
108129 : [];
109 const asked = declared.names.filter((n) => !denied.includes(n));
130 const asked = declared.names.filter((n) => !denied.includes(n) && !gateRefused.includes(n));
110131 const found =
111132 asked.length === 0
112133 ? {}
@@ -131,6 +152,7 @@ export function grantSecrets(
131152 env,
132153 names,
133154 writeRefused: denied,
155 gateRefused,
134156 missing: asked.filter((n) => !(n in found)),
135157 // Only a secret that was actually granted widens the egress.
136158 hosts: [...new Set(names.flatMap((n) => declared.hostOf[n] ?? []))],
src/crew/runner.ts +8
@@ -721,6 +721,14 @@ async function work(
721721 actorId: agent.user.id,
722722 });
723723 for (const why of declared.refused) write(`secret refused: ${why}`);
724 if (grant.gateRefused.length > 0) {
725 const names = grant.gateRefused.join(", ");
726 write(`refused: cloud.json does not declare the vendor of ${names}`);
727 return {
728 state: "failed",
729 summary: `refused: ${names} is not declared in cloud.json`,
730 };
731 }
724732 if (grant.writeRefused.length > 0) {
725733 const names = grant.writeRefused.join(", ");
726734 write(`refused: this run needs writes and ${names} is not write allowed`);
src/http/server.ts +6
@@ -129,8 +129,11 @@ import { releasesPage, rollbackSubmit } from "../web/pages/releases.ts";
129129 import {
130130 cloudAdd,
131131 cloudAudit,
132 cloudCalls,
132133 cloudPage,
133134 cloudRemove,
135 cloudRename,
136 cloudRotate,
134137 cloudVerify,
135138 cloudWrite,
136139 } from "../web/pages/cloud.ts";
@@ -737,6 +740,9 @@ export function buildRouter(): Router<Handler> {
737740 router.add("POST", "/settings/cloud/write", cloudWrite);
738741 router.add("POST", "/settings/cloud/audit", cloudAudit);
739742 router.add("POST", "/settings/cloud/remove", cloudRemove);
743 router.add("POST", "/settings/cloud/rotate", cloudRotate);
744 router.add("POST", "/settings/cloud/rename", cloudRename);
745 router.add("GET", "/settings/cloud/calls", cloudCalls);
740746 router.add("GET", "/settings/access", accessPage);
741747 router.add("GET", "/settings/capacity", capacityPage);
742748 router.add("POST", "/settings/capacity", capacitySet);
src/web/pages/cloud.ts +72 −2
@@ -11,9 +11,13 @@ import {
1111 allowWrite,
1212 auditAccount,
1313 removeAccount,
14 renameAccount,
1415 reverify,
16 rotateAccount,
1517 } from "../../actions/cloud.ts";
16 import { LABEL, PROVIDERS, shape } from "../../cloud/providers.ts";
18 import { usedFor } from "../../cloud/declared.ts";
19 import { BRING_HOME, LABEL, PROVIDERS, shape } from "../../cloud/providers.ts";
20 import { callsToday } from "../../core/cloud_call.ts";
1721 import {
1822 listCloudAccounts,
1923 recentCloudReads,
@@ -50,7 +54,7 @@ function accountsCard(reads: CloudRead[], ctx: Ctx): Html {
5054 return row({
5155 lead: icon("key"),
5256 title: html`${LABEL[a.provider]} / <span class="mono">${a.name}</span>`,
53 meta: html`${a.summary}<br />verified ${a.verifiedAt ? time(a.verifiedAt) : "never"} ·
57 meta: html`${a.summary}<br />${usedFor(a.provider)}<br />${BRING_HOME[a.provider] ?? "Bring it home: remove the token; nothing else depends on it."}<br />verified ${a.verifiedAt ? time(a.verifiedAt) : "never"} ·
5458 ${last ? html`last used ${time(last.at)} by ${runWords(last.run)}` : "never used"} ·
5559 ${a.writeAllowed ? "writes allowed" : "read-only"}`,
5660 trail: html`<div class="row-actions">
@@ -68,6 +72,19 @@ function accountsCard(reads: CloudRead[], ctx: Ctx): Html {
6872 aria-label="Repository for audit findings" maxlength="200" required />
6973 ${btn("Audit", { size: "sm", label: `Audit ${a.name}` })}
7074 </form>
75 <form method="post" action="/settings/cloud/rotate" class="row-actions">
76 ${hidden(a.provider, a.name)}
77 <input class="input" type="password" name="value" placeholder="New credential"
78 aria-label="New credential for ${a.name}" autocomplete="off" required />
79 ${btn("Rotate", { size: "sm", label: `Rotate ${a.name}` })}
80 </form>
81 <form method="post" action="/settings/cloud/rename" class="row-actions">
82 ${hidden(a.provider, a.name)}
83 <input class="input mono" type="text" name="to" placeholder="new name"
84 aria-label="New name for ${a.name}" pattern="[a-z][a-z0-9_]{0,31}" maxlength="32"
85 autocomplete="off" spellcheck="false" required />
86 ${btn("Rename", { size: "sm", label: `Rename ${a.name}` })}
87 </form>
7188 <form method="post" action="/settings/cloud/remove">
7289 ${hidden(a.provider, a.name)}${btn("Remove", { size: "sm", icon: "x", label: `Remove ${a.name}` })}
7390 </form>
@@ -98,6 +115,7 @@ function accountsCard(reads: CloudRead[], ctx: Ctx): Html {
98115 ${btn("Verify and seal", { variant: "primary", size: "sm", icon: "plus" })}
99116 </form>
100117 <div class="card-body">
118 <p class="muted small"><a href="/settings/cloud/calls">Today's vendor calls</a></p>
101119 <p class="muted small">
102120 ${PROVIDERS.map((p) => html`${LABEL[p]}: ${shape[p]}. `)}
103121 </p>
@@ -140,6 +158,38 @@ export function cloudPage(ctx: Ctx): Response {
140158 });
141159 }
142160
161 // GET /settings/cloud/calls
162 export function cloudCalls(ctx: Ctx): Response {
163 const denied = requireAdmin(ctx);
164 if (denied) return denied;
165 const calls = callsToday(ctx.app.db);
166 return page({
167 ctx,
168 title: "Vendor calls today",
169 body: html`<div class="page-head"><h1>Vendor calls today</h1></div>
170 ${settingsLayout(
171 accountSections("cloud", { admin: true }),
172 card(
173 calls.length === 0
174 ? html`<p class="muted small card-body">No vendor has been called today.</p>`
175 : html`<ul class="list">
176 ${calls.map((c) =>
177 row({
178 lead: icon(c.refused ? "x" : "eye"),
179 title: html`${LABEL[c.provider as keyof typeof LABEL] ?? c.provider} /
180 <span class="mono">${c.name}</span>`,
181 meta: html`${c.purpose} · ${c.bytesOut} bytes out ·
182 ${c.refused ? "refused" : "allowed"} · ${time(c.at)}`,
183 }),
184 )}
185 </ul>`,
186 { head: html`${icon("eye")}<h2>Vendor calls today</h2>`, pad: false },
187 ),
188 "Account settings",
189 )}`,
190 });
191 }
192
143193 const said = (ctx: Ctx, r: { ok: boolean }, good: string, bad: string | undefined) =>
144194 flashTo(ctx, BACK, r.ok ? { message: good } : { tone: "danger", message: bad ?? "Not found." });
145195
@@ -198,3 +248,23 @@ export async function cloudRemove(ctx: Ctx): Promise<Response> {
198248 const r = removeAccount(ctx.app, ctx.auth.user, field(form, "provider"), field(form, "name"));
199249 return said(ctx, r, "Removed.", r.ok ? undefined : r.error);
200250 }
251
252 // POST /settings/cloud/rotate

Rotate, rename and the calls list are page-only. The terminal needs the same door (admin-only, through the same actions, value never echoed), and a test for it.

253 export async function cloudRotate(ctx: Ctx): Promise<Response> {
254 const denied = requireAdmin(ctx);
255 if (denied) return denied;
256 const form = await readForm(ctx, "admin");
257 if (form instanceof Response) return form;
258 const r = await rotateAccount(ctx.app, ctx.auth.user, field(form, "provider"), field(form, "name"), field(form, "value").trim());
259 return said(ctx, r, r.ok ? `Rotated. ${r.value}` : "", r.ok ? undefined : r.error);
260 }
261
262 // POST /settings/cloud/rename
263 export async function cloudRename(ctx: Ctx): Promise<Response> {
264 const denied = requireAdmin(ctx);
265 if (denied) return denied;
266 const form = await readForm(ctx, "admin");
267 if (form instanceof Response) return form;
268 const r = renameAccount(ctx.app, ctx.auth.user, field(form, "provider"), field(form, "name"), field(form, "to").trim());
269 return said(ctx, r, "Renamed.", r.ok ? undefined : r.error);
270 }
test/cloud-accounts.test.ts added +160
@@ -0,0 +1,160 @@
1 /**
2 * Cloud accounts, step 2: one token per vendor is attached, rotated, renamed
3 * and removed by an admin; it is sealed and in no page; each says what it is
4 * for; and every vendor call writes an audit row, a refused one included.
5 */
6
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import {
12 addAccount,
13 net,
14 removeAccount,
15 renameAccount,
16 rotateAccount,
17 } from "../src/actions/cloud.ts";
18 import { createRepo } from "../src/actions/repos.ts";
19 import { createApp, type App } from "../src/app.ts";
20 import { grantSecrets, parseDeclaration } from "../src/crew/grant.ts";
21 import { declared } from "../src/cloud/declared.ts";
22 import { callsToday } from "../src/core/cloud_call.ts";
23 import { listCloudAccounts } from "../src/core/cloud_account.ts";
24 import { listSecretNames, resolveSecrets } from "../src/core/secret_store.ts";
25 import { createUser, type User } from "../src/core/users.ts";
26 import { serve, type Servers } from "../src/http/server.ts";
27 import { quietLogs } from "./helpers/globals.ts";
28
29 quietLogs();
30
31 const T1 = "ghp_sealedTokenOne9Zq4TxLm7Kp2";
32 const T2 = "ghp_sealedTokenTwo5Vb8nWcR5Hj3";
33 let hits = 0;
34 net.fetch = async (url, init) => {
35 hits++;
36 const auth = String((init?.headers as Record<string, string>)?.authorization ?? "");
37 const bad = !auth.includes("sealedToken");
38 const u = new URL(url);
39 const reply = (o: unknown) => new Response(JSON.stringify(o), { status: bad ? 401 : 200 });
40 if (u.hostname === "api.github.com" && u.pathname === "/user") return reply({ login: "octo" });
41 if (u.hostname === "api.github.com") return reply([]);
42 return new Response("{}", { status: 404 });
43 };
44
45 describe("cloud accounts, step 2", () => {
46 let dataDir = "";
47 let app: App;
48 let servers: Servers;
49 let alice: User;
50 let bob: User;
51
52 beforeAll(async () => {
53 dataDir = await mkdtemp(join(tmpdir(), "forge-cloud2-"));
54 app = createApp({ dataDir, port: 0 });
55 servers = await serve(app);
56 const a = await createUser(app.db, { trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
57 const b = await createUser(app.db, { trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
58 if (!a.ok || !b.ok) throw new Error("users");
59 alice = a.value;
60 bob = b.value;
61 });
62 afterAll(async () => {
63 declared.override = undefined;
64 servers.stop();
65 app.close();
66 await rm(dataDir, { recursive: true, force: true });
67 });
68
69 const login = async (username: string) =>
70 ((await fetch(`${servers.url}/signin`, {
71 method: "POST",
72 redirect: "manual",
73 headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url },
74 body: new URLSearchParams({ username, password: "a-good-passphrase" }),
75 })).headers.get("set-cookie") ?? "").split(";")[0] ?? "";
76
77 test("an undeclared call is refused, never leaves, and is audited as refused", async () => {
78 declared.override = [];
79 hits = 0;
80 const r = await addAccount(app, alice, "github", "main", T1);
81 expect(r.ok).toBe(false);
82 expect(hits).toBe(0);
83 expect(listCloudAccounts(app.db)).toEqual([]);
84 const rows = callsToday(app.db);
85 expect(rows).toHaveLength(1);
86 expect(rows[0]).toMatchObject({ provider: "github", name: "main", purpose: "attach", refused: true, bytesOut: 0 });
87 });
88
89 test("attach, rotate, rename, remove; the value is sealed and never shown", async () => {
90 declared.override = [{ vendor: "github", use: "storage", why: "mirror of the forge's own source" }];
91 expect((await addAccount(app, bob, "github", "main", T1)).ok).toBe(false);
92 expect((await addAccount(app, alice, "github", "main", "nope")).ok).toBe(false);
93 expect((await addAccount(app, alice, "github", "main", T1)).ok).toBe(true);
94 expect((await addAccount(app, alice, "github", "other", T1)).ok).toBe(false); // one per vendor
95 expect(listSecretNames(app.db, "forge").map((s) => s.name)).toEqual(["CLOUD_GITHUB_MAIN"]);
96
97 expect((await rotateAccount(app, alice, "github", "main", "bad")).ok).toBe(false);
98 expect((await rotateAccount(app, alice, "github", "main", T2)).ok).toBe(true);
99 expect((await rotateAccount(app, bob, "github", "main", T2)).ok).toBe(false);
100 const sealed = (n: string) =>
101 resolveSecrets(app.db, dataDir, app.bus, [n], { actor: alice.id, run: "test" })[n];
102 expect(sealed("CLOUD_GITHUB_MAIN")).toBe(T2);
103
104 expect(renameAccount(app, bob, "github", "main", "work").ok).toBe(false);
105 expect(renameAccount(app, alice, "github", "main", "work").ok).toBe(true);
outdated

This assertion fails because of the one-per-vendor rule, not because the value was rotated, so it would still pass if rotate never replaced the sealed value. Open the secret after rotate and rename (e.g. via resolveSecrets) and assert it equals T2. Also assert that an allowed call's row has bytesOut > 0.

106 expect(listCloudAccounts(app.db).map((a) => a.name)).toEqual(["work"]);
107 expect(listSecretNames(app.db, "forge").map((s) => s.name)).toEqual(["CLOUD_GITHUB_WORK"]);
108 expect(callsToday(app.db).some((c) => c.name === "work" && !c.refused)).toBe(true);
109
110 // the renamed secret is still the rotated one
111 expect(sealed("CLOUD_GITHUB_WORK")).toBe(T2);
112 expect(sealed("CLOUD_GITHUB_MAIN")).toBeUndefined();
113 expect(callsToday(app.db).some((c) => c.name === "work" && !c.refused && c.bytesOut > 0)).toBe(true);
114 });
115
116 test("a run is handed a cloud key only when cloud.json declares it, and either way is audited", async () => {
117 const repo = await createRepo(app, alice, { name: "ops", visibility: "private" });
118 if (!repo.ok) throw new Error("repo");
119 const run = { id: "run9", repoId: repo.value.id, ownerId: alice.id, actorId: alice.id };
120 const d = parseDeclaration("---\nsecrets: [email protected]\n---");
121 declared.override = [];
122 const no = grantSecrets(app.db, dataDir, app.bus, d, run);
123 expect(no.gateRefused).toEqual(["CLOUD_GITHUB_WORK"]);
124 expect(no.env).toEqual({});
125 expect(no.hosts).toEqual([]);
126 expect(callsToday(app.db)[0]).toMatchObject({ provider: "github", name: "work", purpose: "run:run9", refused: true, bytesOut: 0 });
127
128 declared.override = [{ vendor: "github", use: "storage", why: "mirror of the forge's own source" }];
129 const yes = grantSecrets(app.db, dataDir, app.bus, d, { ...run, id: "run10" });
130 expect(yes.gateRefused).toEqual([]);
131 expect(yes.names).toEqual(["CLOUD_GITHUB_WORK"]);
132 expect(callsToday(app.db)[0]).toMatchObject({ purpose: "run:run10", refused: false });
133 yes.release();
134 });
135
136 test("the pages say what it is for, name the way home, and never hold a token", async () => {
137 const c = await login("alice");
138 const get = (path: string, cookie = c) => fetch(`${servers.url}${path}`, { headers: { cookie } });
139 const page = await (await get("/settings/cloud")).text();
140 expect(page).toContain("Used for storage: mirror of the forge&#39;s own source");
141 expect(page).toContain("Bring it home");
142 expect(page).toContain("Rotate");
143 expect(page).toContain("Rename");
144 const calls = await (await get("/settings/cloud/calls")).text();
145 expect(calls).toContain("bytes out");
146 expect(calls).toContain("refused");
147 for (const body of [page, calls]) {
148 expect(body).not.toContain(T1);
149 expect(body).not.toContain(T2);
150 }
151 expect((await get("/settings/cloud/calls", await login("bob"))).status).toBe(404);
152 });
153
154 test("remove drops the sealed value and the row", () => {
155 expect(removeAccount(app, bob, "github", "work").ok).toBe(false);
156 expect(removeAccount(app, alice, "github", "work").ok).toBe(true);
157 expect(listCloudAccounts(app.db)).toEqual([]);
158 expect(listSecretNames(app.db, "forge")).toEqual([]);
159 });
160 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs