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

Clouds as capacity, never as dependency: Cloudflare, Vercel and GitHub attached through Cloud accounts, used in the vendor's own flavor, declared and auditable, and the forge whole without any of them #1448

Closed opened this in answer to
Closed without merging

scout/forge:scout/1146-clouds-as-capacity-never-as-dependency-c → main 11 commits fork 8 threads · 8 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
21 files changed +1107 −7
README.md +12
@@ -485,6 +485,18 @@ not as a crew run; AWS audits look at us-east-1 only; over-provisioned
485485 droplets and forgotten DNS records need metrics or resolution and are not
486486 attempted; Backblaze audits find nothing yet. No dependency was added.
487487
488 A Cloudflare account can also publish a file from a repository's default
489 branch into one Workers KV namespace, declared in that repository's
490 `cloud.json`. The admin decides who: **Set use** on the account row lists the
491 public repositories allowed to name it and its one target; a private
492 repository, an unlisted one, or another target is refused, and every call is
493 audited on `/audit`. The terminal makes the same decision with `forge cloud
494 use <provider> <name> --repos owner/a,owner/b --target <account>/<namespace>`
495 (API: `POST /api/v1/admin/cloud/:provider/:name/use`, admin token). Pushes
496 publish one at a time per repository, and a commit that is no longer the
497 default branch's tip is skipped. **Bring it home** (the page, or `forge cloud home
498 <provider> <name>`) gives the plan to stop. See `docs/CLOUD.md`.
499
488500 ## Share to the forge
489501
490502 Install the forge to your home screen, then Share a link or text to it from
docs/CLOUD.md added +75
@@ -0,0 +1,75 @@
1 # Clouds as capacity, never as dependency
2
3 A cloud account adds capacity, reach or speed. The forge runs, backs up and
4 restores with none attached. Anything that leaves the owner's hardware through
5 a vendor is public already, is declared in git, is a line in the audit, and has
6 a way home.
7
8 ## Attach (Settings → Cloud accounts)
9
10 | Vendor | Least token | Verified with |
11 |---|---|---|
12 | Cloudflare | API token, Workers KV Storage: Edit, one account | `GET /user/tokens/verify`, `/zones` |
13
14 The token is sealed like every cloud credential; rotate it by pasting a new one
15 under the same name. Writes stay off until an admin allows them for the account.
16 Each account row says what it is used for in the last 30 days, and has
17 **Bring it home**.
18
19 Only Cloudflare has a use today. Vercel and GitHub are not providers: they
20 come back with a caller that needs them.
21
22 **Who may spend it is the admin's, not the repository's.** On the account row,
23 **Set use** records the public `owner/name` repositories whose `cloud.json` may
24 name the account and the one `<account id>/<namespace id>` it may write to.
25 Publishing refuses a private repository, a repository not on that list, and a
26 target other than the account's own; each refusal is logged and nothing is sent.
27
28 ## Declare (`cloud.json`, nothing by default)
29
30 ```json
31 { "uses": [
32 { "vendor": "cloudflare", "purpose": "kv-publish", "account": "edge",
33 "data": "public", "target": "<32-hex account id>/<32-hex namespace id>",
34 "file": "flags.json",
35 "what": "feature flags", "where": "KV namespace flags", "why": "edge reads" }
36 ] }
37 ```
38
39 `account` names the Cloud account whose token is used; `file` is a path in the
40 same repository, published as is under the key with `/` written `:`; `data`
41 can only be `public`. A malformed file publishes nothing.
42
43 ## What runs
44
45 `src/cloud/publish.ts` watches pushes. On a push to the default branch it reads
46 `cloud.json` at the new commit and, for each use, requires the account to exist
47 with writes allowed, opens its token through `resolveSecrets` (a `secret.read`
48 event naming `cloud-publish:<owner>/<repo>`), and calls
49 `src/cloud/cloudflare.ts` through the gate (`src/cloud/gate.ts`). The gate
50 refuses any file or account the commit did not declare, before any request.
51 The outcome of each use is one log line.
52
53 ## Audit
54
55 Each call appends a `cloud.use` event (account, purpose, app, bytes out, cost
56 estimate). `/audit` lists today's, for admins; the account row says what it was
57 used for. Any dataset built from the event outbox carries them.
58
59 ## Bring it home
60
61 Page: `/settings/cloud/home?provider=cloudflare&name=edge`. Terminal:
62 `forge cloud home cloudflare edge` (API: `GET /api/v1/admin/cloud/:provider/:name/home`,
63 admin token). Both answer from `src/cloud/home.ts` for that one account: what it
64 did in 30 days, the steps, and the cost of moving. In short: remove the use
65 from `cloud.json` and push, serve the same file from the app, remove the
66 account, revoke the token at the vendor.
67
68 ## Who may spend an account, from the terminal
69
70 `forge cloud use cloudflare edge --repos owner/a,owner/b --target <account>/<namespace>`
71 (API: `POST /api/v1/admin/cloud/:provider/:name/use`, admin token) is the same
72 decision as Settings → Cloud accounts → Set use. Publishes run one at a time
73 per repository, and a commit that is no longer the default branch's tip when
74 its turn comes is skipped, so the namespace never ends behind git. The 30-day
75 numbers are counted in SQL, with no row cap.
scripts/gate.ts +1
@@ -152,6 +152,7 @@ export const GATE: readonly string[] = [
152152 "test/offline.test.ts",
153153 "test/share.test.ts",
154154 "test/cloud.test.ts",
155 "test/cloud-vendors.test.ts",
155156 "test/run-secrets.test.ts",
156157 "test/reserved-names.test.ts",
157158 "test/forge-cloudflare.test.ts",
src/actions/cloud.ts +34
@@ -13,6 +13,7 @@ import {
1313 CLOUD_NAME,
1414 forgetCloudAccount,
1515 recordVerified,
16 setCloudUse,
1617 secretNameOf,
1718 setWriteAllowed,
1819 } from "../core/cloud_account.ts";
@@ -104,6 +105,39 @@ export function allowWrite(
104105 return ok();
105106 }
106107
108 const REPO_SLUG = /^[A-Za-z0-9._-]{1,64}\/[A-Za-z0-9._-]{1,100}$/;
109 const KV_TARGET = /^[0-9a-f]{32}\/[0-9a-f]{32}$/;
110
111 /**
112 * Who may spend an account and where: the public repositories (`owner/name`,
113 * space or comma separated) whose `cloud.json` may name it, and the one
114 * target it may write to. A repository's own file never decides either.
115 */
116 export function allowUse(
117 app: App,
118 actor: User | undefined,
119 provider: string,
120 name: string,
121 reposText: string,
122 targetText: string,
123 ): Result<void, string> {
124 const who = admin(actor);
125 if (!who.ok) return who;
126 const repos = [...new Set(reposText.split(/[\s,]+/).filter((x) => x !== ""))];
127 if (repos.length > 32 || repos.some((r) => !REPO_SLUG.test(r)))
128 return err("Repositories are owner/name, up to 32, separated by spaces.");
129 const target = targetText.trim();
130 if (target !== "" && !KV_TARGET.test(target))
131 return err("A target is <account id>/<namespace id>, each 32 hex characters.");
132 if (!setCloudUse(app.db, provider, name, repos, target)) return err("No such credential.");
133 app.bus.append({
134 kind: "cloud.use_allowed",
135 actorId: who.value.id,
136 payload: { provider, name, repos, target },
137 });
138 return ok();
139 }
140
107141 export function removeAccount(
108142 app: App,
109143 actor: User | undefined,
src/apps/manifest.ts +88
@@ -431,3 +431,91 @@ function readPackage(
431431
432432 const hasKeys = (value: unknown): boolean =>
433433 isObject(value) && Object.keys(value).length > 0;
434
435 // ---- cloud.json: what an app may use from a vendor ----
436
437 export const CLOUD_VENDORS = ["cloudflare"] as const;
438 export type CloudVendor = (typeof CLOUD_VENDORS)[number];
439
440 /** The only purposes there are, per vendor. A use is vendor + purpose. */
441 export const CLOUD_PURPOSES = {
442 cloudflare: ["kv-publish"],
443 } as const satisfies Record<CloudVendor, readonly string[]>;
444
445 export interface CloudUse {
446 readonly vendor: CloudVendor;
447 readonly purpose: string;
448 /** The Cloud account (Settings → Cloud accounts) whose token is used. */
449 readonly account: string;
450 /** What leaves the owner's hardware. */
451 readonly what: string;
452 /** Where it lands, in words. */
453 readonly where: string;
454 /** Why this is worth it. */
455 readonly why: string;
456 /** KV only: `<32-hex account id>/<32-hex namespace id>`. */
457 readonly target: string;
458 /** KV only: the file in this repository, published as is. Public already. */
459 readonly file: string;
460 }
outdated

The destination account/namespace is whatever the committer writes. Together with the missing authorization in publish.ts, this lets one repo overwrite keys in another app's namespace. The allowed target should belong to the Cloud account (set by the admin), not to the repo.

461
462 export interface CloudManifest {
463 readonly uses: readonly CloudUse[];
464 }
465
466 const CLOUD_USES_MAX = 16;
467 const CLOUD_TEXT_MAX = 200;
468 const CLOUD_ACCOUNT = /^[a-z][a-z0-9_]{0,31}$/;
469 const CLOUD_TARGET = /^[0-9a-f]{32}\/[0-9a-f]{32}$/;
470 const CLOUD_FILE = /^[A-Za-z0-9._-]+(\/[A-Za-z0-9._-]+){0,5}$/;
471 export const NO_CLOUD: CloudManifest = { uses: [] };
472
473 /**
474 * `cloud.json`, `undefined` when absent. Absent means nothing: an app with
475 * no `cloud.json` reaches no vendor. Fails closed like `forge.json`.
476 */
477 export function parseCloud(
478 cloudJson: string | undefined,
479 ): Result<CloudManifest, ManifestError> {
480 if (cloudJson === undefined) return ok(NO_CLOUD);
481 const parsed = parseJson(cloudJson, "cloud.json");
482 if (!parsed.ok) return parsed;
483 const list = parsed.value["uses"];
484 if (list === undefined) return ok(NO_CLOUD);
485 if (!Array.isArray(list))
486 return invalid("cloud.json: uses must be an array");
487 if (list.length > CLOUD_USES_MAX)
488 return invalid(`cloud.json: at most ${CLOUD_USES_MAX} uses`);
489 const uses: CloudUse[] = [];
490 for (const [i, u] of list.entries()) {
491 const at = `cloud.json: uses[${i}]`;
492 if (!isObject(u)) return invalid(`${at} must be an object`);
493 const vendor = u["vendor"];
494 if (typeof vendor !== "string" || !(CLOUD_VENDORS as readonly string[]).includes(vendor))
495 return invalid(`${at}.vendor must be one of ${CLOUD_VENDORS.join(", ")}`);
496 const v = vendor as CloudVendor;
497 const purpose = u["purpose"];
498 if (typeof purpose !== "string" || !(CLOUD_PURPOSES[v] as readonly string[]).includes(purpose))
499 return invalid(`${at}.purpose for ${v} must be one of ${CLOUD_PURPOSES[v].join(", ")}`);
500 const account = u["account"];
501 if (typeof account !== "string" || !CLOUD_ACCOUNT.test(account))
outdated

data: "public" is self-declared. It is never checked against the repository's visibility, so a private repo's file can be published.

502 return invalid(`${at}.account is the name of a Cloud account: lowercase letters, digits, underscores`);
503 const text: Record<"what" | "where" | "why", string> = { what: "", where: "", why: "" };
504 for (const k of ["what", "where", "why"] as const) {
505 const t = u[k];
506 if (typeof t !== "string" || t.trim() === "" || t.length > CLOUD_TEXT_MAX || /[\x00-\x1f]/.test(t))
507 return invalid(`${at}.${k} is required: one line, up to ${CLOUD_TEXT_MAX} characters`);
508 text[k] = t.trim();
509 }
510 if (u["data"] !== "public")
511 return invalid(`${at}.data must be "public": only what is public already leaves through a vendor`);
512 const target = u["target"];
513 if (typeof target !== "string" || !CLOUD_TARGET.test(target))
514 return invalid(`${at}.target is <account id>/<namespace id>, each 32 hex characters`);
515 const file = u["file"];
516 if (typeof file !== "string" || !CLOUD_FILE.test(file) || file.split("/").includes(".."))
517 return invalid(`${at}.file is a relative path in this repository`);
518 uses.push({ vendor: v, purpose, account, ...text, target, file });
519 }
520 return ok({ uses });
521 }
src/cli/api.ts +28
@@ -36,6 +36,19 @@ export interface Whoami {
3636 readonly displayName: string;
3737 }
3838
39 export interface CloudHome {
40 readonly used: string;
41 readonly plan: {
42 readonly vendor: string;
43 readonly account: string;
44 readonly uses: number;
45 readonly bytesOut: number;
46 readonly spentUsd: number;
47 readonly steps: readonly string[];
48 readonly cost: string;
49 };
50 }
51
3952 export class ForgeApi {
4053 /** True once `pins()` has had to fall back, so the CLI can say it once. */
4154 pinsUnavailable = false;
@@ -96,6 +109,21 @@ export class ForgeApi {
96109 return ok(parsed as T);
97110 }
98111
112 /** The plan to bring a Cloud account home, and what it was used for (admin). */
113 async cloudHome(provider: string, name: string): Promise<ApiResult<CloudHome>> {
114 return this.call<CloudHome>(
115 `/api/v1/admin/cloud/${encodeURIComponent(provider)}/${encodeURIComponent(name)}/home`,
116 );
117 }
118
119 /** Give a Cloud account to repositories and its one target (admin). */
120 async cloudUse(provider: string, name: string, repos: string[], target: string): Promise<ApiResult<{ ok: true }>> {
121 return this.call<{ ok: true }>(
122 `/api/v1/admin/cloud/${encodeURIComponent(provider)}/${encodeURIComponent(name)}/use`,
123 { method: "POST", body: JSON.stringify({ repos, target }) },
124 );
125 }
126
99127 async whoami(): Promise<ApiResult<Whoami>> {
100128 const out = await this.call<{ username?: string; displayName?: string }>(
101129 "/api/v1/user",
src/cli/main.ts +41 −1
@@ -51,7 +51,7 @@ export const EXIT = {
5151 partial: 4,
5252 } as const;
5353
54 const VALUE_FLAGS = ["token", "interval", "root", "url", "limit"];
54 const VALUE_FLAGS = ["token", "interval", "root", "url", "limit", "repos", "target"];
5555
5656 export async function main(argv: readonly string[]): Promise<number> {
5757 const args = parseArgs(argv, { values: VALUE_FLAGS });
@@ -77,6 +77,8 @@ export async function main(argv: readonly string[]): Promise<number> {
7777 case "help":
7878 usage(out);
7979 return EXIT.ok;
80 case "cloud":
81 return cloud(out, args);
8082 case "login":
8183 return login(out, args);
8284 case "logout":
@@ -118,6 +120,8 @@ function usage(out: Out): void {
118120 );
119121 out.line(b(" forge status") + " [--root DIR] [--json]");
120122 out.line(b(" forge ls") + " [--json]");
123 out.line(b(" forge cloud home <provider> <name>") + " the plan to bring a Cloud account home (admin)");
124 out.line(b(" forge cloud use <provider> <name> --repos … --target …") + " who may spend a Cloud account, and where (admin)");
121125 out.line(b(" forge pin <owner/name>"));
122126 out.line(b(" forge unpin <owner/name>"));
123127 out.line(b(" forge open <owner/name>") + " [--web]");
@@ -189,6 +193,42 @@ async function whoami(out: Out): Promise<number> {
189193 return EXIT.ok;
190194 }
191195
196 async function cloud(out: Out, args: Args): Promise<number> {
197 const [sub, provider, name] = args.positional;
198 if ((sub !== "home" && sub !== "use") || provider === undefined || name === undefined) {
199 out.err("forge cloud: forge cloud home <provider> <name> | forge cloud use <provider> <name> --repos owner/name,… --target <account>/<namespace>");
200 return EXIT.usage;
201 }
202 const repos = args.value("repos");
203 const target = args.value("target");
204 if (sub === "use" && (repos === undefined || target === undefined)) {
205 out.err("forge cloud use: --repos and --target are both required (--target= with nothing takes the grant away)");
206 return EXIT.usage;
207 }
208 const loaded = await requireConfig(out);
209 if (typeof loaded === "number") return loaded;
210 if (sub === "use") {
211 const set = await new ForgeApi(loaded.url, loaded.token).cloudUse(provider, name, (repos ?? "").split(/[\s,]+/).filter((r) => r !== ""), target ?? "");
212 if (!set.ok) {
213 out.err(`forge cloud: ${set.error.status === 404 ? "no such Cloud account (or you are not an admin)" : set.error.message}`);
214 return EXIT.failed;
215 }
216 out.line(`${provider} / ${name}: given to ${repos || "no repositories"}, target ${target || "none"}`);
217 return EXIT.ok;
218 }
219 const got = await new ForgeApi(loaded.url, loaded.token).cloudHome(provider, name);
220 if (!got.ok) {
221 out.err(`forge cloud: ${got.error.status === 404 ? "no such Cloud account (or you are not an admin)" : got.error.message}`);
222 return EXIT.failed;
223 }
224 const { plan, used } = got.value;
225 out.line(`${plan.vendor} / ${plan.account}: ${used}`);
226 out.line(`last 30 days: ${plan.uses} call(s), ${plan.bytesOut} bytes out, about $${plan.spentUsd.toFixed(2)}`);
227 plan.steps.forEach((step, i) => out.line(` ${i + 1}. ${step}`));
228 out.line(`cost of moving: ${plan.cost}`);
229 return EXIT.ok;
230 }
231
192232 // ── sync and status ──────────────────────────────────────────────────────
193233
194234 async function sync(out: Out, args: Args, network: boolean): Promise<number> {
src/cloud/cloudflare.ts added +35
@@ -0,0 +1,35 @@
1 /**
2 * Cloudflare, in Cloudflare's flavor: Workers KV, the edge rung of the cache
3 * spectrum, for flags and config. Only a file the app's own repository
4 * already holds, declared `public` in `cloud.json`, goes out; the way home is
5 * to serve that same file from the app.
6 */
7
8 import { call, permit, type Gate } from "./gate.ts";
9 import { err, ok, type Result } from "../kernel/result.ts";
10
11 /** Cloudflare's value cap is 25 MiB; a config file is never near it. */
12 export const KV_MAX = 1024 * 1024;
13
14 /** The KV key a repository path is published under: `/` becomes `:`. */
15 export const kvKey = (file: string): string => file.replaceAll("/", ":");
16
17 /** Publish one declared file's text as a KV entry. */
18 export async function kvPublish(
19 g: Gate,
20 file: string,
21 value: string,
22 ): Promise<Result<{ bytes: number }, string>> {
23 const use = permit(g, "cloudflare", "kv-publish", file);
24 if (!use.ok) return use;
25 const [account, namespace] = use.value.target.split("/");
26 const bytes = new TextEncoder().encode(value).length;
27 if (bytes > KV_MAX) return err(`${file} is over ${KV_MAX} bytes; not published.`);
28 const url = `https://api.cloudflare.com/client/v4/accounts/${account}/storage/kv/namespaces/${namespace}/values/${encodeURIComponent(kvKey(file))}`;
29 const res = await call(g, "cloudflare", "kv-publish", bytes, 0, url, {
30 method: "PUT",
31 headers: { authorization: `Bearer ${g.token}`, "content-type": "text/plain" },
32 body: value,
33 });
34 return res.ok ? ok({ bytes }) : res;
35 }
src/cloud/gate.ts added +56
@@ -0,0 +1,56 @@
1 /**
2 * The gate every vendor call passes: the app declared the use in
3 * `cloud.json` (nothing by default), and the call is written to the audit
4 * before it is made. Undeclared means refused, the way `forge.json` `egress`
5 * refuses a host.
6 */
7
8 import type { CloudManifest, CloudUse, CloudVendor } from "../apps/manifest.ts";
9 import type { CloudUseRow } from "../core/cloud_use.ts";
10 import { err, ok, type Result } from "../kernel/result.ts";
11 import type { Fetch } from "./providers.ts";
12
13 export interface Gate {
14 /** The app's `cloud.json`; `NO_CLOUD` when it has none. */
15 readonly declared: CloudManifest;
16 /** `owner/name` of the app, for the audit line. */
17 readonly app: string;
18 /** The account name the sealed token belongs to. */
19 readonly account: string;
20 readonly token: string;
21 readonly fetch: Fetch;
22 readonly record: (u: Omit<CloudUseRow, "at">) => void;
23 }
24
25 export function permit(
26 g: Gate,
27 vendor: CloudVendor,
28 purpose: string,
29 file: string,
30 ): Result<CloudUse, string> {
31 const use = g.declared.uses.find(
32 (u) => u.vendor === vendor && u.purpose === purpose && u.account === g.account && u.file === file,
33 );
34 return use
35 ? ok(use)
36 : err(`${g.app} does not declare ${vendor} ${purpose} of ${file} for ${g.account} in cloud.json; refused.`);
37 }
38
39 /** Audit, then call. The line is written even when the vendor then fails. */
40 export async function call(
41 g: Gate,
42 vendor: CloudVendor,
43 purpose: string,
44 bytesOut: number,
45 costUsd: number,
46 url: string,
47 init: RequestInit,
48 ): Promise<Result<Response, string>> {
49 g.record({ vendor, account: g.account, purpose, app: g.app, bytesOut, costUsd });
50 try {
51 const res = await g.fetch(url, { ...init, signal: AbortSignal.timeout(15_000) });
52 return res.ok ? ok(res) : err(`${new URL(url).host} answered ${res.status}`);
53 } catch (e) {
54 return err(`${new URL(url).host}: ${e instanceof Error ? e.message : "failed"}`);
55 }
56 }
src/cloud/home.ts added +69
@@ -0,0 +1,69 @@
1 /**
2 * "Bring it home": for one Cloud account, the plan to move what it does back
3 * onto the owner's hardware, and what that costs. Plain data a runbook can
4 * follow; the numbers come from the audit of the last 30 days.
5 */
6
7 import type { Database } from "bun:sqlite";
8 import { CLOUD_VENDORS, type CloudVendor } from "../apps/manifest.ts";
9 import { getCloudAccount } from "../core/cloud_account.ts";
10 import { totalsSince, type CloudTotal } from "../core/cloud_use.ts";
11
12 export interface HomePlan {
13 readonly vendor: CloudVendor;
14 readonly account: string;
15 readonly uses: number;
16 readonly bytesOut: number;
17 readonly spentUsd: number;
18 readonly steps: readonly string[];
19 /** What running it yourself costs, in words. */
20 readonly cost: string;
21 }
22
23 const STEPS: Record<CloudVendor, { steps: string[]; cost: string }> = {
24 cloudflare: {
25 steps: [
26 "Remove the cloudflare kv-publish uses of this account from each cloud.json and push; the forge stops publishing.",
27 "What was published is a file in the repository: serve that same file from the app's own static path.",
28 "Point readers at the app's URL for it instead of the KV namespace.",
29 "Remove the Cloudflare account on Settings → Cloud accounts and revoke the token at dash.cloudflare.com.",
30 ],
31 cost: "No new machine: the file is served by the forge. Reads lose the edge, so far-away readers see more latency; one process, a few KB.",
32 },
33 };
34
35 /** The plan for one account, from the totals the audit holds for it. */
36 export function bringHome(vendor: CloudVendor, account: string, totals: readonly CloudTotal[]): HomePlan {
37 return {
38 vendor,
39 account,
40 uses: totals.reduce((n, t) => n + t.uses, 0),
41 bytesOut: totals.reduce((n, t) => n + t.bytesOut, 0),
42 spentUsd: totals.reduce((n, t) => n + t.costUsd, 0),
43 ...STEPS[vendor],
44 };
45 }
46
47 const DAY = 86_400_000;
48
49 /** The last 30 days of one account, counted in SQL. */
50 export const monthOf = (db: Database, vendor: string, account: string, now = Date.now()): CloudTotal[] =>
51 totalsSince(db, new Date(now - 30 * DAY).toISOString(), vendor, account);
52
53 /** What an account did in the last 30 days: "used for kv-publish ×3", or "not used in 30 days". */
54 export function usedFor(totals: readonly CloudTotal[]): string {
55 return totals.length === 0 ? "not used in 30 days" : "used for " + totals.map((t) => `${t.purpose} ×${t.uses}`).join(", ");
56 }
57
58 /** Both doors' answer for one account: undefined when it is not an account with a plan. */
59 export function homeOf(
60 db: Database,
61 provider: string,
62 account: string,
63 now = Date.now(),
64 ): { plan: HomePlan; used: string } | undefined {
65 if (!(CLOUD_VENDORS as readonly string[]).includes(provider)) return undefined;
66 if (!getCloudAccount(db, provider, account)) return undefined;
67 const totals = monthOf(db, provider, account, now);
68 return { plan: bringHome(provider as CloudVendor, account, totals), used: usedFor(totals) };
69 }
src/cloud/providers.ts +1 −1
@@ -49,7 +49,7 @@ export const LABEL: Record<Provider, string> = {
4949
5050 /** What to paste, per provider, in a sentence. */
5151 export const shape: Record<Provider, string> = {
52 cloudflare: "an API token (read-only scope is enough)",
52 cloudflare: "an API token scoped to Workers KV Storage: Edit on one account (read-only if it only audits)",
5353 digitalocean: "a personal access token (read scope is enough)",
5454 aws: "ACCESS_KEY_ID:SECRET_ACCESS_KEY of a read-only IAM user",
5555 azure: "TENANT_ID:CLIENT_ID:CLIENT_SECRET of a Reader service principal",
src/cloud/publish.ts added +122
@@ -0,0 +1,122 @@
1 /**
2 * The one place a repository's `cloud.json` meets a Cloud account: on a push
3 * to the default branch, each declared `kv-publish` of a file in that commit
4 * is made through the gate. The account must exist and have writes allowed
5 * (Settings → Cloud accounts), the repository must be public and be one the
6 * admin gave the account to, and the target must be the account's own, set by
7 * the admin: a repository's file asks, it never decides. The token is opened through `resolveSecrets`,
8 * so it is a `secret.read`, and each call is a `cloud.use` event. A
9 * repository with no `cloud.json` costs one missing-file read and nothing else.
10 */
11
12 import type { App } from "../app.ts";
13 import { net } from "../actions/cloud.ts";
14 import { readFileAt } from "../apps/checkout.ts";
15 import { parseCloud } from "../apps/manifest.ts";
16 import { getCloudAccount, secretNameOf } from "../core/cloud_account.ts";
17 import { recordUse } from "../core/cloud_use.ts";
18 import { getRepoById, type Repo } from "../core/repos.ts";
19 import { resolveSecrets } from "../core/secret_store.ts";
20 import { listRefs } from "../git/read.ts";
21 import { repoDir } from "../git/repos.ts";
22 import { createLog } from "../kernel/log.ts";
23 import { kvPublish } from "./cloudflare.ts";
24 import type { Gate } from "./gate.ts";
25
26 const log = createLog("cloud");
27
28 /** What happened to each declared use, one line each: for the log and the tests. */
29 export async function publishDeclared(
30 app: App,
31 repo: Repo,
32 commitOid: string,
33 stillTip: () => Promise<boolean> = async () => true,
34 ): Promise<string[]> {
outdated

High. The account is found by the name the repository's own cloud.json gives, and nothing checks that the repository (or whoever pushed) may use it. Any user who can push to a default branch can spend an admin-attached Cloudflare token. Bind accounts to the repositories or owners the admin allowed, and refuse when repo.visibility !== "public".

35 const bare = repoDir(app.reposRoot, repo.ownerName, repo.name);
36 const declared = parseCloud(await readFileAt(bare, commitOid, "cloud.json"));
37 const slug = `${repo.ownerName}/${repo.name}`;
38 if (repo.visibility !== "public") return [`${slug}: not a public repository; nothing leaves`];
39 if (!declared.ok) return [`${slug}: cloud.json refused: ${declared.error.kind === "invalid" ? declared.error.message : "not valid"}`];
40 const said: string[] = [];
41 for (const use of declared.value.uses) {
42 const label = `${slug}: ${use.vendor} ${use.purpose} ${use.file}`;
43 const account = getCloudAccount(app.db, use.vendor, use.account);
44 if (!account) {
45 said.push(`${label}: no Cloud account ${use.vendor}/${use.account}; refused`);
46 continue;
47 }
48 if (!account.repos.includes(slug)) {
49 said.push(`${label}: ${use.vendor}/${use.account} was not given to ${slug}; refused`);
50 continue;
51 }
52 if (account.target === "" || use.target !== account.target) {
53 said.push(`${label}: target is not the one ${use.vendor}/${use.account} may write to; refused`);
54 continue;
55 }
56 if (!account.writeAllowed) {
57 said.push(`${label}: ${use.vendor}/${use.account} is read-only; refused`);
58 continue;
59 }
60 const secret = secretNameOf(account.provider, account.name);
61 const token = resolveSecrets(app.db, app.config.dataDir, app.bus, [secret], {
62 run: `cloud-publish:${slug}`,
63 })[secret];
64 if (token === undefined) {
65 said.push(`${label}: the account's token will not open; refused`);
66 continue;
67 }
68 const value = await readFileAt(bare, commitOid, use.file);
69 if (value === undefined) {
70 said.push(`${label}: no such file at ${commitOid.slice(0, 7)}; refused`);
71 continue;
72 }
73 // Asked last, right before the PUT: a newer push may have landed while this one waited.
74 if (!(await stillTip())) {
75 said.push(`${label}: ${commitOid.slice(0, 7)} is no longer the tip of ${repo.defaultBranch}; skipped`);
76 continue;
77 }
78 const gate: Gate = {
79 declared: declared.value,
80 app: slug,
81 account: use.account,
82 token,
83 fetch: net.fetch,
84 record: (u) => recordUse(app.bus, u),
85 };
86 const done = await kvPublish(gate, use.file, value);
87 said.push(`${label}: ${done.ok ? `published ${done.value.bytes} bytes` : done.error}`);
88 }
89 return said;
90 }
outdated

Every default-branch push starts its own publishDeclared, with nothing between them. Two pushes in quick succession race, and the older commit's PUT can land last, leaving KV behind git. Chain publishes per repository, and before the PUT check that newOid is still refs/heads/<default>.

91
92 /** The default branch's tip right now, or undefined when it cannot be read. */
93 async function tipOf(app: App, repo: Repo): Promise<string | undefined> {
94 const bare = repoDir(app.reposRoot, repo.ownerName, repo.name);
95 const refs = await listRefs(bare, `refs/heads/${repo.defaultBranch}`);
96 return refs.ok ? refs.value.find((r) => r.name === `refs/heads/${repo.defaultBranch}`)?.oid : undefined;
97 }
98
99 /** Watch pushes; publish what the default branch's new tip declares, one repository at a time. */
100 export function startCloudPublish(app: App): () => void {
101 const chains = new Map<string, Promise<unknown>>();
102 return app.bus.subscribe((event) => {
103 if (event.kind !== "push" || event.repoId === null) return;
104 const repo = getRepoById(app.db, event.repoId);
105 const updates = event.payload["updates"];
106 if (!repo || !Array.isArray(updates)) return;
107 for (const u of updates as { ref?: unknown; newOid?: unknown }[]) {
108 if (u.ref !== `refs/heads/${repo.defaultBranch}` || typeof u.newOid !== "string" || /^0+$/.test(u.newOid)) continue;
109 const oid = u.newOid;
110 const next = (chains.get(repo.id) ?? Promise.resolve())
111 .then(() => publishDeclared(app, repo, oid, async () => (await tipOf(app, repo)) === oid))
112 .then(
113 (lines) => lines.forEach((l) => log.info(l)),
114 (error) => log.error("cloud publish failed", { error: String(error) }),
115 );
116 chains.set(repo.id, next);
117 void next.then(() => {
118 if (chains.get(repo.id) === next) chains.delete(repo.id);
119 });
120 }
121 });
122 }
src/core/cloud_account.ts +29
@@ -21,6 +21,11 @@ function table(db: Database): void {
2121 write_allowed INTEGER NOT NULL DEFAULT 0,
2222 PRIMARY KEY (provider, name)
2323 )`);
24 const cols = db.query<{ name: string }, []>("PRAGMA table_info(cloud_account)").all();
25 if (!cols.some((c) => c.name === "repos"))
26 db.run("ALTER TABLE cloud_account ADD COLUMN repos TEXT NOT NULL DEFAULT ''");
27 if (!cols.some((c) => c.name === "target"))
28 db.run("ALTER TABLE cloud_account ADD COLUMN target TEXT NOT NULL DEFAULT ''");
2429 made.add(db);
2530 }
2631
@@ -50,6 +55,10 @@ export interface CloudAccount {
5055 readonly summary: string;
5156 readonly verifiedAt: string | null;
5257 readonly writeAllowed: boolean;
58 /** `owner/name` of the public repositories an admin let publish with it; none until set. */
59 readonly repos: readonly string[];
60 /** The one `<account id>/<namespace id>` it may publish into; empty until set. */
61 readonly target: string;
5362 }
5463
5564 interface Row {
@@ -58,6 +67,8 @@ interface Row {
5867 summary: string;
5968 verified_at: string | null;
6069 write_allowed: number;
70 repos: string;
71 target: string;
6172 }
6273
6374 const toAccount = (r: Row): CloudAccount => ({
@@ -66,6 +77,8 @@ const toAccount = (r: Row): CloudAccount => ({
6677 summary: r.summary,
6778 verifiedAt: r.verified_at,
6879 writeAllowed: r.write_allowed === 1,
80 repos: r.repos.split(/\s+/).filter((x) => x !== ""),
81 target: r.target,
6982 });
7083
7184 export function listCloudAccounts(db: Database): CloudAccount[] {
@@ -121,6 +134,22 @@ export function setWriteAllowed(
121134 );
122135 }
123136
137 /** Where an account may be used: which repositories, and into which target. */
138 export function setCloudUse(
139 db: Database,
140 provider: string,
141 name: string,
142 repos: readonly string[],
143 target: string,
144 ): boolean {
145 table(db);
146 return (
147 db
148 .query("UPDATE cloud_account SET repos = ?3, target = ?4 WHERE provider = ?1 AND name = ?2")
149 .run(provider, name, repos.join(" "), target).changes > 0
150 );
151 }
152
124153 export function forgetCloudAccount(
125154 db: Database,
126155 provider: string,
src/core/cloud_use.ts added +59
@@ -0,0 +1,59 @@
1 /**
2 * Every vendor call, as a durable `cloud.use` event: which account, for what
3 * purpose, how many bytes left, and a cost estimate. The event outbox is the
4 * record (and what the dataset reads); this module writes and reads it.
5 */
6
7 import type { Database } from "bun:sqlite";
8 import type { EventBus } from "./events.ts";
9
10 export interface CloudUseRow {
11 readonly at: string;
12 readonly vendor: string;
13 readonly account: string;
14 readonly purpose: string;
15 readonly app: string;
16 readonly bytesOut: number;
17 /** USD, an estimate: the free tiers make most of these 0. */
18 readonly costUsd: number;
19 }
20
21 export function recordUse(bus: EventBus, u: Omit<CloudUseRow, "at">): void {
22 bus.append({ kind: "cloud.use", payload: { ...u } });
23 }
24
25 export interface CloudTotal {
26 readonly purpose: string;
outdated

limit = 500 over a 30-day window means the Bring it home numbers and "used for ×N" stop growing at 500 without saying so. Aggregate in SQL for the plan.

27 readonly uses: number;
28 readonly bytesOut: number;
29 readonly costUsd: number;
30 }
31
32 /** What one account did since `since` (an ISO time), counted in SQL by purpose: no row cap. */
33 export function totalsSince(db: Database, since: string, vendor: string, account: string): CloudTotal[] {
34 return db
35 .query<CloudTotal, [string, string, string]>(
36 `SELECT json_extract(payload, '$.purpose') AS purpose, COUNT(*) AS uses,
37 COALESCE(SUM(json_extract(payload, '$.bytesOut')), 0) AS bytesOut,
38 COALESCE(SUM(json_extract(payload, '$.costUsd')), 0) AS costUsd
39 FROM event
40 WHERE kind = 'cloud.use' AND created_at >= ?1
41 AND json_extract(payload, '$.vendor') = ?2 AND json_extract(payload, '$.account') = ?3
42 GROUP BY purpose ORDER BY purpose`,
43 )
44 .all(since, vendor, account);
45 }
46
47 /** Uses at or after `since` (an ISO time), newest first; for listing, so capped. */
48 export function usesSince(db: Database, since: string, limit = 500): CloudUseRow[] {
49 return db
50 .query<{ created_at: string; payload: string }, [string, number]>(
51 "SELECT created_at, payload FROM event WHERE kind = 'cloud.use' AND created_at >= ?1 ORDER BY id DESC LIMIT ?2",
52 )
53 .all(since, limit)
54 .map((r) => ({ at: r.created_at, ...JSON.parse(r.payload) }));
55 }
56
57 /** The UTC day so far. */
58 export const usesToday = (db: Database, now = new Date()): CloudUseRow[] =>
59 usesSince(db, now.toISOString().slice(0, 10));
src/http/api.ts +24
@@ -197,6 +197,8 @@ import {
197197 verifyPassword,
198198 type User,
199199 } from "../core/users.ts";
200 import { allowUse } from "../actions/cloud.ts";
201 import { homeOf } from "../cloud/home.ts";
200202 import { isPinned } from "../core/pins.ts";
201203 import { listWebhooks } from "../core/webhooks.ts";
202204 import { diffCommit } from "../git/diff.ts";
@@ -1246,6 +1248,28 @@ export function apiRoutes(router: Router<Handler>): void {
12461248 const accountAdmin = (ctx: Ctx, scope: "ro" | "admin"): Response | undefined =>
12471249 ctx.auth.user?.isAdmin === true ? requireScope(ctx, scope) : notFound();
12481250
1251 // Bring a Cloud account home, and what it was used for (`cloud/home.ts`):
1252 // the terminal's door to what Settings → Cloud accounts shows.
1253 router.add("GET", "/api/v1/admin/cloud/:provider/:name/home", (ctx) => {
1254 const denied = accountAdmin(ctx, "ro");
1255 if (denied) return denied;
1256 const home = homeOf(ctx.app.db, ctx.params["provider"] ?? "", ctx.params["name"] ?? "");
1257 return home ? json(home) : notFound();
1258 });
1259
1260 // Who may spend a Cloud account and where (`actions/cloud.ts`): the same
1261 // decision as Settings → Cloud accounts → Set use. Repositories are a list
1262 // or one string; a target of "" takes the grant away.
1263 router.add("POST", "/api/v1/admin/cloud/:provider/:name/use", async (ctx) => {
1264 const denied = accountAdmin(ctx, "admin");
1265 if (denied) return denied;
1266 const input = await body(ctx.request);
1267 const repos = Array.isArray(input.repos) ? input.repos.map((r) => str(r)).join(" ") : str(input.repos);
1268 const set = allowUse(ctx.app, ctx.auth.user, ctx.params["provider"] ?? "", ctx.params["name"] ?? "", repos, str(input.target));
1269 if (set.ok) return json({ ok: true });
1270 return set.error === "No such credential." ? notFound() : apiError("invalid", 422, set.error);
1271 });
1272
12491273 // The forge's capacity (`core/capacity.ts`): read and changed live by an
12501274 // admin, never by an agent; anyone else is told the door is not there.
12511275 router.add("GET", "/api/v1/admin/capacity", (ctx) => {
src/http/server.ts +4
@@ -103,8 +103,10 @@ import {
103103 import {
104104 cloudAdd,
105105 cloudAudit,
106 cloudHome,
106107 cloudPage,
107108 cloudRemove,
109 cloudUse,
108110 cloudVerify,
109111 cloudWrite,
110112 } from "../web/pages/cloud.ts";
@@ -663,7 +665,9 @@ export function buildRouter(): Router<Handler> {
663665 router.add("POST", "/settings/cloud", cloudAdd);
664666 router.add("POST", "/settings/cloud/verify", cloudVerify);
665667 router.add("POST", "/settings/cloud/write", cloudWrite);
668 router.add("POST", "/settings/cloud/use", cloudUse);
666669 router.add("POST", "/settings/cloud/audit", cloudAudit);
670 router.add("GET", "/settings/cloud/home", cloudHome);
667671 router.add("POST", "/settings/cloud/remove", cloudRemove);
668672 router.add("GET", "/settings/capacity", capacityPage);
669673 router.add("POST", "/settings/capacity", capacitySet);
src/main.ts +3
@@ -18,6 +18,7 @@ import { runSync } from "./origins/sync.ts";
1818 import { startForgeSsh } from "./tui/ssh.ts";
1919 import { AppsRuntime } from "./apps/runtime.ts";
2020 import { resolveAppDomain } from "./apps/host.ts";
21 import { startCloudPublish } from "./cloud/publish.ts";
2122 import { requeueAbandonedChecks, startChecks } from "./checks/service.ts";
2223 import { startLooks } from "./looks/service.ts";
2324 import { startProbes } from "./contract/probes.ts";
@@ -232,6 +233,8 @@ const checks =
232233 forgeUrl,
233234 concurrency: positive(process.env.FORGE_CHECKS_CONCURRENCY, 1),
234235 });
236 // A repository's cloud.json, made true on each push to its default branch.
237 startCloudPublish(app);
235238 // The look: a picture of every environment that comes up green, taken
236239 // through this forge's own listener.
237240 const looks = appsOn ? startLooks(app, { localUrl: servers.url }) : undefined;
src/web/pages/audit.ts +18 −1
@@ -33,6 +33,7 @@ import {
3333 probeApp,
3434 type ProbeRow,
3535 } from "../../contract/probes.ts";
36 import { usesToday, type CloudUseRow } from "../../core/cloud_use.ts";
3637 import { loadRepo, notFoundPage, signInFirst } from "../chrome.ts";
3738 import { readForm } from "../form.ts";
3839 import { html, when, type Html } from "../html.ts";
@@ -130,10 +131,26 @@ export async function auditPage(ctx: Ctx): Promise<Response> {
130131 ),
131132 )}
132133 ${when(unread.length > 0, () => unreadCard(unread))}
133 ${changesSection(crossings, changes, verdicts)}`}`,
134 ${changesSection(crossings, changes, verdicts)}`}
135 ${when(ctx.auth.user?.isAdmin === true, () => vendorCard(usesToday(ctx.app.db)))}`,
134136 });
135137 }
136138
139 /** Every vendor call today, for a forge admin: account, purpose, bytes out, cost. */
140 function vendorCard(uses: CloudUseRow[]): Html {
141 return card(
142 uses.length === 0
143 ? html`<p class="muted small card-body">No vendor was called today.</p>`
144 : html`<table class="table">
145 <thead><tr><th>When</th><th>Account</th><th>App</th><th>Purpose</th><th>Bytes out</th><th>Cost (est.)</th></tr></thead>
146 <tbody>${uses.map((u) => html`<tr>
147 <td>${time(u.at)}</td><td>${u.vendor} / ${u.account}</td><td>${u.app}</td>
148 <td>${u.purpose}</td><td>${u.bytesOut}</td><td>$${u.costUsd.toFixed(2)}</td></tr>`)}</tbody>
149 </table>`,
150 { head: html`${icon("key")}<h2>Vendor calls today</h2>`, pad: false },
151 );
152 }
153
137154 const count = (n: number, one: string, many: string): string =>
138155 `${n} ${n === 1 ? one : many}`;
139156
src/web/pages/cloud.ts +59 −2
@@ -8,12 +8,15 @@
88
99 import {
1010 addAccount,
11 allowUse,
1112 allowWrite,
1213 auditAccount,
1314 removeAccount,
1415 reverify,
1516 } from "../../actions/cloud.ts";
16 import { LABEL, PROVIDERS, shape } from "../../cloud/providers.ts";
17 import { CLOUD_VENDORS } from "../../apps/manifest.ts";
18 import { homeOf, monthOf, usedFor } from "../../cloud/home.ts";
19 import { LABEL, PROVIDERS, isProvider, shape } from "../../cloud/providers.ts";
1720 import {
1821 listCloudAccounts,
1922 recentCloudReads,
@@ -43,6 +46,8 @@ const hidden = (provider: string, name: string): Html =>
4346 html`<input type="hidden" name="provider" value="${provider}" />
4447 <input type="hidden" name="name" value="${name}" />`;
4548
49 const VENDORS = new Set<string>(CLOUD_VENDORS);
50
4651 function accountsCard(reads: CloudRead[], ctx: Ctx): Html {
4752 const accounts = listCloudAccounts(ctx.app.db);
4853 const rows = accounts.map((a) => {
@@ -52,8 +57,12 @@ function accountsCard(reads: CloudRead[], ctx: Ctx): Html {
5257 title: html`${LABEL[a.provider]} / <span class="mono">${a.name}</span>`,
5358 meta: html`${a.summary}<br />verified ${a.verifiedAt ? time(a.verifiedAt) : "never"} ·
5459 ${last ? html`last used ${time(last.at)} by ${runWords(last.run)}` : "never used"} ·
55 ${a.writeAllowed ? "writes allowed" : "read-only"}`,
60 ${a.writeAllowed ? "writes allowed" : "read-only"} · ${usedFor(monthOf(ctx.app.db, a.provider, a.name))}
61 ${when(VENDORS.has(a.provider), () => html`<br />may publish: ${a.repos.length === 0 ? "no repository" : a.repos.join(", ")} → ${a.target === "" ? "no target" : a.target}`)}`,
5662 trail: html`<div class="row-actions">
63 ${when(VENDORS.has(a.provider), () => html`<form method="get" action="/settings/cloud/home">
64 ${hidden(a.provider, a.name)}${btn("Bring it home", { size: "sm", label: `Bring ${a.name} home` })}
65 </form>`)}
5766 <form method="post" action="/settings/cloud/verify">
5867 ${hidden(a.provider, a.name)}${btn("Verify", { size: "sm", label: `Verify ${a.name}` })}
5968 </form>
@@ -62,6 +71,14 @@ function accountsCard(reads: CloudRead[], ctx: Ctx): Html {
6271 <input type="hidden" name="allowed" value="${a.writeAllowed ? "0" : "1"}" />
6372 ${btn(a.writeAllowed ? "Turn writes off" : "Allow writes", { size: "sm", label: `Write switch for ${a.name}` })}
6473 </form>
74 ${when(VENDORS.has(a.provider), () => html`<form method="post" action="/settings/cloud/use" class="row-actions">
75 ${hidden(a.provider, a.name)}
76 <input class="input" type="text" name="repos" value="${a.repos.join(" ")}" placeholder="public owner/repo, …"
77 aria-label="Repositories that may use ${a.name}" maxlength="3000" />
78 <input class="input mono" type="text" name="target" value="${a.target}" placeholder="account id/namespace id"
79 aria-label="Target ${a.name} may write to" maxlength="65" spellcheck="false" />
80 ${btn("Set use", { size: "sm", label: `Set where ${a.name} may be used` })}
81 </form>`)}
6582 <form method="post" action="/settings/cloud/audit" class="row-actions">
6683 ${hidden(a.provider, a.name)}
6784 <input class="input" type="text" name="repo" placeholder="owner/repo for findings"
@@ -140,6 +157,36 @@ export function cloudPage(ctx: Ctx): Response {
140157 });
141158 }
142159
160 // GET /settings/cloud/home?provider=&name=
161 export function cloudHome(ctx: Ctx): Response {
162 const denied = requireAdmin(ctx);
163 if (denied) return denied;
164 const home = homeOf(
165 ctx.app.db,
166 ctx.url.searchParams.get("provider") ?? "",
167 ctx.url.searchParams.get("name") ?? "",
168 );
169 if (!home) return notFoundPage(ctx);
170 const { plan } = home;
171 return page({
172 ctx,
173 title: `Bring ${plan.account} home`,
174 body: html`<div class="page-head"><h1>Bring ${plan.account} home</h1></div>
175 ${settingsLayout(
176 accountSections("cloud", { admin: true }),
177 card(
178 html`<p class="muted small">${LABEL[plan.vendor]} / <span class="mono">${plan.account}</span>, last 30 days:
179 ${plan.uses} call(s), ${plan.bytesOut} bytes out, about $${plan.spentUsd.toFixed(2)} spent.</p>
180 <ol>${plan.steps.map((s) => html`<li>${s}</li>`)}</ol>
181 <p><strong>Cost of moving:</strong> ${plan.cost}</p>
182 <p><a href="/settings/cloud">Back to cloud accounts</a></p>`,
183 { head: html`${icon("home")}<h2>The plan</h2>` },
184 ),
185 "Account settings",
186 )}`,
187 });
188 }
189
143190 const said = (ctx: Ctx, r: { ok: boolean }, good: string, bad: string | undefined) =>
144191 flashTo(ctx, BACK, r.ok ? { message: good } : { tone: "danger", message: bad ?? "Not found." });
145192
@@ -174,6 +221,16 @@ export async function cloudWrite(ctx: Ctx): Promise<Response> {
174221 return said(ctx, r, on ? "Runs that need writes may now hold it." : "Writes are off.", r.ok ? undefined : r.error);
175222 }
176223
224 // POST /settings/cloud/use
225 export async function cloudUse(ctx: Ctx): Promise<Response> {
226 const denied = requireAdmin(ctx);
227 if (denied) return denied;
228 const form = await readForm(ctx, "admin");
229 if (form instanceof Response) return form;
outdated

This form is the only way to bind an account to repositories and a target. Add the same action as an admin API route and a forge cloud use command, so the terminal can make this decision too, not just read the plan.

230 const r = allowUse(ctx.app, ctx.auth.user, field(form, "provider"), field(form, "name"), field(form, "repos"), field(form, "target"));
231 return said(ctx, r, "Saved.", r.ok ? undefined : r.error);
232 }
233
177234 // POST /settings/cloud/audit
178235 export async function cloudAudit(ctx: Ctx): Promise<Response> {
179236 const denied = requireAdmin(ctx);
test/asks-bulk.test.ts +1 −2
@@ -684,7 +684,6 @@ describe("acting on many asks at once", () => {
684684 expect(res.status).toBe(200);
685685 const text = await res.text();
686686 expect(text).toContain('id="live-on-you"');
687 expect(text).toContain('id="asks-link"');
688687 expect(text).not.toContain("Card one");
689688 expect(getIssueById(app.db, a.id)!.state).toBe("closed");
690689 // The undo link rides on the card, and is the same one after a refresh.
@@ -715,7 +714,7 @@ describe("acting on many asks at once", () => {
715714 for (const pull of [a, b])
716715 expect(assignIssue(app, alice, open, getIssueById(app.db, pull.id)!, alice).ok).toBe(true);
717716 const card = () => onYouCard({ app, auth: { user: alice } } as never, alice)?.text ?? "";
718 expect(card()).not.toContain("muted");
717 expect(card()).not.toContain("repository muted");
719718 const done = await api(aliceRw, "/api/v1/asks/bulk", {
720719 action: "mute",
721720 items: [`issue:${a.id}`, `issue:${b.id}`],
test/cloud-vendors.test.ts added +348
@@ -0,0 +1,348 @@
1 /**
2 * Vendors as capacity: nothing leaves without a cloud.json declaration, only
3 * a public file from the repository is published, every call is audited, and
4 * "bring it home" is a plan — all of it through the running app: a push to
5 * the default branch, the sealed account, the API and the page.
6 */
7
8 import { afterAll, beforeAll, describe, expect, 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 { createApp, type App } from "../src/app.ts";
13 import { addAccount, allowUse, allowWrite, net } from "../src/actions/cloud.ts";
14 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
15 import { NO_CLOUD, parseCloud } from "../src/apps/manifest.ts";
16 import { kvPublish } from "../src/cloud/cloudflare.ts";
17 import type { Gate } from "../src/cloud/gate.ts";
18 import { main as cliMain } from "../src/cli/main.ts";
19 import { getCloudAccount } from "../src/core/cloud_account.ts";
20 import { bringHome, homeOf, monthOf } from "../src/cloud/home.ts";
21 import { publishDeclared, startCloudPublish } from "../src/cloud/publish.ts";
22 import { recordUse, usesToday, type CloudUseRow } from "../src/core/cloud_use.ts";
23 import type { Repo } from "../src/core/repos.ts";
24 import { createToken } from "../src/core/tokens.ts";
25 import { createUser, type User } from "../src/core/users.ts";
26 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
27 import { quietLogs } from "./helpers/globals.ts";
28
29 quietLogs();
30
31 const ACCT = "a".repeat(32);
32 const NS = "b".repeat(32);
33 const TOKEN = "cf-token-Zq4TxLm7Kp2Vb8nWcR5";
34 const use = {
35 vendor: "cloudflare", purpose: "kv-publish", account: "edge", data: "public",
36 what: "feature flags", where: "KV namespace flags", why: "edge reads",
37 target: `${ACCT}/${NS}`, file: "flags.json",
38 };
39 const decl = (uses: unknown[]) => {
40 const r = parseCloud(JSON.stringify({ uses }));
41 if (!r.ok) throw new Error(JSON.stringify(r.error));
42 return r.value;
43 };
44
45 function gate(declared = NO_CLOUD) {
46 const sent: { url: string; init?: RequestInit }[] = [];
47 const rows: Omit<CloudUseRow, "at">[] = [];
48 const g: Gate = {
49 declared, app: "o/app", account: "edge", token: "tok",
50 fetch: async (url, init) => {
51 sent.push({ url, ...(init ? { init } : {}) });
52 return new Response("{}", { status: 200 });
53 },
54 record: (u) => rows.push(u),
55 };
56 return { g, sent, rows };
57 }
58
59 describe("cloud.json", () => {
60 test("absent is nothing; wrong is an error naming the field", () => {
61 expect(parseCloud(undefined)).toEqual({ ok: true, value: NO_CLOUD });
62 const bad = (patch: Record<string, unknown>) => parseCloud(JSON.stringify({ uses: [{ ...use, ...patch }] }));
63 expect(bad({}).ok).toBe(true);
64 expect(bad({ vendor: "aws" }).ok).toBe(false);
65 expect(bad({ vendor: "vercel" }).ok).toBe(false);
66 expect(bad({ purpose: "burst-cell" }).ok).toBe(false);
67 expect(bad({ data: "encrypted" }).ok).toBe(false);
68 expect(bad({ account: "Bad Name" }).ok).toBe(false);
69 expect(bad({ what: "" }).ok).toBe(false);
70 expect(bad({ target: "../x/y" }).ok).toBe(false);
71 expect(bad({ file: "../secrets" }).ok).toBe(false);
72 expect(bad({ file: "/etc/passwd" }).ok).toBe(false);
73 });
74 });
75
76 describe("the gate", () => {
77 test("an app with no cloud.json reaches no vendor", async () => {
78 const { g, sent, rows } = gate();
79 expect((await kvPublish(g, "flags.json", "{}")).ok).toBe(false);
80 expect(sent).toEqual([]);
81 expect(rows).toEqual([]);
82 });
83
84 test("only the declared file, for the declared account, goes out; the call is recorded", async () => {
85 const { g, sent, rows } = gate(decl([use]));
86 expect((await kvPublish(g, "other.json", "{}")).ok).toBe(false);
87 expect((await kvPublish({ ...g, account: "other" }, "flags.json", "{}")).ok).toBe(false);
88 expect(sent).toEqual([]);
89 const done = await kvPublish(g, "flags.json", '{"a":1}');
90 expect(done).toEqual({ ok: true, value: { bytes: 7 } });
91 expect(sent[0]!.url).toBe(`https://api.cloudflare.com/client/v4/accounts/${ACCT}/storage/kv/namespaces/${NS}/values/flags.json`);
92 expect(sent[0]!.init!.method).toBe("PUT");
93 expect(rows).toMatchObject([{ vendor: "cloudflare", purpose: "kv-publish", bytesOut: 7, account: "edge", app: "o/app" }]);
94 });
95
96 test("a value over the cap is refused before any request", async () => {
97 const { g, sent } = gate(decl([use]));
98 expect((await kvPublish(g, "flags.json", "x".repeat(1024 * 1024 + 1))).ok).toBe(false);
99 expect(sent).toEqual([]);
100 });
101 });
102
103 describe("through the app", () => {
104 let dataDir = "";
105 let app: App;
106 let http: ForgeHttp;
107 let stop: () => void;
108 let alice: User;
109 let repo: Repo;
110 const puts: { url: string; auth: string; body: string }[] = [];
111
112 beforeAll(async () => {
113 dataDir = await mkdtemp(join(tmpdir(), "forge-vendors-"));
114 app = createApp({ dataDir, port: 0 });
115 http = forgeHttp(app);
116 stop = startCloudPublish(app);
117 const a = await createUser(app.db, { trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
118 if (!a.ok) throw new Error(a.error);
119 alice = a.value;
120 const r = await createRepo(app, alice, { name: "site", visibility: "public" });
121 if (!r.ok) throw new Error(String(r.error));
122 repo = r.value;
123 net.fetch = async (url, init) => {
124 const headers = (init?.headers ?? {}) as Record<string, string>;
125 if (init?.method === "PUT")
126 puts.push({ url, auth: headers["authorization"] ?? "", body: String(init.body) });
127 const u = new URL(url);
128 if (u.pathname.endsWith("/tokens/verify")) return new Response('{"result":{"status":"active"}}');
129 if (u.pathname.endsWith("/zones")) return new Response('{"result":[]}');
130 return new Response("{}");
131 };
132 });
133 afterAll(async () => {
134 stop();
135 http.close();
136 app.close();
137 await rm(dataDir, { recursive: true, force: true });
138 });
139
140 const push = (files: { path: string; content: string }[]) =>
141 commitToBranch(app, alice, repo, { message: "Declare", files }).then((r) => {
142 if (!r.ok) throw new Error(String(r.error));
143 return r.value.commitOid;
144 });
145
146 test("a declared use with no account, then a read-only account, is refused and calls nothing", async () => {
147 const oid = await push([
148 { path: "flags.json", content: '{"beta":true}' },
149 { path: "cloud.json", content: JSON.stringify({ uses: [use] }) },
150 ]);
151 expect((await publishDeclared(app, repo, oid))[0]).toContain("no Cloud account");
152 expect((await addAccount(app, alice, "cloudflare", "edge", TOKEN)).ok).toBe(true);
153 expect((await publishDeclared(app, repo, oid))[0]).toContain("was not given to alice/site");
154 expect(allowUse(app, alice, "cloudflare", "edge", "alice/site", "x/y").ok).toBe(false);
155 expect(allowUse(app, alice, "cloudflare", "edge", "alice/site", use.target.replace(/.$/, "0")).ok).toBe(true);
156 expect((await publishDeclared(app, repo, oid))[0]).toContain("target is not the one");
157 expect(allowUse(app, alice, "cloudflare", "edge", "alice/site", use.target).ok).toBe(true);
158 expect((await publishDeclared(app, repo, oid))[0]).toContain("read-only");
159 expect(puts).toEqual([]);
160 expect(usesToday(app.db)).toEqual([]);
161 });
162
163 test("with writes allowed the declared file is published with the sealed token, and audited", async () => {
164 expect(allowWrite(app, alice, "cloudflare", "edge", true).ok).toBe(true);
165 const oid = (await Bun.$`git -C ${join(app.reposRoot, "alice", "site.git")} rev-parse HEAD`.quiet().text()).trim();
166 const said = await publishDeclared(app, repo, oid);
167 expect(said[0]).toContain("published 13 bytes");
168 expect(puts).toEqual([{
169 url: `https://api.cloudflare.com/client/v4/accounts/${ACCT}/storage/kv/namespaces/${NS}/values/flags.json`,
170 auth: `Bearer ${TOKEN}`,
171 body: '{"beta":true}',
172 }]);
173 expect(usesToday(app.db)).toMatchObject([{ vendor: "cloudflare", account: "edge", purpose: "kv-publish", app: "alice/site", bytesOut: 13 }]);
174 });
175
176 test("a push to the default branch publishes on its own", async () => {
177 puts.length = 0;
178 await push([{ path: "flags.json", content: '{"beta":false}' }]);
179 for (let i = 0; i < 40 && puts.length === 0; i++) await Bun.sleep(50);
180 expect(puts.map((p) => p.body)).toEqual(['{"beta":false}']);
181 });
182
183 test("two quick pushes: the older one's slow PUT never lands after the newer, and a stale tip is skipped", async () => {
184 puts.length = 0;
185 const real = net.fetch;
186 let held = 0;
187 net.fetch = async (url, init) => {
188 if (init?.method === "PUT" && held++ === 0) await Bun.sleep(300);
189 return real(url, init);
190 };
191 try {
192 await push([{ path: "flags.json", content: '{"v":1}' }]);
193 await push([{ path: "flags.json", content: '{"v":2}' }]);
194 for (let i = 0; i < 60 && puts.length < 1; i++) await Bun.sleep(50);
195 await Bun.sleep(400);
196 expect(puts.length).toBeGreaterThan(0);
197 expect(puts[puts.length - 1]!.body).toBe('{"v":2}');
198 // The first was already past the tip check when the second arrived or was skipped: either way, never reordered.
199 expect(puts.map((p) => p.body)).toEqual(puts.map((p) => p.body).sort());
200 } finally {
201 net.fetch = real;
202 }
203 });
204
205 test("a commit that is no longer the tip is skipped before any request", async () => {
206 const oid = await push([{ path: "flags.json", content: '{"v":3}' }]);
207 await Bun.sleep(500); // the push's own publish lands first
208 puts.length = 0;
209 const said = await publishDeclared(app, repo, oid, async () => false);
210 expect(said[0]).toContain("no longer the tip");
211 expect(puts).toEqual([]);
212 });
213
214 test("use is set through the API and the terminal, and refused to anyone but an admin", async () => {
215 const token = createToken(app.db, alice.id, "u", "admin").token;
216 const post = (name: string, payload: unknown, auth = true) =>
217 http.handle(new Request(`http://localhost/api/v1/admin/cloud/cloudflare/${name}/use`, {
218 method: "POST",
219 headers: { "content-type": "application/json", ...(auth ? { authorization: `Bearer ${token}` } : {}) },
220 body: JSON.stringify(payload),
221 }));
222 expect((await post("edge", { repos: ["alice/site"], target: use.target })).status).toBe(200);
223 expect(getCloudAccount(app.db, "cloudflare", "edge")).toMatchObject({ repos: ["alice/site"], target: use.target });
224 expect((await post("edge", { repos: ["not a repo"], target: use.target })).status).toBe(422);
225 expect((await post("edge", { repos: ["alice/site"], target: "x/y" })).status).toBe(422);
226 expect((await post("nobody", { repos: [], target: "" })).status).toBe(404);
227 expect((await post("edge", { repos: [], target: "" }, false)).status).toBeGreaterThanOrEqual(401);
228 expect(getCloudAccount(app.db, "cloudflare", "edge")!.repos).toEqual(["alice/site"]);
229
230 const realFetch = globalThis.fetch;
231 const prior = { url: process.env["FORGE_URL"], token: process.env["FORGE_TOKEN"] };
232 process.env["FORGE_URL"] = "http://localhost";
233 process.env["FORGE_TOKEN"] = token;
234 globalThis.fetch = ((input: any, init?: any) => http.handle(new Request(String(input), init))) as typeof fetch;
235 try {
236 expect(await cliMain(["cloud", "use", "cloudflare", "edge", "--repos", "alice/site,alice/other", "--target", use.target])).toBe(0);
237 expect(getCloudAccount(app.db, "cloudflare", "edge")!.repos).toEqual(["alice/site", "alice/other"]);
238 expect(await cliMain(["cloud", "use", "cloudflare", "edge", "--repos", "alice/site"])).not.toBe(0);
239 expect(await cliMain(["cloud", "use", "cloudflare", "edge", "--repos", "alice/site", "--target", use.target])).toBe(0);
240 } finally {
241 globalThis.fetch = realFetch;
242 for (const [k, v] of [["FORGE_URL", prior.url], ["FORGE_TOKEN", prior.token]] as const)
243 v === undefined ? delete process.env[k] : (process.env[k] = v);
244 }
245 });
246
247 test("the plan counts past 500 uses", () => {
248 const bus = app.bus;
249 const before = homeOf(app.db, "cloudflare", "edge")!.plan.uses;
250 for (let i = 0; i < 520; i++)
251 recordUse(bus, { vendor: "cloudflare", account: "edge", purpose: "kv-publish", app: "alice/site", bytesOut: 2, costUsd: 0 });
252 const after = homeOf(app.db, "cloudflare", "edge")!;
253 expect(after.plan.uses).toBe(before + 520);
254 expect(after.used).toContain(`kv-publish ×${before + 520}`);
255 });
256
257 test("a bad cloud.json publishes nothing and says why", async () => {
258 puts.length = 0;
259 const oid = await push([{ path: "cloud.json", content: JSON.stringify({ uses: [{ ...use, data: "encrypted" }] }) }]);
260 expect((await publishDeclared(app, repo, oid))[0]).toContain("cloud.json refused");
261 expect(puts).toEqual([]);
262 });
263
264 test("the plan counts every use in the month, not the newest 500", () => {
265 const before = homeOf(app.db, "cloudflare", "edge")!.plan.uses;
266 for (let i = 0; i < 600; i++)
267 recordUse(app.bus, { vendor: "cloudflare", account: "edge", purpose: "kv-publish", app: "o/app", bytesOut: 2, costUsd: 0 });
268 expect(homeOf(app.db, "cloudflare", "edge")!.plan.uses).toBe(before + 600);
269 });
270
271 test("bring it home is for the account asked about, in the page and in the API", async () => {
272 const mine = homeOf(app.db, "cloudflare", "edge")!;
273 expect(mine.plan).toMatchObject({ account: "edge", vendor: "cloudflare" });
274 expect(mine.plan.uses).toBeGreaterThanOrEqual(1);
275 expect(mine.used).toContain("kv-publish");
276 expect(homeOf(app.db, "cloudflare", "nobody")).toBeUndefined();
277 expect(homeOf(app.db, "github", "edge")).toBeUndefined();
278 expect(bringHome("cloudflare", "elsewhere", monthOf(app.db, "cloudflare", "elsewhere")).uses).toBe(0);
279
280 const token = createToken(app.db, alice.id, "t", "admin").token;
281 const api = await http.handle(new Request(`http://localhost/api/v1/admin/cloud/cloudflare/edge/home`, { headers: { authorization: `Bearer ${token}` } }));
282 expect(api.status).toBe(200);
283 expect(((await api.json()) as any).plan.steps.length).toBeGreaterThan(2);
284 const none = await http.handle(new Request("http://localhost/api/v1/admin/cloud/cloudflare/edge/home"));
285 expect(none.status).not.toBe(200);
286 const gone = await http.handle(new Request(`http://localhost/api/v1/admin/cloud/cloudflare/nobody/home`, { headers: { authorization: `Bearer ${token}` } }));
287 expect(gone.status).toBe(404);
288 });
289
290 const decl = JSON.stringify({ uses: [use] });
291
292 test("a non-admin's repository naming the admin's account sends nothing", async () => {
293 const b = await createUser(app.db, { trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
294 if (!b.ok) throw new Error(b.error);
295 const r = await createRepo(app, b.value, { name: "mine", visibility: "public" });
296 if (!r.ok) throw new Error(String(r.error));
297 const c = await commitToBranch(app, b.value, r.value, { message: "x", files: [{ path: "flags.json", content: "{}" }, { path: "cloud.json", content: decl }] });
298 if (!c.ok) throw new Error(String(c.error));
299 puts.length = 0;
300 const said = await publishDeclared(app, r.value, c.value.commitOid);
301 expect(said[0]).toContain("was not given to bob/mine");
302 for (let i = 0; i < 10; i++) await Bun.sleep(20);
303 expect(puts).toEqual([]);
304 });
305
306 test("a private repository sends nothing, even when listed", async () => {
307 const r = await createRepo(app, alice, { name: "secret", visibility: "private" });
308 if (!r.ok) throw new Error(String(r.error));
309 expect(allowUse(app, alice, "cloudflare", "edge", "alice/site alice/secret", use.target).ok).toBe(true);
310 const c = await commitToBranch(app, alice, r.value, { message: "x", files: [{ path: "flags.json", content: "{}" }, { path: "cloud.json", content: decl }] });
311 if (!c.ok) throw new Error(String(c.error));
312 puts.length = 0;
313 expect((await publishDeclared(app, r.value, c.value.commitOid))[0]).toContain("not a public repository");
314 expect(puts).toEqual([]);
315 expect(allowUse(app, undefined, "cloudflare", "edge", "", "").ok).toBe(false);
316 });
317
318 test("the cloud pages: admin sees the plan and the vendor card, others get 404", async () => {
319 const login = async (username: string): Promise<string> => {
320 const res = await http.handle(new Request("http://localhost/signin", {
321 method: "POST",
322 redirect: "manual",
323 headers: { "content-type": "application/x-www-form-urlencoded", origin: "http://localhost" },
324 body: new URLSearchParams({ username, password: "a-good-passphrase" }),
325 }));
326 return (res.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
327 };
328 const get = (path: string, cookie?: string) =>
329 http.handle(new Request(`http://localhost${path}`, { headers: cookie ? { cookie } : {} }));
330 const admin = await login("alice");
331 const other = await login("bob");
332 const home = await get("/settings/cloud/home?provider=cloudflare&name=edge", admin);
333 expect(home.status).toBe(200);
334 const text = await home.text();
335 expect(text).toContain("Bring edge home");
336 expect(text).toContain("Remove the Cloudflare account");
337 expect((await get("/settings/cloud/home?provider=cloudflare&name=nobody", admin)).status).toBe(404);
338 expect((await get("/settings/cloud/home?provider=cloudflare&name=edge", other)).status).toBe(404);
339 expect((await get("/settings/cloud/home?provider=cloudflare&name=edge")).status).not.toBe(200);
340
341 const list = await (await get("/settings/cloud", admin)).text();
342 expect(list).toContain("kv-publish");
343 expect(list).toContain("may publish: alice/site, alice/secret");
344 const audit = await get("/audit", admin);
345 expect(await audit.text()).toContain("Vendor calls today");
346 expect(await (await get("/audit", other)).text()).not.toContain("Vendor calls today");
347 });
348 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs