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 #1358
scout/forge:scout/1146-clouds-as-capacity-never-as-dependency-c → main 2 commits fork 4 threads · 4 unresolved
16 files
changed +791
−4
docs/CLOUD.md added +64
| @@ -0,0 +1,64 @@ | ||
| 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 | | Vercel, GitHub | attach and audit only | `GET /v2/user`, `GET /user` | | |
| 14 | ||
| 15 | The token is sealed like every cloud credential; rotate it by pasting a new one | |
| 16 | under the same name. Writes stay off until an admin allows them for the account. | |
| 17 | Each account row says what it is used for in the last 30 days, and has | |
| 18 | **Bring it home**. | |
| 19 | ||
| 20 | Only Cloudflare has a use today. Vercel burst cells and GitHub gate shards are | |
| 21 | not built: a shard runs inside one check command, so placing one elsewhere | |
| 22 | needs the check runner to change first, and Vercel's sandbox API has not been | |
| 23 | checked against a live account. They get a `cloud.json` purpose when they have | |
| 24 | a caller. | |
| 25 | ||
| 26 | ## Declare (`cloud.json`, nothing by default) | |
| 27 | ||
| 28 | json | |
| 29 | { "uses": [ | |
| 30 | { "vendor": "cloudflare", "purpose": "kv-publish", "account": "edge", | |
| 31 | "data": "public", "target": "<32-hex account id>/<32-hex namespace id>", | |
| 32 | "file": "flags.json", | |
| 33 | "what": "feature flags", "where": "KV namespace flags", "why": "edge reads" } | |
| 34 | ] } | |
| 35 | ||
| 36 | ||
| 37 | `account` names the Cloud account whose token is used; `file` is a path in the | |
| 38 | same repository, published as is under the key with `/` written `:`; `data` | |
| 39 | can only be `public`. A malformed file publishes nothing. | |
| 40 | ||
| 41 | ## What runs | |
| 42 | ||
| 43 | `src/cloud/publish.ts` watches pushes. On a push to the default branch it reads | |
| 44 | `cloud.json` at the new commit and, for each use, requires the account to exist | |
| 45 | with writes allowed, opens its token through `resolveSecrets` (a `secret.read` | |
| 46 | event naming `cloud-publish:<owner>/<repo>`), and calls | |
| 47 | `src/cloud/cloudflare.ts` through the gate (`src/cloud/gate.ts`). The gate | |
| 48 | refuses any file or account the commit did not declare, before any request. | |
| 49 | The outcome of each use is one log line. | |
| 50 | ||
| 51 | ## Audit | |
| 52 | ||
| 53 | Each call appends a `cloud.use` event (account, purpose, app, bytes out, cost | |
| 54 | estimate). `/audit` lists today's, for admins; the account row says what it was | |
| 55 | used for. Any dataset built from the event outbox carries them. | |
| 56 | ||
| 57 | ## Bring it home | |
| 58 | ||
| 59 | Page: `/settings/cloud/home?provider=cloudflare&name=edge`. Terminal: | |
| 60 | `forge cloud home cloudflare edge` (API: `GET /api/v1/admin/cloud/:provider/:name/home`, | |
| 61 | admin token). Both answer from `src/cloud/home.ts` for that one account: what it | |
| 62 | did in 30 days, the steps, and the cost of moving. In short: remove the use | |
| 63 | from `cloud.json` and push, serve the same file from the app, remove the | |
| 64 | account, revoke the token at the vendor. |
src/apps/manifest.ts +88
| @@ -422,3 +422,91 @@ function readPackage( | ||
| 422 | 422 | |
| 423 | 423 | const hasKeys = (value: unknown): boolean => |
| 424 | 424 | isObject(value) && Object.keys(value).length > 0; |
| 425 | ||
| 426 | // ---- cloud.json: what an app may use from a vendor ---- | |
| 427 | ||
| 428 | export const CLOUD_VENDORS = ["cloudflare"] as const; | |
| 429 | export type CloudVendor = (typeof CLOUD_VENDORS)[number]; | |
| 430 | ||
| 431 | /** The only purposes there are, per vendor. A use is vendor + purpose. */ | |
| 432 | export const CLOUD_PURPOSES = { | |
| 433 | cloudflare: ["kv-publish"], | |
| 434 | } as const satisfies Record<CloudVendor, readonly string[]>; | |
| 435 | ||
| 436 | export interface CloudUse { | |
| 437 | readonly vendor: CloudVendor; | |
| 438 | readonly purpose: string; | |
| 439 | /** The Cloud account (Settings → Cloud accounts) whose token is used. */ | |
| 440 | readonly account: string; | |
| 441 | /** What leaves the owner's hardware. */ | |
| 442 | readonly what: string; | |
| 443 | /** Where it lands, in words. */ | |
| 444 | readonly where: string; | |
| 445 | /** Why this is worth it. */ | |
| 446 | readonly why: string; | |
| 447 | /** KV only: `<32-hex account id>/<32-hex namespace id>`. */ | |
| 448 | readonly target: string; | |
| 449 | /** KV only: the file in this repository, published as is. Public already. */ | |
| 450 | readonly file: string; | |
| 451 | } | |
| 452 | ||
| 453 | export interface CloudManifest { | |
| 454 | readonly uses: readonly CloudUse[]; | |
| 455 | } | |
| 456 | ||
| 457 | const CLOUD_USES_MAX = 16; | |
| 458 | const CLOUD_TEXT_MAX = 200; | |
| 459 | const CLOUD_ACCOUNT = /^[a-z][a-z0-9_]{0,31}$/; | |
| 460 | const CLOUD_TARGET = /^[0-9a-f]{32}\/[0-9a-f]{32}$/; | |
| 461 | const CLOUD_FILE = /^[A-Za-z0-9._-]+(\/[A-Za-z0-9._-]+){0,5}$/; | |
| 462 | export const NO_CLOUD: CloudManifest = { uses: [] }; | |
| 463 | ||
| 464 | /** | |
| 465 | * `cloud.json`, `undefined` when absent. Absent means nothing: an app with | |
| 466 | * no `cloud.json` reaches no vendor. Fails closed like `forge.json`. | |
| 467 | */ | |
| 468 | export function parseCloud( | |
| 469 | cloudJson: string | undefined, | |
| 470 | ): Result<CloudManifest, ManifestError> { | |
| 471 | if (cloudJson === undefined) return ok(NO_CLOUD); | |
| 472 | const parsed = parseJson(cloudJson, "cloud.json"); | |
| 473 | if (!parsed.ok) return parsed; | |
| 474 | const list = parsed.value["uses"]; | |
| 475 | if (list === undefined) return ok(NO_CLOUD); | |
| 476 | if (!Array.isArray(list)) | |
| 477 | return invalid("cloud.json: uses must be an array"); | |
| 478 | if (list.length > CLOUD_USES_MAX) | |
| 479 | return invalid(`cloud.json: at most ${CLOUD_USES_MAX} uses`); | |
| 480 | const uses: CloudUse[] = []; | |
| 481 | for (const [i, u] of list.entries()) { | |
| 482 | const at = `cloud.json: uses[${i}]`; | |
| 483 | if (!isObject(u)) return invalid(`${at} must be an object`); | |
| 484 | const vendor = u["vendor"]; | |
| 485 | if (typeof vendor !== "string" || !(CLOUD_VENDORS as readonly string[]).includes(vendor)) | |
| 486 | return invalid(`${at}.vendor must be one of ${CLOUD_VENDORS.join(", ")}`); | |
| 487 | const v = vendor as CloudVendor; | |
| 488 | const purpose = u["purpose"]; | |
| 489 | if (typeof purpose !== "string" || !(CLOUD_PURPOSES[v] as readonly string[]).includes(purpose)) | |
| 490 | return invalid(`${at}.purpose for ${v} must be one of ${CLOUD_PURPOSES[v].join(", ")}`); | |
| 491 | const account = u["account"]; | |
| 492 | if (typeof account !== "string" || !CLOUD_ACCOUNT.test(account)) | |
| 493 | return invalid(`${at}.account is the name of a Cloud account: lowercase letters, digits, underscores`); | |
| 494 | const text: Record<"what" | "where" | "why", string> = { what: "", where: "", why: "" }; | |
| 495 | for (const k of ["what", "where", "why"] as const) { | |
| 496 | const t = u[k]; | |
| 497 | if (typeof t !== "string" || t.trim() === "" || t.length > CLOUD_TEXT_MAX || /[\x00-\x1f]/.test(t)) | |
| 498 | return invalid(`${at}.${k} is required: one line, up to ${CLOUD_TEXT_MAX} characters`); | |
| 499 | text[k] = t.trim(); | |
| 500 | } | |
| 501 | if (u["data"] !== "public") | |
| 502 | return invalid(`${at}.data must be "public": only what is public already leaves through a vendor`); | |
| 503 | const target = u["target"]; | |
| 504 | if (typeof target !== "string" || !CLOUD_TARGET.test(target)) | |
| 505 | return invalid(`${at}.target is <account id>/<namespace id>, each 32 hex characters`); | |
| 506 | const file = u["file"]; | |
| 507 | if (typeof file !== "string" || !CLOUD_FILE.test(file) || file.split("/").includes("..")) | |
| 508 | return invalid(`${at}.file is a relative path in this repository`); | |
| 509 | uses.push({ vendor: v, purpose, account, ...text, target, file }); | |
| 510 | } | |
| 511 | return ok({ uses }); | |
| 512 | } |
src/cli/api.ts +20
| @@ -36,6 +36,19 @@ export interface Whoami { | ||
| 36 | 36 | readonly displayName: string; |
| 37 | 37 | } |
| 38 | 38 | |
| 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 | ||
| 39 | 52 | export class ForgeApi { |
| 40 | 53 | /** True once `pins()` has had to fall back, so the CLI can say it once. */ |
| 41 | 54 | pinsUnavailable = false; |
| @@ -96,6 +109,13 @@ export class ForgeApi { | ||
| 96 | 109 | return ok(parsed as T); |
| 97 | 110 | } |
| 98 | 111 | |
| 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 | ||
| 99 | 119 | async whoami(): Promise<ApiResult<Whoami>> { |
| 100 | 120 | const out = await this.call<{ username?: string; displayName?: string }>( |
| 101 | 121 | "/api/v1/user", |
src/cli/main.ts +24
| @@ -77,6 +77,8 @@ export async function main(argv: readonly string[]): Promise<number> { | ||
| 77 | 77 | case "help": |
| 78 | 78 | usage(out); |
| 79 | 79 | return EXIT.ok; |
| 80 | case "cloud": | |
| 81 | return cloud(out, args); | |
| 80 | 82 | case "login": |
| 81 | 83 | return login(out, args); |
| 82 | 84 | case "logout": |
| @@ -118,6 +120,7 @@ function usage(out: Out): void { | ||
| 118 | 120 | ); |
| 119 | 121 | out.line(b(" forge status") + " [--root DIR] [--json]"); |
| 120 | 122 | out.line(b(" forge ls") + " [--json]"); |
| 123 | out.line(b(" forge cloud home <provider> <name>") + " the plan to bring a Cloud account home (admin)"); | |
| 121 | 124 | out.line(b(" forge pin <owner/name>")); |
| 122 | 125 | out.line(b(" forge unpin <owner/name>")); |
| 123 | 126 | out.line(b(" forge open <owner/name>") + " [--web]"); |
| @@ -189,6 +192,27 @@ async function whoami(out: Out): Promise<number> { | ||
| 189 | 192 | return EXIT.ok; |
| 190 | 193 | } |
| 191 | 194 | |
| 195 | async function cloud(out: Out, args: Args): Promise<number> { | |
| 196 | const [sub, provider, name] = args.positional; | |
| 197 | if (sub !== "home" || provider === undefined || name === undefined) { | |
| 198 | out.err("forge cloud: forge cloud home <provider> <name>"); | |
| 199 | return EXIT.usage; | |
| 200 | } | |
| 201 | const loaded = await requireConfig(out); | |
| 202 | if (typeof loaded === "number") return loaded; | |
| 203 | const got = await new ForgeApi(loaded.url, loaded.token).cloudHome(provider, name); | |
| 204 | if (!got.ok) { | |
| 205 | out.err(`forge cloud: ${got.error.status === 404 ? "no such Cloud account (or you are not an admin)" : got.error.message}`); | |
| 206 | return EXIT.failed; | |
| 207 | } | |
| 208 | const { plan, used } = got.value; | |
| 209 | out.line(`${plan.vendor} / ${plan.account}: ${used}`); | |
| 210 | out.line(`last 30 days: ${plan.uses} call(s), ${plan.bytesOut} bytes out, about $${plan.spentUsd.toFixed(2)}`); | |
| 211 | plan.steps.forEach((step, i) => out.line(` ${i + 1}. ${step}`)); | |
| 212 | out.line(`cost of moving: ${plan.cost}`); | |
| 213 | return EXIT.ok; | |
| 214 | } | |
| 215 | ||
| 192 | 216 | // ── sync and status ────────────────────────────────────────────────────── |
| 193 | 217 | |
| 194 | 218 | 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 +71
| @@ -0,0 +1,71 @@ | ||
| 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 { usesSince, type CloudUseRow } 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 uses the audit holds for it. */ | |
| 36 | export function bringHome(vendor: CloudVendor, account: string, uses: readonly CloudUseRow[]): HomePlan { | |
| 37 | const mine = uses.filter((u) => u.vendor === vendor && u.account === account); | |
| 38 | return { | |
| 39 | vendor, | |
| 40 | account, | |
| 41 | uses: mine.length, | |
| 42 | bytesOut: mine.reduce((n, u) => n + u.bytesOut, 0), | |
| 43 | spentUsd: mine.reduce((n, u) => n + u.costUsd, 0), | |
| 44 | ...STEPS[vendor], | |
outdated
"Raise FORGE_CHECK_SHARD_TOTAL's runner count" is not a real knob: a shard total is not a runner count. Name the actual setting (e.g. Settings → Capacity / check.limits), as the Vercel plan does. |
||
| 45 | }; | |
| 46 | } | |
| 47 | ||
| 48 | const DAY = 86_400_000; | |
| 49 | ||
| 50 | /** What an account did in the last 30 days: "used for kv-publish ×3", or "not used in 30 days". */ | |
| 51 | export function usedFor(uses: readonly CloudUseRow[], vendor: string, account: string): string { | |
| 52 | const by = new Map<string, number>(); | |
| 53 | for (const u of uses) | |
| 54 | if (u.vendor === vendor && u.account === account) by.set(u.purpose, (by.get(u.purpose) ?? 0) + 1); | |
| 55 | return by.size === 0 | |
| 56 | ? "not used in 30 days" | |
| 57 | : "used for " + [...by].map(([p, n]) => `${p} ×${n}`).join(", "); | |
| 58 | } | |
| 59 | ||
| 60 | /** Both doors' answer for one account: undefined when it is not an account with a plan. */ | |
| 61 | export function homeOf( | |
| 62 | db: Database, | |
| 63 | provider: string, | |
| 64 | account: string, | |
| 65 | now = Date.now(), | |
| 66 | ): { plan: HomePlan; used: string } | undefined { | |
| 67 | if (!(CLOUD_VENDORS as readonly string[]).includes(provider)) return undefined; | |
| 68 | if (!getCloudAccount(db, provider, account)) return undefined; | |
| 69 | const uses = usesSince(db, new Date(now - 30 * DAY).toISOString()); | |
| 70 | return { plan: bringHome(provider as CloudVendor, account, uses), used: usedFor(uses, provider, account) }; | |
| 71 | } |
src/cloud/providers.ts +34 −1
| @@ -4,6 +4,8 @@ | ||
| 4 | 4 | * identity lookup — nothing creates, changes or deletes. The complete list: |
| 5 | 5 | * |
| 6 | 6 | * cloudflare GET api.cloudflare.com/client/v4/user/tokens/verify, /zones |
| 7 | * vercel GET api.vercel.com/v2/user | |
| 8 | * github GET api.github.com/user | |
| 7 | 9 | * digitalocean GET api.digitalocean.com/v2/account, /projects, /droplets, |
| 8 | 10 | * /volumes, /reserved_ips |
| 9 | 11 | * aws POST sts.amazonaws.com Action=GetCallerIdentity (a read), |
| @@ -26,6 +28,8 @@ import { err, ok, type Result } from "../kernel/result.ts"; | ||
| 26 | 28 | |
| 27 | 29 | export const PROVIDERS = [ |
| 28 | 30 | "cloudflare", |
| 31 | "vercel", | |
| 32 | "github", | |
| 29 | 33 | "digitalocean", |
| 30 | 34 | "aws", |
| 31 | 35 | "azure", |
| @@ -40,6 +44,8 @@ export function isProvider(v: string): v is Provider { | ||
| 40 | 44 | |
| 41 | 45 | export const LABEL: Record<Provider, string> = { |
| 42 | 46 | cloudflare: "Cloudflare", |
| 47 | vercel: "Vercel", | |
| 48 | github: "GitHub", | |
| 43 | 49 | digitalocean: "DigitalOcean", |
| 44 | 50 | aws: "AWS", |
| 45 | 51 | azure: "Azure", |
| @@ -49,7 +55,9 @@ export const LABEL: Record<Provider, string> = { | ||
| 49 | 55 | |
| 50 | 56 | /** What to paste, per provider, in a sentence. */ |
| 51 | 57 | export const shape: Record<Provider, string> = { |
| 52 | cloudflare: "an API token (read-only scope is enough)", | |
| 58 | cloudflare: "an API token scoped to Workers KV Storage: Edit on one account (read-only if it only audits)", | |
| 59 | vercel: "an access token scoped to one team (Vercel tokens have no narrower scope)", | |
| 60 | github: "a fine-grained token on one repository: Actions read/write, nothing else", | |
| 53 | 61 | digitalocean: "a personal access token (read scope is enough)", |
| 54 | 62 | aws: "ACCESS_KEY_ID:SECRET_ACCESS_KEY of a read-only IAM user", |
| 55 | 63 | azure: "TENANT_ID:CLIENT_ID:CLIENT_SECRET of a Reader service principal", |
| @@ -209,6 +217,27 @@ export async function verify( | ||
| 209 | 217 | canWrite: null, |
| 210 | 218 | }); |
| 211 | 219 | } |
| 220 | case "vercel": { | |
| 221 | const u = await json(f, "https://api.vercel.com/v2/user", { headers: bearer(value) }); | |
| 222 | return ok({ | |
| 223 | summary: `Vercel token belongs to ${String(u.user?.username ?? "?")}; Vercel does not expose a token's scope, so it is bound to one team.`, | |
| 224 | canWrite: null, | |
| 225 | }); | |
| 226 | } | |
| 227 | case "github": { | |
| 228 | const res = await f("https://api.github.com/user", { | |
| 229 | headers: { ...bearer(value), accept: "application/vnd.github+json", "user-agent": "forge" }, | |
| 230 | signal: AbortSignal.timeout(10_000), | |
| 231 | }); | |
| 232 | if (!res.ok) throw new Error(`api.github.com answered ${res.status}`); | |
| 233 | const u: any = await res.json(); | |
| 234 | const scopes = res.headers.get("x-oauth-scopes"); | |
| 235 | const broad = scopes !== null && /(^|,\s*)(repo|admin:[a-z_]+|delete_repo)(,|$)/.test(scopes); | |
| 236 | return ok({ | |
| 237 | summary: `GitHub token belongs to ${String(u.login ?? "?")}${scopes === null ? "; a fine-grained token, whose repositories GitHub does not list here" : scopes === "" ? "; no classic scopes" : `; classic scopes: ${scopes}${broad ? " — broader than the forge needs" : ""}`}.`, | |
| 238 | canWrite: scopes === null ? null : broad, | |
| 239 | }); | |
| 240 | } | |
| 212 | 241 | case "digitalocean": { |
| 213 | 242 | const h = bearer(value); |
| 214 | 243 | const a = await json(f, "https://api.digitalocean.com/v2/account", { headers: h }); |
| @@ -347,6 +376,10 @@ export async function audit( | ||
| 347 | 376 | 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); |
| 348 | 377 | break; |
| 349 | 378 | } |
| 379 | case "vercel": | |
| 380 | case "github": | |
| 381 | // Used for capacity, not audited for waste. | |
| 382 | break; | |
| 350 | 383 | case "backblaze": |
| 351 | 384 | // Bucket size needs a file listing per bucket; not attempted. |
| 352 | 385 | break; |
src/cloud/publish.ts added +85
| @@ -0,0 +1,85 @@ | ||
| 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 token is opened through `resolveSecrets`, | |
| 6 | * so it is a `secret.read`, and each call is a `cloud.use` event. A | |
| 7 | * repository with no `cloud.json` costs one missing-file read and nothing else. | |
| 8 | */ | |
| 9 | ||
| 10 | import type { App } from "../app.ts"; | |
| 11 | import { net } from "../actions/cloud.ts"; | |
| 12 | import { readFileAt } from "../apps/checkout.ts"; | |
| 13 | import { parseCloud } from "../apps/manifest.ts"; | |
| 14 | import { getCloudAccount, secretNameOf } from "../core/cloud_account.ts"; | |
| 15 | import { recordUse } from "../core/cloud_use.ts"; | |
| 16 | import { getRepoById, type Repo } from "../core/repos.ts"; | |
| 17 | import { resolveSecrets } from "../core/secret_store.ts"; | |
| 18 | import { repoDir } from "../git/repos.ts"; | |
| 19 | import { createLog } from "../kernel/log.ts"; | |
| 20 | import { kvPublish } from "./cloudflare.ts"; | |
| 21 | import type { Gate } from "./gate.ts"; | |
| 22 | ||
| 23 | const log = createLog("cloud"); | |
| 24 | ||
| 25 | /** What happened to each declared use, one line each: for the log and the tests. */ | |
| 26 | export async function publishDeclared(app: App, repo: Repo, commitOid: string): Promise<string[]> { | |
| 27 | const bare = repoDir(app.reposRoot, repo.ownerName, repo.name); | |
| 28 | const declared = parseCloud(await readFileAt(bare, commitOid, "cloud.json")); | |
| 29 | const slug = `${repo.ownerName}/${repo.name}`; | |
| 30 | if (!declared.ok) return [`${slug}: cloud.json refused: ${declared.error.kind === "invalid" ? declared.error.message : "not valid"}`]; | |
| 31 | const said: string[] = []; | |
| 32 | for (const use of declared.value.uses) { | |
| 33 | const label = `${slug}: ${use.vendor} ${use.purpose} ${use.file}`; | |
| 34 | const account = getCloudAccount(app.db, use.vendor, use.account); | |
| 35 | if (!account) { | |
| 36 | said.push(`${label}: no Cloud account ${use.vendor}/${use.account}; refused`); | |
| 37 | continue; | |
| 38 | } | |
| 39 | if (!account.writeAllowed) { | |
| 40 | said.push(`${label}: ${use.vendor}/${use.account} is read-only; refused`); | |
| 41 | continue; | |
| 42 | } | |
| 43 | const secret = secretNameOf(account.provider, account.name); | |
| 44 | const token = resolveSecrets(app.db, app.config.dataDir, app.bus, [secret], { | |
| 45 | run: `cloud-publish:${slug}`, | |
| 46 | })[secret]; | |
| 47 | if (token === undefined) { | |
| 48 | said.push(`${label}: the account's token will not open; refused`); | |
| 49 | continue; | |
| 50 | } | |
| 51 | const value = await readFileAt(bare, commitOid, use.file); | |
| 52 | if (value === undefined) { | |
| 53 | said.push(`${label}: no such file at ${commitOid.slice(0, 7)}; refused`); | |
| 54 | continue; | |
| 55 | } | |
| 56 | const gate: Gate = { | |
| 57 | declared: declared.value, | |
| 58 | app: slug, | |
| 59 | account: use.account, | |
| 60 | token, | |
| 61 | fetch: net.fetch, | |
| 62 | record: (u) => recordUse(app.bus, u), | |
| 63 | }; | |
| 64 | const done = await kvPublish(gate, use.file, value); | |
| 65 | said.push(`${label}: ${done.ok ? `published ${done.value.bytes} bytes` : done.error}`); | |
| 66 | } | |
| 67 | return said; | |
| 68 | } | |
| 69 | ||
| 70 | /** Watch pushes; publish what the default branch's new tip declares. */ | |
| 71 | export function startCloudPublish(app: App): () => void { | |
| 72 | return app.bus.subscribe((event) => { | |
| 73 | if (event.kind !== "push" || event.repoId === null) return; | |
| 74 | const repo = getRepoById(app.db, event.repoId); | |
| 75 | const updates = event.payload["updates"]; | |
| 76 | if (!repo || !Array.isArray(updates)) return; | |
| 77 | for (const u of updates as { ref?: unknown; newOid?: unknown }[]) { | |
| 78 | if (u.ref !== `refs/heads/${repo.defaultBranch}` || typeof u.newOid !== "string" || /^0+$/.test(u.newOid)) continue; | |
| 79 | publishDeclared(app, repo, u.newOid).then( | |
| 80 | (lines) => lines.forEach((l) => log.info(l)), | |
| 81 | (error) => log.error("cloud publish failed", { error: String(error) }), | |
| 82 | ); | |
| 83 | } | |
| 84 | }); | |
| 85 | } |
src/core/cloud_use.ts added +37
| @@ -0,0 +1,37 @@ | ||
| 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 | /** Uses at or after `since` (an ISO time), newest first. */ | |
| 26 | export function usesSince(db: Database, since: string, limit = 500): CloudUseRow[] { | |
| 27 | return db | |
| 28 | .query<{ created_at: string; payload: string }, [string, number]>( | |
| 29 | "SELECT created_at, payload FROM event WHERE kind = 'cloud.use' AND created_at >= ?1 ORDER BY id DESC LIMIT ?2", | |
| 30 | ) | |
| 31 | .all(since, limit) | |
| 32 | .map((r) => ({ at: r.created_at, ...JSON.parse(r.payload) })); | |
| 33 | } | |
| 34 | ||
| 35 | /** The UTC day so far. */ | |
| 36 | export const usesToday = (db: Database, now = new Date()): CloudUseRow[] => | |
| 37 | usesSince(db, now.toISOString().slice(0, 10)); |
src/http/api.ts +10
| @@ -188,6 +188,7 @@ import { | ||
| 188 | 188 | verifyPassword, |
| 189 | 189 | type User, |
| 190 | 190 | } from "../core/users.ts"; |
| 191 | import { homeOf } from "../cloud/home.ts"; | |
| 191 | 192 | import { isPinned } from "../core/pins.ts"; |
| 192 | 193 | import { listWebhooks } from "../core/webhooks.ts"; |
| 193 | 194 | import { diffCommit } from "../git/diff.ts"; |
| @@ -1233,6 +1234,15 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 1233 | 1234 | const accountAdmin = (ctx: Ctx, scope: "ro" | "admin"): Response | undefined => |
| 1234 | 1235 | ctx.auth.user?.isAdmin === true ? requireScope(ctx, scope) : notFound(); |
| 1235 | 1236 | |
| 1237 | // Bring a Cloud account home, and what it was used for (`cloud/home.ts`): | |
| 1238 | // the terminal's door to what Settings → Cloud accounts shows. | |
| 1239 | router.add("GET", "/api/v1/admin/cloud/:provider/:name/home", (ctx) => { | |
| 1240 | const denied = accountAdmin(ctx, "ro"); | |
| 1241 | if (denied) return denied; | |
| 1242 | const home = homeOf(ctx.app.db, ctx.params["provider"] ?? "", ctx.params["name"] ?? ""); | |
| 1243 | return home ? json(home) : notFound(); | |
| 1244 | }); | |
| 1245 | ||
| 1236 | 1246 | // The forge's capacity (`core/capacity.ts`): read and changed live by an |
| 1237 | 1247 | // admin, never by an agent; anyone else is told the door is not there. |
| 1238 | 1248 | router.add("GET", "/api/v1/admin/capacity", (ctx) => { |
src/http/server.ts +2
| @@ -94,6 +94,7 @@ import { | ||
| 94 | 94 | import { |
| 95 | 95 | cloudAdd, |
| 96 | 96 | cloudAudit, |
| 97 | cloudHome, | |
| 97 | 98 | cloudPage, |
| 98 | 99 | cloudRemove, |
| 99 | 100 | cloudVerify, |
| @@ -645,6 +646,7 @@ export function buildRouter(): Router<Handler> { | ||
| 645 | 646 | router.add("POST", "/settings/cloud/verify", cloudVerify); |
| 646 | 647 | router.add("POST", "/settings/cloud/write", cloudWrite); |
| 647 | 648 | router.add("POST", "/settings/cloud/audit", cloudAudit); |
| 649 | router.add("GET", "/settings/cloud/home", cloudHome); | |
| 648 | 650 | router.add("POST", "/settings/cloud/remove", cloudRemove); |
| 649 | 651 | router.add("GET", "/settings/capacity", capacityPage); |
| 650 | 652 | router.add("POST", "/settings/capacity", capacitySet); |
src/main.ts +3
| @@ -18,6 +18,7 @@ import { runSync } from "./origins/sync.ts"; | ||
| 18 | 18 | import { startForgeSsh } from "./tui/ssh.ts"; |
| 19 | 19 | import { AppsRuntime } from "./apps/runtime.ts"; |
| 20 | 20 | import { resolveAppDomain } from "./apps/host.ts"; |
| 21 | import { startCloudPublish } from "./cloud/publish.ts"; | |
| 21 | 22 | import { requeueAbandonedChecks, startChecks } from "./checks/service.ts"; |
| 22 | 23 | import { startLooks } from "./looks/service.ts"; |
| 23 | 24 | import { startProbes } from "./contract/probes.ts"; |
| @@ -232,6 +233,8 @@ const checks = | ||
| 232 | 233 | forgeUrl, |
| 233 | 234 | concurrency: positive(process.env.FORGE_CHECKS_CONCURRENCY, 1), |
| 234 | 235 | }); |
| 236 | // A repository's cloud.json, made true on each push to its default branch. | |
| 237 | startCloudPublish(app); | |
| 235 | 238 | // The look: a picture of every environment that comes up green, taken |
| 236 | 239 | // through this forge's own listener. |
| 237 | 240 | const looks = appsOn ? startLooks(app, { localUrl: servers.url }) : undefined; |
src/web/pages/audit.ts +18 −1
| @@ -33,6 +33,7 @@ import { | ||
| 33 | 33 | probeApp, |
| 34 | 34 | type ProbeRow, |
| 35 | 35 | } from "../../contract/probes.ts"; |
| 36 | import { usesToday, type CloudUseRow } from "../../core/cloud_use.ts"; | |
| 36 | 37 | import { loadRepo, notFoundPage, signInFirst } from "../chrome.ts"; |
| 37 | 38 | import { readForm } from "../form.ts"; |
| 38 | 39 | import { html, when, type Html } from "../html.ts"; |
| @@ -130,10 +131,26 @@ export async function auditPage(ctx: Ctx): Promise<Response> { | ||
| 130 | 131 | ), |
| 131 | 132 | )} |
| 132 | 133 | ${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)))}`, | |
| 134 | 136 | }); |
| 135 | 137 | } |
| 136 | 138 | |
| 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 | ||
| 137 | 154 | const count = (n: number, one: string, many: string): string => |
| 138 | 155 | `${n} ${n === 1 ? one : many}`; |
| 139 | 156 |
src/web/pages/cloud.ts +43 −2
| @@ -13,7 +13,10 @@ import { | ||
| 13 | 13 | removeAccount, |
| 14 | 14 | reverify, |
| 15 | 15 | } from "../../actions/cloud.ts"; |
| 16 | import { LABEL, PROVIDERS, shape } from "../../cloud/providers.ts"; | |
| 16 | import { CLOUD_VENDORS } from "../../apps/manifest.ts"; | |
| 17 | import { homeOf, usedFor } from "../../cloud/home.ts"; | |
| 18 | import { LABEL, PROVIDERS, isProvider, shape } from "../../cloud/providers.ts"; | |
| 19 | import { usesSince } from "../../core/cloud_use.ts"; | |
| 17 | 20 | import { |
| 18 | 21 | listCloudAccounts, |
| 19 | 22 | recentCloudReads, |
| @@ -43,8 +46,13 @@ const hidden = (provider: string, name: string): Html => | ||
| 43 | 46 | html`<input type="hidden" name="provider" value="${provider}" /> |
| 44 | 47 | <input type="hidden" name="name" value="${name}" />`; |
| 45 | 48 | |
| 49 | const VENDORS = new Set<string>(CLOUD_VENDORS); | |
| 50 | const monthOfUses = (ctx: Ctx) => | |
| 51 | usesSince(ctx.app.db, new Date(Date.now() - 30 * 86_400_000).toISOString()); | |
| 52 | ||
| 46 | 53 | function accountsCard(reads: CloudRead[], ctx: Ctx): Html { |
| 47 | 54 | const accounts = listCloudAccounts(ctx.app.db); |
| 55 | const uses = monthOfUses(ctx); | |
| 48 | 56 | const rows = accounts.map((a) => { |
| 49 | 57 | const last = reads.find((r) => r.provider === a.provider && r.name === a.name); |
| 50 | 58 | return row({ |
| @@ -52,8 +60,11 @@ function accountsCard(reads: CloudRead[], ctx: Ctx): Html { | ||
| 52 | 60 | title: html`${LABEL[a.provider]} / <span class="mono">${a.name}</span>`, |
| 53 | 61 | meta: html`${a.summary}<br />verified ${a.verifiedAt ? time(a.verifiedAt) : "never"} · |
| 54 | 62 | ${last ? html`last used ${time(last.at)} by ${runWords(last.run)}` : "never used"} · |
| 55 | ${a.writeAllowed ? "writes allowed" : "read-only"}`, | |
| 63 | ${a.writeAllowed ? "writes allowed" : "read-only"} · ${usedFor(uses, a.provider, a.name)}`, | |
| 56 | 64 | trail: html`<div class="row-actions"> |
| 65 | ${when(VENDORS.has(a.provider), () => html`<form method="get" action="/settings/cloud/home"> | |
| 66 | ${hidden(a.provider, a.name)}${btn("Bring it home", { size: "sm", label: `Bring ${a.name} home` })} | |
| 67 | </form>`)} | |
| 57 | 68 | <form method="post" action="/settings/cloud/verify"> |
| 58 | 69 | ${hidden(a.provider, a.name)}${btn("Verify", { size: "sm", label: `Verify ${a.name}` })} |
| 59 | 70 | </form> |
| @@ -140,6 +151,36 @@ export function cloudPage(ctx: Ctx): Response { | ||
| 140 | 151 | }); |
| 141 | 152 | } |
| 142 | 153 | |
| 154 | // GET /settings/cloud/home?provider=&name= | |
| 155 | export function cloudHome(ctx: Ctx): Response { | |
| 156 | const denied = requireAdmin(ctx); | |
| 157 | if (denied) return denied; | |
| 158 | const home = homeOf( | |
| 159 | ctx.app.db, | |
| 160 | ctx.url.searchParams.get("provider") ?? "", | |
| 161 | ctx.url.searchParams.get("name") ?? "", | |
| 162 | ); | |
| 163 | if (!home) return notFoundPage(ctx); | |
| 164 | const { plan } = home; | |
| 165 | return page({ | |
| 166 | ctx, | |
| 167 | title: `Bring ${plan.account} home`, | |
| 168 | body: html`<div class="page-head"><h1>Bring ${plan.account} home</h1></div> | |
| 169 | ${settingsLayout( | |
| 170 | accountSections("cloud", { admin: true }), | |
| 171 | card( | |
| 172 | html`<p class="muted small">${LABEL[plan.vendor]} / <span class="mono">${plan.account}</span>, last 30 days: | |
| 173 | ${plan.uses} call(s), ${plan.bytesOut} bytes out, about $${plan.spentUsd.toFixed(2)} spent.</p> | |
| 174 | <ol>${plan.steps.map((s) => html`<li>${s}</li>`)}</ol> | |
| 175 | <p><strong>Cost of moving:</strong> ${plan.cost}</p> | |
| 176 | <p><a href="/settings/cloud">Back to cloud accounts</a></p>`, | |
| 177 | { head: html`${icon("home")}<h2>The plan</h2>` }, | |
| 178 | ), | |
| 179 | "Account settings", | |
| 180 | )}`, | |
| 181 | }); | |
| 182 | } | |
| 183 | ||
| 143 | 184 | const said = (ctx: Ctx, r: { ok: boolean }, good: string, bad: string | undefined) => |
| 144 | 185 | flashTo(ctx, BACK, r.ok ? { message: good } : { tone: "danger", message: bad ?? "Not found." }); |
| 145 | 186 |
test/cloud-vendors.test.ts added +201
| @@ -0,0 +1,201 @@ | ||
| 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, 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 { bringHome, homeOf } from "../src/cloud/home.ts"; | |
| 19 | import { publishDeclared, startCloudPublish } from "../src/cloud/publish.ts"; | |
| 20 | import { usesToday, type CloudUseRow } from "../src/core/cloud_use.ts"; | |
| 21 | import type { Repo } from "../src/core/repos.ts"; | |
| 22 | import { createToken } from "../src/core/tokens.ts"; | |
| 23 | import { createUser, type User } from "../src/core/users.ts"; | |
| 24 | import { forgeHttp, type ForgeHttp } from "../src/http/server.ts"; | |
| 25 | import { quietLogs } from "./helpers/globals.ts"; | |
| 26 | ||
| 27 | quietLogs(); | |
| 28 | ||
| 29 | const ACCT = "a".repeat(32); | |
| 30 | const NS = "b".repeat(32); | |
| 31 | const TOKEN = "cf-token-Zq4TxLm7Kp2Vb8nWcR5"; | |
| 32 | const use = { | |
| 33 | vendor: "cloudflare", purpose: "kv-publish", account: "edge", data: "public", | |
| 34 | what: "feature flags", where: "KV namespace flags", why: "edge reads", | |
| 35 | target: `${ACCT}/${NS}`, file: "flags.json", | |
| 36 | }; | |
| 37 | const decl = (uses: unknown[]) => { | |
| 38 | const r = parseCloud(JSON.stringify({ uses })); | |
| 39 | if (!r.ok) throw new Error(JSON.stringify(r.error)); | |
| 40 | return r.value; | |
| 41 | }; | |
| 42 | ||
| 43 | function gate(declared = NO_CLOUD) { | |
| 44 | const sent: { url: string; init?: RequestInit }[] = []; | |
| 45 | const rows: Omit<CloudUseRow, "at">[] = []; | |
| 46 | const g: Gate = { | |
| 47 | declared, app: "o/app", account: "edge", token: "tok", | |
| 48 | fetch: async (url, init) => { | |
| 49 | sent.push({ url, ...(init ? { init } : {}) }); | |
| 50 | return new Response("{}", { status: 200 }); | |
| 51 | }, | |
| 52 | record: (u) => rows.push(u), | |
| 53 | }; | |
| 54 | return { g, sent, rows }; | |
| 55 | } | |
| 56 | ||
| 57 | describe("cloud.json", () => { | |
| 58 | test("absent is nothing; wrong is an error naming the field", () => { | |
| 59 | expect(parseCloud(undefined)).toEqual({ ok: true, value: NO_CLOUD }); | |
| 60 | const bad = (patch: Record<string, unknown>) => parseCloud(JSON.stringify({ uses: [{ ...use, ...patch }] })); | |
| 61 | expect(bad({}).ok).toBe(true); | |
| 62 | expect(bad({ vendor: "aws" }).ok).toBe(false); | |
| 63 | expect(bad({ vendor: "vercel" }).ok).toBe(false); | |
| 64 | expect(bad({ purpose: "burst-cell" }).ok).toBe(false); | |
| 65 | expect(bad({ data: "encrypted" }).ok).toBe(false); | |
| 66 | expect(bad({ account: "Bad Name" }).ok).toBe(false); | |
| 67 | expect(bad({ what: "" }).ok).toBe(false); | |
| 68 | expect(bad({ target: "../x/y" }).ok).toBe(false); | |
| 69 | expect(bad({ file: "../secrets" }).ok).toBe(false); | |
| 70 | expect(bad({ file: "/etc/passwd" }).ok).toBe(false); | |
| 71 | }); | |
| 72 | }); | |
| 73 | ||
| 74 | describe("the gate", () => { | |
| 75 | test("an app with no cloud.json reaches no vendor", async () => { | |
| 76 | const { g, sent, rows } = gate(); | |
| 77 | expect((await kvPublish(g, "flags.json", "{}")).ok).toBe(false); | |
| 78 | expect(sent).toEqual([]); | |
| 79 | expect(rows).toEqual([]); | |
| 80 | }); | |
| 81 | ||
| 82 | test("only the declared file, for the declared account, goes out; the call is recorded", async () => { | |
| 83 | const { g, sent, rows } = gate(decl([use])); | |
| 84 | expect((await kvPublish(g, "other.json", "{}")).ok).toBe(false); | |
| 85 | expect((await kvPublish({ ...g, account: "other" }, "flags.json", "{}")).ok).toBe(false); | |
| 86 | expect(sent).toEqual([]); | |
| 87 | const done = await kvPublish(g, "flags.json", '{"a":1}'); | |
| 88 | expect(done).toEqual({ ok: true, value: { bytes: 7 } }); | |
| 89 | expect(sent[0]!.url).toBe(`https://api.cloudflare.com/client/v4/accounts/${ACCT}/storage/kv/namespaces/${NS}/values/flags.json`); | |
| 90 | expect(sent[0]!.init!.method).toBe("PUT"); | |
| 91 | expect(rows).toMatchObject([{ vendor: "cloudflare", purpose: "kv-publish", bytesOut: 7, account: "edge", app: "o/app" }]); | |
| 92 | }); | |
| 93 | ||
| 94 | test("a value over the cap is refused before any request", async () => { | |
| 95 | const { g, sent } = gate(decl([use])); | |
| 96 | expect((await kvPublish(g, "flags.json", "x".repeat(1024 * 1024 + 1))).ok).toBe(false); | |
| 97 | expect(sent).toEqual([]); | |
| 98 | }); | |
| 99 | }); | |
| 100 | ||
| 101 | describe("through the app", () => { | |
| 102 | let dataDir = ""; | |
| 103 | let app: App; | |
| 104 | let http: ForgeHttp; | |
| 105 | let stop: () => void; | |
| 106 | let alice: User; | |
| 107 | let repo: Repo; | |
| 108 | const puts: { url: string; auth: string; body: string }[] = []; | |
| 109 | ||
| 110 | beforeAll(async () => { | |
| 111 | dataDir = await mkdtemp(join(tmpdir(), "forge-vendors-")); | |
| 112 | app = createApp({ dataDir, port: 0 }); | |
| 113 | http = forgeHttp(app); | |
| 114 | stop = startCloudPublish(app); | |
| 115 | const a = await createUser(app.db, { trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 116 | if (!a.ok) throw new Error(a.error); | |
| 117 | alice = a.value; | |
| 118 | const r = await createRepo(app, alice, { name: "site", visibility: "public" }); | |
| 119 | if (!r.ok) throw new Error(String(r.error)); | |
| 120 | repo = r.value; | |
| 121 | net.fetch = async (url, init) => { | |
| 122 | const headers = (init?.headers ?? {}) as Record<string, string>; | |
| 123 | if (init?.method === "PUT") | |
| 124 | puts.push({ url, auth: headers["authorization"] ?? "", body: String(init.body) }); | |
| 125 | const u = new URL(url); | |
| 126 | if (u.pathname.endsWith("/tokens/verify")) return new Response('{"result":{"status":"active"}}'); | |
| 127 | if (u.pathname.endsWith("/zones")) return new Response('{"result":[]}'); | |
| 128 | return new Response("{}"); | |
| 129 | }; | |
| 130 | }); | |
| 131 | afterAll(async () => { | |
| 132 | stop(); | |
| 133 | http.close(); | |
| 134 | app.close(); | |
| 135 | await rm(dataDir, { recursive: true, force: true }); | |
| 136 | }); | |
| 137 | ||
| 138 | const push = (files: { path: string; content: string }[]) => | |
| 139 | commitToBranch(app, alice, repo, { message: "Declare", files }).then((r) => { | |
| 140 | if (!r.ok) throw new Error(String(r.error)); | |
| 141 | return r.value.commitOid; | |
| 142 | }); | |
| 143 | ||
| 144 | test("a declared use with no account, then a read-only account, is refused and calls nothing", async () => { | |
| 145 | const oid = await push([ | |
| 146 | { path: "flags.json", content: '{"beta":true}' }, | |
| 147 | { path: "cloud.json", content: JSON.stringify({ uses: [use] }) }, | |
| 148 | ]); | |
| 149 | expect((await publishDeclared(app, repo, oid))[0]).toContain("no Cloud account"); | |
| 150 | expect((await addAccount(app, alice, "cloudflare", "edge", TOKEN)).ok).toBe(true); | |
| 151 | expect((await publishDeclared(app, repo, oid))[0]).toContain("read-only"); | |
| 152 | expect(puts).toEqual([]); | |
| 153 | expect(usesToday(app.db)).toEqual([]); | |
| 154 | }); | |
| 155 | ||
| 156 | test("with writes allowed the declared file is published with the sealed token, and audited", async () => { | |
| 157 | expect(allowWrite(app, alice, "cloudflare", "edge", true).ok).toBe(true); | |
| 158 | const oid = (await Bun.$`git -C ${join(app.reposRoot, "alice", "site.git")} rev-parse HEAD`.quiet().text()).trim(); | |
| 159 | const said = await publishDeclared(app, repo, oid); | |
| 160 | expect(said[0]).toContain("published 13 bytes"); | |
| 161 | expect(puts).toEqual([{ | |
| 162 | url: `https://api.cloudflare.com/client/v4/accounts/${ACCT}/storage/kv/namespaces/${NS}/values/flags.json`, | |
| 163 | auth: `Bearer ${TOKEN}`, | |
| 164 | body: '{"beta":true}', | |
| 165 | }]); | |
| 166 | expect(usesToday(app.db)).toMatchObject([{ vendor: "cloudflare", account: "edge", purpose: "kv-publish", app: "alice/site", bytesOut: 13 }]); | |
| 167 | }); | |
| 168 | ||
| 169 | test("a push to the default branch publishes on its own", async () => { | |
| 170 | puts.length = 0; | |
| 171 | await push([{ path: "flags.json", content: '{"beta":false}' }]); | |
| 172 | for (let i = 0; i < 40 && puts.length === 0; i++) await Bun.sleep(50); | |
| 173 | expect(puts.map((p) => p.body)).toEqual(['{"beta":false}']); | |
| 174 | }); | |
| 175 | ||
| 176 | test("a bad cloud.json publishes nothing and says why", async () => { | |
| 177 | puts.length = 0; | |
| 178 | const oid = await push([{ path: "cloud.json", content: JSON.stringify({ uses: [{ ...use, data: "encrypted" }] }) }]); | |
| 179 | expect((await publishDeclared(app, repo, oid))[0]).toContain("cloud.json refused"); | |
| 180 | expect(puts).toEqual([]); | |
| 181 | }); | |
| 182 | ||
| 183 | test("bring it home is for the account asked about, in the page and in the API", async () => { | |
| 184 | const mine = homeOf(app.db, "cloudflare", "edge")!; | |
| 185 | expect(mine.plan).toMatchObject({ account: "edge", vendor: "cloudflare" }); | |
| 186 | expect(mine.plan.uses).toBeGreaterThanOrEqual(1); | |
| 187 | expect(mine.used).toContain("kv-publish"); | |
| 188 | expect(homeOf(app.db, "cloudflare", "nobody")).toBeUndefined(); | |
| 189 | expect(homeOf(app.db, "github", "edge")).toBeUndefined(); | |
| 190 | expect(bringHome("cloudflare", "elsewhere", usesToday(app.db)).uses).toBe(0); | |
| 191 | ||
| 192 | const token = createToken(app.db, alice.id, "t", "admin").token; | |
| 193 | const api = await http.handle(new Request(`http://localhost/api/v1/admin/cloud/cloudflare/edge/home`, { headers: { authorization: `Bearer ${token}` } })); | |
| 194 | expect(api.status).toBe(200); | |
| 195 | expect(((await api.json()) as any).plan.steps.length).toBeGreaterThan(2); | |
| 196 | const none = await http.handle(new Request("http://localhost/api/v1/admin/cloud/cloudflare/edge/home")); | |
| 197 | expect(none.status).not.toBe(200); | |
| 198 | const gone = await http.handle(new Request(`http://localhost/api/v1/admin/cloud/cloudflare/nobody/home`, { headers: { authorization: `Bearer ${token}` } })); | |
| 199 | expect(gone.status).toBe(404); | |
| 200 | }); | |
| 201 | }); |
new above
offline
parseCloudis never called outside tests: cloud.json is not read from any repository, so nothing is "declared in git" yet.