Public: anyone can read this; the crew can change it.
A deployed forge is claimed by one link over HTTPS on its own name, on a hardened machine #16255
Check · Review · Land · Live done — Landed and live in production.
sold/claim-and-harden → main 0 commits
71 files
changed +4022
−475
AGENTS.md +2 −1
| @@ -92,5 +92,6 @@ A pull that changes code under `src/` adds or edits a `test/*.test.ts` too, or s | ||
| 92 | 92 | |
| 93 | 93 | A pull that adds a page (`src/web/pages/*.ts`), an MCP tool (`src/http/mcp/tools/*.ts`) or a settings module (`src/settings/*.ts`) has a commit line `Replaces: <what it takes the place of>` or `Replaces: nothing, <why>` (#14249, `src/kernel/replaces.ts`); `bun scripts/gate.ts` says it as a note, never a refusal, and the reviewer holds the pull to that line. |
| 94 | 94 | `src/release/shipped_held.ts`: `heldShipped`, per forge, the public changelog answer (`shippedHeld`, which `GET /api/v1/changelog` answers from; the page, feeds and MCP walk fresh) held 60 s per `?repo=` value (20 at most) so the first call and the second share one git walk (#15631); `recordRelease`, `recordAppRelease` and `setReleaseTests` drop it (`forgetShipped`) so a release is never served stale; a walk that fails is not held; the route names the phase `shipped` in `server-timing` (`desc="hit"` when held); gone on restart. |
| 95 | ||
| 95 | `src/spawn/own_code.ts`: `queues`, the tail of each one-at-a-time turn (`oneAtATime`), by data directory and name. `src/actions/pinned.ts` takes two kinds of turn there: `pinned-account:<provider>/<account>`, held from a create's ceiling check until the machine it made is in its row, so creates asked together are counted one after the other, and `pinned-forge:<name>`, held through an Update, Rollback or new claim link, so two never delete and make a machine each. A key leaves when its last turn settles, refusals included (`test/pinned-ceiling.test.ts`); gone on restart, when nothing was in flight. | |
| 96 | `src/crew/sandbox_policy.ts`: `standing`, per forge (a WeakMap on the app), whether the sandbox is required, what the last probe found and how to ask again; written by the crew at its start and after each probe (`crew/dispatch.ts`, `noteSandbox`), read by `sandboxRefusal` wherever an agent process would start (a held run, a conversation turn, a one-shot). The probe is taken again at most once every `SANDBOX_REPROBE_MS` and one at a time (`reprober`), only while something waits on it. One entry per forge, gone on restart, when the crew probes afresh. | |
| 96 | 97 | `src/actions/places_refresh.ts`: `running`, the one catalog refresh in flight per forge database (#16203), so concurrent admin reads wait on it; at most one per forge, gone on restart. Its terminal door is `src/tui/screens/places.ts` (`p` pins; `pinPlace` gives the API and the terminal the same gate and the `cloud.place_pinned` event). |
docs/APPS.md +1
| @@ -1864,6 +1864,7 @@ a link to the milestone (`docs/PLANNING.md`); its progress never does. | ||
| 1864 | 1864 | | `FORGE_CREW_CPUS` | `4` | cores one crew run may use (`cpu.max` on its own cell cgroup, where the cpu controller is delegated) | |
| 1865 | 1865 | | `FORGE_CREW_BUDGET_USD` | `5` | spend per run unless the agent says otherwise | |
| 1866 | 1866 | | `FORGE_CREW_TIMEOUT_MIN` | `45` | wall-clock limit of one agent run | |
| 1867 | | `FORGE_CREW_SANDBOX` | `off` | `require` keeps crew runs queued (held, with the reason in the run's log) while the host cannot run the shell sandbox, and refuses conversation turns and one-shots with the same reason: no agent process starts. The probe is taken again, at most once a minute, while something waits on it, so a fixed host needs no restart. `off` runs them unrestricted on purpose | | |
| 1867 | 1868 | | `FORGE_CREW_ALLOW_HOSTS` | — | hosts an agent's shell may reach, comma-separated | |
| 1868 | 1869 | | `FORGE_CLAUDE` | `claude` on `PATH` | the Claude Code binary | |
| 1869 | 1870 | | `FORGE_CLAUDE_CONFIG_DIR` | conversations: `$FORGE_APP_DATA/claude-config`; runs: Claude Code's own | a `CLAUDE_CONFIG_DIR`; conversation sessions live there so a release keeps them | |
docs/OPERATING.md +6 −1
| @@ -18,7 +18,12 @@ respond to an attack or a leaked token, see | ||
| 18 | 18 | Configuration is environment variables, all with defaults: `FORGE_DATA` |
| 19 | 19 | (`data/`; the forge refuses to boot when it is the checkout itself or a path |
| 20 | 20 | inside it that git does not ignore), `PORT` (`3000`), `FORGE_SSH_PORT` (`2222`; `0` turns SSH off), and |
| 21 | `FORGE_HOST` (`localhost`, the hostname in clone URLs). `FORGE_DRAIN_LINGER_S` | |
| 21 | `FORGE_HOST` (`localhost`, the hostname in clone URLs). `FORGE_BIND` is the one | |
| 22 | IPv4 address the web listener binds (unset, every interface; `127.0.0.1` behind a | |
| 23 | proxy on the same machine, which is how a pinned forge runs). `FORGE_FIRST_ADMIN_SEED` | |
| 24 | (`<sha256>@<deadline>`, set by the forge that deployed this one, never by hand) | |
| 25 | seeds the first-admin code of a deployed forge: `docs/features/pinned-forge.md`. | |
| 26 | `FORGE_DRAIN_LINGER_S` | |
| 22 | 27 | (`10`, 0 to 120) is how long a forge sent SIGTERM keeps answering while |
| 23 | 28 | routers learn it is going, so a roll refuses nobody (`docs/ops/ROLL.md`). |
| 24 | 29 | Connecting origins |
docs/REFERENCE.md +5 −2
| @@ -232,8 +232,11 @@ a passkey and an email address (there is no password signup), and the browser | ||
| 232 | 232 | at `/signup`, the API and the terminal all make an account that is not an |
| 233 | 233 | admin. The site admin is made from the operator's terminal with |
| 234 | 234 | `--first-admin`, which needs no browser at all and works whatever signup says, |
| 235 | or, on a spawned child, by its `/claim` link (code that sets a forge up | |
| 236 | directly, like test fixtures, seeds one): | |
| 235 | or, on a spawned child, by its `/claim` link, or, on a forge another forge | |
| 236 | deployed to a cloud, by the claim link that deploy showed once: the same | |
| 237 | first-admin code, whose hash the machine was started with and which stands | |
| 238 | for 7 days (`docs/features/pinned-forge.md`). Code that sets a forge up | |
| 239 | directly, like test fixtures, seeds one: | |
| 237 | 240 | |
| 238 | 241 | sh |
| 239 | 242 | # One-time code, printed only here: works once, for 15 minutes, and never once |
docs/features/deploy-to-hetzner.md +6 −2
| @@ -8,14 +8,18 @@ A pinned forge can run in your own Hetzner Cloud project the way it runs on Digi | ||
| 8 | 8 | |
| 9 | 9 | 1. **Make a token.** In the Hetzner Cloud console open the project, Security → API tokens, and make a token with **Read & Write**. Hetzner scopes a token to one project and offers nothing narrower, and a read-only token can only check a forge, never make one. |
| 10 | 10 | 2. **Attach it.** Settings → Cloud accounts (`/settings/cloud`), provider Hetzner Cloud, then **allow writes** on the account. The token is sealed; it is opened for one call at a time. |
| 11 | 3. **Deploy.** Any door takes the account as `hetzner/<name>`: the `/deploy-to` list ("Hetzner Cloud / main"), the terminal's Pinned forges screen (`d`, then `acme hetzner/main alice/shop https://… v1.0.0`), the HTTP and MCP `target` `hetzner`. | |
| 11 | 3. **Deploy.** Any door takes the account as `hetzner/<name>` and the name the forge is served on: the `/deploy-to` list ("Hetzner Cloud / main") and its Hostname field, the terminal's Pinned forges screen (`src/tui/screens/pinned.ts`: `d`, then `acme forge.acme.com hetzner/main alice/shop https://… v1.0.0`), the HTTP and MCP `target` `hetzner` with `host`. | |
| 12 | 4. **Keep the claim link.** The answer shows it once: it is the only way to become the new forge's first admin, it works once and for 7 days, and this forge keeps only its hash. Hand it to the person the forge is for. | |
| 13 | 5. **Create the DNS record** the answer names, `<host> A <address>`, DNS only. The server then gets its own certificate and the forge answers at `https://<host>/`; Check says what it is still waiting for. | |
| 12 | 14 | |
| 13 | 15 | ## What it makes |
| 14 | 16 | |
| 15 | 17 | - Location **Nuremberg** (`nbg1`), an EU location: the US ones cost about three times as much for a tenth of the traffic. |
| 16 | 18 | - The server **type is chosen from Hetzner's own lists at order time**: the cheapest cost-optimized (CX), x86 type with at least 2 GiB that Hetzner says can be ordered in Nuremberg now. No type is named in the code. |
| 17 | 19 | - A 10 GiB volume, attached and automounted at `/mnt/HC_Volume_<id>`. Update deletes the server and makes a new one on the same volume; the data is not touched. |
| 18 | - The address is read back from the server by Check, as on DigitalOcean. | |
| 20 | - The server is made with a throwaway SSH key (made and deleted per create), so Hetzner never emails a root password; the machine accepts no password, no root login and nothing on port 22, and opens only 80 and 443. See "What the booted machine is" in `pinned-forge.md`. | |
| 21 | - The address is read back from the server, for the DNS record; the forge itself is served only on its name over HTTPS, by Caddy from Ubuntu's own packages, as on DigitalOcean. | |
| 22 | - A replaced server (Update, Roll back, a new claim link) has a new address: change the record to the one Check names. | |
| 19 | 23 | |
| 20 | 24 | ## When nothing is in stock |
| 21 | 25 |
docs/features/pinned-forge.md +55 −13
| @@ -4,18 +4,37 @@ row: A pinned forge | ||
| 4 | 4 | --- |
| 5 | 5 | # A pinned forge (#8697) |
| 6 | 6 | |
| 7 | A pinned forge is a forge the owner put on their own cloud. It has **no crew** and **no automatic release**. Its version and config change only through one explicit `Update`, recorded with who and when; `Rollback` is one action to the previous version. | |
| 7 | A pinned forge is a forge the owner put on their own cloud. It has **no crew** and **no automatic release**. Its version and config change only through one explicit `Update`, recorded with who and when; `Rollback` is one action to the previous version. It is served on its own name over HTTPS, and its first admin is whoever holds the one-time claim link the deploy shows (#16217). | |
| 8 | 8 | |
| 9 | 9 | ## Doors (forge admin, admin-scope token) |
| 10 | 10 | |
| 11 | - HTTP: `GET /api/v1/admin/pinned` (forges, their changes, the targets), `POST /api/v1/admin/pinned` (deploy), `POST /api/v1/admin/pinned/:name/update`, `POST /api/v1/admin/pinned/:name/rollback`, `POST /api/v1/admin/pinned/:name/claim`. | |
| 12 | - Terminal: palette → **Pinned forges** (forge admin): `d` deploy, `u` update, `r` roll back, `h` hand to buyer (after a confirm); it follows the bus, so a change made at any door shows at once (`src/tui/screens/pinned.ts`). | |
| 13 | - Web: `/deploy-to` (forge admin; linked from Cloud accounts) is a server-rendered form for cloud account, app, source, version and name. The link `/deploy-to?app=owner/name&source=https://…&version=v1.2.3` (`deployToHref` in `src/web/pinned.ts`) lands on it with those filled in after one sign-in; nothing deploys until the button is pressed. The POST is same-origin checked and calls the same `deployPinned` (`src/http/pinned_routes.ts`). | |
| 14 | - Web list: `/pinned` (forge admin; 404 otherwise) is server-rendered, with actions; one block of plain rows per forge: name, app, version, address (a link), health (the state), when the last check ran (the newest `pinned.check` event; `never checked` before the first), and the last change with who and when, from the same `pinnedForges` read as the API (`src/web/pages/pinned.ts`). The intro links `/deploy-to`; an empty list says so. A person can update, roll back and check a forge from `/pinned`, as the terminal's `u`, `r` and `c` do: each row has three buttons (Update, Roll back, Check), and each goes through the confirm page before it runs (Update also asks for the version). They post to `POST /pinned/:name/:act` (`act` is `update`, `rollback` or `check`; admin only, same-origin, 404 for non-admins and unknown acts); the result, or the sentence that refuses it, is shown as a flash on `/pinned` (`src/http/pinned_routes.ts`). | |
| 15 | - Web **Hand to buyer** on `/pinned` (confirm page, then `POST /pinned/:name/claim`) and MCP `pinned_forge` verb `claim` hand a forge over; see After the claim below. | |
| 16 | - MCP: `pinned_forge` with `verb` `list`, `deploy`, `update`, `rollback`, `check` and `claim` — the same words and the same checks (`src/actions/pinned.ts`). | |
| 11 | - HTTP: `GET /api/v1/admin/pinned` (forges, their changes, the targets), `POST /api/v1/admin/pinned` (deploy; the answer holds `claim.link`), `POST /api/v1/admin/pinned/:name/update`, `POST /api/v1/admin/pinned/:name/rollback`, `POST /api/v1/admin/pinned/:name/claim` (a new claim link). | |
| 12 | - Terminal: palette → **Pinned forges** (forge admin): `d` deploy, `u` update, `r` roll back, `n` a new claim link (asked first); a deploy and `n` show the link in a dialog to copy; it follows the bus, so a change made at any door shows at once (`src/tui/screens/pinned.ts`). | |
| 13 | - Web: `/deploy-to` (forge admin; linked from Cloud accounts) is a server-rendered form for cloud account, app, source, version, name and hostname. Its answer is a page with the claim link, sent `no-store`, not a redirect. The link `/deploy-to?app=owner/name&source=https://…&version=v1.2.3` (`deployToHref` in `src/web/pinned.ts`) lands on it with those filled in after one sign-in; nothing deploys until the button is pressed. The POST is same-origin checked and calls the same `deployPinned` (`src/http/pinned_routes.ts`). | |
| 14 | - Web list: `/pinned` (forge admin; 404 otherwise) is server-rendered, with actions; one block of plain rows per forge: name, app, version, address (a link), health (the state), when the last check ran (the newest `pinned.check` event; `never checked` before the first), and the last change with who and when, from the same `pinnedForges` read as the API (`src/web/pages/pinned.ts`). The intro links `/deploy-to`; an empty list says so. A person can update, roll back and check a forge from `/pinned`, as the terminal's `u`, `r` and `c` do: each row has four buttons (Update, Roll back, Check, New claim link), and each goes through the confirm page before it runs (Update also asks for the version). The row also shows the DNS record and when the claim link runs out. They post to `POST /pinned/:name/:act` (`act` is `update`, `rollback`, `check` or `claim`; admin only, same-origin, 404 for non-admins and unknown acts); the result, or the sentence that refuses it, is shown as a flash on `/pinned` (`src/http/pinned_routes.ts`). | |
| 15 | - MCP: `pinned_forge` with `verb` `list`, `deploy`, `claim`, `update`, `rollback` (and `check`) — the same words and the same checks (`src/actions/pinned.ts`). | |
| 17 | 16 | |
| 18 | A deploy names a cloud account (Settings → Cloud accounts, **writes allowed**), the app (`owner/name`), a git `source` (https) and a `version` (a 40-character commit id or a tag like `v1.2.3` — never a branch, so nothing moves under it). | |
| 17 | A deploy names a cloud account (Settings → Cloud accounts, **writes allowed**), the app (`owner/name`), a git `source` (https), a `version` (a 40-character commit id or a tag like `v1.2.3` — never a branch, so nothing moves under it) and a `host`: the DNS name the forge is served on. | |
| 18 | ||
| 19 | ## The name and HTTPS (#16217) | |
| 20 | ||
| 21 | A forge is served at `https://<host>/` and nowhere else. `host` is a full lowercase DNS name you control (`forge.example.com`): no address, port, wildcard or trailing dot, checked by one pattern (`validHost` in `src/core/pinned.ts`) before it is written anywhere, and one forge a name. | |
| 22 | ||
| 23 | - **The certificate is the machine's own.** The forge has no ACME client. Caddy is one of the machine's packages, from Ubuntu's repository, running as its own service under its own user (never inside the forge's unit), with a config that is the name, `reverse_proxy 127.0.0.1:<PORT or 3000>` and where certificates are kept (`proxyConfig` in `src/cloud/machine.ts`). Caddy gets a certificate for that name from Let's Encrypt, renews it, redirects port 80 to 443 and answers no other name. The config is written to `/etc/caddy/Caddyfile` before the package is installed (cloud-init writes files first, and dpkg keeps a config file that is already there), so Caddy never serves its welcome page. | |
| 24 | - **The certificate lives on the data volume**, in `<mount>/caddy`, owned by Caddy's user and skipped by the forge's ownership walk. An Update, Roll back or new claim link starts a machine that finds it there and asks Let's Encrypt for nothing; otherwise six replacements in a week would meet its limit of five certificates for one name. Caddy waits for the volume's mount (a `RequiresMountsFor` drop-in). | |
| 25 | - **The forge listens on loopback.** The machine's environment sets `FORGE_BIND=127.0.0.1`, `FORGE_URL=https://<host>`, `FORGE_HOST=<host>` and `FORGE_TRUSTED_PROXIES=127.0.0.1/32` (`servedEnv`); a deploy's config may not name them. So until the certificate exists nothing of the forge can be reached, and plain HTTP only ever gets the proxy's redirect and its ACME challenge. `FORGE_BIND` governs the web listener alone, and the SSH listener binds every interface, so the machine's environment also sets `FORGE_SSH_PORT=0`: a pinned forge has no SSH listener, and git and every door go over HTTPS. | |
| 26 | - **You create one DNS record.** `<host> A <address>`, DNS only (not proxied). The deploy answer names it when the cloud has already assigned the address; otherwise Check reads the address and names it. Every view carries it as `dns`. Nothing here creates the record for you. | |
| 27 | - **The address changes when the machine is replaced.** Update, Roll back and a new claim link each start a new machine on the same volume, and a new machine has a new address: Check says "waiting for DNS" with the new record until you change it. | |
| 28 | ||
| 29 | ## The claim (#16217) | |
| 30 | ||
| 31 | A deploy is for one person. Its answer holds a **claim link**, `https://<host>/first-admin#<code>`, shown once: on the page, in the HTTP and MCP answer (`claim.link`, `claim.expiresAt`), and in the terminal's dialog. Whoever opens it makes the forge's first admin with a passkey; an agent trades the part after `#` at `POST /api/v1/first-admin` for a token. It works once, for 7 days (`FIRST_ADMIN_SEED_TTL_MS`), and never once the forge has an admin. A visitor without it gets the refusal any wrong code gets, and a new forge's signup is by invite, so nobody else gets an account there first. | |
| 32 | ||
| 33 | - **Nobody stores the link.** This forge keeps its sha256 and deadline (`pinned_forge.claim_hash`, `claim_expires`); the machine is booted with the same two as `FORGE_FIRST_ADMIN_SEED=<sha256>@<deadline>`. Boot config stays readable through the cloud's API and the machine's metadata endpoint, so it must not open the forge, and a hash does not. `test/pinned-claim.test.ts` shows the boot config is a function of the stored row and that the row, the events and the audit hold no form of the link. | |
| 34 | - **It is the first-admin code, not a second mechanism.** At boot the deployed forge takes the seed as its one first-admin row (`seedFirstAdmin` in `src/core/first_admin.ts`): the same row `--first-admin` writes, spent by the same statement at the same doors under the same throttle. Each seed is taken once, so a restart revives nothing; a seed that is not a hash and a deadline stops the boot. | |
| 35 | - **A new claim link** (`claim`, `n`, the button) is for a link that ran out unused or was lost. A new hash can reach a machine nobody can sign in to only through new boot config, so the machine is replaced on its volume, as an Update replaces it; the forge takes the new seed and the link before it is dead. It is refused once the forge has said it was claimed (After the claim, below), and a replacement the cloud refuses issues nothing: the row takes the new hash only when the machine that holds it exists. | |
| 36 | - **Check says what became of it.** Once the forge answers, Check asks it `GET /api/v1/first-admin/claim?seed=<sha256>`, which answers `waiting`, `claimed` or `expired` to that hash and 404 to anything else. The result carries it as `claim` (`unknown` while the forge cannot be asked). | |
| 37 | - A forge deployed before forges had names has no `host`: Update and Roll back are refused until a new claim link gives it one (the claim takes `host` once). | |
| 19 | 38 | |
| 20 | 39 | ## Why it cannot move on its own |
| 21 | 40 | |
| @@ -23,11 +42,26 @@ A deploy names a cloud account (Settings → Cloud accounts, **writes allowed**) | ||
| 23 | 42 | |
| 24 | 43 | ## Credentials |
| 25 | 44 | |
| 26 | The cloud token stays sealed. It is opened for the one call that needs it (a `secret.read` event names the run), sent as an `Authorization` header over HTTPS, and never reaches argv, a row, an event, a request body or the boot script. The boot script holds no secret: the new forge's first visitor claims it. Config refuses names that look like secrets. | |
| 45 | The cloud token stays sealed. It is opened for the one call that needs it (a `secret.read` event names the run), sent as an `Authorization` header over HTTPS, and never reaches argv, a row, an event, a request body or the boot script. The boot script holds no secret: of the claim it carries the sha256 alone (see The claim). Config refuses names that look like secrets. | |
| 46 | ||
| 47 | ## What the booted machine is (#16218) | |
| 48 | ||
| 49 | A pinned forge runs on a public address, so its machine is set up for that (`src/cloud/harden.ts`; `test/pinned-harden.test.ts`). | |
| 50 | ||
| 51 | - **User.** The forge runs as `forge`, an unprivileged system user with no login shell, never as root. Bun is installed under `/opt/bun`, owned by root, so the forge can run it and cannot change it. The checkout is `/opt/forge`, owned by `forge` and read-only to the running service. The unit sets `NoNewPrivileges`, `PrivateTmp`, `ProtectSystem=strict`, `ProtectHome`, `RestrictSUIDSGID`, and nothing that hides a part of /proc or /sys (the sandbox mounts its own /proc and may only under a whole one), and leaves only the data volume and `/var/lib/forge` writable. At every start the volume is made `forge`'s, which also covers a volume an earlier root forge wrote. | |
| 52 | - **Ports.** Only 80 and 443 are open to the world, by ufw on the machine. What listens on them is the machine's proxy (The name and HTTPS); the forge's own port is bound to loopback and closed from outside, and it has no SSH listener. The provider's own firewall (Hetzner firewalls, DigitalOcean cloud firewalls) is **not** used yet. | |
| 53 | - **SSH.** Port 22 is closed, password login is off, root login is off, and only public keys could ever be accepted. Nobody gets a shell. No root password is ever made: both clouds email one to the account holder when a server is created with no SSH key, so each create sends a fresh Ed25519 public key whose private half was never exported and is dropped at once, and deletes the key from the account after the call (`src/cloud/throwaway_key.ts`). The DigitalOcean token therefore needs the SSH key write permission as well as droplets and volumes. | |
| 54 | - **Updates.** Security updates install themselves (`unattended-upgrades`), and the first boot upgrades packages. The machine does not reboot by itself: a new kernel takes effect at the next Update, which replaces the machine. | |
| 55 | - **Sandbox.** The boot installs bubblewrap and socat. Ubuntu 24.04 refuses user namespaces to unconfined programs (`kernel.apparmor_restrict_unprivileged_userns=1`), so an AppArmor profile (`/etc/apparmor.d/forge-bwrap`) lets `/usr/bin/bwrap`, and only it, make one; the system-wide setting stays on. Where bubblewrap still cannot start, the forge says so (`agent sandbox not available here; runs are unrestricted`, `src/crew/dispatch.ts`), and a pinned forge has no crew. The machine's environment sets `FORGE_CREW_SANDBOX=require` (#16233): where the profile did not load (the boot goes on), no agent process starts, a run's log and a refused turn name the cause, and that forge's admin reads it at the foot of every page (`Reduced protection: crew shells (…) its runs are refused`). The forge asks again each minute while something waits, so loading the profile by hand needs no restart. | |
| 56 | - **Config.** A config name that steers the loader, the runtime or the path (`LD_*`, `DYLD_*`, `NODE_*`, `BUN_*`, `GIT_*`, `PATH`, `HOME`, `SHELL`, `USER`, `IFS`, `ENV`, `BASH_ENV`, `TMPDIR`, …) is refused, as is any name that looks like a secret (secret, token, password, passphrase, auth, cookie, credential, private, key). So is a name the boot sets itself (`BOOT_NAMES` in `src/core/pinned.ts`: `FORGE_URL`, `FORGE_HOST`, `FORGE_BIND`, `FORGE_TRUSTED_PROXIES`, `FORGE_SSH_PORT`, `FORGE_FIRST_ADMIN_SEED`, `FORGE_CREW_SANDBOX`, `FORGE_APP_DATA`); those are written after the config, `FORGE_APP_DATA` last. | |
| 57 | ||
| 58 | ### What only a real boot proves | |
| 59 | ||
| 60 | On a new machine (reach it through the provider's console, since SSH is closed): `ufw status verbose` lists only 80 and 443; `systemctl show forge -p User` says `forge` and `ps -o user= -C bun` too; `sshd -T | grep -Ei 'passwordauthentication|permitrootlogin'` says `no`; `apt-config dump | grep Unattended-Upgrade::` and `systemctl status apt-daily-upgrade.timer`; `journalctl -t forge-boot` says `sandbox ready`; `systemd-run --wait --pty -p User=forge -p NoNewPrivileges=yes -p ProtectSystem=strict -p PrivateTmp=yes bwrap --unshare-user --ro-bind / / -- /bin/true` exits 0 (the one that proves `NoNewPrivileges` and bubblewrap agree); the same with every directive of the unit and a sandbox that mounts its own /proc, `systemd-run --wait --pty -p User=forge -p NoNewPrivileges=yes -p ProtectSystem=strict -p ProtectHome=yes -p PrivateTmp=yes -p ProtectKernelModules=yes -p ProtectClock=yes -p RestrictSUIDSGID=yes bwrap --unshare-user --unshare-pid --ro-bind / / --proc /proc --dev /dev -- /bin/true`, exits 0 (the unit hides no part of /proc, which is why it has no `ProtectKernelLogs`); `stat -c %A /usr/bin/bwrap` is not setuid; `journalctl -u forge` shows no read-only-file-system error from the checkout; `systemctl is-active caddy` says `active` and `ss -ltnp` shows Caddy on 80 and 443 and Bun on `127.0.0.1` alone; `cat /etc/caddy/Caddyfile` is the forge's own and `curl -s http://<address>/` never showed Caddy's welcome page (the claim that dpkg kept the file); `stat -c %U <mount>/caddy` says `caddy` after a forge restart; once the DNS record exists, `journalctl -u caddy` shows the certificate obtained, and after an Update it shows none requested. HTTP/3 is not offered a way in (ufw opens 443/tcp only; browsers fall back). The forge's start walks the whole volume to set ownership, which is slow on a large one. No email from the provider with a root password arrives. | |
| 27 | 61 | |
| 28 | 62 | ## After the claim: what the host can still do (#16204) |
| 29 | 63 | |
| 30 | `claim` (web `Hand to buyer` on `/pinned`, MCP `pinned_forge` verb `claim`, `POST /api/v1/admin/pinned/:name/claim`, terminal `h`) records that the forge was handed to its buyer (`pinned_forge.claimed_at`, event `pinned.claimed`). From then the selling forge refuses `update` and `rollback` for it: updates are the buyer's to take. `/pinned` (once, when any forge is claimed) and `/deploy-to` say what the host still can while the machine is in the host's cloud account (`HOST_CAN` in `src/core/pinned.ts`): open its console, boot it into rescue, snapshot its disk, read its boot data. It never says "no access". The path that gives the host none is the buyer's own cloud account: deploy there (the account picker on `/deploy-to`; choosing it at purchase is #16203). | |
| 64 | Nobody marks a forge claimed by hand: the deployed forge says so. Check, and every Update, Roll back and request for a new claim link, asks it first; when one hears `claimed` (The claim, above), the selling forge records it once (`pinned_forge.claimed_at`, event `pinned.claimed`). From then it refuses `update`, `rollback` and a new claim link for that forge, each with the same sentence (`CLAIMED_REFUSAL`): updates are the buyer's to take, and no machine of theirs is replaced from here. A forge that cannot be asked is never recorded as claimed, and is not taken as unclaimed either: once its current machine has answered about its claim (`pinned_forge.reached`), silence from it (a broken DNS record, a forge that is down) refuses Update, Roll back and a new claim link, with a sentence saying the forge could not be reached to confirm nobody claimed it and to run Check until it answers. A forge whose current machine has never answered (still booting, DNS not pointed yet, a first boot that failed) may still be replaced, or it could never be recovered. The question starts with a read of the machine at its cloud: when the cloud refuses that read the change is refused with the cloud's answer, before anything is recorded; a machine that is gone (404) has nobody to ask and is replaced. `/pinned` (once, when any forge is claimed) and `/deploy-to` say what the host still can while the machine is in the host's cloud account (`HOST_CAN` in `src/core/pinned.ts`): open its console, boot it into rescue, snapshot its disk, read its boot data. It never says "no access". The path that gives the host none is the buyer's own cloud account: deploy there (the account picker on `/deploy-to`; choosing it at purchase is #16203). | |
| 31 | 65 | |
| 32 | 66 | ## Targets: what runs, what it costs, what is refused |
| 33 | 67 | |
| @@ -50,7 +84,11 @@ Open-source "Deploy to" buttons (Heroku's `app.json`, Render's `render.yaml`, Di | ||
| 50 | 84 | |
| 51 | 85 | ## Address and health check (#8745) |
| 52 | 86 | |
| 53 | `check` (`POST /api/v1/admin/pinned/:name/check`, MCP `pinned_forge` verb `check`, terminal `c`) reads the droplet from DigitalOcean (`GET /droplets/{id}`, read-only, no write permission needed), records its public IPv4 (`pinned_forge.address`, validated as IPv4), and probes `http://<address>:<PORT or 3000>/`. Every view carries `url` (empty until an address is read). A forge that answers is set `running`, so a `failed` one recovers by itself once its droplet is up; one that does not answer keeps its state and the result says `healthy: false`. Deploy and Update do not read the address: a new droplet has none for a while, so ask with `check`. | |
| 87 | `check` (`POST /api/v1/admin/pinned/:name/check`, MCP `pinned_forge` verb `check`, terminal `c`) reads the machine from its cloud (read-only, no write permission needed) and records its public IPv4 (`pinned_forge.address`, validated as IPv4). It then asks DNS for the forge's name. Until the name resolves to that address the result is `healthy: false`, `waiting: "dns"` with the record to create, and nothing is sent anywhere: the probe only ever goes to the machine this forge made. Once it does, Check probes `https://<host>/`; no answer yet is `waiting: "answer"` (the machine is booting, or its certificate is not issued). Every view carries `url` (`https://<host>/`) and `dns`. A forge that answers is set `running`, so a `failed` one recovers by itself once its machine is up; one that does not answer keeps its state. A deploy and a new claim read the address once, so their answer can name the record; a cloud that has not assigned one yet leaves it to `check`. | |
| 88 | ||
| 89 | ## One at a time | |
| 90 | ||
| 91 | Every create (a deploy, and the machine an Update, Roll back or new claim link makes) is held to its cloud account's ceiling (`src/cloud/ceiling.ts`, set on `/settings/cloud`). A forge is priced from the one catalog of places (`src/cloud/places.ts`, `GET /api/v1/places`): what the provider's own API last said its size costs where the drivers order it, with its volume and address, converted at the day's rate and rounded up. The forge reads the catalog again before a create when it is stale or was never read; a size it still has no price for is refused, never counted as free. Creates on one account run one after the other from the ceiling check until the machine is recorded, so two asked together cannot both fit where one does. Changes to one forge run one after the other too: two new claim links asked together make two replacements in turn, never two machines at once, and the second link is the one that works. | |
| 54 | 92 | |
| 55 | 93 | ## Failing half-way |
| 56 | 94 | |
| @@ -59,7 +97,11 @@ Each id is recorded the moment it exists. A first deploy that fails before a dro | ||
| 59 | 97 | ## Not done |
| 60 | 98 | |
| 61 | 99 | - No canary result on a real account yet: the script is written, the run needs an owner's token (#8746, see Canary). |
| 62 | - No TLS or domain: the URL is `http://<droplet IPv4>:<PORT or 3000>/`. | |
| 100 | - The DNS record is made by hand, and again after each Update, Roll back or new claim link, because a replaced machine has a new address. A reserved address, or writing the record through an attached Cloudflare account, would end that; neither is written. | |
| 101 | - The boot config (the hardened unit, ufw, the sandbox profile, Caddy from Ubuntu 24.04's repository and its certificate) has not run on a real machine: it was written with no network. The first real deploy is the check, with the list above and the canary below. | |
| 102 | - A forge that answered and then stays unreachable for good (its machine broken, unclaimed) cannot be updated, rolled back or reissued from here: the forge will not guess that nobody claimed it. Nothing overrides that yet; the way out is to make it answer, or to deploy another. | |
| 103 | - A forge claimed on a machine that never answered this forge (the buyer used the link before the seller's DNS view or any Check or change reached it, and it is unreachable now) is not known to be claimed, and may still be replaced. Its data is on the volume and its admin stays; a new seed is ignored. | |
| 104 | - No provider firewall, and no way to give the deployer a shell: an optional deployer-supplied SSH key is not accepted. | |
| 63 | 105 | - AWS and Azure drivers. |
| 64 | 106 | |
| 65 | 107 | ## Canary (#8746) |
| @@ -67,7 +109,7 @@ Each id is recorded the moment it exists. A first deploy that fails before a dro | ||
| 67 | 109 | The driver is tested against a fake API only. `scripts/pinned-canary.ts` runs one real Deploy, Update and Rollback through the admin API, times each, and fails past 10 minutes or when a version or state is not the asked one: |
| 68 | 110 | |
| 69 | 111 | |
| 70 | FORGE_TOKEN=<admin token> bun scripts/pinned-canary.ts https://your.forge --account <do account, writes allowed> \ | |
| 112 | FORGE_TOKEN=<admin token> bun scripts/pinned-canary.ts https://your.forge --account <do account, writes allowed> --host <a name you control> \ | |
| 71 | 113 | --app owner/name --source https://… --version <commit> --next <second commit or tag> |
| 72 | 114 | |
| 73 | 115 |
docs/threats/automated-attacker.md +6
| @@ -129,3 +129,9 @@ Wants: accounts, spam, resources, or a way to exhaust the forge. | ||
| 129 | 129 | app an admin or an admin's org owns gets the door, so signing up as |
| 130 | 130 | `trevato` and taking the `foundry` slug plants nothing (#14769). |
| 131 | 131 | Enforced by: `test/api-forge-view.test.ts` |
| 132 | - A forge deployed to a cloud is claimed only with the one-time link its | |
| 133 | deployer was shown: the machine's boot config, readable through the cloud's | |
| 134 | API, holds the link's sha256 and never the link, the forge listens on | |
| 135 | loopback behind a proxy that serves its one name over HTTPS, and a scanner | |
| 136 | that finds it first gets the refusal any wrong code gets (#16217). | |
| 137 | Enforced by: `test/pinned-claim.test.ts` |
scripts/pinned-canary.ts +11 −7
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | /** |
| 2 | * `bun scripts/pinned-canary.ts <forge url> --account <name> --app <owner/name> --source <https git url> | |
| 2 | * `bun scripts/pinned-canary.ts <forge url> --account <name> --host <dns name> --app <owner/name> --source <https git url> | |
| 3 | 3 | * --version <40-hex or vX.Y.Z> --next <second version> [--name <pinned name>] [--budget <seconds>]` |
| 4 | 4 | * |
| 5 | 5 | * The canary for pinned forges (#8746): one real Deploy, Update and Rollback |
| @@ -10,6 +10,10 @@ | ||
| 10 | 10 | * into docs/features/pinned-forge.md ("Canary results") and exits 1 when a step |
| 11 | 11 | * fails, a version is not the one asked for, or the budget is spent. |
| 12 | 12 | * |
| 13 | * `--host` is the name the forge is served on; the canary times the cloud's | |
| 14 | * calls and does not wait for DNS, a certificate or a claim, and it drops the | |
| 15 | * deploy's one-time claim link unread. | |
| 16 | * | |
| 13 | 17 | * It creates a droplet and a volume the driver cannot delete: remove them in |
| 14 | 18 | * the cloud console afterwards (the report names the ids). |
| 15 | 19 | */ |
| @@ -38,12 +42,12 @@ const text = (v: unknown): string => (typeof v === "string" ? v : ""); | ||
| 38 | 42 | export async function canary( |
| 39 | 43 | call: Call, |
| 40 | 44 | now: () => number, |
| 41 | o: { name: string; account: string; app: string; source: string; version: string; next: string; budget: number }, | |
| 45 | o: { name: string; host: string; account: string; app: string; source: string; version: string; next: string; budget: number }, | |
| 42 | 46 | ): Promise<Report> { |
| 43 | 47 | const steps: Step[] = []; |
| 44 | 48 | const t0 = now(); |
| 45 | 49 | const plan: Array<[string, string, unknown, string]> = [ |
| 46 | ["deploy", "/api/v1/admin/pinned", { name: o.name, target: "digitalocean", account: o.account, app: o.app, source: o.source, version: o.version }, o.version], | |
| 50 | ["deploy", "/api/v1/admin/pinned", { name: o.name, host: o.host, target: "digitalocean", account: o.account, app: o.app, source: o.source, version: o.version }, o.version], | |
| 47 | 51 | ["update", `/api/v1/admin/pinned/${o.name}/update`, { version: o.next }, o.next], |
| 48 | 52 | ["rollback", `/api/v1/admin/pinned/${o.name}/rollback`, {}, o.version], |
| 49 | 53 | ]; |
| @@ -108,10 +112,10 @@ if (import.meta.main) { | ||
| 108 | 112 | }; |
| 109 | 113 | const base = args[0]; |
| 110 | 114 | const token = process.env.FORGE_TOKEN; |
| 111 | const [account, app, source, version, next] = ["--account", "--app", "--source", "--version", "--next"].map(flag); | |
| 115 | const [account, host, app, source, version, next] = ["--account", "--host", "--app", "--source", "--version", "--next"].map(flag); | |
| 112 | 116 | const budget = Number(flag("--budget") ?? 600); |
| 113 | if (!base?.startsWith("http") || !token || !account || !app || !source || !version || !next || !(budget > 0)) { | |
| 114 | console.error("usage: FORGE_TOKEN=<admin token> bun scripts/pinned-canary.ts <forge url> --account <n> --app <owner/name> --source <https url> --version <v> --next <v2> [--name <n>] [--budget <s>]"); | |
| 117 | if (!base?.startsWith("http") || !token || !account || !host || !app || !source || !version || !next || !(budget > 0)) { | |
| 118 | console.error("usage: FORGE_TOKEN=<admin token> bun scripts/pinned-canary.ts <forge url> --account <n> --host <dns name> --app <owner/name> --source <https url> --version <v> --next <v2> [--name <n>] [--budget <s>]"); | |
| 115 | 119 | process.exit(2); |
| 116 | 120 | } |
| 117 | 121 | const call: Call = async (path, body) => { |
| @@ -128,7 +132,7 @@ if (import.meta.main) { | ||
| 128 | 132 | process.exit(2); |
| 129 | 133 | } |
| 130 | 134 | const name = flag("--name") ?? `canary-${new Date().toISOString().slice(0, 19).replace(/\D/g, "").replace(/^(\d{8})/, "$1-")}`; |
| 131 | const report = await canary(call, () => performance.now() / 1000, { name, account, app, source, version, next, budget }); | |
| 135 | const report = await canary(call, () => performance.now() / 1000, { name, host, account, app, source, version, next, budget }); | |
| 132 | 136 | console.log(table(report)); |
| 133 | 137 | if (report.failure) { |
| 134 | 138 | console.error(`FAILED: ${report.failure}\nStill billing, remove in the cloud console: ${leftovers(report)}`); |
src/actions/cloud_ceiling.ts added +22
| @@ -0,0 +1,22 @@ | ||
| 1 | /** | |
| 2 | * The monthly spend ceiling of a cloud account (cloud/ceiling.ts), as a forge admin changes it: | |
| 3 | * whole US dollars, recorded as an event with the old and new value. Anyone who is not a forge | |
| 4 | * admin is told `not_found`. | |
| 5 | */ | |
| 6 | ||
| 7 | import type { App } from "../app.ts"; | |
| 8 | import { getCloudAccount, setCeilingDollars } from "../core/cloud_account.ts"; | |
| 9 | import type { User } from "../core/users.ts"; | |
| 10 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 11 | ||
| 12 | export const MAX_CEILING_DOLLARS = 100_000; | |
| 13 | ||
| 14 | export function setCeiling(app: App, actor: User | undefined, provider: string, name: string, dollars: unknown): Result<string, string> { | |
| 15 | if (actor?.isAdmin !== true) return err("not_found"); | |
| 16 | if (typeof dollars !== "number" || !Number.isInteger(dollars) || dollars < 0 || dollars > MAX_CEILING_DOLLARS) | |
| 17 | return err(`A ceiling is a whole number of US dollars a month, from 0 to ${MAX_CEILING_DOLLARS}.`); | |
| 18 | const before = getCloudAccount(app.db, provider, name); | |
| 19 | if (!before || !setCeilingDollars(app.db, provider, name, dollars)) return err("No such credential."); | |
| 20 | app.bus.append({ kind: "cloud.ceiling", actorId: actor.id, payload: { provider, name, from: before.ceilingDollars, to: dollars } }); | |
| 21 | return ok(`ceiling is $${dollars} a month`); | |
| 22 | } |
src/actions/pinned.ts +302 −56
| @@ -7,38 +7,99 @@ | ||
| 7 | 7 | * change is recorded with who and when before the cloud is touched; if the |
| 8 | 8 | * cloud refuses, the record stays and the forge says `failed`, so nothing |
| 9 | 9 | * moves without a line saying so. |
| 10 | * | |
| 11 | * A forge is deployed for one person (#16217). `deploy` names the host it is | |
| 12 | * served on and answers, once, with a claim link on that name: the only way to | |
| 13 | * become the new forge's first admin. This forge keeps the link's sha256 and | |
| 14 | * deadline (the machine is booted with the same two, `cloud/machine.ts`) and | |
| 15 | * never the link, so it can say whether the claim stands and issue another, | |
| 16 | * and nothing it stores opens the forge. `claim` issues a fresh link for a | |
| 17 | * forge nobody has claimed: the machine is replaced on its volume, as an | |
| 18 | * Update replaces it, because new boot config is the only way a new hash | |
| 19 | * reaches a machine nobody can sign in to; the link before it is dead from | |
| 20 | * that boot on. The row takes the new hash only when the machine that holds | |
| 21 | * it exists, so a replacement the cloud refuses issues nothing and leaves | |
| 22 | * the claim as it was. `check` says what the forge waits for (its address, its DNS | |
| 23 | * record, its certificate) and, once it answers, what became of the claim, as | |
| 24 | * the deployed forge itself reports it. | |
| 10 | 25 | */ |
| 11 | 26 | |
| 27 | import { resolve4 } from "node:dns/promises"; | |
| 12 | 28 | import type { App } from "../app.ts"; |
| 13 | 29 | import { gatedFetch } from "../cloud/gate.ts"; |
| 30 | import { capped, CeilingRefusal } from "../cloud/ceiling.ts"; | |
| 14 | 31 | import { driverOf } from "../cloud/drivers.ts"; |
| 15 | import { provision, read, replace } from "../cloud/machine.ts"; | |
| 32 | import { orderable, provision, read, replace } from "../cloud/machine.ts"; | |
| 16 | 33 | import type { Fetch } from "../cloud/providers.ts"; |
| 17 | 34 | import { target as targetOf } from "../cloud/targets.ts"; |
| 18 | 35 | import { getCloudAccount, secretNameOf } from "../core/cloud_account.ts"; |
| 36 | import { FIRST_ADMIN_SEED_TTL_MS, firstAdminLink, newFirstAdminCode, type SeedState } from "../core/first_admin.ts"; | |
| 19 | 37 | import { |
| 20 | APP, CLAIMED_REFUSAL, NAME, changesOf, checkConfig, getPinned, insertPinned, listPinned, previousOf, | |
| 21 | dropPinned, markClaimed, recordChange, setRemote, urlOf, validSource, validVersion, type Change, type Pinned, | |
| 38 | APP, CLAIMED_REFUSAL, NAME, changesOf, checkConfig, dnsRecordOf, getPinned, insertPinned, listPinned, previousOf, | |
| 39 | dropPinned, markClaimed, markReached, recordChange, setClaim, setHost, setRemote, urlOf, validHost, validSource, validVersion, unconfirmedRefusal, type Change, type Pinned, | |
| 22 | 40 | } from "../core/pinned.ts"; |
| 23 | 41 | import { resolveSecrets } from "../core/secret_store.ts"; |
| 24 | 42 | import type { User } from "../core/users.ts"; |
| 25 | 43 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 26 | 44 | import { boundedSignal } from "../kernel/fetch_timeout.ts"; |
| 45 | import { refreshIfDue } from "./places_refresh.ts"; | |
| 46 | import { oneAtATime } from "../spawn/own_code.ts"; | |
| 27 | 47 | |
| 28 | /** Swapped in tests; the real forge always uses `fetch`. */ | |
| 29 | export const net: { fetch: Fetch; probe: Fetch } = { fetch: (u, i) => fetch(u, { ...i, signal: boundedSignal(i?.signal) }), probe: (u, i) => fetch(u, { ...i, signal: boundedSignal(i?.signal) }) }; | |
| 48 | /** Swapped in tests; the real forge always uses `fetch`, and asks DNS for a name's A records. */ | |
| 49 | export const net: { fetch: Fetch; probe: Fetch; resolve: (host: string) => Promise<string[]> } = { | |
| 50 | fetch: (u, i) => fetch(u, { ...i, signal: boundedSignal(i?.signal) }), | |
| 51 | probe: (u, i) => fetch(u, { ...i, signal: boundedSignal(i?.signal) }), | |
| 52 | resolve: (host) => resolve4(host).catch(() => []), | |
| 53 | }; | |
| 30 | 54 | |
| 31 | 55 | const admin = (a: User | undefined): Result<User, string> => (a?.isAdmin ? ok(a) : err("not_found")); |
| 32 | 56 | |
| 33 | export interface PinnedView extends Pinned { | |
| 34 | /** Where it is served, once the droplet's address is read; empty before. */ | |
| 57 | export interface PinnedView extends Omit<Pinned, "claimHash"> { | |
| 58 | /** Where it is served: HTTPS on its name; empty for a forge deployed before it had one. */ | |
| 35 | 59 | readonly url: string; |
| 60 | /** | |
| 61 | * The DNS record its name needs, `<host> A <address>`, once the address is read; empty before. | |
| 62 | */ | |
| 63 | readonly dns: string; | |
| 36 | 64 | readonly crew: false; |
| 37 | 65 | readonly autoRelease: false; |
| 38 | 66 | readonly changes: Change[]; |
| 39 | 67 | } |
| 40 | 68 | |
| 41 | const view = (app: App, p: Pinned): PinnedView => ({ ...p, url: urlOf(p), crew: false, autoRelease: false, changes: changesOf(app.db, p.id) }); | |
| 69 | const view = (app: App, p: Pinned): PinnedView => { | |
| 70 | // The hash stays in the row: it is what the deployed forge answers a claim question to. | |
| 71 | const { claimHash: _kept, ...shown } = p; | |
| 72 | return { ...shown, url: urlOf(p), dns: dnsRecordOf(p), crew: false, autoRelease: false, changes: changesOf(app.db, p.id) }; | |
| 73 | }; | |
| 74 | ||
| 75 | /** A claim just issued: the link is in this value and nowhere else, so it is shown once. */ | |
| 76 | export interface IssuedClaim { | |
| 77 | /** `https://<host>/first-admin#<code>`: the code rides the fragment, which no request carries. */ | |
| 78 | readonly link: string; | |
| 79 | readonly expiresAt: string; | |
| 80 | } | |
| 81 | ||
| 82 | export type Issued = PinnedView & { readonly claim: IssuedClaim }; | |
| 83 | ||
| 84 | const HOST_WORDS = "A hostname is a full DNS name you control, such as forge.example.com: lowercase letters, digits, dashes and dots."; | |
| 85 | const NAMELESS = "This forge was deployed before forges had names: issue a claim for it with a hostname first."; | |
| 86 | ||
| 87 | /** The name asked for, or why it cannot be this forge's: one forge a name. */ | |
| 88 | function hostFor(app: App, name: string, raw: string): Result<string, string> { | |
| 89 | const host = raw.trim().toLowerCase(); | |
| 90 | if (!validHost(host)) return err(HOST_WORDS); | |
| 91 | if (listPinned(app.db).some((q) => q.host === host && q.name !== name)) return err("Another pinned forge is served on that name."); | |
| 92 | return ok(host); | |
| 93 | } | |
| 94 | ||
| 95 | /** | |
| 96 | * A new code with its hash and deadline; the code leaves this module only inside an `IssuedClaim`. | |
| 97 | */ | |
| 98 | function newClaim(now = Date.now()): { code: string; hash: string; expires: string } { | |
| 99 | return { ...newFirstAdminCode(), expires: new Date(now + FIRST_ADMIN_SEED_TTL_MS).toISOString() }; | |
| 100 | } | |
| 101 | ||
| 102 | const issued = (app: App, p: Pinned, code: string): Issued => ({ ...view(app, p), claim: { link: firstAdminLink(urlOf(p), code), expiresAt: p.claimExpires } }); | |
| 42 | 103 | |
| 43 | 104 | export function pinnedForges(app: App, actor: User | undefined): Result<PinnedView[], string> { |
| 44 | 105 | const who = admin(actor); |
| @@ -50,16 +111,47 @@ async function withCloud<T>(app: App, who: User, p: Pinned, purpose: string, go: | ||
| 50 | 111 | const account = getCloudAccount(app.db, p.target, p.account); |
| 51 | 112 | if (!account) return err("No such cloud account."); |
| 52 | 113 | if (writes && !account.writeAllowed) return err("That cloud account is read-only; allow writes on it first."); |
| 114 | // A create is priced from the Places catalog (`cloud/ceiling.ts`): read again here when it is | |
| 115 | // stale or was never read, so a forge nobody has opened Places on still knows what things cost. | |
| 116 | if (writes) await refreshIfDue(app, who); | |
| 53 | 117 | const secret = secretNameOf(account.provider, account.name); |
| 54 | 118 | const token = resolveSecrets(app.db, app.config.dataDir, app.bus, [secret], { actor: who.id, run: `pinned:${purpose}` })[secret]; |
| 55 | 119 | if (token === undefined) return err("No such credential."); |
| 56 | 120 | try { |
| 57 | 121 | return ok(await go(gatedFetch(app.db, { provider: p.target, account: p.account }, `pinned:${purpose}`, net.fetch), token)); |
| 58 | 122 | } catch (e) { |
| 123 | if (e instanceof CeilingRefusal) return err(e.message); | |
| 59 | 124 | return err(`The cloud refused: ${e instanceof Error ? e.message.slice(0, 200) : "failed"}`); |
| 60 | 125 | } |
| 61 | 126 | } |
| 62 | 127 | |
| 128 | /** | |
| 129 | * Make a machine for `p`, one create at a time per cloud account. The ceiling is checked inside | |
| 130 | * `go` (`capped`) against the machines the rows say exist, and a machine only counts once | |
| 131 | * `record` has written it: held in one turn, the check of the next create sees this one's cost, so | |
| 132 | * two deploys asked together cannot both fit under a ceiling with room for one. The turn ends on | |
| 133 | * every path. A create that did not happen marks the forge `failed` only when the row no longer | |
| 134 | * says what runs: it left the forge with no machine (a first deploy, or a replacement whose old | |
| 135 | * machine was already deleted), or the pin had `moved` for it (an Update or Rollback, recorded | |
| 136 | * before the cloud is asked). One refused with nothing changed, here or at the cloud, leaves a | |
| 137 | * running forge as it was, with the refusal as the answer. | |
| 138 | */ | |
| 139 | function create<T>(app: App, who: User, p: Pinned, purpose: string, go: (f: Fetch, token: string) => Promise<T>, record: (made: T) => void, moved = false): Promise<Result<T, string>> { | |
| 140 | return oneAtATime(app, `pinned-account:${p.target}/${p.account}`, async () => { | |
| 141 | const made = await withCloud(app, who, p, purpose, go); | |
| 142 | if (made.ok) record(made.value); | |
| 143 | else if (moved || getPinned(app.db, p.name)?.remote === "") setRemote(app.db, p.name, { state: "failed" }); | |
| 144 | return made; | |
| 145 | }); | |
| 146 | } | |
| 147 | ||
| 148 | /** | |
| 149 | * One change at a time per forge: an Update, a Rollback and a new claim link each delete a machine | |
| 150 | * and make one, and two of them together would each do both. The second reads the row the first | |
| 151 | * left. | |
| 152 | */ | |
| 153 | const oneChange = <T>(app: App, name: string, go: () => Promise<T>): Promise<T> => oneAtATime(app, `pinned-forge:${name}`, go); | |
| 154 | ||
| 63 | 155 | /** |
| 64 | 156 | * Read the machine back and record its public IPv4 (empty while none is assigned). The cloud's |
| 65 | 157 | * refusal is returned, so "no address yet" and "the call was refused" differ. |
| @@ -76,8 +168,8 @@ async function readAddress(app: App, who: User, name: string): Promise<Result<st | ||
| 76 | 168 | export async function deployPinned( |
| 77 | 169 | app: App, |
| 78 | 170 | actor: User | undefined, |
| 79 | input: { name: string; target: string; account: string; app: string; source: string; version: string; config?: unknown }, | |
| 80 | ): Promise<Result<PinnedView, string>> { | |
| 171 | input: { name: string; host: string; target: string; account: string; app: string; source: string; version: string; config?: unknown }, | |
| 172 | ): Promise<Result<Issued, string>> { | |
| 81 | 173 | const who = admin(actor); |
| 82 | 174 | if (!who.ok) return who; |
| 83 | 175 | const t = targetOf(input.target); |
| @@ -85,6 +177,8 @@ export async function deployPinned( | ||
| 85 | 177 | if (t.status === "refused") return err(t.refused); |
| 86 | 178 | if (t.status !== "first") return err(`${t.label} is not written yet: ${t.refused}`); |
| 87 | 179 | if (!NAME.test(input.name)) return err("A name is lowercase letters, digits and dashes, starting with a letter."); |
| 180 | const host = hostFor(app, input.name, input.host); | |
| 181 | if (!host.ok) return host; | |
| 88 | 182 | if (!APP.test(input.app)) return err("Name the app as owner/name."); |
| 89 | 183 | if (!validSource(input.source)) return err("The source is an https git address."); |
| 90 | 184 | if (!validVersion(input.version)) return err("A version is a full 40-character commit id or a tag like v1.2.3."); |
| @@ -95,24 +189,35 @@ export async function deployPinned( | ||
| 95 | 189 | const old = getPinned(app.db, input.name); |
| 96 | 190 | if (old && !(old.state === "failed" && old.remote === "" && old.target === t.id)) return err("A pinned forge has that name already."); |
| 97 | 191 | if (old) dropPinned(app.db, old.name); |
| 98 | const p = insertPinned(app.db, { ...input, target: t.id, config: config.value }, who.value.id); | |
| 192 | const claim = newClaim(); | |
| 193 | const p = insertPinned(app.db, { ...input, target: t.id, config: config.value, host: host.value, claimHash: claim.hash, claimExpires: claim.expires }, who.value.id); | |
| 99 | 194 | app.bus.append({ kind: "pinned.deployed", actorId: who.value.id, payload: { name: p.name, target: p.target, version: p.version } }); |
| 100 | 195 | if (old?.volume) setRemote(app.db, p.name, { volume: old.volume }); |
| 101 | const made = await withCloud(app, who.value, p, "deploy", (f, token) => | |
| 102 | provision(driverOf(p.target), f, token, getPinned(app.db, p.name)!, { | |
| 103 | ...(old?.volume ? { have: old.volume } : {}), | |
| 104 | onVolume: (volume) => setRemote(app.db, p.name, { volume }), | |
| 105 | }), | |
| 196 | const made = await create( | |
| 197 | app, who.value, p, "deploy", | |
| 198 | (f, token) => | |
| 199 | provision(capped(app, p.name, driverOf(p.target)), f, token, getPinned(app.db, p.name)!, { | |
| 200 | ...(old?.volume ? { have: old.volume } : {}), | |
| 201 | onVolume: (volume) => setRemote(app.db, p.name, { volume }), | |
| 202 | }), | |
| 203 | (m) => setRemote(app.db, p.name, { ...m, state: "running" }), | |
| 106 | 204 | ); |
| 107 | if (!made.ok) { | |
| 108 | setRemote(app.db, p.name, { state: "failed" }); | |
| 109 | return made; | |
| 110 | } | |
| 111 | setRemote(app.db, p.name, { ...made.value, state: "running" }); | |
| 112 | return ok(view(app, getPinned(app.db, p.name)!)); | |
| 205 | if (!made.ok) return made; | |
| 206 | // One read for the address, so the answer can name the DNS record; a cloud that has not | |
| 207 | // assigned one yet (or refuses the read) leaves it to `check`. | |
| 208 | await readAddress(app, who.value, p.name); | |
| 209 | return ok(issued(app, getPinned(app.db, p.name)!, claim.code)); | |
| 113 | 210 | } |
| 114 | 211 | |
| 115 | async function change( | |
| 212 | const change = ( | |
| 213 | app: App, | |
| 214 | actor: User | undefined, | |
| 215 | name: string, | |
| 216 | kind: "update" | "rollback", | |
| 217 | next: (p: Pinned) => Result<{ version: string; config: Record<string, string> }, string>, | |
| 218 | ): Promise<Result<PinnedView, string>> => oneChange(app, name, () => changeNow(app, actor, name, kind, next)); | |
| 219 | ||
| 220 | async function changeNow( | |
| 116 | 221 | app: App, |
| 117 | 222 | actor: User | undefined, |
| 118 | 223 | name: string, |
| @@ -124,37 +229,42 @@ async function change( | ||
| 124 | 229 | const before = getPinned(app.db, name); |
| 125 | 230 | if (!before) return err("No such pinned forge."); |
| 126 | 231 | if (before.claimedAt !== "") return err(CLAIMED_REFUSAL); |
| 232 | if (before.host === "") return err(NAMELESS); | |
| 127 | 233 | const to = next(before); |
| 128 | 234 | if (!to.ok) return to; |
| 129 | 235 | const same = to.value.version === before.version && JSON.stringify(to.value.config) === JSON.stringify(before.config); |
| 130 | 236 | // A failed forge may be asked again for what it already says, to finish the replacement; nothing new to record. |
| 131 | 237 | if (same && before.state !== "failed") return err("That is what it runs already."); |
| 238 | const ours = await sellersStill(app, who.value, name); | |
| 239 | if (!ours.ok) return ours; | |
| 240 | // Asked of the cloud before the pin moves: what cannot be ordered, or would pass the account's | |
| 241 | // ceiling, is refused while the row and the running machine still agree, and nothing is recorded. | |
| 242 | const fits = await withCloud(app, who.value, before, kind, (f, token) => orderable(capped(app, before.name, driverOf(before.target)), f, token)); | |
| 243 | if (!fits.ok) return fits; | |
| 132 | 244 | if (!same) { |
| 133 | 245 | const c = recordChange(app.db, before, kind, to.value, who.value.id); |
| 134 | 246 | app.bus.append({ kind: kind === "update" ? "pinned.update" : "pinned.rollback", actorId: who.value.id, payload: { name, from: c.fromVersion, to: c.toVersion } }); |
| 135 | 247 | } |
| 136 | 248 | const after = getPinned(app.db, name)!; |
| 137 | const done = await withCloud(app, who.value, after, kind, (f, token) => replace(driverOf(after.target), f, token, after, { onDeleted: () => setRemote(app.db, name, { remote: "", address: "" }) })); | |
| 138 | if (!done.ok) { | |
| 139 | setRemote(app.db, name, { state: "failed" }); | |
| 140 | return done; | |
| 141 | } | |
| 142 | setRemote(app.db, name, { ...done.value, address: "", state: "running" }); | |
| 249 | const done = await create( | |
| 250 | app, who.value, after, kind, | |
| 251 | (f, token) => replace(capped(app, after.name, driverOf(after.target)), f, token, after, { onDeleted: () => setRemote(app.db, name, { remote: "", address: "" }) }), | |
| 252 | (m) => setRemote(app.db, name, { ...m, address: "", state: "running" }), | |
| 253 | true, | |
| 254 | ); | |
| 255 | if (!done.ok) return done; | |
| 143 | 256 | return ok(view(app, getPinned(app.db, name)!)); |
| 144 | 257 | } |
| 145 | 258 | |
| 146 | 259 | /** |
| 147 | * The forge was handed to its buyer. From here Update and Rollback are refused for it; the buyer's | |
| 148 | * forge fetches its own versions. Recorded with who and when; claiming twice says so. | |
| 260 | * The forge is its buyer's (#16220): the deployed forge said its claim was used. Nobody here can | |
| 261 | * say so by hand; `reach` is the one source. Recorded once, with the admin whose check or claim | |
| 262 | * learnt it, and from then Update, Rollback and a new claim link are refused for it | |
| 263 | * (`CLAIMED_REFUSAL`): the buyer's forge takes its own versions, and no machine of theirs is | |
| 264 | * replaced from here. | |
| 149 | 265 | */ |
| 150 | export function claimPinned(app: App, actor: User | undefined, name: string): Result<PinnedView, string> { | |
| 151 | const who = admin(actor); | |
| 152 | if (!who.ok) return who; | |
| 153 | const p = getPinned(app.db, name); | |
| 154 | if (!p) return err("No such pinned forge."); | |
| 155 | if (!markClaimed(app.db, name)) return err("That forge was handed over already."); | |
| 156 | app.bus.append({ kind: "pinned.claimed", actorId: who.value.id, payload: { name } }); | |
| 157 | return ok(view(app, getPinned(app.db, name)!)); | |
| 266 | function noteClaimed(app: App, who: User, name: string): void { | |
| 267 | if (markClaimed(app.db, name)) app.bus.append({ kind: "pinned.claimed", actorId: who.id, payload: { name } }); | |
| 158 | 268 | } |
| 159 | 269 | |
| 160 | 270 | /** The only door to a new version or config. Either may be left as it is. */ |
| @@ -179,12 +289,157 @@ export const rollbackPinned = (app: App, actor: User | undefined, name: string): | ||
| 179 | 289 | }); |
| 180 | 290 | |
| 181 | 291 | /** |
| 182 | * The health check: read the droplet's address back, ask the forge there for | |
| 183 | * its front page, and say what it answered. A forge that answers is `running`, | |
| 184 | * so one marked `failed` by a refused call recovers by itself once its droplet | |
| 185 | * is up; one that does not answer keeps its state, and `healthy` is false. | |
| 292 | * A fresh claim for a forge nobody has claimed (its link expired unused, or was lost). The new | |
| 293 | * hash is recorded, then the machine is replaced on its volume with boot config that carries it; | |
| 294 | * the deployed forge takes the new seed at boot and the code before it is gone. Refused for a forge | |
| 295 | * that was claimed, as Update and Rollback are: recorded here already, or said by the forge itself | |
| 296 | * now, which records it. A forge deployed before forges had names is given `host` | |
| 297 | * here, once. | |
| 186 | 298 | */ |
| 187 | export async function checkPinned(app: App, actor: User | undefined, name: string): Promise<Result<PinnedView & { healthy: boolean }, string>> { | |
| 299 | export const claimPinned = (app: App, actor: User | undefined, name: string, input: { host?: string | undefined } = {}): Promise<Result<Issued, string>> => | |
| 300 | oneChange(app, name, () => claimNow(app, actor, name, input)); | |
| 301 | ||
| 302 | async function claimNow(app: App, actor: User | undefined, name: string, input: { host?: string | undefined }): Promise<Result<Issued, string>> { | |
| 303 | const who = admin(actor); | |
| 304 | if (!who.ok) return who; | |
| 305 | const before = getPinned(app.db, name); | |
| 306 | if (!before) return err("No such pinned forge."); | |
| 307 | if (before.claimedAt !== "") return err(CLAIMED_REFUSAL); | |
| 308 | const asked = (input.host ?? "").trim().toLowerCase(); | |
| 309 | if (before.host === "" && asked === "") return err(NAMELESS); | |
| 310 | if (before.host !== "" && asked !== "" && asked !== before.host) return err(`This forge is served on ${before.host}; its name does not change.`); | |
| 311 | const host = before.host === "" ? hostFor(app, name, asked) : ok(before.host); | |
| 312 | if (!host.ok) return host; | |
| 313 | if (before.volume === "") return err("This forge never reached a machine; deploy it again, which issues a claim."); | |
| 314 | // Named in the same breath as the check above, before anything is awaited: one forge a name. | |
| 315 | if (before.host === "") setHost(app.db, name, host.value); | |
| 316 | const ours = await sellersStill(app, who.value, name); | |
| 317 | if (!ours.ok) return ours; | |
| 318 | const claim = newClaim(); | |
| 319 | // The machine is booted from the row as it will be. The row itself takes the new hash once that | |
| 320 | // machine exists: a replacement the cloud refuses then issues nothing, and the claim it had | |
| 321 | // stands. | |
| 322 | const after: Pinned = { ...getPinned(app.db, name)!, claimHash: claim.hash, claimExpires: claim.expires }; | |
| 323 | const done = await create( | |
| 324 | app, who.value, after, "claim", | |
| 325 | (f, token) => replace(capped(app, after.name, driverOf(after.target)), f, token, after, { onDeleted: () => setRemote(app.db, name, { remote: "", address: "" }) }), | |
| 326 | (m) => { | |
| 327 | setClaim(app.db, name, { hash: claim.hash, expires: claim.expires }); | |
| 328 | setRemote(app.db, name, { ...m, address: "", state: "running" }); | |
| 329 | }, | |
| 330 | ); | |
| 331 | if (!done.ok) return done; | |
| 332 | app.bus.append({ kind: "pinned.claim_issued", actorId: who.value.id, payload: { name, expires: claim.expires } }); | |
| 333 | await readAddress(app, who.value, name); | |
| 334 | return ok(issued(app, getPinned(app.db, name)!, claim.code)); | |
| 335 | } | |
| 336 | ||
| 337 | /** | |
| 338 | * What a forge is waiting for before it can answer: a `name` (deployed before forges had one), its | |
| 339 | * machine's `address`, the `dns` record that points the name at it, or an `answer` (the machine is | |
| 340 | * still booting, or its certificate is not issued yet). Empty when it answers. | |
| 341 | */ | |
| 342 | export type Waiting = "" | "name" | "address" | "dns" | "answer"; | |
| 343 | /** What became of the claim, as the deployed forge says; `unknown` while it cannot be asked. */ | |
| 344 | export type ClaimState = SeedState | "unknown"; | |
| 345 | ||
| 346 | /** | |
| 347 | * Ask the forge on its name. Nothing is sent until the name resolves to the address its cloud | |
| 348 | * reported, so the probe and the claim question only ever go to the machine this forge made. The | |
| 349 | * claim question carries the hash, which the deployed forge already holds, and never the link. | |
| 350 | */ | |
| 351 | async function reach(app: App, p: Pinned): Promise<{ waiting: Waiting; claim: ClaimState }> { | |
| 352 | if (p.host === "") return { waiting: "name", claim: "unknown" }; | |
| 353 | if (p.address === "") return { waiting: "address", claim: "unknown" }; | |
| 354 | if (!(await net.resolve(p.host)).includes(p.address)) return { waiting: "dns", claim: "unknown" }; | |
| 355 | // Audited like every other call made for this account; the host is a validated name. | |
| 356 | const probe = gatedFetch(app.db, { provider: p.target, account: p.account }, "pinned:probe", net.probe); | |
| 357 | const ask = (path: string): Promise<Response> => probe(`${urlOf(p)}${path}`, { signal: AbortSignal.timeout(5_000), redirect: "manual" }); | |
| 358 | try { | |
| 359 | const front = await ask(""); | |
| 360 | if (front.status < 200 || front.status >= 400) return { waiting: "answer", claim: "unknown" }; | |
| 361 | } catch { | |
| 362 | return { waiting: "answer", claim: "unknown" }; | |
| 363 | } | |
| 364 | if (p.claimHash === "") return { waiting: "", claim: "unknown" }; | |
| 365 | try { | |
| 366 | const said = await ask(`api/v1/first-admin/claim?seed=${p.claimHash}`); | |
| 367 | const state: unknown = said.ok ? ((await said.json()) as { state?: unknown }).state : undefined; | |
| 368 | return { waiting: "", claim: state === "waiting" || state === "claimed" || state === "expired" ? state : "unknown" }; | |
| 369 | } catch { | |
| 370 | return { waiting: "", claim: "unknown" }; | |
| 371 | } | |
| 372 | } | |
| 373 | ||
| 374 | /** | |
| 375 | * Ask the forge and keep what it said: a definite answer about its claim (waiting, claimed or | |
| 376 | * expired) is remembered against the machine that gave it, and `claimed` is recorded once | |
| 377 | * (`noteClaimed`). Check, and every change that would replace the machine, hear it through here. | |
| 378 | */ | |
| 379 | async function hear(app: App, who: User, p: Pinned): Promise<{ waiting: Waiting; claim: ClaimState }> { | |
| 380 | const heard = await reach(app, p); | |
| 381 | if (heard.claim === "unknown") return heard; | |
| 382 | if (p.remote !== "") markReached(app.db, p.name, p.remote); | |
| 383 | if (heard.claim === "claimed") noteClaimed(app, who, p.name); | |
| 384 | return heard; | |
| 385 | } | |
| 386 | ||
| 387 | /** | |
| 388 | * Whether the seller may still replace this forge's machine (an Update, a Rollback, a new claim | |
| 389 | * link): asked of the forge itself, at the address its cloud reports now, never taken from the row | |
| 390 | * alone. `claimed` is refused and recorded. No answer is refused too once the forge's current | |
| 391 | * machine has answered before: silence from a forge that was reachable may be a buyer's forge | |
| 392 | * behind a broken DNS record, and its machine is not replaced on a guess. A forge whose current | |
| 393 | * machine has never answered (still booting, its DNS not pointed yet, a first boot that failed), | |
| 394 | * one with no machine or whose machine is gone, and one deployed before claims, may still be replaced: there is nobody to | |
| 395 | * have claimed it through this forge's link, and it could not be recovered otherwise. | |
| 396 | */ | |
| 397 | async function sellersStill(app: App, who: User, name: string): Promise<Result<true, string>> { | |
| 398 | // A read the cloud refuses is not "no address": the forge could not be asked, so the change is | |
| 399 | // refused with the cloud's answer before anything is recorded. A machine that is gone (404) has | |
| 400 | // nobody to ask, and replacing it is how it comes back. | |
| 401 | const read = await readAddress(app, who, name); | |
| 402 | if (!read.ok && !read.error.endsWith("answered 404")) return read; | |
| 403 | const p = getPinned(app.db, name)!; | |
| 404 | const heard = await hear(app, who, p); | |
| 405 | if (heard.claim === "claimed") return err(CLAIMED_REFUSAL); | |
| 406 | if (heard.claim === "unknown" && p.claimHash !== "" && p.remote !== "" && p.reached === p.remote) return err(unconfirmedRefusal(p)); | |
| 407 | return ok(true); | |
| 408 | } | |
| 409 | ||
| 410 | export type Checked = PinnedView & { readonly healthy: boolean; readonly waiting: Waiting; readonly claim: ClaimState }; | |
| 411 | ||
| 412 | /** What a check found, in the one sentence every door says. */ | |
| 413 | export function checkWords(v: Checked): string { | |
| 414 | if (v.waiting === "name") return `${v.name} has no name to be served on: issue a claim for it with a hostname.`; | |
| 415 | if (v.waiting === "address") return `${v.name} has no address yet; check again in a minute.`; | |
| 416 | if (v.waiting === "dns") return `${v.name} is waiting for DNS: create the record ${v.dns} (DNS only, not proxied), then check again.`; | |
| 417 | if (v.waiting === "answer") return `${v.name} does not answer at ${v.url} yet: its certificate is issued once the name resolves to it, which takes a few minutes.`; | |
| 418 | const claim = | |
| 419 | v.claim === "claimed" ? " It has been claimed: it is its buyer's, and Update, Roll back and a new claim link are refused from here." | |
| 420 | : v.claim === "waiting" ? ` Its claim link has not been used; it works until ${v.claimExpires}.` | |
| 421 | : v.claim === "expired" ? " Its claim link can no longer be used: issue a new one." | |
| 422 | : ""; | |
| 423 | return `${v.name} answers at ${v.url}; it is ${v.state}.${claim}`; | |
| 424 | } | |
| 425 | ||
| 426 | /** | |
| 427 | * What to do with a claim just issued, in the sentences every door says; the link itself is shown | |
| 428 | * beside them. | |
| 429 | */ | |
| 430 | export function claimWords(v: Issued): string { | |
| 431 | const dns = v.dns !== "" ? `Create the DNS record ${v.dns} (DNS only, not proxied)` : `Check reads its address; then create the DNS record ${v.host} A <that address>`; | |
| 432 | return `${dns}: the forge gets its own certificate once the name resolves, and is served only at ${v.url}. The claim link makes its first admin: it works once, until ${v.claim.expiresAt}, and is shown only now.`; | |
| 433 | } | |
| 434 | ||
| 435 | /** | |
| 436 | * The health check: read the machine's address back, see that the forge's name | |
| 437 | * resolves to it, ask the forge there for its front page over HTTPS, and say | |
| 438 | * what it answered. A forge that answers is `running`, so one marked `failed` | |
| 439 | * by a refused call recovers by itself once its machine is up; one that does | |
| 440 | * not answer keeps its state, `healthy` is false, and `waiting` says for what. | |
| 441 | */ | |
| 442 | export async function checkPinned(app: App, actor: User | undefined, name: string): Promise<Result<Checked, string>> { | |
| 188 | 443 | const who = admin(actor); |
| 189 | 444 | if (!who.ok) return who; |
| 190 | 445 | const p = getPinned(app.db, name); |
| @@ -193,19 +448,10 @@ export async function checkPinned(app: App, actor: User | undefined, name: strin | ||
| 193 | 448 | const read = await readAddress(app, who.value, name); |
| 194 | 449 | if (!read.ok) return read; |
| 195 | 450 | const now = getPinned(app.db, name)!; |
| 196 | let healthy = false; | |
| 197 | if (now.address !== "") { | |
| 198 | // The probe is audited like every other call made for this account; the address is a validated public IPv4 and the port is 1-65535. | |
| 199 | const probe = gatedFetch(app.db, { provider: now.target, account: now.account }, "pinned:probe", net.probe); | |
| 200 | try { | |
| 201 | const res = await probe(urlOf(now), { signal: AbortSignal.timeout(5_000), redirect: "manual" }); | |
| 202 | healthy = res.status >= 200 && res.status < 400; | |
| 203 | } catch { | |
| 204 | healthy = false; | |
| 205 | } | |
| 206 | } | |
| 451 | const reached = await hear(app, who.value, now); | |
| 452 | const healthy = reached.waiting === ""; | |
| 207 | 453 | if (healthy && now.state !== "running") setRemote(app.db, name, { state: "running" }); |
| 208 | 454 | const after = getPinned(app.db, name)!; |
| 209 | 455 | app.bus.append({ kind: "pinned.check", actorId: who.value.id, payload: { name, address: after.address, state: after.state, healthy } }); |
| 210 | return ok({ ...view(app, after), healthy }); | |
| 456 | return ok({ ...view(app, after), healthy, ...reached }); | |
| 211 | 457 | } |
src/actions/talk.ts +1
| @@ -34,6 +34,7 @@ export const TALK_WORDS: Readonly<Record<TalkRefusal, readonly [number, string]> | ||
| 34 | 34 | answering: [409, "the forge is still answering; send pictures when it has finished"], |
| 35 | 35 | busy: [429, "the forge's agent is answering as many people as it can at once; try again in a minute"], |
| 36 | 36 | off: [503, "the forge's agent is not running here"], |
| 37 | sandbox: [503, "this forge requires the agent sandbox and it is unavailable here, so its agent does not run; an admin sees the cause at the foot of any page"], | |
| 37 | 38 | running: [409, "the forge is still answering; wait for it to finish"], |
| 38 | 39 | nothing: [409, "there is nothing here to do that to"], |
| 39 | 40 | retried: [409, "That turn was already retried."], |
src/app.ts +5
| @@ -75,6 +75,11 @@ export interface ForgeConfig { | ||
| 75 | 75 | codeBudgetMs?: number; |
| 76 | 76 | /** @default 3000 */ |
| 77 | 77 | port?: number; |
| 78 | /** | |
| 79 | * The one IPv4 address the web listener binds (`FORGE_BIND`): `127.0.0.1` on a machine whose | |
| 80 | * proxy is the only thing that should reach the forge. Unset, every interface. | |
| 81 | */ | |
| 82 | bind?: string; | |
| 78 | 83 | /** The hostname clone URLs are built from. @default "localhost" */ |
| 79 | 84 | host?: string; |
| 80 | 85 | /** |
src/cloud/ceiling.ts added +165
| @@ -0,0 +1,165 @@ | ||
| 1 | /** | |
| 2 | * The spend ceiling of a cloud account: what the forge reckons the account costs a month from the | |
| 3 | * forges it made on it and has not retired, and the refusal to make one more thing that would take | |
| 4 | * it over (cloud providers send alerts, not caps, so the forge is the cap). Whole US dollars for | |
| 5 | * the ceiling, whole US cents for money. The check runs in `capped`, the driver's own `plan` step: | |
| 6 | * after what to order is read, before anything is made. | |
| 7 | * | |
| 8 | * There is one source of prices, the Places catalog (#16203, `places.ts`, `places_read.ts`): what | |
| 9 | * each provider's own API last said a place costs, a place being a datacenter and a machine size | |
| 10 | * with the forge's volume and address. The ceiling prices a forge as the place the drivers order | |
| 11 | * it at (`WHERE`), from the vendor's own amount, converted by the catalog's one conversion | |
| 12 | * (`toUsd`) at the rate that stands and rounded up, since this figure guards spending. A size the | |
| 13 | * catalog has no price for, a currency with no rate, and a catalog never read are all the same | |
| 14 | * answer: refused, never counted as free. The forge's reckoning is not the bill; the provider's | |
| 15 | * bill is the truth. | |
| 16 | */ | |
| 17 | ||
| 18 | import type { Database } from "bun:sqlite"; | |
| 19 | import type { App } from "../app.ts"; | |
| 20 | import { getCloudAccount } from "../core/cloud_account.ts"; | |
| 21 | import { getPinned, listPinned, type Pinned } from "../core/pinned.ts"; | |
| 22 | import { REGION, SIZE as DROPLET_SIZE } from "./droplet.ts"; | |
| 23 | import { LOCATION } from "./hetzner.ts"; | |
| 24 | import type { Driver } from "./machine.ts"; | |
| 25 | import { keptPlaces } from "./places_read.ts"; | |
| 26 | import { dollars, toUsd } from "./prices.ts"; | |
| 27 | import { keptRate } from "./rates.ts"; | |
| 28 | ||
| 29 | export const DEFAULT_CEILING_DOLLARS = 50; | |
| 30 | ||
| 31 | /** Where the ceiling is raised, named in every refusal. */ | |
| 32 | export const CEILING_PAGE = "/settings/cloud"; | |
| 33 | ||
| 34 | /** A refusal in words meant to be shown as they are; withCloud passes it on whole. */ | |
| 35 | export class CeilingRefusal extends Error {} | |
| 36 | ||
| 37 | /** The datacenter each driver orders in: with a size, the place a forge is. */ | |
| 38 | const WHERE: Readonly<Record<string, string>> = { digitalocean: REGION, hetzner: LOCATION }; | |
| 39 | ||
| 40 | /** The size each driver orders when it decides nothing at plan time. */ | |
| 41 | const FIXED_SIZE: Readonly<Record<string, string>> = { digitalocean: DROPLET_SIZE }; | |
| 42 | ||
| 43 | /** The size a machine was recorded with at creation; none for a machine made before sizes were kept. */ | |
| 44 | function recordedSize(db: Database, pinnedId: string): string | undefined { | |
| 45 | return db.query<{ size: string }, [string]>("SELECT size FROM pinned_size WHERE pinned_id = ?1").get(pinnedId)?.size; | |
| 46 | } | |
| 47 | ||
| 48 | function noteSize(db: Database, pinnedId: string, size: string): void { | |
| 49 | db.query("INSERT INTO pinned_size (pinned_id, size) VALUES (?1, ?2) ON CONFLICT(pinned_id) DO UPDATE SET size = excluded.size").run(pinnedId, size); | |
| 50 | } | |
| 51 | ||
| 52 | /** | |
| 53 | * The catalog as the ceiling reads it, taken once for a reckoning: what a forge of a size costs a | |
| 54 | * month on a cloud, in US cents rounded up (its machine, its volume and its address, as the | |
| 55 | * catalog's place has them), and the dearest the cloud has where the driver orders. Undefined for | |
| 56 | * a place the catalog does not hold, or holds with no price or no rate. | |
| 57 | */ | |
| 58 | export interface Priced { | |
| 59 | forge(cloud: string, size: string): number | undefined; | |
| 60 | dearest(cloud: string): number | undefined; | |
| 61 | } | |
| 62 | ||
| 63 | export function priced(db: Database): Priced { | |
| 64 | const rate = keptRate(db, "EUR"); | |
| 65 | const cents = new Map<string, number>(); | |
| 66 | for (const p of keptPlaces(db, rate)) { | |
| 67 | // A place the catalog could not price says so with no cost; it is not a place that costs nothing. | |
| 68 | if (p.costCents <= 0 || p.datacenter !== WHERE[p.provider]) continue; | |
| 69 | try { | |
| 70 | cents.set(`${p.provider}:${p.size}`, toUsd(p.price.vendorAmount, p.price.vendorCurrency, rate, "up").usdCents); | |
| 71 | } catch { | |
| 72 | // no rate for its currency: no price | |
| 73 | } | |
| 74 | } | |
| 75 | return { | |
| 76 | forge: (cloud, size) => cents.get(`${cloud}:${size}`), | |
| 77 | dearest: (cloud) => { | |
| 78 | const all = [...cents].filter(([k]) => k.startsWith(`${cloud}:`)).map(([, c]) => c); | |
| 79 | return all.length === 0 ? undefined : Math.max(...all); | |
| 80 | }, | |
| 81 | }; | |
| 82 | } | |
| 83 | ||
| 84 | type Row = Pick<Pinned, "id" | "target" | "remote" | "volume">; | |
| 85 | ||
| 86 | /** | |
| 87 | * What one pinned row costs a month, cents. A row with a machine or a volume is counted as the | |
| 88 | * whole forge of its recorded size: the catalog prices a place whole, and a volume waiting for its | |
| 89 | * machine is about to be one. A machine of no recorded size, or of one the catalog no longer | |
| 90 | * lists, is counted at the dearest the cloud has there: the reckoning errs high. Zero only for a | |
| 91 | * row with nothing made, or when the catalog holds nothing for the cloud at all (then nothing new | |
| 92 | * is admitted either). | |
| 93 | */ | |
| 94 | export function rowCents(db: Database, p: Row, prices: Priced = priced(db)): number { | |
| 95 | if (p.remote === "" && p.volume === "") return 0; | |
| 96 | return prices.forge(p.target, recordedSize(db, p.id) ?? "") ?? prices.dearest(p.target) ?? 0; | |
| 97 | } | |
| 98 | ||
| 99 | /** What the forge reckons an account costs a month, in cents: the sum over its own pinned rows. */ | |
| 100 | export function accountCents(db: Database, provider: string, account: string, prices: Priced = priced(db)): number { | |
| 101 | return listPinned(db) | |
| 102 | .filter((p) => p.target === provider && p.account === account) | |
| 103 | .reduce((sum, p) => sum + rowCents(db, p, prices), 0); | |
| 104 | } | |
| 105 | ||
| 106 | export interface Spend { | |
| 107 | readonly ceilingDollars: number; | |
| 108 | readonly monthlyCents: number; | |
| 109 | /** Cents left under the ceiling; negative when over it. */ | |
| 110 | readonly leftCents: number; | |
| 111 | } | |
| 112 | ||
| 113 | export function spendOf(db: Database, provider: string, account: string, prices: Priced = priced(db)): Spend { | |
| 114 | const ceilingDollars = getCloudAccount(db, provider, account)?.ceilingDollars ?? DEFAULT_CEILING_DOLLARS; | |
| 115 | const monthlyCents = accountCents(db, provider, account, prices); | |
| 116 | return { ceilingDollars, monthlyCents, leftCents: ceilingDollars * 100 - monthlyCents }; | |
| 117 | } | |
| 118 | ||
| 119 | /** | |
| 120 | * Refuse, in a plain sentence, when making the machine named by `plan` for pinned forge `name` | |
| 121 | * would put its account over the ceiling. What the row is already counted at comes off, so a | |
| 122 | * replace of a same-size machine, and the machine of a volume that was waiting for one, add | |
| 123 | * nothing; a forge already over a lowered ceiling may still be replaced by what costs no more. | |
| 124 | */ | |
| 125 | export function admit(app: App, name: string, plan: unknown): void { | |
| 126 | const p = getPinned(app.db, name); | |
| 127 | if (!p) return; | |
| 128 | const who = `${p.target}/${p.account}`; | |
| 129 | const size = typeof plan === "string" ? plan : FIXED_SIZE[p.target]; | |
| 130 | const prices = priced(app.db); | |
| 131 | const price = size === undefined ? undefined : prices.forge(p.target, size); | |
| 132 | if (size === undefined || price === undefined) | |
| 133 | throw new CeilingRefusal( | |
| 134 | `The forge has no price for ${size ?? "the machine"} in ${WHERE[p.target] ?? "its datacenter"} on ${p.target}, so it cannot hold ${who} to its ceiling; nothing was made. ` + | |
| 135 | "Prices come from the provider's own list (Places, GET /api/v1/places), which the forge reads before a create and could not read a price from; try again in a few minutes.", | |
| 136 | ); | |
| 137 | const { ceilingDollars, monthlyCents } = spendOf(app.db, p.target, p.account, prices); | |
| 138 | const add = price - rowCents(app.db, p, prices); | |
| 139 | if (add <= 0 || monthlyCents + add <= ceilingDollars * 100) return; | |
| 140 | throw new CeilingRefusal( | |
| 141 | `${who} is held to $${ceilingDollars} a month and runs ${dollars(monthlyCents)} now; this would add ${dollars(add)}, which is over it, so nothing was made. ` + | |
| 142 | `Raise the ceiling at ${CEILING_PAGE} if you mean to spend more. This is the forge's own reckoning from list prices; the provider's bill is the truth.`, | |
| 143 | ); | |
| 144 | } | |
| 145 | ||
| 146 | /** | |
| 147 | * The driver, held to the account's ceiling: its `plan` checks before the first thing is made, and | |
| 148 | * the size of each machine it makes is kept so a replace can be counted against it. | |
| 149 | */ | |
| 150 | export function capped<P>(app: App, name: string, d: Driver<P>): Driver<P> { | |
| 151 | return { | |
| 152 | ...d, | |
| 153 | async plan(call) { | |
| 154 | const plan = await d.plan(call); | |
| 155 | admit(app, name, plan); | |
| 156 | return plan; | |
| 157 | }, | |
| 158 | async createMachine(call, p, volume, plan) { | |
| 159 | const remote = await d.createMachine(call, p, volume, plan); | |
| 160 | const size = typeof plan === "string" ? plan : FIXED_SIZE[p.target]; | |
| 161 | if (size !== undefined) noteSize(app.db, p.id, size); | |
| 162 | return remote; | |
| 163 | }, | |
| 164 | }; | |
| 165 | } |
src/cloud/droplet.ts +20 −10
| @@ -2,12 +2,13 @@ | ||
| 2 | 2 | * DigitalOcean, the first target (#8697): its calls only; the sequence they |
| 3 | 3 | * run in is machine.ts. |
| 4 | 4 | * |
| 5 | * Calls (DigitalOcean API v2): POST /volumes, POST /droplets, DELETE /droplets/{id}, GET /droplets/{id} | |
| 6 | * (the public IPv4 the droplet was given, read back after it boots). | |
| 5 | * Calls (DigitalOcean API v2): POST /volumes, POST /account/keys and DELETE /account/keys/{id} (a | |
| 6 | * throwaway key, so no root password is mailed), POST /droplets, DELETE /droplets/{id}, GET | |
| 7 | * /droplets/{id} (the public IPv4 the droplet was given, read back after it boots). | |
| 7 | 8 | */ |
| 8 | 9 | |
| 9 | import { bootConfig as boot, ipv4, volumeName, type Driver } from "./machine.ts"; | |
| 10 | import type { Pinned } from "../core/pinned.ts"; | |
| 10 | import { dropThrowawayKey, makeThrowawayKey } from "./throwaway_key.ts"; | |
| 11 | import { bootConfig as boot, ipv4, volumeName, type Booted, type Driver } from "./machine.ts"; | |
| 11 | 12 | |
| 12 | 13 | export { BUN_VERSION } from "./machine.ts"; |
| 13 | 14 | export const REGION = "nyc3"; |
| @@ -16,7 +17,10 @@ export const SIZE = "s-1vcpu-2gb"; | ||
| 16 | 17 | /** DigitalOcean mounts a volume at /mnt/<its name, dashes as underscores>. */ |
| 17 | 18 | const dataDir = (name: string) => `/mnt/${volumeName(name).replace(/-/g, "_")}`; |
| 18 | 19 | |
| 19 | export const bootConfig = (p: Pick<Pinned, "name" | "source" | "version" | "config">): string => boot(p, dataDir(p.name)); | |
| 20 | export const bootConfig = (p: Booted): string => boot(p, dataDir(p.name)); | |
| 21 | ||
| 22 | /** DigitalOcean's collection of account SSH keys. */ | |
| 23 | const KEYS = "/account/keys"; | |
| 20 | 24 | |
| 21 | 25 | export const digitalocean: Driver = { |
| 22 | 26 | api: "https://api.digitalocean.com/v2", |
| @@ -26,11 +30,17 @@ export const digitalocean: Driver = { | ||
| 26 | 30 | return String(v.volume?.id ?? ""); |
| 27 | 31 | }, |
| 28 | 32 | async createMachine(call, p, volume) { |
| 29 | const d = await call("POST", "/droplets", { | |
| 30 | name: `forge-${p.name}`, region: REGION, size: SIZE, image: "ubuntu-24-04-x64", | |
| 31 | volumes: [volume], user_data: bootConfig(p), tags: ["forge-pinned"], | |
| 32 | }); | |
| 33 | return String(d.droplet?.id ?? ""); | |
| 33 | // A droplet made with no SSH key is sent a root password by email; see throwaway_key.ts. | |
| 34 | const key = await makeThrowawayKey(call, KEYS, p.name); | |
| 35 | try { | |
| 36 | const d = await call("POST", "/droplets", { | |
| 37 | name: `forge-${p.name}`, region: REGION, size: SIZE, image: "ubuntu-24-04-x64", | |
| 38 | volumes: [volume], user_data: bootConfig(p), tags: ["forge-pinned"], ssh_keys: [Number(key)], | |
| 39 | }); | |
| 40 | return String(d.droplet?.id ?? ""); | |
| 41 | } finally { | |
| 42 | await dropThrowawayKey(call, KEYS, key); | |
| 43 | } | |
| 34 | 44 | }, |
| 35 | 45 | async deleteMachine(call, remote) { |
| 36 | 46 | await call("DELETE", `/droplets/${remote}`); |
src/cloud/harden.ts added +179
| @@ -0,0 +1,179 @@ | ||
| 1 | /** | |
| 2 | * What the booted machine is (#16218): the pieces of its cloud-config that make a sold forge safe | |
| 3 | * to leave on a public address. `machine.ts` composes them into the one boot config; each is plain | |
| 4 | * text from fixed words and the driver's own mount point, nothing a deployer typed. | |
| 5 | * | |
| 6 | * - The forge runs as `forge`, an unprivileged system user, from a Bun under /opt/bun that root | |
| 7 | * owns, so a hijacked forge cannot rewrite the runtime it starts from. | |
| 8 | * - Only the ports in `PUBLIC_PORTS` are open, enforced on the machine by ufw. SSH is closed. | |
| 9 | * What listens on them is the machine's proxy (Caddy, a packaged service of its own, set up | |
| 10 | * in `machine.ts`), which holds the certificate; the forge itself listens on loopback. | |
| 11 | * - Nobody gets a shell: no password login, no root login, no key accepted (see | |
| 12 | * `throwaway_key.ts` for why a key is sent at all). | |
| 13 | * - Security updates install themselves. | |
| 14 | * - The crew and apps hold their shells in bubblewrap, which needs bubblewrap, socat and an | |
| 15 | * AppArmor profile that lets /usr/bin/bwrap make a user namespace: Ubuntu 24.04 refuses that | |
| 16 | * to every unconfined program, and a sandbox that quietly cannot start is one that does not run | |
| 17 | * (`sandboxAvailable`, src/crew/sandbox.ts, then answers "runs are unrestricted"). | |
| 18 | */ | |
| 19 | ||
| 20 | /** The only ports reachable from the world. A front that terminates TLS listens on these. */ | |
| 21 | export const PUBLIC_PORTS: readonly number[] = [80, 443]; | |
| 22 | /** The account the forge runs as. */ | |
| 23 | export const FORGE_USER = "forge"; | |
| 24 | /** Where Bun is installed: root's, so the forge can run it and cannot change it. */ | |
| 25 | export const BUN_HOME = "/opt/bun"; | |
| 26 | /** The forge's checkout; owned by the forge user, mounted read-only to the running unit. */ | |
| 27 | export const CHECKOUT = "/opt/forge"; | |
| 28 | /** The forge user's home: Bun's cache and the git config live here. */ | |
| 29 | export const FORGE_HOME = "/var/lib/forge"; | |
| 30 | ||
| 31 | /** | |
| 32 | * The mount points the drivers use (/mnt/<letters, digits, underscores>); anything else is refused. | |
| 33 | */ | |
| 34 | const MOUNT = /^\/mnt\/[A-Za-z0-9_]{1,80}$/; | |
| 35 | export function mount(dataDir: string): string { | |
| 36 | if (!MOUNT.test(dataDir)) | |
| 37 | throw new Error("the data directory is not a plain mount point under /mnt"); | |
| 38 | return dataDir; | |
| 39 | } | |
| 40 | ||
| 41 | /** | |
| 42 | * Where the machine's proxy keeps its certificates: on the data volume, so they outlive the | |
| 43 | * machine, and the proxy's own, so the forge's walk below leaves it alone. | |
| 44 | */ | |
| 45 | export const proxyStore = (dataDir: string): string => `${mount(dataDir)}/caddy`; | |
| 46 | ||
| 47 | const indent = (text: string, spaces: number): string => | |
| 48 | text | |
| 49 | .split("\n") | |
| 50 | .map((l) => (l === "" ? l : " ".repeat(spaces) + l)) | |
| 51 | .join("\n"); | |
| 52 | ||
| 53 | /** Top-level cloud-config keys: no password login, no root login, packages, updates. */ | |
| 54 | export function hardenHead(): string { | |
| 55 | return `ssh_pwauth: false | |
| 56 | disable_root: true | |
| 57 | package_update: true | |
| 58 | package_upgrade: true | |
| 59 | packages: | |
| 60 | - bubblewrap | |
| 61 | - caddy | |
| 62 | - socat | |
| 63 | - ufw | |
| 64 | - unattended-upgrades | |
| 65 | - git | |
| 66 | - curl | |
| 67 | - unzip | |
| 68 | - ca-certificates | |
| 69 | `; | |
| 70 | } | |
| 71 | ||
| 72 | /** | |
| 73 | * The systemd unit. `NoNewPrivileges` stays on: Ubuntu's bubblewrap is not setuid, it makes | |
| 74 | * its sandbox with an unprivileged user namespace, and that works under no_new_privs; only a | |
| 75 | * setuid bwrap would not. What the sandbox and the cells still need is left alone: no | |
| 76 | * `RestrictNamespaces`, `PrivateUsers`, `SystemCallFilter`, `PrivateDevices` or | |
| 77 | * `ProtectControlGroups`, and no `MemoryDenyWriteExecute` (Bun's JIT). | |
| 78 | * | |
| 79 | * Nothing here may mask or mount over any part of /proc or /sys. The sandbox mounts a fresh /proc | |
| 80 | * in its own user and pid namespace, and the kernel allows that only to a process whose own /proc | |
| 81 | * is whole: one file hidden (as `ProtectKernelLogs` hides /proc/kmsg) and every sandboxed shell | |
| 82 | * fails to start, which under `FORGE_CREW_SANDBOX=require` holds every run. So no | |
| 83 | * `ProtectKernelLogs`, `ProtectKernelTunables`, `ProtectControlGroups`, `ProtectProc` or | |
| 84 | * `ProcSubset`. `ProtectKernelModules` (hides /usr/lib/modules, drops a capability) and | |
| 85 | * `ProtectClock` (drops a capability, narrows device access) touch neither, and stay. | |
| 86 | */ | |
| 87 | export function serviceUnit( | |
| 88 | name: string, | |
| 89 | version: string, | |
| 90 | dataDir: string, | |
| 91 | ): string { | |
| 92 | const dir = mount(dataDir); | |
| 93 | return `[Unit] | |
| 94 | Description=forge ${name} pinned at ${version} | |
| 95 | After=network-online.target | |
| 96 | RequiresMountsFor=${dir} | |
| 97 | [Service] | |
| 98 | User=${FORGE_USER} | |
| 99 | Group=${FORGE_USER} | |
| 100 | EnvironmentFile=/etc/forge/env | |
| 101 | WorkingDirectory=${CHECKOUT} | |
| 102 | ExecStartPre=+/bin/sh -c 'mkdir -p ${dir} && find ${dir} -xdev -path ${proxyStore(dir)} -prune -o ! -user ${FORGE_USER} -exec chown -h ${FORGE_USER}:${FORGE_USER} {} +' | |
| 103 | ExecStart=${BUN_HOME}/bin/bun run src/main.ts | |
| 104 | Restart=on-failure | |
| 105 | RestartSec=5 | |
| 106 | NoNewPrivileges=yes | |
| 107 | PrivateTmp=yes | |
| 108 | ProtectSystem=strict | |
| 109 | ProtectHome=yes | |
| 110 | ReadWritePaths=${dir} ${FORGE_HOME} | |
| 111 | ProtectKernelModules=yes | |
| 112 | ProtectClock=yes | |
| 113 | RestrictSUIDSGID=yes | |
| 114 | [Install] | |
| 115 | WantedBy=multi-user.target | |
| 116 | `; | |
| 117 | } | |
| 118 | ||
| 119 | /** The `write_files` entries (already indented as list items) that harden the machine. */ | |
| 120 | export function hardenFiles(): string { | |
| 121 | const item = (path: string, body: string) => | |
| 122 | ` - path: ${path}\n permissions: "0644"\n content: |\n${indent(body, 6)}`; | |
| 123 | return [ | |
| 124 | // First match wins in sshd_config, so this sorts before cloud-init's own 50-cloud-init.conf. | |
| 125 | item( | |
| 126 | "/etc/ssh/sshd_config.d/00-forge.conf", | |
| 127 | `PasswordAuthentication no | |
| 128 | KbdInteractiveAuthentication no | |
| 129 | PermitRootLogin no | |
| 130 | AuthenticationMethods publickey | |
| 131 | `, | |
| 132 | ), | |
| 133 | item( | |
| 134 | "/etc/apt/apt.conf.d/20auto-upgrades", | |
| 135 | `APT::Periodic::Update-Package-Lists "1"; | |
| 136 | APT::Periodic::Unattended-Upgrade "1"; | |
| 137 | `, | |
| 138 | ), | |
| 139 | // Ubuntu 24.04 (kernel.apparmor_restrict_unprivileged_userns=1) lets an unconfined program make | |
| 140 | // a user namespace only without capabilities in it, which bwrap cannot work with. This names | |
| 141 | // /usr/bin/bwrap alone as allowed to make one; the system-wide restriction stays on. | |
| 142 | item( | |
| 143 | "/etc/apparmor.d/forge-bwrap", | |
| 144 | `abi <abi/4.0>, | |
| 145 | include <tunables/global> | |
| 146 | ||
| 147 | profile forge-bwrap /usr/bin/bwrap flags=(unconfined) { | |
| 148 | userns, | |
| 149 | } | |
| 150 | `, | |
| 151 | ), | |
| 152 | ].join("\n"); | |
| 153 | } | |
| 154 | ||
| 155 | /** | |
| 156 | * `runcmd` items (list items) that run first: the forge's user, the firewall, the sandbox profile. | |
| 157 | */ | |
| 158 | export function hardenEarly(): string { | |
| 159 | const rules = PUBLIC_PORTS.map((n) => ` - ufw allow ${n}/tcp`); | |
| 160 | return [ | |
| 161 | ` - useradd --system --user-group --home-dir ${FORGE_HOME} --create-home --shell /usr/sbin/nologin ${FORGE_USER}`, | |
| 162 | " - ufw default deny incoming", | |
| 163 | " - ufw default allow outgoing", | |
| 164 | ...rules, | |
| 165 | " - ufw --force enable", | |
| 166 | " - apparmor_parser -r /etc/apparmor.d/forge-bwrap || true", | |
| 167 | ].join("\n"); | |
| 168 | } | |
| 169 | ||
| 170 | /** | |
| 171 | * `runcmd` items that run once the checkout is there: ownership, then a note of whether the sandbox | |
| 172 | * works. | |
| 173 | */ | |
| 174 | export function hardenLate(): string { | |
| 175 | return [ | |
| 176 | ` - chown -R ${FORGE_USER}:${FORGE_USER} ${CHECKOUT}`, | |
| 177 | ` - runuser -u ${FORGE_USER} -- bwrap --unshare-user --ro-bind / / -- /bin/true && logger -t forge-boot sandbox ready || logger -t forge-boot sandbox not available, user namespaces refused`, | |
| 178 | ].join("\n"); | |
| 179 | } |
src/cloud/hetzner.ts +22 −12
| @@ -4,13 +4,14 @@ | ||
| 4 | 4 | * read-write, nothing narrower. |
| 5 | 5 | * |
| 6 | 6 | * Calls (Hetzner Cloud API v1): GET /server_types and /datacenters (what can be |
| 7 | * ordered where, read before anything is made), POST /volumes, POST /servers | |
| 8 | * (the volume attached and automounted at /mnt/HC_Volume_<id>), DELETE | |
| 9 | * /servers/{id}, GET /servers/{id} (the public IPv4 read back after it boots). | |
| 7 | * ordered where, read before anything is made), POST /volumes, POST /ssh_keys and DELETE | |
| 8 | * /ssh_keys/{id} (a throwaway key, so no root password is mailed), POST /servers (the volume | |
| 9 | * attached and automounted at /mnt/HC_Volume_<id>), DELETE /servers/{id}, GET /servers/{id} (the | |
| 10 | * public IPv4 read back after it boots). | |
| 10 | 11 | */ |
| 11 | 12 | |
| 12 | import { bootConfig as boot, ipv4, volumeName, type Call, type Driver } from "./machine.ts"; | |
| 13 | import type { Pinned } from "../core/pinned.ts"; | |
| 13 | import { dropThrowawayKey, makeThrowawayKey } from "./throwaway_key.ts"; | |
| 14 | import { bootConfig as boot, ipv4, volumeName, type Booted, type Call, type Driver } from "./machine.ts"; | |
| 14 | 15 | |
| 15 | 16 | /** |
| 16 | 17 | * Nuremberg: an EU location, because the US ones cost about three times as much for a tenth of the |
| @@ -29,7 +30,7 @@ const IMAGE = "ubuntu-24.04"; | ||
| 29 | 30 | /** Hetzner mounts an attached volume, when automount is asked for, under /mnt/HC_Volume_<id>. */ |
| 30 | 31 | const dataDir = (volume: string) => `/mnt/HC_Volume_${volume}`; |
| 31 | 32 | |
| 32 | export const bootConfig = (p: Pick<Pinned, "name" | "source" | "version" | "config">, volume: string): string => boot(p, dataDir(volume)); | |
| 33 | export const bootConfig = (p: Booted, volume: string): string => boot(p, dataDir(volume)); | |
| 33 | 34 | |
| 34 | 35 | /** |
| 35 | 36 | * The cheapest x86 server type of the CX line with at least MIN_MEMORY_GIB that |
| @@ -52,6 +53,9 @@ export async function pickType(call: Call, location = LOCATION): Promise<string> | ||
| 52 | 53 | return String(best.name); |
| 53 | 54 | } |
| 54 | 55 | |
| 56 | /** Hetzner's collection of project SSH keys. */ | |
| 57 | const KEYS = "/ssh_keys"; | |
| 58 | ||
| 55 | 59 | export const hetzner: Driver<string> = { |
| 56 | 60 | api: "https://api.hetzner.cloud/v1", |
| 57 | 61 | plan: (call) => pickType(call), |
| @@ -60,12 +64,18 @@ export const hetzner: Driver<string> = { | ||
| 60 | 64 | return String(v.volume?.id ?? ""); |
| 61 | 65 | }, |
| 62 | 66 | async createMachine(call, p, volume, type) { |
| 63 | const s = await call("POST", "/servers", { | |
| 64 | name: `forge-${p.name}`, server_type: type, location: LOCATION, image: IMAGE, | |
| 65 | volumes: [Number(volume)], automount: true, user_data: bootConfig(p, volume), | |
| 66 | public_net: { enable_ipv4: true, enable_ipv6: true }, start_after_create: true, labels: { "forge-pinned": "true" }, | |
| 67 | }); | |
| 68 | return String(s.server?.id ?? ""); | |
| 67 | // A server made with no SSH key is sent a root password by email; see throwaway_key.ts. | |
| 68 | const key = await makeThrowawayKey(call, KEYS, p.name); | |
| 69 | try { | |
| 70 | const s = await call("POST", "/servers", { | |
| 71 | name: `forge-${p.name}`, server_type: type, location: LOCATION, image: IMAGE, | |
| 72 | volumes: [Number(volume)], automount: true, user_data: bootConfig(p, volume), ssh_keys: [Number(key)], | |
| 73 | public_net: { enable_ipv4: true, enable_ipv6: true }, start_after_create: true, labels: { "forge-pinned": "true" }, | |
| 74 | }); | |
| 75 | return String(s.server?.id ?? ""); | |
| 76 | } finally { | |
| 77 | await dropThrowawayKey(call, KEYS, key); | |
| 78 | } | |
| 69 | 79 | }, |
| 70 | 80 | async deleteMachine(call, remote) { |
| 71 | 81 | await call("DELETE", `/servers/${remote}`); |
src/cloud/machine.ts +109 −22
| @@ -5,13 +5,23 @@ | ||
| 5 | 5 | * new provider costs its API calls and nothing else. Plain data in, plain data |
| 6 | 6 | * out: the caller owns the token and the fetch. The token travels in an |
| 7 | 7 | * Authorization header over HTTPS, never on argv, and the boot script holds no |
| 8 | * secret at all: the new forge's first visitor claims it at /first-admin. | |
| 8 | * secret at all. A machine's boot config stays readable through its cloud's | |
| 9 | * API and metadata endpoint, so what it carries of the claim is the sha256 of | |
| 10 | * a one-time link the deployer was shown once (`servedEnv`): the new forge | |
| 11 | * takes it as its first-admin code (`core/first_admin.ts`), so only the | |
| 12 | * person holding the link becomes its admin, and a visitor without it gets | |
| 13 | * the same refusal as any wrong code. The forge listens on loopback; the | |
| 14 | * machine's packaged proxy (`proxyConfig`) gets and renews a certificate for | |
| 15 | * the forge's own name and is the only thing on 80 and 443, so until the | |
| 16 | * certificate exists nothing of the forge is reachable, and never in plain HTTP. | |
| 9 | 17 | * The caller records each id the moment it exists (`onVolume`, `onDeleted`), so |
| 10 | 18 | * a failure half-way leaves a row a retry can finish, never an orphan. |
| 11 | 19 | */ |
| 12 | 20 | |
| 13 | 21 | import type { Fetch } from "./providers.ts"; |
| 14 | import type { Pinned } from "../core/pinned.ts"; | |
| 22 | import { firstAdminSeed, readSeed } from "../core/first_admin.ts"; | |
| 23 | import { BOOT_NAMES, portOf, validHost, type Pinned } from "../core/pinned.ts"; | |
| 24 | import { BUN_HOME, CHECKOUT, hardenEarly, hardenFiles, hardenHead, hardenLate, mount, proxyStore, serviceUnit } from "./harden.ts"; | |
| 15 | 25 | |
| 16 | 26 | /** |
| 17 | 27 | * The Bun the machine installs: it moves only when this line does, in a pull, so the runtime is |
| @@ -22,38 +32,106 @@ export const BUN_VERSION = "1.4.4"; | ||
| 22 | 32 | /** The name of the volume holding a forge's data, the same on every cloud. */ |
| 23 | 33 | export const volumeName = (name: string) => `forge-${name}-data`; |
| 24 | 34 | |
| 35 | /** What a machine is booted from: the pin, the name it is served on, and the hash of its claim. */ | |
| 36 | export type Booted = Pick<Pinned, "name" | "source" | "version" | "config" | "host" | "claimHash" | "claimExpires">; | |
| 37 | ||
| 25 | 38 | /** |
| 26 | * cloud-config for the machine: Bun, the pinned source at the pinned version, a systemd unit; | |
| 27 | * `dataDir` is where the volume is mounted. | |
| 39 | * What the forge is told about its name, its claim and its sandbox (#16217); these win over the | |
| 40 | * config's own, which `checkConfig` refuses to name at all. It answers as `https://<host>`, | |
| 41 | * listens on loopback only, hears the client's address from the proxy beside it and from nobody | |
| 42 | * else, takes the claim's sha256 and deadline as its first-admin seed, and is told its crew runs | |
| 43 | * in the sandbox or not at all. The hash is all there is of the claim: the link is never handed | |
| 44 | * to this function. | |
| 28 | 45 | */ |
| 29 | export function bootConfig(p: Pick<Pinned, "name" | "source" | "version" | "config">, dataDir: string): string { | |
| 30 | const env = Object.entries({ ...p.config, FORGE_APP_DATA: dataDir }) | |
| 46 | export function servedEnv(p: Booted): Record<string, string> { | |
| 47 | if (!validHost(p.host)) throw new Error("this forge has no name to be served on"); | |
| 48 | const seed = p.claimHash === "" ? "" : firstAdminSeed(p.claimHash, p.claimExpires); | |
| 49 | if (seed !== "" && readSeed(seed) === undefined) throw new Error("this forge's claim is not a hash and a deadline"); | |
| 50 | return { | |
| 51 | FORGE_URL: `https://${p.host}`, | |
| 52 | FORGE_HOST: p.host, | |
| 53 | FORGE_BIND: "127.0.0.1", | |
| 54 | FORGE_TRUSTED_PROXIES: "127.0.0.1/32", | |
| 55 | // No SSH listener: it binds every interface whatever FORGE_BIND says, and nothing reaches it | |
| 56 | // behind a firewall that opens 80 and 443 alone. Git and the forge's doors are HTTPS here. | |
| 57 | FORGE_SSH_PORT: "0", | |
| 58 | // The crew's shells run in the sandbox the machine was given (`harden.ts`), or not at all. | |
| 59 | FORGE_CREW_SANDBOX: "require", | |
| 60 | ...(seed === "" ? {} : { FORGE_FIRST_ADMIN_SEED: seed }), | |
| 61 | }; | |
| 62 | } | |
| 63 | ||
| 64 | /** | |
| 65 | * The machine's proxy, Caddy from Ubuntu's own package repository: the forge has no ACME client, | |
| 66 | * and Caddy gets and renews a certificate for a named site by itself, redirects port 80 to 443 and | |
| 67 | * answers no other name. The whole config is the name, where the forge listens, and where the | |
| 68 | * certificate is kept: on the data volume (`proxyStore`), so a machine that replaces this one | |
| 69 | * finds it there and asks the authority for nothing, whose weekly limit on certificates for one | |
| 70 | * name a few Updates would otherwise spend. | |
| 71 | */ | |
| 72 | export const proxyConfig = (p: Booted, dataDir: string): string => | |
| 73 | `{\n\tstorage file_system ${proxyStore(dataDir)}\n}\n${p.host} {\n\treverse_proxy 127.0.0.1:${portOf(p)}\n}\n`; | |
| 74 | ||
| 75 | /** | |
| 76 | * The proxy's `write_files` entries. Its config is written where the package reads it, before | |
| 77 | * the package is installed: cloud-init writes files first and installs with dpkg keeping a config | |
| 78 | * file that is already there, so the proxy's first start is on this config and never on the | |
| 79 | * package's welcome page. The drop-in holds it until the volume its certificates live on is | |
| 80 | * mounted. | |
| 81 | */ | |
| 82 | const proxyFiles = (p: Booted, dataDir: string): string => ` - path: /etc/caddy/Caddyfile | |
| 83 | content: ${JSON.stringify(proxyConfig(p, dataDir))} | |
| 84 | - path: /etc/systemd/system/caddy.service.d/forge.conf | |
| 85 | content: | | |
| 86 | [Unit] | |
| 87 | RequiresMountsFor=${mount(dataDir)}`; | |
| 88 | ||
| 89 | /** | |
| 90 | * The `runcmd` lines that give the proxy its place on the volume and start it there. The package | |
| 91 | * itself is one of the machine's (`hardenHead`), a service of its own under its own user: nothing | |
| 92 | * of it runs inside the forge's unit, and the firewall's two open ports are the two it listens on. | |
| 93 | * They run after the forge's unit is started, which waits for the mount. The store is made the | |
| 94 | * proxy's again on every new machine, where the packaged user may have another number. | |
| 95 | */ | |
| 96 | const proxyCommands = (dataDir: string): string => ` - install -d -m 0700 -o caddy -g caddy ${proxyStore(dataDir)} | |
| 97 | - chown -R caddy:caddy ${proxyStore(dataDir)} | |
| 98 | - systemctl daemon-reload | |
| 99 | - systemctl enable caddy.service | |
| 100 | - systemctl restart caddy.service`; | |
| 101 | ||
| 102 | /** | |
| 103 | * cloud-config for the machine: Bun, the pinned source at the pinned version, a systemd unit, and | |
| 104 | * the proxy that serves it on its name; `dataDir` is where the volume is mounted. What makes it | |
| 105 | * safe to leave on the internet (an unprivileged user, a firewall, no shell, updates, the sandbox) | |
| 106 | * is `harden.ts`. What the boot sets is written after the config, the data directory last. | |
| 107 | */ | |
| 108 | export function bootConfig(p: Booted, dataDir: string): string { | |
| 109 | // A row from before `checkConfig` refused these names may still hold one: it is dropped, so what | |
| 110 | // the boot sets is said once and in its own place. | |
| 111 | const settings = Object.fromEntries(Object.entries(p.config).filter(([k]) => !BOOT_NAMES.includes(k))); | |
| 112 | const env = Object.entries({ ...settings, ...servedEnv(p), FORGE_APP_DATA: dataDir }) | |
| 31 | 113 | .map(([k, v]) => `${k}=${v}`) |
| 32 | 114 | .join("\n"); |
| 33 | // Every interpolated value is validated in core/pinned.ts (version, source, config) or by NAME; | |
| 34 | // dataDir is the driver's own. | |
| 115 | // Every interpolated value is validated in core/pinned.ts (version, source, config, host) or by | |
| 116 | // NAME; the seed is checked in servedEnv; dataDir is the driver's own. | |
| 35 | 117 | return `#cloud-config |
| 36 | write_files: | |
| 118 | ${hardenHead()}write_files: | |
| 37 | 119 | - path: /etc/forge/env |
| 38 | 120 | permissions: "0600" |
| 39 | 121 | content: ${JSON.stringify(env + "\n")} |
| 122 | ${proxyFiles(p, dataDir)} | |
| 40 | 123 | - path: /etc/systemd/system/forge.service |
| 41 | 124 | content: | |
| 42 | [Unit] | |
| 43 | Description=forge ${p.name} pinned at ${p.version} | |
| 44 | After=network-online.target | |
| 45 | [Service] | |
| 46 | EnvironmentFile=/etc/forge/env | |
| 47 | WorkingDirectory=/opt/forge | |
| 48 | ExecStart=/root/.bun/bin/bun run src/main.ts | |
| 49 | Restart=on-failure | |
| 50 | [Install] | |
| 51 | WantedBy=multi-user.target | |
| 125 | ${serviceUnit(p.name, p.version, dataDir).replace(/^(?=.)/gm, " ")} | |
| 126 | ${hardenFiles()} | |
| 52 | 127 | runcmd: |
| 53 | - curl -fsSL https://bun.sh/install | bash -s "bun-v${BUN_VERSION}" | |
| 54 | - git clone ${p.source} /opt/forge | |
| 55 | - git -C /opt/forge checkout --detach ${p.version} | |
| 128 | ${hardenEarly()} | |
| 129 | - curl -fsSL https://bun.sh/install | BUN_INSTALL=${BUN_HOME} bash -s "bun-v${BUN_VERSION}" | |
| 130 | - git clone ${p.source} ${CHECKOUT} | |
| 131 | - git -C ${CHECKOUT} checkout --detach ${p.version} | |
| 132 | ${hardenLate()} | |
| 56 | 133 | - systemctl enable --now forge.service |
| 134 | ${proxyCommands(dataDir)} | |
| 57 | 135 | `; |
| 58 | 136 | } |
| 59 | 137 | |
| @@ -137,6 +215,15 @@ export async function replace<P>( | ||
| 137 | 215 | return { remote: await d.createMachine(call, p, p.volume, plan) }; |
| 138 | 216 | } |
| 139 | 217 | |
| 218 | /** | |
| 219 | * Decide what would be ordered, and make nothing: the driver's `plan` alone, which is where a | |
| 220 | * cloud that cannot deliver, or a ceiling (`ceiling.ts`), refuses. Asked before a change is | |
| 221 | * recorded, so a refusal leaves the row and the machine agreeing. | |
| 222 | */ | |
| 223 | export async function orderable<P>(d: Driver<P>, f: Fetch, token: string): Promise<void> { | |
| 224 | await d.plan(caller(d, f, token)); | |
| 225 | } | |
| 226 | ||
| 140 | 227 | const IPV4 = /^(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)$/; |
| 141 | 228 | /** Only a well-formed IPv4 address is ever kept. */ |
| 142 | 229 | export const ipv4 = (v: unknown): string => (typeof v === "string" && IPV4.test(v) ? v : ""); |
src/cloud/overview.ts +9
| @@ -12,6 +12,7 @@ import { listCloudAccounts, recentCloudReads } from "../core/cloud_account.ts"; | ||
| 12 | 12 | import type { User } from "../core/users.ts"; |
| 13 | 13 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 14 | 14 | import { usedFor, type VendorUse } from "./declared.ts"; |
| 15 | import { spendOf } from "./ceiling.ts"; | |
| 15 | 16 | import { VENDOR_OF, type Provider } from "./providers.ts"; |
| 16 | 17 | |
| 17 | 18 | export interface AccountRow { |
| @@ -23,6 +24,13 @@ export interface AccountRow { | ||
| 23 | 24 | readonly lastUsedAt: string | null; |
| 24 | 25 | readonly writeAllowed: boolean; |
| 25 | 26 | readonly callsToday: number; |
| 27 | /** | |
| 28 | * The forge's own reckoning from list prices (the provider's bill is the truth): the ceiling in | |
| 29 | * whole dollars, the monthly cost in cents, and the cents left. | |
| 30 | */ | |
| 31 | readonly ceilingDollars: number; | |
| 32 | readonly monthlyCents: number; | |
| 33 | readonly leftCents: number; | |
| 26 | 34 | } |
| 27 | 35 | |
| 28 | 36 | export interface CloudOverview { |
| @@ -48,6 +56,7 @@ export function cloudOverview( | ||
| 48 | 56 | lastUsedAt: reads.find((r) => r.provider === a.provider && r.name === a.name)?.at ?? null, |
| 49 | 57 | writeAllowed: a.writeAllowed, |
| 50 | 58 | callsToday: today.filter((r) => r.provider === a.provider && r.account === a.name).length, |
| 59 | ...spendOf(app.db, a.provider, a.name), | |
| 51 | 60 | })); |
| 52 | 61 | return ok({ accounts, today }); |
| 53 | 62 | } |
src/cloud/throwaway_key.ts added +69
| @@ -0,0 +1,69 @@ | ||
| 1 | /** | |
| 2 | * A key nobody can use, sent so the cloud never makes a root password (#16218). | |
| 3 | * | |
| 4 | * Hetzner generates a root password and emails it to the account holder when a server is created | |
| 5 | * with no SSH key; DigitalOcean does the same. A password that exists is a password that can be | |
| 6 | * forwarded, logged or guessed. The only documented way to stop it is to give the create call an | |
| 7 | * SSH key, so each machine gets a fresh Ed25519 key whose private half is made non-extractable and | |
| 8 | * dropped with this function's scope: it is never exported, written, logged or returned. The | |
| 9 | * public half is registered with the cloud for the one create call and deleted right after. | |
| 10 | * The machine's own sshd refuses root, passwords and, behind a closed port 22, everyone | |
| 11 | * (`harden.ts`), so the key opens nothing even though its public half sits in a file. | |
| 12 | */ | |
| 13 | ||
| 14 | import type { Call } from "./machine.ts"; | |
| 15 | ||
| 16 | /** One OpenSSH public key line, `ssh-ed25519 <base64>`, for a keypair that exists only here. */ | |
| 17 | export async function throwawayPublicKey(): Promise<string> { | |
| 18 | const pair = (await crypto.subtle.generateKey({ name: "Ed25519" }, false, [ | |
| 19 | "sign", | |
| 20 | "verify", | |
| 21 | ])) as unknown as CryptoKeyPair; | |
| 22 | const raw = new Uint8Array( | |
| 23 | await crypto.subtle.exportKey("raw", pair.publicKey), | |
| 24 | ); | |
| 25 | const type = new TextEncoder().encode("ssh-ed25519"); | |
| 26 | const blob = new Uint8Array(4 + type.length + 4 + raw.length); | |
| 27 | const view = new DataView(blob.buffer); | |
| 28 | view.setUint32(0, type.length); | |
| 29 | blob.set(type, 4); | |
| 30 | view.setUint32(4 + type.length, raw.length); | |
| 31 | blob.set(raw, 8 + type.length); | |
| 32 | return `ssh-ed25519 ${Buffer.from(blob).toString("base64")}`; | |
| 33 | } | |
| 34 | ||
| 35 | /** | |
| 36 | * Register a throwaway key at `path` (the cloud's key collection) and return its id; the caller | |
| 37 | * puts the id in the create call and passes the same `path` to `dropThrowawayKey` afterwards. | |
| 38 | */ | |
| 39 | export async function makeThrowawayKey( | |
| 40 | call: Call, | |
| 41 | path: string, | |
| 42 | forge: string, | |
| 43 | ): Promise<string> { | |
| 44 | const made = await call("POST", path, { | |
| 45 | name: `forge-${forge}-${crypto.randomUUID().slice(0, 8)}`, | |
| 46 | public_key: await throwawayPublicKey(), | |
| 47 | }); | |
| 48 | const id = String(made.ssh_key?.id ?? ""); | |
| 49 | if (!/^\d+$/.test(id)) | |
| 50 | throw new Error( | |
| 51 | "the cloud made no SSH key to stand in for a root password; nothing more was made", | |
| 52 | ); | |
| 53 | return id; | |
| 54 | } | |
| 55 | ||
| 56 | /** | |
| 57 | * Delete the key again. A failure leaves one unusable public key in the account, never a machine. | |
| 58 | */ | |
| 59 | export async function dropThrowawayKey( | |
| 60 | call: Call, | |
| 61 | path: string, | |
| 62 | id: string, | |
| 63 | ): Promise<void> { | |
| 64 | try { | |
| 65 | await call("DELETE", `${path}/${id}`); | |
| 66 | } catch { | |
| 67 | // The key opens nothing: it is not worth failing a machine that exists. | |
| 68 | } | |
| 69 | } |
src/contract/openapi/routes/getApiV1FirstAdminClaim.ts added +15
| @@ -0,0 +1,15 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "get", | |
| 5 | path: "/api/v1/first-admin/claim", | |
| 6 | summary: "Ask a deployed forge what became of the claim it was started with", | |
| 7 | detail: | |
| 8 | "Ask a deployed forge what became of the claim it was started with: for the forge that deployed it, which holds the claim's sha256; `seed` is that hash, never the claim; answers { state } as waiting, claimed or expired, and 404 to any other value, so nobody else is told anything", | |
| 9 | auth: false, | |
| 10 | role: "anonymous", | |
| 11 | query: { seed: "string" }, | |
| 12 | refusals: { | |
| 13 | not_found: "404, seed is not the hash of the claim this forge was started with", | |
| 14 | }, | |
| 15 | }; |
src/contract/openapi/routes/index.ts +1
| @@ -95,6 +95,7 @@ export { route as getApiV1FeaturesSlugFeed } from "./getApiV1FeaturesSlugFeed.ts | ||
| 95 | 95 | export { route as getApiV1Feed } from "./getApiV1Feed.ts"; |
| 96 | 96 | export { route as getApiV1FeedChips } from "./getApiV1FeedChips.ts"; |
| 97 | 97 | export { route as getApiV1FeedLikes } from "./getApiV1FeedLikes.ts"; |
| 98 | export { route as getApiV1FirstAdminClaim } from "./getApiV1FirstAdminClaim.ts"; | |
| 98 | 99 | export { route as getApiV1Flags } from "./getApiV1Flags.ts"; |
| 99 | 100 | export { route as getApiV1FleetGraph } from "./getApiV1FleetGraph.ts"; |
| 100 | 101 | export { route as getApiV1FleetOps } from "./getApiV1FleetOps.ts"; |
src/contract/openapi/routes/postApiV1AdminPinned.ts +2 −2
| @@ -4,11 +4,11 @@ export const route: Route = { | ||
| 4 | 4 | method: "post", |
| 5 | 5 | path: "/api/v1/admin/pinned", |
| 6 | 6 | summary: "Put a pinned forge on the owner's cloud: no crew, no automatic release", |
| 7 | detail: "Put a pinned forge on the owner's cloud: no crew, no automatic release; needs an admin-scope token and a cloud account with writes allowed", | |
| 7 | detail: "Put a pinned forge on the owner's cloud: no crew, no automatic release; needs an admin-scope token and a cloud account with writes allowed; `host` is the name it is served on over HTTPS; answers the forge with { claim: { link, expiresAt } }, the one-time link that makes its first admin, shown in this answer only, and `dns`, the record to create", | |
| 8 | 8 | auth: true, |
| 9 | 9 | role: "admin", |
| 10 | 10 | status: 201, |
| 11 | body: { name: "string", target: "string", account: "string", app: "string", source: "string", version: "string", config: "object" }, | |
| 11 | body: { name: "string", host: "string", target: "string", account: "string", app: "string", source: "string", version: "string", config: "object" }, | |
| 12 | 12 | refusals: { |
| 13 | 13 | not_found: "only a forge administrator sees this route", |
| 14 | 14 | refused: "the request was understood and refused; the message says why (422)", |
src/contract/openapi/routes/postApiV1AdminPinnedNameCheck.ts +2 −2
| @@ -3,8 +3,8 @@ import type { Route } from "../shared.ts"; | ||
| 3 | 3 | export const route: Route = { |
| 4 | 4 | method: "post", |
| 5 | 5 | path: "/api/v1/admin/pinned/{name}/check", |
| 6 | summary: "Probe a pinned forge's droplet and mark it running if it answers", | |
| 7 | detail: "Read the droplet's public address back, probe the forge there, and say whether it answers; one that does is marked running", | |
| 6 | summary: "Probe a pinned forge on its name and mark it running if it answers", | |
| 7 | detail: "Read the machine's public address back, see that the forge's name resolves to it, probe the forge over HTTPS and ask what became of its claim; answers `healthy`, `waiting` (address, dns or answer; empty when it answers), `dns` (the record to create) and `claim` (waiting, claimed, expired or unknown); one that answers is marked running", | |
| 8 | 8 | auth: true, |
| 9 | 9 | role: "admin", |
| 10 | 10 | refusals: { |
src/contract/openapi/routes/postApiV1AdminPinnedNameClaim.ts +4 −1
| @@ -3,9 +3,12 @@ import type { Route } from "../shared.ts"; | ||
| 3 | 3 | export const route: Route = { |
| 4 | 4 | method: "post", |
| 5 | 5 | path: "/api/v1/admin/pinned/{name}/claim", |
| 6 | summary: "Record that the forge was handed to its buyer, for good", | |
| 6 | summary: "Issue a new one-time claim link for a pinned forge nobody has claimed", | |
| 7 | detail: | |
| 8 | "Issue a new one-time claim link for a pinned forge nobody has claimed: the machine is replaced on the same volume with the new claim's hash, so the link before it stops working; answers the forge with { claim: { link, expiresAt } }, shown in this answer only; `host` names a forge deployed before it had a name", | |
| 7 | 9 | auth: true, |
| 8 | 10 | role: "admin", |
| 11 | body: { host: "string" }, | |
| 9 | 12 | refusals: { |
| 10 | 13 | not_found: "only a forge administrator sees this route", |
| 11 | 14 | refused: "the request was understood and refused; the message says why (422)", |
src/core/cloud_account.ts +9
| @@ -50,6 +50,8 @@ export interface CloudAccount { | ||
| 50 | 50 | readonly summary: string; |
| 51 | 51 | readonly verifiedAt: string | null; |
| 52 | 52 | readonly writeAllowed: boolean; |
| 53 | /** The most the forge will let this account cost a month, whole US dollars (ceiling.ts). */ | |
| 54 | readonly ceilingDollars: number; | |
| 53 | 55 | } |
| 54 | 56 | |
| 55 | 57 | interface Row { |
| @@ -58,6 +60,7 @@ interface Row { | ||
| 58 | 60 | summary: string; |
| 59 | 61 | verified_at: string | null; |
| 60 | 62 | write_allowed: number; |
| 63 | ceiling_dollars: number; | |
| 61 | 64 | } |
| 62 | 65 | |
| 63 | 66 | const toAccount = (r: Row): CloudAccount => ({ |
| @@ -66,6 +69,7 @@ const toAccount = (r: Row): CloudAccount => ({ | ||
| 66 | 69 | summary: r.summary, |
| 67 | 70 | verifiedAt: r.verified_at, |
| 68 | 71 | writeAllowed: r.write_allowed === 1, |
| 72 | ceilingDollars: r.ceiling_dollars, | |
| 69 | 73 | }); |
| 70 | 74 | |
| 71 | 75 | export function listCloudAccounts(db: Database): CloudAccount[] { |
| @@ -121,6 +125,11 @@ export function setWriteAllowed( | ||
| 121 | 125 | ); |
| 122 | 126 | } |
| 123 | 127 | |
| 128 | export function setCeilingDollars(db: Database, provider: string, name: string, dollars: number): boolean { | |
| 129 | table(db); | |
| 130 | return db.query("UPDATE cloud_account SET ceiling_dollars = ?3 WHERE provider = ?1 AND name = ?2").run(provider, name, dollars).changes > 0; | |
| 131 | } | |
| 132 | ||
| 124 | 133 | export function renameCloudAccount( |
| 125 | 134 | db: Database, |
| 126 | 135 | provider: string, |
src/core/event_audience.ts +1
| @@ -301,6 +301,7 @@ export function classifiedAudience(kind: string): EventAudience | undefined { | ||
| 301 | 301 | kind === "forge.upstream" || |
| 302 | 302 | kind === "forge.updates_taken" || |
| 303 | 303 | kind === "cloud.write_allowed" || |
| 304 | kind === "cloud.ceiling" || | |
| 304 | 305 | // A plan's pinned default place is an admin's act (`actions/places.ts`, #16203). |
| 305 | 306 | kind === "cloud.place_pinned" || |
| 306 | 307 | // A bet's name, share and what is left are the owner's plan (#8713). |
src/core/first_admin.ts +95 −4
| @@ -26,9 +26,20 @@ | ||
| 26 | 26 | * `POST /api/v1/first-admin/recover` for a new expiring token for that |
| 27 | 27 | * account. It makes no account, and it dies the moment any admin can sign in. |
| 28 | 28 | * Each kind of code is refused at the other's door. |
| 29 | * | |
| 30 | * Seeded. A forge deployed for someone (`cloud/machine.ts`) has no operator | |
| 31 | * at a terminal, so its first-admin row is seeded at boot from | |
| 32 | * `FORGE_FIRST_ADMIN_SEED`: the sha256 of a code the deploying forge made | |
| 33 | * and showed its deployer once, and a deadline (`FIRST_ADMIN_SEED_TTL_MS` | |
| 34 | * at most). The environment holds the hash, never the code, since a | |
| 35 | * machine's boot config stays readable through its cloud's API. It is the | |
| 36 | * same row, redeemed at the same doors by the same statement; each seed is | |
| 37 | * taken once (`first_admin.seed` remembers the last), so a restart never | |
| 38 | * revives a spent or replaced code, and a new seed ends the one before it. | |
| 29 | 39 | */ |
| 30 | 40 | |
| 31 | 41 | import type { Database } from "bun:sqlite"; |
| 42 | import { timingSafeEqual } from "node:crypto"; | |
| 32 | 43 | import { sha256 } from "../kernel/hash.ts"; |
| 33 | 44 | import { hasAdmin } from "../spawn/claim.ts"; |
| 34 | 45 | |
| @@ -36,6 +47,11 @@ const KEY = "first_admin.code"; | ||
| 36 | 47 | /** Who `forge_setting.updated_by` names for a code: the terminal, not an account. */ |
| 37 | 48 | export const OPERATOR_ACTOR = "operator"; |
| 38 | 49 | export const FIRST_ADMIN_TTL_MS = 15 * 60 * 1000; |
| 50 | const SEED_KEY = "first_admin.seed"; | |
| 51 | /** Who `forge_setting.updated_by` names for a seeded code: the forge that deployed this one. */ | |
| 52 | export const SEED_ACTOR = "deployer"; | |
| 53 | /** How long a seeded code may stand: a forge handed to a buyer, who may not open the link today. */ | |
| 54 | export const FIRST_ADMIN_SEED_TTL_MS = 7 * 24 * 60 * 60 * 1000; | |
| 39 | 55 | |
| 40 | 56 | interface Stored { |
| 41 | 57 | /** sha256 of the code, hex. */ |
| @@ -123,18 +139,93 @@ export function mintFirstAdminRecovery( | ||
| 123 | 139 | return store(db, userId, now); |
| 124 | 140 | } |
| 125 | 141 | |
| 126 | function store(db: Database, recover: string | undefined, now: number): { code: string; expiresAt: string } { | |
| 142 | /** A new code and its sha256: 32 random bytes, the only shape any door accepts. */ | |
| 143 | export function newFirstAdminCode(): { code: string; hash: string } { | |
| 127 | 144 | const code = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64url"); |
| 128 | const expiresAt = new Date(now + FIRST_ADMIN_TTL_MS).toISOString(); | |
| 129 | const value: Stored = { h: sha256(code), e: expiresAt, u: null, ...(recover === undefined ? {} : { r: recover }) }; | |
| 145 | return { code, hash: sha256(code) }; | |
| 146 | } | |
| 147 | ||
| 148 | function put(db: Database, key: string, value: string, by: string, now: number): void { | |
| 130 | 149 | db.query( |
| 131 | 150 | `INSERT INTO forge_setting (key, value, updated_by, updated_at) VALUES (?1, ?2, ?3, ?4) |
| 132 | 151 | ON CONFLICT (key) DO UPDATE SET value = excluded.value, |
| 133 | 152 | updated_by = excluded.updated_by, updated_at = excluded.updated_at`, |
| 134 | ).run(KEY, JSON.stringify(value), OPERATOR_ACTOR, new Date(now).toISOString()); | |
| 153 | ).run(key, value, by, new Date(now).toISOString()); | |
| 154 | } | |
| 155 | ||
| 156 | function store(db: Database, recover: string | undefined, now: number): { code: string; expiresAt: string } { | |
| 157 | const { code, hash } = newFirstAdminCode(); | |
| 158 | const expiresAt = new Date(now + FIRST_ADMIN_TTL_MS).toISOString(); | |
| 159 | const value: Stored = { h: hash, e: expiresAt, u: null, ...(recover === undefined ? {} : { r: recover }) }; | |
| 160 | put(db, KEY, JSON.stringify(value), OPERATOR_ACTOR, now); | |
| 135 | 161 | return { code, expiresAt }; |
| 136 | 162 | } |
| 137 | 163 | |
| 164 | const SEED = /^([0-9a-f]{64})@(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z)$/; | |
| 165 | ||
| 166 | /** What `FORGE_FIRST_ADMIN_SEED` holds: a code's sha256 and its deadline, never the code. */ | |
| 167 | export const firstAdminSeed = (hash: string, expiresAt: string): string => `${hash}@${expiresAt}`; | |
| 168 | ||
| 169 | /** A seed read back as its hash and deadline (ms), or undefined when it is not one. */ | |
| 170 | export function readSeed(seed: string): { hash: string; expires: number } | undefined { | |
| 171 | const m = SEED.exec(seed); | |
| 172 | const expires = Date.parse(m?.[2] ?? ""); | |
| 173 | return m && Number.isFinite(expires) ? { hash: m[1]!, expires } : undefined; | |
| 174 | } | |
| 175 | ||
| 176 | /** | |
| 177 | * Take the seed this forge was started with. `none`: there is none. | |
| 178 | * `invalid`: it is not a seed, and nothing was written. `kept`: this seed | |
| 179 | * was taken at an earlier boot, so the row is left as it stands (spent, | |
| 180 | * replaced or waiting). `owned`: a person already administers the forge; | |
| 181 | * the seed is remembered and makes no code. `seeded`: its hash is now the | |
| 182 | * one first-admin code, unused, until the seed's deadline or | |
| 183 | * `FIRST_ADMIN_SEED_TTL_MS` from now, whichever is sooner. | |
| 184 | */ | |
| 185 | export function seedFirstAdmin( | |
| 186 | db: Database, | |
| 187 | seed: string | undefined, | |
| 188 | now = Date.now(), | |
| 189 | ): "none" | "invalid" | "kept" | "owned" | "seeded" { | |
| 190 | if (seed === undefined || seed.trim() === "") return "none"; | |
| 191 | const read = readSeed(seed.trim()); | |
| 192 | if (read === undefined) return "invalid"; | |
| 193 | return db.transaction((): "kept" | "owned" | "seeded" => { | |
| 194 | const last = db.query<{ value: string }, [string]>("SELECT value FROM forge_setting WHERE key = ?1").get(SEED_KEY); | |
| 195 | if (last?.value === read.hash) return "kept"; | |
| 196 | put(db, SEED_KEY, read.hash, SEED_ACTOR, now); | |
| 197 | if (hasAdmin(db)) return "owned"; | |
| 198 | const expiresAt = new Date(Math.min(read.expires, now + FIRST_ADMIN_SEED_TTL_MS)).toISOString(); | |
| 199 | put(db, KEY, JSON.stringify({ h: read.hash, e: expiresAt, u: null } satisfies Stored), SEED_ACTOR, now); | |
| 200 | return "seeded"; | |
| 201 | })(); | |
| 202 | } | |
| 203 | ||
| 204 | /** Where a seeded code stands, as the forge that deployed this one may ask. */ | |
| 205 | export type SeedState = "waiting" | "claimed" | "expired"; | |
| 206 | ||
| 207 | /** | |
| 208 | * What became of the seed with this hash, or undefined when `hash` is not the | |
| 209 | * seed this forge last took, so only whoever holds the hash (the deploying | |
| 210 | * forge, which made it) is told anything. `claimed`: a person administers | |
| 211 | * the forge. `waiting`: its code is unused and in time. `expired`: it can no | |
| 212 | * longer be used (out of time, or replaced from the operator's terminal). | |
| 213 | */ | |
| 214 | export function seedState(db: Database, hash: string, now = Date.now()): SeedState | undefined { | |
| 215 | const last = db.query<{ value: string }, [string]>("SELECT value FROM forge_setting WHERE key = ?1").get(SEED_KEY); | |
| 216 | if (last === null || !/^[0-9a-f]{64}$/.test(hash) || last.value.length !== hash.length) return undefined; | |
| 217 | if (!timingSafeEqual(Buffer.from(last.value), Buffer.from(hash))) return undefined; | |
| 218 | if (hasAdmin(db)) return "claimed"; | |
| 219 | const row = db.query<{ value: string }, [string]>("SELECT value FROM forge_setting WHERE key = ?1").get(KEY); | |
| 220 | let stored: Stored | undefined; | |
| 221 | try { | |
| 222 | stored = row === null ? undefined : (JSON.parse(row.value) as Stored); | |
| 223 | } catch { | |
| 224 | stored = undefined; | |
| 225 | } | |
| 226 | return stored !== undefined && stored.h === hash && stored.u === null && Date.parse(stored.e) > now ? "waiting" : "expired"; | |
| 227 | } | |
| 228 | ||
| 138 | 229 | function judge( |
| 139 | 230 | db: Database, |
| 140 | 231 | code: string, |
src/core/migration-pins/20261123140000-cloud-account-ceiling.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | f1a13b8af4ce84c052fa49aefd82e50e1959bd6dde0925baf1be646d565c0567 |
src/core/migration-pins/20261124042209-pinned-host-claim.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 810353c923e9f510df3dbf42a4077a599e7db0605cd7abc2eeed651588103f53 |
src/core/migration-pins/20261124053225-pinned-reached.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 8f0195e5e4578c26ce8c94ac21ba6eac21e24ce52d4f2a88fd4e0645a8cdfe7d |
src/core/migrations/20261123140000-cloud-account-ceiling.ts added +19
| @@ -0,0 +1,19 @@ | ||
| 1 | // A monthly spend ceiling on every cloud account, in whole US dollars, 50 for each account that | |
| 2 | // exists and each that is added. Also the size of each machine a pinned forge was given, so a | |
| 3 | // replace can be counted against the machine it replaces. The cloud_account table is otherwise | |
| 4 | // made on first use; made here too, in its same shape, so the column has a table to join. Additive. | |
| 5 | export default ` | |
| 6 | CREATE TABLE IF NOT EXISTS cloud_account ( | |
| 7 | provider TEXT NOT NULL, | |
| 8 | name TEXT NOT NULL, | |
| 9 | summary TEXT NOT NULL DEFAULT '', | |
| 10 | verified_at TEXT, | |
| 11 | write_allowed INTEGER NOT NULL DEFAULT 0, | |
| 12 | PRIMARY KEY (provider, name) | |
| 13 | ); | |
| 14 | ALTER TABLE cloud_account ADD COLUMN ceiling_dollars INTEGER NOT NULL DEFAULT 50; | |
| 15 | CREATE TABLE IF NOT EXISTS pinned_size ( | |
| 16 | pinned_id TEXT PRIMARY KEY, | |
| 17 | size TEXT NOT NULL | |
| 18 | ); | |
| 19 | `; |
src/core/migrations/20261124042209-pinned-host-claim.ts added +10
| @@ -0,0 +1,10 @@ | ||
| 1 | // A pinned forge is served on a hostname and handed over by a one-time claim | |
| 2 | // (#16217). `host` is the name it answers on over HTTPS; `claim_hash` and | |
| 3 | // `claim_expires` are the sha256 and deadline of the claim link its deployer | |
| 4 | // was shown once: the link itself is never stored, here or on the machine. | |
| 5 | // Additive; empty on a forge deployed before it had a name. | |
| 6 | export default ` | |
| 7 | ALTER TABLE pinned_forge ADD COLUMN host TEXT NOT NULL DEFAULT ''; | |
| 8 | ALTER TABLE pinned_forge ADD COLUMN claim_hash TEXT NOT NULL DEFAULT ''; | |
| 9 | ALTER TABLE pinned_forge ADD COLUMN claim_expires TEXT NOT NULL DEFAULT ''; | |
| 10 | `; |
src/core/migrations/20261124053225-pinned-reached.ts added +7
| @@ -0,0 +1,7 @@ | ||
| 1 | // The machine a pinned forge last answered from about its claim (#16217): its id at the cloud, | |
| 2 | // written when the deployed forge says waiting, claimed or expired. While it is the forge's | |
| 3 | // current machine, the seller knows the forge has been reachable since that machine was made, so | |
| 4 | // silence from it is not taken as "unclaimed". Additive; empty until a forge first answers. | |
| 5 | export default ` | |
| 6 | ALTER TABLE pinned_forge ADD COLUMN reached TEXT NOT NULL DEFAULT ''; | |
| 7 | `; |
src/core/pinned.ts +82 −10
| @@ -25,6 +25,17 @@ export interface Pinned { | ||
| 25 | 25 | /** When the forge was handed to its buyer; empty while the seller still holds it. */ |
| 26 | 26 | readonly claimedAt: string; |
| 27 | 27 | readonly createdAt: string; |
| 28 | /** The name it is served on over HTTPS; empty on a forge deployed before it had one. */ | |
| 29 | readonly host: string; | |
| 30 | /** sha256 of the claim link its deployer was shown once; the link is never stored. */ | |
| 31 | readonly claimHash: string; | |
| 32 | /** When that claim stops working, ISO; empty when none was issued. */ | |
| 33 | readonly claimExpires: string; | |
| 34 | /** | |
| 35 | * The machine (its id at the cloud) the forge last answered from about its claim; while it is | |
| 36 | * `remote`, the forge has been reached since its current machine was made. | |
| 37 | */ | |
| 38 | readonly reached: string; | |
| 28 | 39 | } |
| 29 | 40 | |
| 30 | 41 | export interface Change { |
| @@ -41,11 +52,27 @@ export const NAME = /^[a-z][a-z0-9-]{0,39}$/; | ||
| 41 | 52 | export const VERSION = /^(?:[0-9a-f]{40}|v\d{1,4}\.\d{1,4}\.\d{1,4})$/; |
| 42 | 53 | export const APP = /^[a-z0-9][a-z0-9_-]{0,38}\/[a-z0-9][a-z0-9_.-]{0,99}$/; |
| 43 | 54 | const SOURCE = /^https:\/\/[a-z0-9][a-z0-9.-]{0,100}(?:\/[A-Za-z0-9._~-]{1,100}){1,4}$/; |
| 55 | /** | |
| 56 | * The name a forge is served on: lowercase DNS labels of letters, digits and inner dashes, two or | |
| 57 | * more, the last one letters, 253 characters at most. No port, no trailing dot, no wildcard, never | |
| 58 | * an address: it is written into the machine's boot config and its proxy's, so nothing a shell, | |
| 59 | * YAML or the proxy's own syntax could read as more than a name. | |
| 60 | */ | |
| 61 | const HOST = /^(?=.{4,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/; | |
| 44 | 62 | const KEY = /^[A-Z][A-Z0-9_]{0,63}$/; |
| 45 | 63 | // A value is written to a systemd EnvironmentFile on the machine: no quote, |
| 46 | 64 | // backslash, dollar, backtick or newline can reach it. |
| 47 | 65 | const VALUE = /^[A-Za-z0-9 _.,:\/@+=-]{0,512}$/; |
| 48 | const SECRETISH = /SECRET|TOKEN|PASSWORD|PASSWD|PRIVATE|CREDENTIAL|API_?KEY|ACCESS_?KEY/; | |
| 66 | /** | |
| 67 | * What the boot config sets itself (`servedEnv` and the data directory, `cloud/machine.ts`): the | |
| 68 | * forge's name, its listeners, who may say the client's address, its claim, its sandbox, its data. | |
| 69 | */ | |
| 70 | export const BOOT_NAMES: readonly string[] = ["FORGE_URL", "FORGE_HOST", "FORGE_BIND", "FORGE_TRUSTED_PROXIES", "FORGE_SSH_PORT", "FORGE_FIRST_ADMIN_SEED", "FORGE_CREW_SANDBOX", "FORGE_APP_DATA"]; | |
| 71 | const SECRETISH = /SECRET|TOKEN|PASSWORD|PASSWD|PASSPHRASE|PRIVATE|CREDENTIAL|COOKIE|AUTH(?!OR)|API_?KEY|ACCESS_?KEY|(?:^|_)KEYS?(?:_|$)/; | |
| 72 | // A name that steers the dynamic loader, the runtime, the path or the shell of the process it is | |
| 73 | // set for is never a setting: it is the unit's environment, and a forge that runs as itself must | |
| 74 | // not be told to load someone's library. The service's own HOME, USER and PATH come from systemd. | |
| 75 | const STEERING = /^(?:LD_|DYLD_|NODE_|BUN_|GIT_|GCONV_|MALLOC_|PYTHON)|^(?:PATH|HOME|SHELL|USER|LOGNAME|IFS|ENV|BASH_ENV|CDPATH|PWD|OLDPWD|TMPDIR|LOCPATH|NLSPATH|HOSTALIASES|RESOLV_HOST_CONF)$/; | |
| 49 | 76 | |
| 50 | 77 | export function validVersion(v: string): boolean { |
| 51 | 78 | return VERSION.test(v); |
| @@ -55,6 +82,10 @@ export function validSource(s: string): boolean { | ||
| 55 | 82 | return SOURCE.test(s) && !s.includes(".."); |
| 56 | 83 | } |
| 57 | 84 | |
| 85 | export function validHost(h: string): boolean { | |
| 86 | return HOST.test(h); | |
| 87 | } | |
| 88 | ||
| 58 | 89 | /** Config is plain, non-secret settings; a secret-looking name is refused so none lands in a row. */ |
| 59 | 90 | export function checkConfig(raw: unknown): Result<Record<string, string>, string> { |
| 60 | 91 | if (raw === undefined) return ok({}); |
| @@ -65,6 +96,8 @@ export function checkConfig(raw: unknown): Result<Record<string, string>, string | ||
| 65 | 96 | if (entries.length > 40) return err("config holds at most 40 settings"); |
| 66 | 97 | for (const [k, v] of entries) { |
| 67 | 98 | if (!KEY.test(k)) return err(`config name ${k.slice(0, 20)} is capitals, digits and underscores`); |
| 99 | if (BOOT_NAMES.includes(k)) return err(`${k} is set by the deploy itself (the forge's name, listener, claim, sandbox and data); it is not a setting`); | |
| 100 | if (STEERING.test(k)) return err(`${k} steers the loader, the runtime or the path of the process; it is not a setting`); | |
| 68 | 101 | if (SECRETISH.test(k)) return err(`${k} looks like a secret; secrets are sealed in cloud accounts, never in config`); |
| 69 | 102 | if (typeof v !== "string" || !VALUE.test(v)) return err(`config ${k} is plain text of letters, digits and . , : / @ + = - _`); |
| 70 | 103 | out[k] = v; |
| @@ -75,12 +108,14 @@ export function checkConfig(raw: unknown): Result<Record<string, string>, string | ||
| 75 | 108 | interface Row { |
| 76 | 109 | id: string; name: string; target: string; account: string; app: string; source: string; |
| 77 | 110 | version: string; config: string; remote: string; volume: string; address: string; state: string; claimed_at: string; created_at: string; |
| 111 | host: string; claim_hash: string; claim_expires: string; reached: string; | |
| 78 | 112 | } |
| 79 | 113 | |
| 80 | 114 | const toPinned = (r: Row): Pinned => ({ |
| 81 | 115 | id: r.id, name: r.name, target: r.target, account: r.account, app: r.app, source: r.source, |
| 82 | 116 | version: r.version, config: JSON.parse(r.config) as Record<string, string>, |
| 83 | 117 | remote: r.remote, volume: r.volume, address: r.address, state: r.state, claimedAt: r.claimed_at, createdAt: r.created_at, |
| 118 | host: r.host, claimHash: r.claim_hash, claimExpires: r.claim_expires, reached: r.reached, | |
| 84 | 119 | }); |
| 85 | 120 | |
| 86 | 121 | export const listPinned = (db: Database): Pinned[] => |
| @@ -102,7 +137,7 @@ export function changesOf(db: Database, pinnedId: string): Change[] { | ||
| 102 | 137 | |
| 103 | 138 | export function insertPinned( |
| 104 | 139 | db: Database, |
| 105 | p: { name: string; target: string; account: string; app: string; source: string; version: string; config: Record<string, string> }, | |
| 140 | p: { name: string; target: string; account: string; app: string; source: string; version: string; config: Record<string, string>; host: string; claimHash: string; claimExpires: string }, | |
| 106 | 141 | by: string, |
| 107 | 142 | ): Pinned { |
| 108 | 143 | const at = new Date().toISOString(); |
| @@ -113,8 +148,8 @@ export function insertPinned( | ||
| 113 | 148 | .query("INSERT INTO pinned_change (pinned_id, kind, from_version, to_version, from_config, to_config, by, at) VALUES (?1, 'deploy', NULL, ?2, NULL, ?3, ?4, ?5)") |
| 114 | 149 | .run(pid, p.version, config, by, at); |
| 115 | 150 | db.query( |
| 116 | "INSERT INTO pinned_forge (id, name, target, account, app, source, version, config, change_id, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)", | |
| 117 | ).run(pid, p.name, p.target, p.account, p.app, p.source, p.version, config, Number(c.lastInsertRowid), at); | |
| 151 | "INSERT INTO pinned_forge (id, name, target, account, app, source, version, config, change_id, created_at, host, claim_hash, claim_expires) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)", | |
| 152 | ).run(pid, p.name, p.target, p.account, p.app, p.source, p.version, config, Number(c.lastInsertRowid), at, p.host, p.claimHash, p.claimExpires); | |
| 118 | 153 | })(); |
| 119 | 154 | return getPinned(db, p.name)!; |
| 120 | 155 | } |
| @@ -163,8 +198,27 @@ export function setRemote(db: Database, name: string, f: { remote?: string; volu | ||
| 163 | 198 | } |
| 164 | 199 | |
| 165 | 200 | /** |
| 166 | * Hand the forge to its buyer. Once only; returns false when it was claimed already or does not | |
| 167 | * exist. | |
| 201 | * A new claim for the forge: the hash and deadline replace the ones before, so the row never holds | |
| 202 | * two. | |
| 203 | */ | |
| 204 | export function setClaim(db: Database, name: string, c: { hash: string; expires: string }): void { | |
| 205 | db.query("UPDATE pinned_forge SET claim_hash = ?1, claim_expires = ?2 WHERE name = ?3").run(c.hash, c.expires, name); | |
| 206 | } | |
| 207 | ||
| 208 | /** The forge answered about its claim from the machine it has now. */ | |
| 209 | export function markReached(db: Database, name: string, remote: string): void { | |
| 210 | db.query("UPDATE pinned_forge SET reached = ?1 WHERE name = ?2 AND remote = ?1").run(remote, name); | |
| 211 | } | |
| 212 | ||
| 213 | /** Name a forge deployed before forges had names; a forge that has a name keeps it. */ | |
| 214 | export function setHost(db: Database, name: string, host: string): void { | |
| 215 | db.query("UPDATE pinned_forge SET host = ?1 WHERE name = ?2 AND host = ''").run(host, name); | |
| 216 | } | |
| 217 | ||
| 218 | /** | |
| 219 | * Record that the forge is its buyer's: the deployed forge itself said its claim was used | |
| 220 | * (`actions/pinned.ts`), which is the only thing that calls this. Once only; returns false when it | |
| 221 | * was recorded already or the forge does not exist. | |
| 168 | 222 | */ |
| 169 | 223 | export function markClaimed(db: Database, name: string): boolean { |
| 170 | 224 | return db.query("UPDATE pinned_forge SET claimed_at = ?1 WHERE name = ?2 AND claimed_at = ''").run(new Date().toISOString(), name).changes === 1; |
| @@ -177,7 +231,15 @@ export function markClaimed(db: Database, name: string): boolean { | ||
| 177 | 231 | export const HOST_CAN = |
| 178 | 232 | "In its host's cloud account the host can open a forge's console, boot it into rescue, snapshot its disk and read its boot data; only the buyer's own cloud account gives the host none of that."; |
| 179 | 233 | |
| 180 | /** The sentence a refused Update or Rollback gives after the claim. */ | |
| 234 | /** | |
| 235 | * The sentence a refused Update, Rollback or new claim link gives while the forge cannot be asked | |
| 236 | * whether it was claimed, though its current machine has answered before. | |
| 237 | */ | |
| 238 | export const unconfirmedRefusal = (p: Pick<Pinned, "name" | "host" | "address">): string => | |
| 239 | `${p.name} has answered from this machine before and cannot be reached now, so this forge cannot confirm that nobody has claimed it; nothing was changed. ` + | |
| 240 | `Run Check until it says the forge answers (its name ${p.host} must resolve to ${p.address === "" ? "its machine" : p.address}), then ask again.`; | |
| 241 | ||
| 242 | /** The sentence a refused Update, Rollback or new claim link gives after the claim. */ | |
| 181 | 243 | export const CLAIMED_REFUSAL = "This forge was handed to its buyer: its updates are theirs to take, and this forge no longer changes it."; |
| 182 | 244 | |
| 183 | 245 | /** The row of a deploy that never reached a droplet, so its name can be tried again; its recorded change stays as history. */ |
| @@ -185,14 +247,24 @@ export function dropPinned(db: Database, name: string): void { | ||
| 185 | 247 | db.query("DELETE FROM pinned_forge WHERE name = ?1 AND remote = '' AND state = 'failed'").run(name); |
| 186 | 248 | } |
| 187 | 249 | |
| 188 | /** The port the forge listens on at its droplet: the config's PORT, else the forge's own default. */ | |
| 250 | /** | |
| 251 | * The port the forge listens on at its machine, on loopback behind the machine's proxy: the | |
| 252 | * config's PORT, else the forge's own default. | |
| 253 | */ | |
| 189 | 254 | export const portOf = (p: Pick<Pinned, "config">): string => { |
| 190 | 255 | const n = Number(p.config["PORT"]); |
| 191 | 256 | return /^\d{1,5}$/.test(p.config["PORT"] ?? "") && n >= 1 && n <= 65535 ? String(n) : "3000"; |
| 192 | 257 | }; |
| 193 | 258 | |
| 194 | /** Where a pinned forge is served, once its droplet's address is known; empty before. */ | |
| 195 | export const urlOf = (p: Pick<Pinned, "address" | "config">): string => (p.address === "" ? "" : `http://${p.address}:${portOf(p)}/`); | |
| 259 | /** | |
| 260 | * Where a pinned forge is served: HTTPS on its own name, never an address or a port. Empty for a | |
| 261 | * forge deployed before it had a name. | |
| 262 | */ | |
| 263 | export const urlOf = (p: Pick<Pinned, "host">): string => (p.host === "" ? "" : `https://${p.host}/`); | |
| 264 | ||
| 265 | /** The one DNS record the name needs, once the machine's address is read; empty before. */ | |
| 266 | export const dnsRecordOf = (p: Pick<Pinned, "host" | "address">): string => | |
| 267 | p.host === "" || p.address === "" ? "" : `${p.host} A ${p.address}`; | |
| 196 | 268 | |
| 197 | 269 | /** When the newest `check` of this forge ran, from the event it recorded; undefined before the first (or once pruned). */ |
| 198 | 270 | export function lastCheckOf(db: Database, name: string): string | undefined { |
src/crew/conversation.ts +6 −2
| @@ -50,6 +50,7 @@ import { isRateLimited, takeLimit, whenText } from "./limits.ts"; | ||
| 50 | 50 | import { turnBudget } from "./model_access.ts"; |
| 51 | 51 | import { credentialEnv, holdModelCredential, listenForSteer, steerable, steerRun } from "./runner.ts"; |
| 52 | 52 | import { sandboxPolicy } from "./sandbox.ts"; |
| 53 | import { sandboxRefusal } from "./sandbox_policy.ts"; | |
| 53 | 54 | |
| 54 | 55 | export interface ConversationOptions { |
| 55 | 56 | readonly binary: string; |
| @@ -278,7 +279,7 @@ export function mcpConfig(localUrl: string): string { | ||
| 278 | 279 | }); |
| 279 | 280 | } |
| 280 | 281 | |
| 281 | export type SayRefusal = "not_found" | "unauthorized" | "empty" | "too_long" | "no_account" | "resting" | "busy" | "answering" | "queue_full" | "file_taken"; | |
| 282 | export type SayRefusal = "not_found" | "unauthorized" | "empty" | "too_long" | "no_account" | "resting" | "busy" | "answering" | "queue_full" | "file_taken" | "sandbox"; | |
| 282 | 283 | |
| 283 | 284 | export interface Said { |
| 284 | 285 | /** |
| @@ -590,7 +591,10 @@ function begin( | ||
| 590 | 591 | * answers. |
| 591 | 592 | */ |
| 592 | 593 | follow?: { readonly words: string }, |
| 593 | ): Result<Promise<void>, "no_account" | "resting" | "unauthorized"> { | |
| 594 | ): Result<Promise<void>, "no_account" | "resting" | "unauthorized" | "sandbox"> { | |
| 595 | // A forge that requires the sandbox and cannot make one starts no agent process at all, a turn | |
| 596 | // with no shell included (`sandbox_policy.ts`); any other forge is not asked. | |
| 597 | if (sandboxRefusal(app) !== undefined) return err("sandbox"); | |
| 594 | 598 | const userId = conversation.userId; |
| 595 | 599 | const runId = id(); |
| 596 | 600 | const now = new Date(); |
src/crew/dispatch.ts +43 −6
| @@ -110,6 +110,7 @@ import { | ||
| 110 | 110 | } from "./guard.ts"; |
| 111 | 111 | import { noteProtection } from "../kernel/protection.ts"; |
| 112 | 112 | import { dataInTemp, sandboxAvailable, sweepRunTmp } from "./sandbox.ts"; |
| 113 | import { SANDBOX_ENV, noteSandbox, reprober, sandboxHoldSentence, sandboxRefusal, type SandboxProbe } from "./sandbox_policy.ts"; | |
| 113 | 114 | import { sandboxCause } from "./sandbox_cause.ts"; |
| 114 | 115 | import { mayDirectCrew } from "./direct.ts"; |
| 115 | 116 | import { |
| @@ -239,7 +240,9 @@ export async function startCrew( | ||
| 239 | 240 | // The default the Capacity page shows and goes back to (`core/capacity.ts`). |
| 240 | 241 | noteBooted(app.db, "crew.concurrency", String(options.concurrency)); |
| 241 | 242 | const sandbox = await sandboxAvailable(); |
| 242 | noteProtection(app, "crew shells", sandbox); | |
| 243 | const noteShells = (probe: SandboxProbe): void => | |
| 244 | noteProtection(app, "crew shells", probe, options.sandboxRequired === true ? `its runs are refused (${SANDBOX_ENV}=require)` : undefined); | |
| 245 | noteShells(sandbox); | |
| 243 | 246 | // Temp directories of runs a stopped forge never finished: old enough |
| 244 | 247 | // that no forge beside this one (a rollout) can still be using them. |
| 245 | 248 | try { |
| @@ -255,18 +258,40 @@ export async function startCrew( | ||
| 255 | 258 | "the data directory is inside the temp directory: agents' shells are denied only the forge's own pieces of it, not all of it", |
| 256 | 259 | { dataDir: app.config.dataDir, tmpdir: tmpdir() }, |
| 257 | 260 | ); |
| 258 | if (!sandbox.ok) | |
| 261 | if (!sandbox.ok && options.sandboxRequired === true) | |
| 262 | log.warn("agent sandbox not available here; crew runs are refused", { | |
| 263 | cause: sandboxCause(sandbox.reason).words, | |
| 264 | reason: sandbox.reason, | |
| 265 | }); | |
| 266 | else if (!sandbox.ok) | |
| 259 | 267 | log.warn("agent sandbox not available here; runs are unrestricted", { |
| 260 | 268 | cause: sandboxCause(sandbox.reason).words, |
| 261 | 269 | reason: sandbox.reason, |
| 262 | 270 | }); |
| 263 | const ready: CrewOptions = { | |
| 271 | const standing = (probe: SandboxProbe): CrewOptions => ({ | |
| 264 | 272 | ...options, |
| 265 | sandboxEnforced: sandbox.ok, | |
| 266 | ...(sandbox.ok ? {} : { sandboxNote: sandbox.reason }), | |
| 267 | }; | |
| 273 | sandboxEnforced: probe.ok, | |
| 274 | ...(probe.ok ? {} : { sandboxNote: probe.reason }), | |
| 275 | }); | |
| 276 | let ready: CrewOptions = standing(sandbox); | |
| 268 | 277 | |
| 269 | 278 | let stopped = false; |
| 279 | // A host that could not hold the sandbox is asked again while something waits on it (a held | |
| 280 | // run, a refused turn), at most once a minute: fixed, it is heard without a restart, the footer | |
| 281 | // stops saying reduced, and what was held starts. | |
| 282 | const again = reprober({ | |
| 283 | last: Date.now(), | |
| 284 | heard: (probe) => { | |
| 285 | if (stopped) return; | |
| 286 | ready = standing(probe); | |
| 287 | noteShells(probe); | |
| 288 | noteSandbox(app, options.sandboxRequired === true, probe, again); | |
| 289 | if (!probe.ok) return; | |
| 290 | log.info("agent sandbox is available now; what waited on it starts"); | |
| 291 | pump(app, ready, inFlight); | |
| 292 | }, | |
| 293 | }); | |
| 294 | noteSandbox(app, options.sandboxRequired === true, sandbox, again); | |
| 270 | 295 | // Runs `pump` has started and not yet seen finish. `stop()` aborts each |
| 271 | 296 | // and waits for it: without this, a run `pump` fired (fire-and-forget) |
| 272 | 297 | // keeps cloning, spawning and eventually calling `finishRun`/`announceRun` |
| @@ -1752,6 +1777,18 @@ export function pump( | ||
| 1752 | 1777 | } |
| 1753 | 1778 | const fresh = getRun(app.db, queued.id); |
| 1754 | 1779 | if (!fresh || fresh.state !== "queued") continue; |
| 1780 | // No sandbox and the forge asked for one: agent-written shell does not run unrestricted | |
| 1781 | // (`sandbox_policy.ts`). | |
| 1782 | if (options.sandboxRequired === true && options.sandboxEnforced === false) { | |
| 1783 | held.set(fresh.id, "sandbox"); | |
| 1784 | // Asks for the probe again (at most once a minute): the crew's own pass is what notices. | |
| 1785 | sandboxRefusal(app); | |
| 1786 | if (!noted.has(fresh.id)) { | |
| 1787 | noted.add(fresh.id); | |
| 1788 | appendRunLog(app.config.dataDir, fresh.id, `queued, not started: ${sandboxHoldSentence(options.sandboxNote ?? "")}`); | |
| 1789 | } | |
| 1790 | continue; | |
| 1791 | } | |
| 1755 | 1792 | // A fresh run queued before Archive is cancelled, not started, and |
| 1756 | 1793 | // stays cancelled through Wake. One carrying on after a pause or a |
| 1757 | 1794 | // restart (attempt > 0) is already going, and finishes. |
src/crew/one_shot.ts +4 −1
| @@ -19,17 +19,20 @@ import { isRateLimited } from "./limits.ts"; | ||
| 19 | 19 | import { turnBudget } from "./model_access.ts"; |
| 20 | 20 | import { credentialEnv, holdModelCredential } from "./runner.ts"; |
| 21 | 21 | import { sandboxPolicy } from "./sandbox.ts"; |
| 22 | import { sandboxRefusal } from "./sandbox_policy.ts"; | |
| 22 | 23 | |
| 23 | 24 | /** The most one such question may spend, in dollars. */ |
| 24 | 25 | export const ONE_SHOT_USD = 0.05; |
| 25 | 26 | /** The longest one may take. */ |
| 26 | 27 | export const ONE_SHOT_MS = 60_000; |
| 27 | 28 | |
| 28 | export type OneShotRefusal = "off" | "no_account" | "resting" | "failed"; | |
| 29 | export type OneShotRefusal = "off" | "no_account" | "resting" | "failed" | "sandbox"; | |
| 29 | 30 | |
| 30 | 31 | export async function oneShot(app: App, userId: string, system: string, prompt: string, model?: string): Promise<Result<string, OneShotRefusal>> { |
| 31 | 32 | const options = conversationOptions(app); |
| 32 | 33 | if (options === undefined) return err("off"); |
| 34 | // As a turn is: no agent process on a forge that requires the sandbox and cannot make one. | |
| 35 | if (sandboxRefusal(app) !== undefined) return err("sandbox"); | |
| 33 | 36 | const now = new Date(); |
| 34 | 37 | const runId = id(); |
| 35 | 38 | const picked = pickSubscription(app.db, app.config.dataDir, { repoId: "", ownerId: userId, agentId: "" }, now, { runId, usd: ONE_SHOT_USD }); |
src/crew/runner.ts +2
| @@ -260,6 +260,8 @@ export interface CrewOptions { | ||
| 260 | 260 | readonly sandboxEnforced?: boolean | undefined; |
| 261 | 261 | /** Why it cannot, when it cannot — said once in every run's log. */ |
| 262 | 262 | readonly sandboxNote?: string | undefined; |
| 263 | /** Refuse crew runs while the sandbox is unavailable (`sandbox_policy.ts`). */ | |
| 264 | readonly sandboxRequired?: boolean | undefined; | |
| 263 | 265 | /** Milliseconds between the crew's ticks; tests pass a small one. @default 5000 */ |
| 264 | 266 | readonly tickMs?: number | undefined; |
| 265 | 267 | /** |
src/crew/sandbox_policy.ts added +98
| @@ -0,0 +1,98 @@ | ||
| 1 | /** | |
| 2 | * Whether a forge whose host cannot hold an agent's shell to the sandbox | |
| 3 | * still runs the crew. | |
| 4 | * | |
| 5 | * `FORGE_CREW_SANDBOX` says it: `require` refuses crew runs while the sandbox | |
| 6 | * is unavailable (they stay queued, held as "sandbox", with the sentence below | |
| 7 | * in the run's log); `off` runs them unrestricted on purpose (a developer's | |
| 8 | * machine, a container that is already the sandbox) and the boot warning stays. | |
| 9 | * Unset follows `DEFAULT_MODE`: `off` until every forge that legitimately runs | |
| 10 | * without bubblewrap sets it, then `require` — the one line to change. | |
| 11 | */ | |
| 12 | ||
| 13 | import { sandboxAvailable } from "./sandbox.ts"; | |
| 14 | import { sandboxCause } from "./sandbox_cause.ts"; | |
| 15 | ||
| 16 | export const SANDBOX_ENV = "FORGE_CREW_SANDBOX"; | |
| 17 | ||
| 18 | export type SandboxMode = "require" | "off"; | |
| 19 | ||
| 20 | /** What an unset `FORGE_CREW_SANDBOX` means. */ | |
| 21 | export const DEFAULT_MODE: SandboxMode = "off"; | |
| 22 | ||
| 23 | /** The mode `env` asks for; anything unrecognised is the default. */ | |
| 24 | export function sandboxMode(env: Record<string, string | undefined>): SandboxMode { | |
| 25 | const value = (env[SANDBOX_ENV] ?? "").trim().toLowerCase(); | |
| 26 | return value === "require" || value === "off" ? value : DEFAULT_MODE; | |
| 27 | } | |
| 28 | ||
| 29 | /** What the probe (`sandboxAvailable`) answered. */ | |
| 30 | export type SandboxProbe = { ok: true } | { ok: false; reason: string }; | |
| 31 | ||
| 32 | /** The least time between two probes of a host that could not hold the sandbox. */ | |
| 33 | export const SANDBOX_REPROBE_MS = 60_000; | |
| 34 | ||
| 35 | /** | |
| 36 | * Where each forge's sandbox stands: whether it is required, what the last probe found, and how to | |
| 37 | * ask again. Written by the crew when it starts and after each probe (`crew/dispatch.ts`); one | |
| 38 | * entry per forge, gone with it. | |
| 39 | */ | |
| 40 | const standing = new WeakMap<object, { required: boolean; probe: SandboxProbe; again: () => void }>(); | |
| 41 | ||
| 42 | export function noteSandbox(app: object, required: boolean, probe: SandboxProbe, again: () => void): void { | |
| 43 | standing.set(app, { required, probe, again }); | |
| 44 | } | |
| 45 | ||
| 46 | /** | |
| 47 | * The sentence that refuses anything the agent would run on this forge now (a crew run, a | |
| 48 | * conversation turn, a one-shot), or undefined when it may run: the forge requires the sandbox and | |
| 49 | * the last probe could not make one. Refusing asks for the probe to be taken again, so a host that | |
| 50 | * was fixed is heard without a restart. A forge that does not require it is never refused here. | |
| 51 | * One that requires it and has no probe on record yet (asked before the crew's first probe at | |
| 52 | * boot, or with no crew started) is refused as well: unproven is not available, and nothing runs | |
| 53 | * on the assumption. | |
| 54 | */ | |
| 55 | export function sandboxRefusal(app: object, env: Record<string, string | undefined> = process.env): string | undefined { | |
| 56 | const s = standing.get(app); | |
| 57 | if (s === undefined) return sandboxMode(env) === "require" ? SANDBOX_UNPROVEN : undefined; | |
| 58 | if (!s.required || s.probe.ok) return undefined; | |
| 59 | s.again(); | |
| 60 | return sandboxHoldSentence(s.probe.reason); | |
| 61 | } | |
| 62 | ||
| 63 | /** What a forge that requires the sandbox says before its first probe has answered. */ | |
| 64 | export const SANDBOX_UNPROVEN = `this forge requires the agent sandbox and has not yet checked that it works here; try again in a moment.`; | |
| 65 | ||
| 66 | /** | |
| 67 | * The probe, taken again when asked: one at a time, and no sooner than `SANDBOX_REPROBE_MS` after | |
| 68 | * the last. Returns whether this ask started one; `heard` is told each answer. | |
| 69 | */ | |
| 70 | export function reprober(o: { | |
| 71 | /** When the sandbox was last probed, ms. */ | |
| 72 | last: number; | |
| 73 | heard: (probe: SandboxProbe) => void; | |
| 74 | probe?: () => Promise<SandboxProbe>; | |
| 75 | now?: () => number; | |
| 76 | }): () => boolean { | |
| 77 | const now = o.now ?? Date.now; | |
| 78 | const probe = o.probe ?? sandboxAvailable; | |
| 79 | let last = o.last; | |
| 80 | let asking = false; | |
| 81 | return () => { | |
| 82 | if (asking || now() - last < SANDBOX_REPROBE_MS) return false; | |
| 83 | asking = true; | |
| 84 | void probe() | |
| 85 | .catch((error: unknown): SandboxProbe => ({ ok: false, reason: error instanceof Error ? error.message : String(error) })) | |
| 86 | .then((answer) => { | |
| 87 | last = now(); | |
| 88 | asking = false; | |
| 89 | o.heard(answer); | |
| 90 | }); | |
| 91 | return true; | |
| 92 | }; | |
| 93 | } | |
| 94 | ||
| 95 | /** Why a run waits, naming the cause the probe reported and what to do. */ | |
| 96 | export function sandboxHoldSentence(reason: string): string { | |
| 97 | return `this forge requires the agent sandbox and it is unavailable here (${sandboxCause(reason).words}); make the host able to run bubblewrap and socat, or set ${SANDBOX_ENV}=off to run the crew unrestricted on purpose.`; | |
| 98 | } |
src/engine/crossing.ts +1
| @@ -24,6 +24,7 @@ export const CROSSES = [ | ||
| 24 | 24 | "dataDir", |
| 25 | 25 | "codeBudgetMs", |
| 26 | 26 | "port", |
| 27 | "bind", | |
| 27 | 28 | "host", |
| 28 | 29 | "url", |
| 29 | 30 | "edgeToken", |
src/http/api.ts +12
| @@ -281,6 +281,7 @@ import { | ||
| 281 | 281 | recoverFirstAdmin, |
| 282 | 282 | redeemFirstAdmin, |
| 283 | 283 | } from "../actions/first_admin.ts"; |
| 284 | import { seedState } from "../core/first_admin.ts"; | |
| 284 | 285 | import { cookieValue, crossOrigin, type Ctx, type Handler } from "./context.ts"; |
| 285 | 286 | import { |
| 286 | 287 | apiError, |
| @@ -1459,6 +1460,17 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo | ||
| 1459 | 1460 | ); |
| 1460 | 1461 | }); |
| 1461 | 1462 | |
| 1463 | // What became of the claim a deployed forge was started with (`core/first_admin.ts`, | |
| 1464 | // `seedState`): | |
| 1465 | // asked by the forge that deployed it, which holds the claim's sha256 and nothing more. Any other | |
| 1466 | // value, and a forge that was started with no claim, answers the 404 of a route that is not | |
| 1467 | // there. | |
| 1468 | router.add("GET", "/api/v1/first-admin/claim", (ctx) => { | |
| 1469 | const state = seedState(ctx.app.db, ctx.url.searchParams.get("seed") ?? ""); | |
| 1470 | if (state === undefined) return notFound(); | |
| 1471 | return new Response(JSON.stringify({ state }), { headers: { "content-type": "application/json", "cache-control": "no-store" } }); | |
| 1472 | }); | |
| 1473 | ||
| 1462 | 1474 | // A stranded admin, headless (`core/first_admin.ts`): every admin's way in |
| 1463 | 1475 | // has lapsed, and the operator's recovery code buys the one it names a new |
| 1464 | 1476 | // expiring token. No account is made; refusals read as the door above. |
src/http/api/admin.ts +18 −9
| @@ -70,6 +70,12 @@ export function adminRoutes(router: Router<Handler>): void { | ||
| 70 | 70 | const pinnedFail = (error: string): Response => |
| 71 | 71 | error === "not_found" || error === "No such pinned forge." ? notFound() : apiError("refused", 422, error); |
| 72 | 72 | |
| 73 | /** An answer that holds a claim link: no cache between here and the caller keeps it. */ | |
| 74 | const once = (response: Response): Response => { | |
| 75 | response.headers.set("cache-control", "no-store"); | |
| 76 | return response; | |
| 77 | }; | |
| 78 | ||
| 73 | 79 | router.add("GET", "/api/v1/admin/pinned", (ctx) => { |
| 74 | 80 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); |
| 75 | 81 | const denied = accountAdmin(ctx, "ro"); |
| @@ -83,10 +89,20 @@ export function adminRoutes(router: Router<Handler>): void { | ||
| 83 | 89 | if (denied) return denied; |
| 84 | 90 | const i = await body(ctx.request); |
| 85 | 91 | const made = await deployPinned(ctx.app, ctx.auth.user, { |
| 86 | name: str(i.name), target: str(i.target), account: str(i.account), app: str(i.app), | |
| 92 | name: str(i.name), host: str(i.host), target: str(i.target), account: str(i.account), app: str(i.app), | |
| 87 | 93 | source: str(i.source), version: str(i.version), config: i.config, |
| 88 | 94 | }); |
| 89 | return made.ok ? json(made.value, 201) : pinnedFail(made.error); | |
| 95 | // The answer holds the claim link, shown once: nothing between here and the caller keeps it. | |
| 96 | return made.ok ? once(json(made.value, 201)) : pinnedFail(made.error); | |
| 97 | }); | |
| 98 | ||
| 99 | // A fresh claim link for a forge nobody has claimed; the one before it stops working. | |
| 100 | router.add("POST", "/api/v1/admin/pinned/:name/claim", async (ctx) => { | |
| 101 | const denied = accountAdmin(ctx, "admin"); | |
| 102 | if (denied) return denied; | |
| 103 | const i = await body(ctx.request); | |
| 104 | const done = await claimPinned(ctx.app, ctx.auth.user, ctx.params.name!, { host: i.host === undefined ? undefined : str(i.host) }); | |
| 105 | return done.ok ? once(json(done.value)) : pinnedFail(done.error); | |
| 90 | 106 | }); |
| 91 | 107 | |
| 92 | 108 | router.add("POST", "/api/v1/admin/pinned/:name/update", async (ctx) => { |
| @@ -113,13 +129,6 @@ export function adminRoutes(router: Router<Handler>): void { | ||
| 113 | 129 | return done.ok ? json(done.value) : pinnedFail(done.error); |
| 114 | 130 | }); |
| 115 | 131 | |
| 116 | router.add("POST", "/api/v1/admin/pinned/:name/claim", (ctx) => { | |
| 117 | const denied = accountAdmin(ctx, "admin"); | |
| 118 | if (denied) return denied; | |
| 119 | const done = claimPinned(ctx.app, ctx.auth.user, ctx.params.name!); | |
| 120 | return done.ok ? json(done.value) : pinnedFail(done.error); | |
| 121 | }); | |
| 122 | ||
| 123 | 132 | // ---- accounts: the owner's view of who joined (#660) ---- |
| 124 | 133 | const accountError = (error: string): Response => |
| 125 | 134 | error === "not_found" |
src/http/marks/settings.json +1
| @@ -61,6 +61,7 @@ | ||
| 61 | 61 | "/settings/cloud": "admin", |
| 62 | 62 | "/settings/cloud/verify": "admin", |
| 63 | 63 | "/settings/cloud/write": "admin", |
| 64 | "/settings/cloud/ceiling": "admin", | |
| 64 | 65 | "/settings/cloud/audit": "admin", |
| 65 | 66 | "/settings/cloud/rotate": "admin", |
| 66 | 67 | "/settings/cloud/rename": "admin", |
src/http/mcp/tools/cloud_account.ts +9 −5
| @@ -1,4 +1,5 @@ | ||
| 1 | 1 | import { addAccount, allowWrite, auditAccount, removeAccount, renameAccount, reverify, rotateAccount } from "../../../actions/cloud.ts"; |
| 2 | import { setCeiling } from "../../../actions/cloud_ceiling.ts"; | |
| 2 | 3 | import { PROVIDERS } from "../../../cloud/providers.ts"; |
| 3 | 4 | import { scopeAllows } from "../../../core/tokens.ts"; |
| 4 | 5 | import { good, bad, type Tool, str } from "../shared.ts"; |
| @@ -6,19 +7,20 @@ import { good, bad, type Tool, str } from "../shared.ts"; | ||
| 6 | 7 | export const tool: Tool = { |
| 7 | 8 | name: "cloud_account", |
| 8 | 9 | listedTo: "admin", |
| 9 | doc: "`{ verb, provider, name, value?, to?, allowed?, repo? }`: change a cloud account: `attach` or `rotate` a token (`value`), `verify` it, `rename` it (`to`), `remove` it, `allow_writes` (`allowed` true or false) or `audit` (`repo` owner/name); a forge admin with an admin-scope token; answers a one-line `says`", | |
| 10 | doc: "`{ verb, provider, name, value?, to?, allowed?, repo?, dollars? }`: change a cloud account: `attach` or `rotate` a token (`value`), `verify` it, `rename` it (`to`), `remove` it, `allow_writes` (`allowed` true or false), `set_ceiling` (`dollars`: the most the forge lets it cost a month, whole US dollars, 50 until changed) or `audit` (`repo` owner/name); a forge admin with an admin-scope token; answers a one-line `says`", | |
| 10 | 11 | description: |
| 11 | 12 | "Change a cloud account by `verb` (admin).", |
| 12 | 13 | inputSchema: { |
| 13 | 14 | type: "object", |
| 14 | 15 | properties: { |
| 15 | verb: { type: "string", enum: ["attach", "verify", "rotate", "rename", "remove", "allow_writes", "audit"] }, | |
| 16 | verb: { type: "string", enum: ["attach", "verify", "rotate", "rename", "remove", "allow_writes", "set_ceiling", "audit"] }, | |
| 16 | 17 | provider: { type: "string", enum: [...PROVIDERS] }, |
| 17 | 18 | name: { type: "string", maxLength: 32 }, |
| 18 | 19 | value: { type: "string", maxLength: 4096, description: "For attach, rotate." }, |
| 19 | 20 | to: { type: "string", maxLength: 32 }, |
| 20 | 21 | allowed: { type: "boolean" }, |
| 21 | 22 | repo: { type: "string", maxLength: 200 }, |
| 23 | dollars: { type: "integer", minimum: 0, maximum: 100000, description: "For set_ceiling." }, | |
| 22 | 24 | }, |
| 23 | 25 | required: ["verb", "provider", "name"], |
| 24 | 26 | }, |
| @@ -48,10 +50,12 @@ export const tool: Tool = { | ||
| 48 | 50 | ? removeAccount(ctx.app, user, provider, name) |
| 49 | 51 | : verb === "allow_writes" |
| 50 | 52 | ? allowWrite(ctx.app, user, provider, name, args["allowed"] === true) |
| 51 | : verb === "audit" | |
| 52 | ? await auditAccount(ctx.app, user, provider, name, str(args["repo"])) | |
| 53 | : verb === "set_ceiling" | |
| 54 | ? setCeiling(ctx.app, user, provider, name, args["dollars"]) | |
| 55 | : verb === "audit" | |
| 56 | ? await auditAccount(ctx.app, user, provider, name, str(args["repo"])) | |
| 53 | 57 | : undefined; |
| 54 | if (done === undefined) return bad("bad_verb", "verb is attach, verify, rotate, rename, remove, allow_writes or audit"); | |
| 58 | if (done === undefined) return bad("bad_verb", "verb is attach, verify, rotate, rename, remove, allow_writes, set_ceiling or audit"); | |
| 55 | 59 | if (!done.ok) return bad("refused", done.error); |
| 56 | 60 | const v = done.value as unknown; |
| 57 | 61 | const said = |
src/http/mcp/tools/pinned_forge.ts +25 −16
| @@ -1,4 +1,4 @@ | ||
| 1 | import { checkPinned, claimPinned, deployPinned, pinnedForges, rollbackPinned, updatePinned } from "../../../actions/pinned.ts"; | |
| 1 | import { checkPinned, checkWords, claimPinned, claimWords, deployPinned, pinnedForges, rollbackPinned, updatePinned } from "../../../actions/pinned.ts"; | |
| 2 | 2 | import { TARGETS } from "../../../cloud/targets.ts"; |
| 3 | 3 | import { scopeAllows } from "../../../core/tokens.ts"; |
| 4 | 4 | import { good, bad, type Tool, str } from "../shared.ts"; |
| @@ -6,13 +6,14 @@ import { good, bad, type Tool, str } from "../shared.ts"; | ||
| 6 | 6 | export const tool: Tool = { |
| 7 | 7 | name: "pinned_forge", |
| 8 | 8 | listedTo: "admin", |
| 9 | doc: "`{ verb, name?, target?, account?, app?, source?, version?, config? }`: a pinned forge on the owner's cloud has no crew and no automatic release. `list` shows them with every recorded change and the targets (what runs, what it costs, what is refused); `deploy` puts one on `target` with a cloud `account` (writes allowed) serving `app` owner/name from `source` at `version`; `update` is the only way its `version` or `config` change; `rollback` goes back one; `claim` records that the forge was handed to its buyer, after which update and rollback are refused; `check` reads the machine's address back and probes it (`url`, `healthy`). A forge admin with an admin-scope token", | |
| 10 | description: "Pinned forges on your cloud: list, deploy, update, rollback, check (admin).", | |
| 9 | doc: "`{ verb, name?, host?, target?, account?, app?, source?, version?, config? }`: a pinned forge on the owner's cloud has no crew and no automatic release. `list` shows them with every recorded change and the targets (what runs, what it costs, what is refused); `deploy` puts one on `target` with a cloud `account` (writes allowed) serving `app` owner/name from `source` at `version` on `host`, its own name over HTTPS, and answers once with `claim.link`, the only way to become its first admin, and `dns`, the record to create; `claim` issues a fresh link for a forge nobody has claimed (the machine is replaced, the old link stops); `update` is the only way its `version` or `config` change; `rollback` goes back one; `check` reads the machine's address back and says what the forge waits for (`waiting`: address, dns, answer) or that it answers and what became of its claim (`url`, `healthy`, `claim`). A forge admin with an admin-scope token", | |
| 10 | description: "Pinned forges on your cloud: list, deploy, claim, update, rollback, check (admin).", | |
| 11 | 11 | inputSchema: { |
| 12 | 12 | type: "object", |
| 13 | 13 | properties: { |
| 14 | verb: { type: "string", enum: ["list", "deploy", "update", "rollback", "check", "claim"] }, | |
| 14 | verb: { type: "string", enum: ["list", "deploy", "claim", "update", "rollback", "check"] }, | |
| 15 | 15 | name: { type: "string", maxLength: 40 }, |
| 16 | host: { type: "string", maxLength: 253, description: "The DNS name it is served on over HTTPS." }, | |
| 16 | 17 | target: { type: "string", enum: TARGETS.map((t) => t.id) }, |
| 17 | 18 | account: { type: "string", maxLength: 32 }, |
| 18 | 19 | app: { type: "string", maxLength: 140 }, |
| @@ -37,25 +38,33 @@ export const tool: Tool = { | ||
| 37 | 38 | if (!scopeAllows(ctx.auth.scope ?? "ro", "admin")) |
| 38 | 39 | return bad("forbidden", "changing a pinned forge needs an admin-scope token"); |
| 39 | 40 | const name = str(args["name"]); |
| 41 | // A claim is shown once: the answer holds the link and the sentences that say what to do with | |
| 42 | // it. | |
| 43 | if (verb === "deploy" || verb === "claim") { | |
| 44 | const made = | |
| 45 | verb === "deploy" | |
| 46 | ? await deployPinned(ctx.app, user, { | |
| 47 | name, host: str(args["host"]), target: str(args["target"]), account: str(args["account"]), app: str(args["app"]), | |
| 48 | source: str(args["source"]), version: str(args["version"]), config: args["config"], | |
| 49 | }) | |
| 50 | : await claimPinned(ctx.app, user, name, { host: args["host"] === undefined ? undefined : str(args["host"]) }); | |
| 51 | if (!made.ok) return bad("refused", made.error); | |
| 52 | return good({ says: `${verb} ${name}: now ${made.value.version}, ${made.value.state} at ${made.value.url}. ${claimWords(made.value)}`, claim: made.value.claim, forge: made.value }); | |
| 53 | } | |
| 54 | if (verb === "check") { | |
| 55 | const seen = await checkPinned(ctx.app, user, name); | |
| 56 | return seen.ok ? good({ says: `check ${name}: now ${seen.value.version}. ${checkWords(seen.value)}`, forge: seen.value }) : bad("refused", seen.error); | |
| 57 | } | |
| 40 | 58 | const done = |
| 41 | verb === "deploy" | |
| 42 | ? await deployPinned(ctx.app, user, { | |
| 43 | name, target: str(args["target"]), account: str(args["account"]), app: str(args["app"]), | |
| 44 | source: str(args["source"]), version: str(args["version"]), config: args["config"], | |
| 45 | }) | |
| 46 | : verb === "update" | |
| 59 | verb === "update" | |
| 47 | 60 | ? await updatePinned(ctx.app, user, name, { |
| 48 | 61 | version: args["version"] === undefined ? undefined : str(args["version"]), |
| 49 | 62 | config: args["config"], |
| 50 | 63 | }) |
| 51 | 64 | : verb === "rollback" |
| 52 | 65 | ? await rollbackPinned(ctx.app, user, name) |
| 53 | : verb === "check" | |
| 54 | ? await checkPinned(ctx.app, user, name) | |
| 55 | : verb === "claim" | |
| 56 | ? claimPinned(ctx.app, user, name) | |
| 57 | : undefined; | |
| 58 | if (done === undefined) return bad("bad_verb", "verb is list, deploy, update, rollback, check or claim"); | |
| 66 | : undefined; | |
| 67 | if (done === undefined) return bad("bad_verb", "verb is list, deploy, claim, update, rollback or check"); | |
| 59 | 68 | if (!done.ok) return bad("refused", done.error); |
| 60 | 69 | return good({ says: `${verb} ${name}: now ${done.value.version}, ${done.value.state}${done.value.url ? ` at ${done.value.url}` : ""}.`, forge: done.value }); |
| 61 | 70 | }, |
src/http/pinned_routes.ts +25 −15
| @@ -3,9 +3,11 @@ | ||
| 3 | 3 | * filled from `app`, `source` and `version` in the link; signed out, it sends |
| 4 | 4 | * the visitor through one sign-in and back to the same link. POST is the same |
| 5 | 5 | * `deployPinned` the API, MCP and terminal call, admin only and same-origin. |
| 6 | * A deploy and a new claim answer with the claim link on the page itself, | |
| 7 | * never through a redirect or a flash: it is shown once and stored nowhere. | |
| 6 | 8 | */ |
| 7 | 9 | |
| 8 | import { checkPinned, claimPinned, deployPinned, pinnedForges, rollbackPinned, updatePinned } from "../actions/pinned.ts"; | |
| 10 | import { checkPinned, checkWords, claimPinned, deployPinned, pinnedForges, rollbackPinned, updatePinned, type Issued } from "../actions/pinned.ts"; | |
| 9 | 11 | import { listCloudAccounts } from "../core/cloud_account.ts"; |
| 10 | 12 | import { lastCheckOf } from "../core/pinned.ts"; |
| 11 | 13 | import { getUsersByIds } from "../core/users.ts"; |
| @@ -13,7 +15,7 @@ import { notFoundPage, signInFirst } from "../web/chrome.ts"; | ||
| 13 | 15 | import { field, readForm } from "../web/form.ts"; |
| 14 | 16 | import { flashTo, page } from "../web/layout.ts"; |
| 15 | 17 | import { pinnedListPage } from "../web/pages/pinned.ts"; |
| 16 | import { deployPage, nameFor, type DeployForm } from "../web/pinned.ts"; | |
| 18 | import { deployPage, issuedPage, nameFor, type DeployForm } from "../web/pinned.ts"; | |
| 17 | 19 | import type { Handler, Ctx } from "./context.ts"; |
| 18 | 20 | import type { Router } from "./router.ts"; |
| 19 | 21 | |
| @@ -25,9 +27,17 @@ const seen = (get: (k: string) => string): DeployForm => { | ||
| 25 | 27 | version: get("version").trim().slice(0, 40), |
| 26 | 28 | account: get("account").trim().slice(0, 60), |
| 27 | 29 | name: get("name").trim().slice(0, 40) || nameFor(app), |
| 30 | host: get("host").trim().toLowerCase().slice(0, 253), | |
| 28 | 31 | }; |
| 29 | 32 | }; |
| 30 | 33 | |
| 34 | /** The claim link, on the page that answers the request and nowhere after it. */ | |
| 35 | function shown(ctx: Ctx, title: string, v: Issued): Response { | |
| 36 | const response = page({ ctx, title, body: issuedPage(title, v) }); | |
| 37 | response.headers.set("cache-control", "no-store"); | |
| 38 | return response; | |
| 39 | } | |
| 40 | ||
| 31 | 41 | function render(ctx: Ctx, v: DeployForm, flash?: { tone: "danger"; message: string }): Response { |
| 32 | 42 | return page( |
| 33 | 43 | { |
| @@ -59,7 +69,7 @@ async function deployToSubmit(ctx: Ctx): Promise<Response> { | ||
| 59 | 69 | const [target, account] = bits.length === 2 ? (bits as [string, string]) : ["digitalocean", v.account]; |
| 60 | 70 | const made = await deployPinned(ctx.app, ctx.auth.user, { ...v, target, account }); |
| 61 | 71 | if (!made.ok) return render(ctx, v, { tone: "danger", message: made.error }); |
| 62 | return flashTo(ctx, "/deploy-to", { message: `Deployed ${made.value.name} at ${made.value.version.slice(0, 12)}. It changes only when you press Update.` }); | |
| 72 | return shown(ctx, `Deployed ${made.value.name}`, made.value); | |
| 63 | 73 | } |
| 64 | 74 | |
| 65 | 75 | function listPage(ctx: Ctx): Response { |
| @@ -76,7 +86,10 @@ function listPage(ctx: Ctx): Response { | ||
| 76 | 86 | return page({ ctx, title: "Pinned forges", body: pinnedListPage(forges.value, { names, checks }) }); |
| 77 | 87 | } |
| 78 | 88 | |
| 79 | /** Update, Roll back and Check: the same actions the terminal's `u`, `r` and `c` call; admin only, same-origin, each refusal shown as its sentence. */ | |
| 89 | /** | |
| 90 | * Update, Roll back, Check and New claim link: the same actions the terminal's `u`, `r`, `c` and | |
| 91 | * `n` call; admin only, same-origin, each refusal shown as its sentence. | |
| 92 | */ | |
| 80 | 93 | async function pinnedAct(ctx: Ctx): Promise<Response> { |
| 81 | 94 | if (!ctx.auth.user) return signInFirst(ctx); |
| 82 | 95 | if (!ctx.auth.user.isAdmin) return notFoundPage(ctx); |
| @@ -88,19 +101,16 @@ async function pinnedAct(ctx: Ctx): Promise<Response> { | ||
| 88 | 101 | let done; |
| 89 | 102 | if (act === "update") done = await updatePinned(ctx.app, user, name, { version: field(form, "version").trim().slice(0, 40) }); |
| 90 | 103 | else if (act === "rollback") done = await rollbackPinned(ctx.app, user, name); |
| 91 | else if (act === "claim") done = claimPinned(ctx.app, user, name); | |
| 92 | else if (act === "check") done = await checkPinned(ctx.app, user, name); | |
| 93 | else return notFoundPage(ctx); | |
| 104 | else if (act === "check") { | |
| 105 | const seen = await checkPinned(ctx.app, user, name); | |
| 106 | return flashTo(ctx, "/pinned", seen.ok ? { tone: seen.value.healthy ? "success" : "attn", message: checkWords(seen.value) } : { tone: "danger", message: seen.error }); | |
| 107 | } else if (act === "claim") { | |
| 108 | const made = await claimPinned(ctx.app, user, name, { host: field(form, "host") }); | |
| 109 | return made.ok ? shown(ctx, `A new claim link for ${name}`, made.value) : flashTo(ctx, "/pinned", { tone: "danger", message: made.error }); | |
| 110 | } else return notFoundPage(ctx); | |
| 94 | 111 | if (!done.ok) return flashTo(ctx, "/pinned", { tone: "danger", message: done.error }); |
| 95 | 112 | const at = done.value.version.slice(0, 12); |
| 96 | const message = | |
| 97 | act === "check" | |
| 98 | ? `${name} ${"healthy" in done.value && done.value.healthy ? "answers" : "did not answer"}; it is ${done.value.state}.` | |
| 99 | : act === "claim" | |
| 100 | ? `${name} is handed to its buyer; Update and Roll back are refused from now on.` | |
| 101 | : act === "update" | |
| 102 | ? `Updated ${name} to ${at}.` | |
| 103 | : `Rolled ${name} back to ${at}.`; | |
| 113 | const message = act === "update" ? `Updated ${name} to ${at}.` : `Rolled ${name} back to ${at}.`; | |
| 104 | 114 | return flashTo(ctx, "/pinned", { tone: "success", message }); |
| 105 | 115 | } |
| 106 | 116 |
src/http/server.ts +3 −1
| @@ -3030,6 +3030,8 @@ export async function serve(app: App, options: { warm?: { families?: readonly Fa | ||
| 3030 | 3030 | const firstAnswer = new Promise<void>((resolve) => (firstAnswered = resolve)); |
| 3031 | 3031 | const web = Bun.serve({ |
| 3032 | 3032 | port: app.config.port ?? 3000, |
| 3033 | // Bound to one address when the operator named it (FORGE_BIND): loopback behind a proxy. | |
| 3034 | ...(app.config.bind === undefined ? {} : { hostname: app.config.bind }), | |
| 3033 | 3035 | // A release swaps in beside this process on the same port (#1663). |
| 3034 | 3036 | ...(app.config.selfSwap === true ? { reusePort: true } : {}), |
| 3035 | 3037 | idleTimeout: 120, |
| @@ -3089,7 +3091,7 @@ export async function serve(app: App, options: { warm?: { families?: readonly Fa | ||
| 3089 | 3091 | await response.arrayBuffer(); |
| 3090 | 3092 | return { status: response.status, ms: performance.now() - started }; |
| 3091 | 3093 | }, |
| 3092 | url: `http://localhost:${port}`, | |
| 3094 | url: `http://${app.config.bind ?? "localhost"}:${port}`, | |
| 3093 | 3095 | port, |
| 3094 | 3096 | get inFlight() { |
| 3095 | 3097 | return web.pendingRequests; |
src/http/settings_routes.ts +2
| @@ -68,6 +68,7 @@ import { | ||
| 68 | 68 | cloudAdd, |
| 69 | 69 | cloudAudit, |
| 70 | 70 | cloudAuditPage, |
| 71 | cloudCeiling, | |
| 71 | 72 | cloudRename, |
| 72 | 73 | cloudRotate, |
| 73 | 74 | cloudPage, |
| @@ -234,6 +235,7 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea | ||
| 234 | 235 | router.add("POST", "/settings/cloud", cloudAdd); |
| 235 | 236 | router.add("POST", "/settings/cloud/verify", cloudVerify); |
| 236 | 237 | router.add("POST", "/settings/cloud/write", cloudWrite); |
| 238 | router.add("POST", "/settings/cloud/ceiling", cloudCeiling); | |
| 237 | 239 | router.add("POST", "/settings/cloud/audit", cloudAudit); |
| 238 | 240 | router.add("GET", "/settings/cloud/audit", cloudAuditPage); |
| 239 | 241 | router.add("POST", "/settings/cloud/rotate", cloudRotate); |
src/kernel/protection.ts +10 −6
| @@ -12,7 +12,9 @@ | ||
| 12 | 12 | * run one file's note was another file's footer. |
| 13 | 13 | */ |
| 14 | 14 | |
| 15 | const lacking = new WeakMap<object, Map<string, string>>(); | |
| 15 | const UNCONTAINED = "uncontained"; | |
| 16 | ||
| 17 | const lacking = new WeakMap<object, Map<string, { reason: string; outcome: string }>>(); | |
| 16 | 18 | |
| 17 | 19 | /** |
| 18 | 20 | * A part says what it lacks (`ok`: nothing) and why, |
| @@ -22,19 +24,21 @@ export function noteProtection( | ||
| 22 | 24 | app: object, |
| 23 | 25 | part: string, |
| 24 | 26 | result: { ok: true } | { ok: false; reason: string }, |
| 27 | outcome = UNCONTAINED, | |
| 25 | 28 | ): void { |
| 26 | 29 | let notes = lacking.get(app); |
| 27 | 30 | if (notes === undefined) lacking.set(app, (notes = new Map())); |
| 28 | 31 | if (result.ok) notes.delete(part); |
| 29 | else notes.set(part, result.reason); | |
| 32 | else notes.set(part, { reason: result.reason, outcome }); | |
| 30 | 33 | } |
| 31 | 34 | |
| 32 | 35 | /** The one-line notice, or `undefined` when nothing is reduced. Plain text: escape it. */ |
| 33 | 36 | export function protectionNotice(app: object): string | undefined { |
| 34 | 37 | const notes = lacking.get(app); |
| 35 | 38 | if (notes === undefined || notes.size === 0) return undefined; |
| 36 | const parts = [...notes] | |
| 37 | .sort(([a], [b]) => a.localeCompare(b)) | |
| 38 | .map(([part, reason]) => `${part} (${reason})`); | |
| 39 | return `Reduced protection: ${parts.join("; ")} run${parts.length === 1 ? "s" : ""} uncontained.`; | |
| 39 | const sorted = [...notes].sort(([a], [b]) => a.localeCompare(b)); | |
| 40 | const open = sorted.filter(([, n]) => n.outcome === UNCONTAINED).map(([part, n]) => `${part} (${n.reason})`); | |
| 41 | const stopped = sorted.filter(([, n]) => n.outcome !== UNCONTAINED).map(([part, n]) => `${part} (${n.reason}) ${n.outcome}`); | |
| 42 | const said = [...(open.length === 0 ? [] : [`${open.join("; ")} run${open.length === 1 ? "s" : ""} uncontained`]), ...stopped]; | |
| 43 | return `Reduced protection: ${said.join("; ")}.`; | |
| 40 | 44 | } |
src/main.ts +25
| @@ -90,6 +90,7 @@ import { takePresence, warmBehind } from "./apps/presence.ts"; | ||
| 90 | 90 | import { STALE_AFTER_MS } from "./runs/lease.ts"; |
| 91 | 91 | import { runnerSettings, startCrew, sweepAssigned } from "./crew/dispatch.ts"; |
| 92 | 92 | import { configureConversation, resumeInterrupted } from "./crew/conversation.ts"; |
| 93 | import { sandboxMode } from "./crew/sandbox_policy.ts"; | |
| 93 | 94 | import { CREW_OFF_IN_PREVIEW, crewOffInPreview } from "./crew/preview.ts"; |
| 94 | 95 | import { typeSafeDecider } from "./crew/decide.ts"; |
| 95 | 96 | import { graphInstagram } from "./crew/instagram.ts"; |
| @@ -160,6 +161,7 @@ import { waitForPeer } from "./runs/peer.ts"; | ||
| 160 | 161 | import { noteWritePause } from "./keeper/pause.ts"; |
| 161 | 162 | import { closeStaleSessions } from "./machines/shell.ts"; |
| 162 | 163 | import { setOwnHost } from "./kernel/own_host.ts"; |
| 164 | import { seedFirstAdmin } from "./core/first_admin.ts"; | |
| 163 | 165 | |
| 164 | 166 | // `forge hook <name>` re-enters here from a git hook stub. It relays to the |
| 165 | 167 | // running forge over its socket and exits — it must never boot a server. |
| @@ -269,6 +271,15 @@ if (lingerMs === null) { | ||
| 269 | 271 | process.exit(1); |
| 270 | 272 | } |
| 271 | 273 | |
| 274 | // FORGE_BIND is the one IPv4 address the web listener binds; unset, every interface. A machine | |
| 275 | // whose proxy holds the certificate sets 127.0.0.1, so the forge is reached through it or not at | |
| 276 | // all. | |
| 277 | const bind = (process.env.FORGE_BIND ?? "").trim(); | |
| 278 | if (bind !== "" && !/^(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)$/.test(bind)) { | |
| 279 | console.error(`FORGE_BIND: an IPv4 address such as 127.0.0.1, not "${bind.slice(0, 40)}"`); | |
| 280 | process.exit(1); | |
| 281 | } | |
| 282 | ||
| 272 | 283 | const trustedProxies = (process.env.FORGE_TRUSTED_PROXIES ?? "") |
| 273 | 284 | .split(",") |
| 274 | 285 | .map((s) => s.trim()) |
| @@ -320,6 +331,7 @@ const app = createApp({ | ||
| 320 | 331 | seedSignup: true, |
| 321 | 332 | ...(parentUrl === "" ? {} : { parentUrl }), |
| 322 | 333 | port: Number(process.env.PORT ?? 3000), |
| 334 | ...(bind === "" ? {} : { bind }), | |
| 323 | 335 | ...(process.env.FORGE_HOST === undefined |
| 324 | 336 | ? {} |
| 325 | 337 | : { host: process.env.FORGE_HOST }), |
| @@ -397,6 +409,18 @@ const app = createApp({ | ||
| 397 | 409 | }); |
| 398 | 410 | stallRelay.attach(liveOf(app)); |
| 399 | 411 | |
| 412 | // A forge deployed for someone is started with the hash of their claim (`cloud/machine.ts`): it | |
| 413 | // becomes the one first-admin code, once per seed, so a restart revives nothing | |
| 414 | // (`core/first_admin.ts`). A seed that is not one fails the boot: the forge could never be claimed. | |
| 415 | if (!readOnly) { | |
| 416 | const seeded = seedFirstAdmin(app.db, process.env.FORGE_FIRST_ADMIN_SEED); | |
| 417 | if (seeded === "invalid") { | |
| 418 | console.error("FORGE_FIRST_ADMIN_SEED: a sha256 and a deadline as <64 hex>@<ISO time>; never the code itself"); | |
| 419 | process.exit(1); | |
| 420 | } | |
| 421 | if (seeded === "seeded") app.log.info("first-admin code seeded by the forge that deployed this one"); | |
| 422 | } | |
| 423 | ||
| 400 | 424 | // A statement that holds the thread past 200 ms names its caller (#6957). |
| 401 | 425 | timeStatements(app.db, createLog("sql")); |
| 402 | 426 | loadFlags(app.db); |
| @@ -738,6 +762,7 @@ const crew = appsOn && !crewHeldOff | ||
| 738 | 762 | concurrency: positive(process.env.FORGE_CREW_CONCURRENCY, hosted ? 1 : Number(capacityDefault("crew.concurrency"))), |
| 739 | 763 | budgetUsd: Number(process.env.FORGE_CREW_BUDGET_USD) || 5, |
| 740 | 764 | runTimeoutMs: crewRunMs, |
| 765 | sandboxRequired: sandboxMode(process.env) === "require", | |
| 741 | 766 | allowHosts: (process.env.FORGE_CREW_ALLOW_HOSTS ?? "") |
| 742 | 767 | .split(",") |
| 743 | 768 | .map((h) => h.trim()) |
src/runs/held.ts +2 −1
| @@ -21,7 +21,7 @@ import type { Database } from "bun:sqlite"; | ||
| 21 | 21 | export const HELD_FRESH_MS = 2 * 60_000; |
| 22 | 22 | |
| 23 | 23 | /** Why the dispatcher held a run. */ |
| 24 | export type HoldCause = "valve" | "pace" | "limit" | "maintenance" | "issue" | "memory" | "cap" | "clone" | "focus"; | |
| 24 | export type HoldCause = "valve" | "pace" | "limit" | "maintenance" | "issue" | "memory" | "cap" | "clone" | "focus" | "sandbox"; | |
| 25 | 25 | |
| 26 | 26 | /** How vitals names each cause: "2 by a shut valve". */ |
| 27 | 27 | export const HOLD_WORDS: Readonly<Record<HoldCause, string>> = { |
| @@ -34,6 +34,7 @@ export const HOLD_WORDS: Readonly<Record<HoldCause, string>> = { | ||
| 34 | 34 | cap: "a bet's daily cap", |
| 35 | 35 | clone: "a clone backing off", |
| 36 | 36 | focus: "the owner's focus", |
| 37 | sandbox: "the agent sandbox being unavailable", | |
| 37 | 38 | }; |
| 38 | 39 | |
| 39 | 40 | /** How long a pass remembers when it last held a run; a day bounds the map. */ |
src/tui/screens/pinned.ts +52 −26
| @@ -2,24 +2,63 @@ | ||
| 2 | 2 | * Pinned forges in the terminal, a forge admin's (#8697): each forge with its |
| 3 | 3 | * version, state and last changes, as the API lists them. `d` deploys, `u` |
| 4 | 4 | * updates (the only way its version or config move), `r` rolls back to the |
| 5 | * previous version, `c` reads the address back and probes it, each through | |
| 5 | * previous version, `c` reads the address back and probes it, `n` issues a | |
| 6 | * new claim link (shown once, as a deploy's is), each through | |
| 6 | 7 | * `actions/pinned.ts`, so the checks, the record of who and when and the events |
| 7 | 8 | * the web screens follow are the API's. |
| 8 | 9 | * Anyone else sees nothing and does nothing. |
| 9 | 10 | */ |
| 10 | 11 | |
| 11 | import { checkPinned, claimPinned, deployPinned, pinnedForges, rollbackPinned, updatePinned } from "../../actions/pinned.ts"; | |
| 12 | import { checkPinned, checkWords, claimPinned, claimWords, deployPinned, pinnedForges, rollbackPinned, updatePinned, type Issued } from "../../actions/pinned.ts"; | |
| 12 | 13 | import type { Ctx, Screen } from "../app/app.ts"; |
| 13 | 14 | import { binding } from "../app/keys.ts"; |
| 14 | 15 | import { style } from "../term/style.ts"; |
| 15 | 16 | import { truncate } from "../term/width.ts"; |
| 16 | 17 | import type { Session } from "../session.ts"; |
| 17 | 18 | import { fill, len, split } from "../ui/layout.ts"; |
| 18 | import { ListState, confirmScreen, drawList, live, promptScreen, type ListRow } from "./common.ts"; | |
| 19 | import { ListState, confirmScreen, drawList, later, linkScreen, live, promptScreen, type ListRow } from "./common.ts"; | |
| 19 | 20 | import type { PaletteEntry } from "./entries.ts"; |
| 20 | 21 | |
| 21 | 22 | const short = (v: string): string => (v.length === 40 ? v.slice(0, 10) : v); |
| 22 | 23 | |
| 24 | /** | |
| 25 | * A claim just issued: what to do with it on the screen's line, and the link itself in the one | |
| 26 | * dialog that shows it, held nowhere once that closes. | |
| 27 | */ | |
| 28 | async function hand(ctx: Ctx, say: (text: string) => void, r: Promise<{ ok: true; value: Issued } | { ok: false; error: string }>, parent: Screen): Promise<void> { | |
| 29 | const made = await r; | |
| 30 | if (!made.ok) return say(made.error); | |
| 31 | say(claimWords(made.value)); | |
| 32 | ctx.push(linkScreen(ctx, made.value.claim.link, parent)); | |
| 33 | } | |
| 34 | ||
| 35 | /** | |
| 36 | * `n`: a new claim link replaces the machine and ends the link before it, so it is asked first. A | |
| 37 | * forge deployed before forges had names is asked for one before that. | |
| 38 | */ | |
| 39 | function offerClaim(f: Session, ctx: Ctx, screen: Screen, say: (text: string) => void, p: { name: string; host: string }): void { | |
| 40 | const ask = (host?: string): Screen => | |
| 41 | confirmScreen(ctx, screen, { | |
| 42 | title: `A new claim link for ${p.name}?`, | |
| 43 | body: ["Its machine is replaced on the same volume, and the link before this one stops working.", "The new link is shown once."], | |
| 44 | actions: [{ label: "Issue a new link" }, { label: "Keep the old one" }], | |
| 45 | width: 96, | |
| 46 | onChoose: (i) => { | |
| 47 | if (i !== 0) return; | |
| 48 | say(`Issuing a claim link for ${p.name}…`); | |
| 49 | void hand(ctx, say, claimPinned(f.app, f.user, p.name, { host }), screen); | |
| 50 | }, | |
| 51 | }); | |
| 52 | if (p.host !== "") return ctx.push(ask()); | |
| 53 | ctx.push( | |
| 54 | promptScreen(ctx, screen, { | |
| 55 | title: `A name for ${p.name}`, | |
| 56 | label: "the hostname it is served on, such as forge.example.com", | |
| 57 | onSubmit: (host) => later(ctx, () => ask(host.trim().toLowerCase())), | |
| 58 | }), | |
| 59 | ); | |
| 60 | } | |
| 61 | ||
| 23 | 62 | export function pinnedScreen(f: Session, ctx: Ctx): Screen { |
| 24 | 63 | const state = new ListState(); |
| 25 | 64 | let note = ""; |
| @@ -40,22 +79,22 @@ export function pinnedScreen(f: Session, ctx: Ctx): Screen { | ||
| 40 | 79 | const deploy = (parent: Screen): Screen => |
| 41 | 80 | promptScreen(ctx, parent, { |
| 42 | 81 | title: "Deploy a pinned forge", |
| 43 | label: "name provider/account owner/app https-source version", | |
| 44 | placeholder: "acme digitalocean/main alice/shop https://host/alice/shop v1.0.0", | |
| 82 | label: "name hostname provider/account owner/app https-source version", | |
| 83 | placeholder: "acme forge.acme.com digitalocean/main alice/shop https://host/alice/shop v1.0.0", | |
| 45 | 84 | onSubmit: (raw) => { |
| 46 | const [name = "", cloud = "", app = "", source = "", version = "", ...rest] = raw.trim().split(/\s+/); | |
| 85 | const [name = "", host = "", cloud = "", app = "", source = "", version = "", ...rest] = raw.trim().split(/\s+/); | |
| 47 | 86 | const [target = "", account = "", ...more] = cloud.split("/"); |
| 48 | if (rest.length > 0 || more.length > 0 || version === "" || account === "") return "Write: name provider/account owner/app source version."; | |
| 87 | if (rest.length > 0 || more.length > 0 || version === "" || account === "") return "Write: name hostname provider/account owner/app source version."; | |
| 49 | 88 | say(`Deploying ${name}…`); |
| 50 | return settle(deployPinned(f.app, f.user, { name, target, account, app, source, version }), "Deployed"); | |
| 89 | return hand(ctx, say, deployPinned(f.app, f.user, { name, host, target, account, app, source, version }), parent); | |
| 51 | 90 | }, |
| 52 | 91 | }); |
| 53 | 92 | |
| 54 | 93 | const screen: Screen = { |
| 55 | 94 | title: "Pinned forges", |
| 56 | keys: [binding(["j", "k"], "move cursor"), binding(["d"], "deploy"), binding(["u"], "update"), binding(["r"], "roll back"), binding(["c"], "check"), binding(["h"], "hand to buyer")], | |
| 95 | keys: [binding(["j", "k"], "move cursor"), binding(["d"], "deploy"), binding(["u"], "update"), binding(["r"], "roll back"), binding(["c"], "check"), binding(["n"], "new claim link")], | |
| 57 | 96 | async load(signal) { |
| 58 | live(f, signal, { kinds: ["pinned.deployed", "pinned.update", "pinned.rollback", "pinned.check", "pinned.claimed"] }, () => ctx.invalidate()); | |
| 97 | live(f, signal, { kinds: ["pinned.deployed", "pinned.update", "pinned.rollback", "pinned.check", "pinned.claim_issued", "pinned.claimed"] }, () => ctx.invalidate()); | |
| 59 | 98 | }, |
| 60 | 99 | render(area, s) { |
| 61 | 100 | const c = ctx.theme.c; |
| @@ -84,24 +123,11 @@ export function pinnedScreen(f: Session, ctx: Ctx): Screen { | ||
| 84 | 123 | if (e.key === "r") { |
| 85 | 124 | say(`Rolling ${p.name} back…`); |
| 86 | 125 | void settle(rollbackPinned(f.app, f.user, p.name), "Rolled back"); |
| 87 | } else if (e.key === "h") { | |
| 88 | const name = p.name; | |
| 89 | ctx.push( | |
| 90 | confirmScreen(ctx, screen, { | |
| 91 | title: `Hand ${name} to its buyer`, | |
| 92 | body: ["From now on this forge refuses Update and Roll back for it.", "This cannot be undone here."], | |
| 93 | actions: [{ label: "Hand over", variant: "danger" }, { label: "Cancel" }], | |
| 94 | onChoose: (i) => { | |
| 95 | if (i !== 0) return; | |
| 96 | const done = claimPinned(f.app, f.user, name); | |
| 97 | say(done.ok ? `${name} is handed to its buyer; Update and Roll back are refused from now on.` : done.error); | |
| 98 | }, | |
| 99 | }), | |
| 100 | ); | |
| 101 | 126 | } else if (e.key === "c") { |
| 102 | 127 | say(`Checking ${p.name}…`); |
| 103 | void checkPinned(f.app, f.user, p.name).then((r) => say(r.ok ? `${p.name} ${r.value.healthy ? "answers" : "does not answer"}${r.value.url ? ` at ${r.value.url}` : " yet: no address"}.` : r.error)); | |
| 104 | } else if (e.key === "u") | |
| 128 | void checkPinned(f.app, f.user, p.name).then((r) => say(r.ok ? checkWords(r.value) : r.error)); | |
| 129 | } else if (e.key === "n") offerClaim(f, ctx, screen, say, p); | |
| 130 | else if (e.key === "u") | |
| 105 | 131 | ctx.push( |
| 106 | 132 | promptScreen(ctx, screen, { |
| 107 | 133 | title: `Update ${p.name}`, |
src/web/pages/cloud.ts +30 −3
| @@ -6,6 +6,7 @@ | ||
| 6 | 6 | * event. "Write allowed" is off until someone turns it on here. |
| 7 | 7 | */ |
| 8 | 8 | |
| 9 | import type { Database } from "bun:sqlite"; | |
| 9 | 10 | import { sshOn } from "../../settings/ssh.ts"; |
| 10 | 11 | import { |
| 11 | 12 | addAccount, |
| @@ -18,6 +19,8 @@ import { | ||
| 18 | 19 | } from "../../actions/cloud.ts"; |
| 19 | 20 | import { LABEL, PROVIDERS, VENDOR_OF, isProvider, shape } from "../../cloud/providers.ts"; |
| 20 | 21 | import { HOME, usedFor, usesByVendor, type VendorUse } from "../../cloud/declared.ts"; |
| 22 | import { spendOf } from "../../cloud/ceiling.ts"; | |
| 23 | import { dollars } from "../../cloud/prices.ts"; | |
| 21 | 24 | import { auditToday } from "../../core/cloud_audit.ts"; |
| 22 | 25 | import { |
| 23 | 26 | listCloudAccounts, |
| @@ -29,6 +32,7 @@ import { nameFrame, notePhase, takeSessionTime, timePhase, timePhaseAsync } from | ||
| 29 | 32 | import type { Ctx } from "../../http/context.ts"; |
| 30 | 33 | import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts"; |
| 31 | 34 | import { field, readForm } from "../form.ts"; |
| 35 | import { setCeiling } from "../../actions/cloud_ceiling.ts"; | |
| 32 | 36 | import { html, type Html } from "../html.ts"; |
| 33 | 37 | import { flashTo, page } from "../layout.ts"; |
| 34 | 38 | import { btn, confirmAction, icon, row, time } from "../ui.ts"; |
| @@ -51,7 +55,12 @@ const hidden = (provider: string, name: string): Html => | ||
| 51 | 55 | html`<input type="hidden" name="provider" value="${provider}" /> |
| 52 | 56 | <input type="hidden" name="name" value="${name}" />`; |
| 53 | 57 | |
| 54 | function accountsCard(accounts: CloudAccount[], reads: CloudRead[], uses: Map<string, VendorUse[]>): Html { | |
| 58 | function ceilingLine(db: Database, a: CloudAccount): string { | |
| 59 | const s = spendOf(db, a.provider, a.name); | |
| 60 | return `ceiling $${s.ceilingDollars} a month · the forge reckons ${dollars(s.monthlyCents)} now · ${s.leftCents >= 0 ? `${dollars(s.leftCents)} left` : `${dollars(-s.leftCents)} over`}`; | |
| 61 | } | |
| 62 | ||
| 63 | function accountsCard(db: Database, accounts: CloudAccount[], reads: CloudRead[], uses: Map<string, VendorUse[]>): Html { | |
| 55 | 64 | const rows = accounts.map((a) => { |
| 56 | 65 | const last = reads.find((r) => r.provider === a.provider && r.name === a.name); |
| 57 | 66 | return row({ |
| @@ -59,7 +68,7 @@ function accountsCard(accounts: CloudAccount[], reads: CloudRead[], uses: Map<st | ||
| 59 | 68 | title: html`${LABEL[a.provider]} / <span class="mono">${a.name}</span>`, |
| 60 | 69 | meta: html`${a.summary}<br />${usedFor(uses.get(VENDOR_OF[a.provider]))}<br />${HOME[a.provider]}<br />verified ${a.verifiedAt ? time(a.verifiedAt) : "never"} · |
| 61 | 70 | ${last ? html`last used ${time(last.at)} by ${runWords(last.run)}` : "never used"} · |
| 62 | ${a.writeAllowed ? "writes allowed" : "read-only"}`, | |
| 71 | ${a.writeAllowed ? "writes allowed" : "read-only"}<br />${ceilingLine(db, a)}`, | |
| 63 | 72 | trail: html`<div class="row-fields"> |
| 64 | 73 | <form method="post" action="/settings/cloud/verify"> |
| 65 | 74 | ${hidden(a.provider, a.name)}${btn("Verify", { size: "sm", label: `Verify ${a.name}` })} |
| @@ -69,6 +78,12 @@ function accountsCard(accounts: CloudAccount[], reads: CloudRead[], uses: Map<st | ||
| 69 | 78 | <input type="hidden" name="allowed" value="${a.writeAllowed ? "0" : "1"}" /> |
| 70 | 79 | ${btn(a.writeAllowed ? "Turn writes off" : "Allow writes", { size: "sm", label: `Write switch for ${a.name}` })} |
| 71 | 80 | </form> |
| 81 | <form method="post" action="/settings/cloud/ceiling" class="row-fields"> | |
| 82 | ${hidden(a.provider, a.name)} | |
| 83 | <input class="input mono" type="number" name="dollars" value="${a.ceilingDollars}" min="0" max="100000" step="1" | |
| 84 | aria-label="Monthly ceiling in US dollars for ${a.name}" required /> | |
| 85 | ${btn("Set ceiling", { size: "sm", label: `Set the ceiling of ${a.name}` })} | |
| 86 | </form> | |
| 72 | 87 | <form method="post" action="/settings/cloud/audit" class="row-fields"> |
| 73 | 88 | ${hidden(a.provider, a.name)} |
| 74 | 89 | <input class="input" type="text" name="repo" placeholder="owner/repo for findings" |
| @@ -98,6 +113,7 @@ function accountsCard(accounts: CloudAccount[], reads: CloudRead[], uses: Map<st | ||
| 98 | 113 | }); |
| 99 | 114 | return html`<section class="settings-block"> |
| 100 | 115 | <h2>Cloud accounts</h2> |
| 116 | <p class="muted small">Each account has a monthly spend ceiling, $50 until you change it: the forge refuses to make a machine or volume that would take it past. The cost shown is the forge's own reckoning from list prices; the provider's bill is the truth.</p> | |
| 101 | 117 | <p class="muted small">Paste a credential once; the forge checks it read-only, seals it, and never shows it again.</p> |
| 102 | 118 | ${rows.length > 0 |
| 103 | 119 | ? html`<ul class="list setting-list">${rows}</ul>` |
| @@ -154,7 +170,7 @@ export async function cloudPage(ctx: Ctx): Promise<Response> { | ||
| 154 | 170 | body: html`<div class="page-head"><h1>Cloud accounts</h1></div> |
| 155 | 171 | ${settingsLayout( |
| 156 | 172 | accountSections("cloud", { admin: true, ssh: sshOn(ctx.app.db) }), |
| 157 | html`${accountsCard(accounts, reads, uses)}${readsCard(reads)} | |
| 173 | html`${accountsCard(ctx.app.db, accounts, reads, uses)}${readsCard(reads)} | |
| 158 | 174 | <p class="muted small"><a href="/settings/cloud/audit">Every vendor call today</a> · <a href="/pinned">Pinned forges</a> · <a href="/deploy-to">Deploy a pinned forge</a></p>`, |
| 159 | 175 | "Account settings", |
| 160 | 176 | )}`, |
| @@ -197,6 +213,17 @@ export async function cloudWrite(ctx: Ctx): Promise<Response> { | ||
| 197 | 213 | return said(ctx, r, on ? "Runs that need writes may now hold it." : "Writes are off.", r.ok ? undefined : r.error); |
| 198 | 214 | } |
| 199 | 215 | |
| 216 | // POST /settings/cloud/ceiling: an account's monthly spend ceiling, whole US dollars. | |
| 217 | export async function cloudCeiling(ctx: Ctx): Promise<Response> { | |
| 218 | const denied = requireAdmin(ctx); | |
| 219 | if (denied) return denied; | |
| 220 | const form = await readForm(ctx, "admin"); | |
| 221 | if (form instanceof Response) return form; | |
| 222 | const raw = field(form, "dollars").trim(); | |
| 223 | const r = setCeiling(ctx.app, ctx.auth.user, field(form, "provider"), field(form, "name"), /^\d{1,6}$/.test(raw) ? Number(raw) : NaN); | |
| 224 | return flashTo(ctx, "/settings/cloud", r.ok ? { message: `Saved: ${r.value}.` } : { tone: "danger", message: r.error }); | |
| 225 | } | |
| 226 | ||
| 200 | 227 | // POST /settings/cloud/audit |
| 201 | 228 | export async function cloudAudit(ctx: Ctx): Promise<Response> { |
| 202 | 229 | const denied = requireAdmin(ctx); |
src/web/pages/pinned.ts +11 −4
| @@ -20,7 +20,11 @@ export interface PinnedFacts { | ||
| 20 | 20 | const fact = (label: string, value: Html): Html => html`<div class="status-row"><dt>${label}</dt><dd>${value}</dd></div>`; |
| 21 | 21 | const none = (text: string): Html => html`<span class="muted">${text}</span>`; |
| 22 | 22 | |
| 23 | /** Update asks for the version, Roll back and Check for nothing; each goes through the confirm page, which posts to `/pinned/<name>/<act>`. */ | |
| 23 | /** | |
| 24 | * Update asks for the version, Roll back, Check and New claim link for nothing (a forge deployed | |
| 25 | * before forges had names is asked for its hostname); each goes through the confirm page, which | |
| 26 | * posts to `/pinned/<name>/<act>`. | |
| 27 | */ | |
| 24 | 28 | function actions(p: PinnedView): Html { |
| 25 | 29 | const to = (act: string): string => `/pinned/${p.name}/${act}`; |
| 26 | 30 | const check = html`<form method="get" action="/-/confirm"> |
| @@ -41,7 +45,8 @@ function actions(p: PinnedView): Html { | ||
| 41 | 45 | ${check} |
| 42 | 46 | <form method="get" action="/-/confirm"> |
| 43 | 47 | <input type="hidden" name="to" value="${to("claim")}" /> |
| 44 | ${btn("Hand to buyer", { variant: "ghost", label: `Hand ${p.name} to its buyer` })} | |
| 48 | ${p.host === "" ? html`<input class="mono" name="host" placeholder="forge.example.com" maxlength="253" required spellcheck="false" autocomplete="off" aria-label="Hostname for ${p.name}" />` : null} | |
| 49 | ${btn("New claim link", { variant: "ghost", label: `New claim link for ${p.name}` })} | |
| 45 | 50 | </form> |
| 46 | 51 | </div>`; |
| 47 | 52 | } |
| @@ -54,11 +59,13 @@ function forge(p: PinnedView, f: PinnedFacts): Html { | ||
| 54 | 59 | <dl class="status-rows"> |
| 55 | 60 | ${fact("App", html`<span class="mono">${p.app}</span>`)} |
| 56 | 61 | ${fact("Version", html`<span class="mono" title="${p.version}">${p.version.slice(0, 12)}</span>`)} |
| 57 | ${fact("Address", p.url === "" ? none("not read yet") : html`<a class="mono" href="${p.url}" rel="noopener noreferrer">${p.url}</a>`)} | |
| 62 | ${fact("Address", p.url === "" ? none("no name yet") : html`<a class="mono" href="${p.url}" rel="noopener noreferrer">${p.url}</a>`)} | |
| 63 | ${fact("DNS record", p.dns === "" ? none("Check reads the machine's address") : html`<span class="mono">${p.dns}</span>`)} | |
| 64 | ${fact("Claim link", p.claimedAt !== "" ? html`used` : p.claimExpires === "" ? none("none issued") : html`shown once; works until ${time(p.claimExpires)} unless used. Check asks the forge whether it was.`)} | |
| 58 | 65 | ${fact("Health", badge(p.state, { tone: TONE[p.state] ?? "default" }))} |
| 59 | 66 | ${fact("Last check", checked ? time(checked) : none("never checked"))} |
| 60 | 67 | ${fact("Last change", last ? html`${last.kind} to <span class="mono">${last.toVersion.slice(0, 12)}</span>` : none("none"))} |
| 61 | ${fact("Handed to buyer", p.claimedAt === "" ? none("not yet") : time(p.claimedAt))} | |
| 68 | ${fact("Claimed by its buyer", p.claimedAt === "" ? none("not as of the last check") : time(p.claimedAt))} | |
| 62 | 69 | ${last ? fact("Changed by", html`${f.names.get(last.by) ?? last.by} ${time(last.at)}`) : null} |
| 63 | 70 | </dl> |
| 64 | 71 | ${p.claimedAt === "" ? null : html`<p class="muted small">Its updates are the buyer's to take; Update and Roll back are refused here.</p>`} |
src/web/pages/search.ts +5 −4
| @@ -1029,15 +1029,16 @@ const DESTRUCTIVE: { | ||
| 1029 | 1029 | }; |
| 1030 | 1030 | if (m[2] === "claim") |
| 1031 | 1031 | return { |
| 1032 | verb: "Hand over", | |
| 1033 | title: `Hand ${name} to its buyer?`, | |
| 1034 | detail: "From now on this forge refuses Update and Roll back for it: its updates are the buyer's to take. This cannot be undone here.", | |
| 1032 | verb: "Issue a new link", | |
| 1033 | title: `A new claim link for ${name}?`, | |
| 1034 | detail: "Its machine is replaced on the same volume, and the claim link before this one stops working. The new link is shown once, on the next page. A forge its buyer has claimed is refused and left as it is.", | |
| 1035 | 1035 | phrase: "", |
| 1036 | carries: "host", | |
| 1036 | 1037 | }; |
| 1037 | 1038 | return { |
| 1038 | 1039 | verb: "Check", |
| 1039 | 1040 | title: `Check ${name}?`, |
| 1040 | detail: "The forge reads its droplet's address back and asks the forge there for its front page. Nothing is changed but what it says about itself.", | |
| 1041 | detail: "The forge reads its machine's address back and, once its name resolves there, asks the forge for its front page and what became of its claim. Nothing is changed but what it says about itself.", | |
| 1041 | 1042 | phrase: "", |
| 1042 | 1043 | }; |
| 1043 | 1044 | }, |
src/web/pinned.ts +24 −2
| @@ -1,15 +1,19 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * The Deploy to… page (#8744): a form that puts a pinned forge on the owner's |
| 3 | 3 | * cloud. A link carrying `app`, `source` and `version` lands here with those |
| 4 | * filled in; nothing is deployed until the admin presses the button. | |
| 4 | * filled in; nothing is deployed until the admin presses the button. The | |
| 5 | * answer to a deploy, and to a new claim, is `issuedPage`: the claim link, | |
| 6 | * once. | |
| 5 | 7 | */ |
| 6 | 8 | |
| 9 | import { claimWords, type Issued } from "../actions/pinned.ts"; | |
| 7 | 10 | import type { CloudAccount } from "../core/cloud_account.ts"; |
| 8 | 11 | import { HOST_CAN } from "../core/pinned.ts"; |
| 9 | 12 | import { LABEL } from "../cloud/providers.ts"; |
| 10 | 13 | import { TARGETS } from "../cloud/targets.ts"; |
| 14 | import { pageHead } from "./chrome.ts"; | |
| 11 | 15 | import { html, type Html } from "./html.ts"; |
| 12 | import { btn, card, field, selectField } from "./ui.ts"; | |
| 16 | import { btn, card, copyField, field, selectField } from "./ui.ts"; | |
| 13 | 17 | |
| 14 | 18 | export interface DeployForm { |
| 15 | 19 | name: string; |
| @@ -17,6 +21,7 @@ export interface DeployForm { | ||
| 17 | 21 | app: string; |
| 18 | 22 | source: string; |
| 19 | 23 | version: string; |
| 24 | host: string; | |
| 20 | 25 | } |
| 21 | 26 | |
| 22 | 27 | /** Name a new forge after the app it runs, when the link does not say. */ |
| @@ -31,6 +36,22 @@ export function deployToHref(o: { app: string; source: string; version: string } | ||
| 31 | 36 | return `/deploy-to?${q}`; |
| 32 | 37 | } |
| 33 | 38 | |
| 39 | /** | |
| 40 | * The answer to a deploy or a new claim: what to do next, and the claim link, on this page only. | |
| 41 | * The forge keeps the link's hash, so leaving the page is losing the link; a new one is one button. | |
| 42 | */ | |
| 43 | export function issuedPage(title: string, v: Issued): Html { | |
| 44 | return html`${pageHead(title, { sub: "The claim link is shown on this page only." })} | |
| 45 | ${card( | |
| 46 | html`<p>${claimWords(v)}</p> | |
| 47 | ${copyField("pinned-claim-link", v.claim.link, `Claim link for ${v.name}`, "Copy the link")} | |
| 48 | <p class="muted small"> | |
| 49 | Hand it to the person the forge is for, by a channel you trust. This forge keeps only its hash: if the | |
| 50 | link is lost or runs out, issue a new one from <a href="/pinned">Pinned forges</a>, and this one stops working. | |
| 51 | </p>`, | |
| 52 | )}`; | |
| 53 | } | |
| 54 | ||
| 34 | 55 | /** The providers a forge can be deployed to: every target that deploys today. */ |
| 35 | 56 | const DEPLOYABLE = new Set<string>(TARGETS.filter((t) => t.status === "first").map((t) => t.id)); |
| 36 | 57 | |
| @@ -64,6 +85,7 @@ export function deployPage(accounts: CloudAccount[], v: DeployForm): Html { | ||
| 64 | 85 | ${field({ name: "source", label: "Source", value: v.source, placeholder: "https://…", mono: true, required: true, maxlength: 400, spellcheck: false, hint: "An https git address." })} |
| 65 | 86 | ${field({ name: "version", label: "Version", value: v.version, mono: true, required: true, maxlength: 40, spellcheck: false, hint: "A full 40-character commit id or a tag like v1.2.3 — never a branch." })} |
| 66 | 87 | ${field({ name: "name", label: "Name", value: v.name, mono: true, required: true, maxlength: 40, spellcheck: false, hint: "Lowercase letters, digits and dashes." })} |
| 88 | ${field({ name: "host", label: "Hostname", value: v.host, placeholder: "forge.example.com", mono: true, required: true, maxlength: 253, spellcheck: false, hint: "The name it is served on, over HTTPS only. You create its DNS record once the deploy says the address." })} | |
| 67 | 89 | ${btn("Deploy", { variant: "primary", icon: "plus" })} |
| 68 | 90 | </form>`, |
| 69 | 91 | )}`; |
test/crew-sandbox-required.test.ts added +259
| @@ -0,0 +1,259 @@ | ||
| 1 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 2 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 3 | import { tmpdir } from "node:os"; | |
| 4 | import { join } from "node:path"; | |
| 5 | import { createApp, type App } from "../src/app.ts"; | |
| 6 | import { createRun, getRun } from "../src/core/runs.ts"; | |
| 7 | import { createUser } from "../src/core/users.ts"; | |
| 8 | import { pump } from "../src/crew/dispatch.ts"; | |
| 9 | import type { CrewOptions } from "../src/crew/runner.ts"; | |
| 10 | import { TALK_WORDS } from "../src/actions/talk.ts"; | |
| 11 | import { configureConversation, say, type ConversationOptions } from "../src/crew/conversation.ts"; | |
| 12 | import { oneShot } from "../src/crew/one_shot.ts"; | |
| 13 | import { DEFAULT_MODE, SANDBOX_REPROBE_MS, SANDBOX_UNPROVEN, noteSandbox, reprober, sandboxHoldSentence, sandboxMode, sandboxRefusal, type SandboxProbe } from "../src/crew/sandbox_policy.ts"; | |
| 14 | import { noteProtection, protectionNotice } from "../src/kernel/protection.ts"; | |
| 15 | import { heldRuns } from "../src/runs/held.ts"; | |
| 16 | import { readRunLog } from "../src/runs/log.ts"; | |
| 17 | ||
| 18 | describe("FORGE_CREW_SANDBOX", () => { | |
| 19 | test("require and off are read; anything else is the default", () => { | |
| 20 | expect(sandboxMode({ FORGE_CREW_SANDBOX: "require" })).toBe("require"); | |
| 21 | expect(sandboxMode({ FORGE_CREW_SANDBOX: " OFF " })).toBe("off"); | |
| 22 | expect(sandboxMode({})).toBe(DEFAULT_MODE); | |
| 23 | expect(sandboxMode({ FORGE_CREW_SANDBOX: "maybe" })).toBe(DEFAULT_MODE); | |
| 24 | }); | |
| 25 | test("the sentence names the cause and what to do, in one line", () => { | |
| 26 | const words = sandboxHoldSentence("bwrap is not installed"); | |
| 27 | expect(words).toContain("missing binary: bwrap"); | |
| 28 | expect(words).toContain("FORGE_CREW_SANDBOX=off"); | |
| 29 | expect(words).not.toContain("\n"); | |
| 30 | }); | |
| 31 | test("the footer says refused, beside what runs uncontained", () => { | |
| 32 | const app = {}; | |
| 33 | noteProtection(app, "crew shells", { ok: false, reason: "x" }, "its runs are refused (FORGE_CREW_SANDBOX=require)"); | |
| 34 | expect(protectionNotice(app)).toBe("Reduced protection: crew shells (x) its runs are refused (FORGE_CREW_SANDBOX=require)."); | |
| 35 | noteProtection(app, "apps", { ok: false, reason: "y" }); | |
| 36 | expect(protectionNotice(app)).toContain("apps (y) runs uncontained; crew shells (x)"); | |
| 37 | }); | |
| 38 | }); | |
| 39 | ||
| 40 | describe("the dispatcher and a host without the sandbox", () => { | |
| 41 | let dataDir: string; | |
| 42 | let app: App; | |
| 43 | let repoId = ""; | |
| 44 | const roomy = () => ({ freeBytes: 100, totalBytes: 100 }); | |
| 45 | const base = { | |
| 46 | forgeUrl: "http://127.0.0.1:1", | |
| 47 | localUrl: "http://127.0.0.1:1", | |
| 48 | binary: "/nonexistent-agent", | |
| 49 | concurrency: 3, | |
| 50 | budgetUsd: 1, | |
| 51 | runTimeoutMs: 60_000, | |
| 52 | sandboxEnforced: false, | |
| 53 | sandboxNote: "bwrap is not installed", | |
| 54 | }; | |
| 55 | const as = (extra: object) => ({ ...base, ...extra }) as unknown as CrewOptions; | |
| 56 | ||
| 57 | beforeAll(async () => { | |
| 58 | dataDir = await mkdtemp(join(tmpdir(), "forge-sandbox-required-")); | |
| 59 | app = createApp({ dataDir, port: 0, disk: roomy }); | |
| 60 | const owner = await createUser(app.db, { | |
| 61 | origin: "seed", | |
| 62 | trusted: true, | |
| 63 | username: "sandboxer", | |
| 64 | email: "[email protected]", | |
| 65 | password: "a-good-passphrase", | |
| 66 | }); | |
| 67 | if (!owner.ok) throw new Error(String(owner.error)); | |
| 68 | repoId = crypto.randomUUID(); | |
| 69 | app.db | |
| 70 | .query("INSERT INTO repo (id, owner_id, name, visibility, created_at) VALUES (?1, ?2, 'sbx', 'private', ?3)") | |
| 71 | .run(repoId, owner.value.id, new Date().toISOString()); | |
| 72 | }); | |
| 73 | afterAll(async () => { | |
| 74 | app.close(); | |
| 75 | await rm(dataDir, { recursive: true, force: true }); | |
| 76 | }); | |
| 77 | ||
| 78 | test("required and unavailable: the run stays queued, held as sandbox, with the sentence once", () => { | |
| 79 | const queued = createRun(app.db, { repoId, kind: "agent" }); | |
| 80 | const going = new Map<string, Promise<void>>(); | |
| 81 | let asked = 0; | |
| 82 | noteSandbox(app, true, { ok: false, reason: "bwrap is not installed" }, () => asked++); | |
| 83 | pump(app, as({ sandboxRequired: true }), going); | |
| 84 | pump(app, as({ sandboxRequired: true }), going); | |
| 85 | // Each pass that holds a run for the sandbox asks for the probe again (the asker paces itself). | |
| 86 | expect(asked).toBe(2); | |
| 87 | noteSandbox(app, false, { ok: true }, () => {}); | |
| 88 | expect(getRun(app.db, queued.id)?.state).toBe("queued"); | |
| 89 | expect(going.size).toBe(0); | |
| 90 | expect(heldRuns(app.db).get(queued.id)).toBe("sandbox"); | |
| 91 | const log = readRunLog(dataDir, queued.id).lines.join("\n"); | |
| 92 | expect(log).toContain("queued, not started: this forge requires the agent sandbox"); | |
| 93 | expect(log).toContain("missing binary: bwrap"); | |
| 94 | expect(log.split("requires the agent sandbox").length - 1).toBe(1); | |
| 95 | }); | |
| 96 | ||
| 97 | test("not required (the opt-out, or today's default): the run starts", async () => { | |
| 98 | const queued = createRun(app.db, { repoId, kind: "agent" }); | |
| 99 | const going = new Map<string, Promise<void>>(); | |
| 100 | pump(app, as({ sandboxRequired: false }), going); | |
| 101 | expect(going.has(queued.id)).toBe(true); | |
| 102 | await Promise.all(going.values()); | |
| 103 | expect(heldRuns(app.db).get(queued.id)).toBeUndefined(); | |
| 104 | }); | |
| 105 | ||
| 106 | test("required and the sandbox available: the run starts", async () => { | |
| 107 | const queued = createRun(app.db, { repoId, kind: "agent" }); | |
| 108 | const going = new Map<string, Promise<void>>(); | |
| 109 | pump(app, as({ sandboxRequired: true, sandboxEnforced: true }), going); | |
| 110 | expect(going.has(queued.id)).toBe(true); | |
| 111 | await Promise.all(going.values()); | |
| 112 | }); | |
| 113 | }); | |
| 114 | ||
| 115 | describe("required and unavailable: nothing of the agent runs, a turn and a one-shot included", () => { | |
| 116 | let dataDir: string; | |
| 117 | let app: App; | |
| 118 | let userId = ""; | |
| 119 | const NO_USERNS = "user namespaces are refused here (bwrap: setting up uid map: Permission denied)"; | |
| 120 | const options: ConversationOptions = { | |
| 121 | binary: "/nonexistent-agent", | |
| 122 | localUrl: "http://127.0.0.1:1", | |
| 123 | budgetUsd: 1, | |
| 124 | timeoutMs: 60_000, | |
| 125 | signal: new AbortController().signal, | |
| 126 | }; | |
| 127 | ||
| 128 | beforeAll(async () => { | |
| 129 | dataDir = await mkdtemp(join(tmpdir(), "forge-sandbox-turns-")); | |
| 130 | app = createApp({ dataDir, port: 0 }); | |
| 131 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "talker", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 132 | if (!made.ok) throw new Error(String(made.error)); | |
| 133 | userId = made.value.id; | |
| 134 | configureConversation(app, options); | |
| 135 | }); | |
| 136 | afterAll(async () => { | |
| 137 | app.close(); | |
| 138 | await rm(dataDir, { recursive: true, force: true }); | |
| 139 | }); | |
| 140 | ||
| 141 | test("required with no probe on record yet: refused, never run on the assumption", async () => { | |
| 142 | // Before the crew's first probe at boot the forge knows nothing of its sandbox. | |
| 143 | expect(sandboxRefusal(app, {})).toBeUndefined(); | |
| 144 | expect(sandboxRefusal(app, { FORGE_CREW_SANDBOX: "off" })).toBeUndefined(); | |
| 145 | expect(sandboxRefusal(app, { FORGE_CREW_SANDBOX: "require" })).toBe(SANDBOX_UNPROVEN); | |
| 146 | const was = process.env["FORGE_CREW_SANDBOX"]; | |
| 147 | process.env["FORGE_CREW_SANDBOX"] = "require"; | |
| 148 | try { | |
| 149 | const runs = () => (app.db.query("SELECT count(*) AS n FROM conversation_run").get() as { n: number }).n; | |
| 150 | const before = runs(); | |
| 151 | expect(say(app, options, userId, "hello")).toEqual({ ok: false, error: "sandbox" }); | |
| 152 | expect(await oneShot(app, userId, "s", "p")).toEqual({ ok: false, error: "sandbox" }); | |
| 153 | expect(runs()).toBe(before); | |
| 154 | } finally { | |
| 155 | if (was === undefined) delete process.env["FORGE_CREW_SANDBOX"]; | |
| 156 | else process.env["FORGE_CREW_SANDBOX"] = was; | |
| 157 | } | |
| 158 | }); | |
| 159 | ||
| 160 | test("a forge whose crew never said, or that does not require it, is never refused: today's answers stand", async () => { | |
| 161 | expect(sandboxRefusal(app)).toBeUndefined(); | |
| 162 | const before = { turn: say(app, options, userId, "hello"), shot: await oneShot(app, userId, "s", "p") }; | |
| 163 | let asked = 0; | |
| 164 | noteSandbox(app, false, { ok: false, reason: NO_USERNS }, () => asked++); | |
| 165 | expect(sandboxRefusal(app)).toBeUndefined(); | |
| 166 | expect(asked).toBe(0); | |
| 167 | const turn = say(app, options, userId, "hello"); | |
| 168 | const shot = await oneShot(app, userId, "s", "p"); | |
| 169 | // Whatever they answered with no policy at all, they answer still, and never "sandbox". | |
| 170 | expect(turn.ok ? "started" : turn.error).toBe(before.turn.ok ? "started" : before.turn.error); | |
| 171 | expect(shot.ok ? "ok" : shot.error).toBe(before.shot.ok ? "ok" : before.shot.error); | |
| 172 | for (const r of [turn, shot]) expect(r.ok ? "" : r.error).not.toBe("sandbox"); | |
| 173 | if (turn.ok && turn.value.how === "started") await turn.value.done; | |
| 174 | if (before.turn.ok && before.turn.value.how === "started") await before.turn.value.done; | |
| 175 | }); | |
| 176 | ||
| 177 | test("required and unavailable: a turn and a one-shot are refused before anything starts, and the probe is asked again", async () => { | |
| 178 | let asked = 0; | |
| 179 | noteSandbox(app, true, { ok: false, reason: NO_USERNS }, () => asked++); | |
| 180 | const runs = () => (app.db.query("SELECT count(*) AS n FROM conversation_run").get() as { n: number }).n; | |
| 181 | const spends = () => (app.db.query("SELECT count(*) AS n FROM one_shot_spend").get() as { n: number }).n; | |
| 182 | const [r, s] = [runs(), spends()]; | |
| 183 | expect(say(app, options, userId, "hello again")).toEqual({ ok: false, error: "sandbox" }); | |
| 184 | expect(await oneShot(app, userId, "s", "p")).toEqual({ ok: false, error: "sandbox" }); | |
| 185 | expect(runs()).toBe(r); | |
| 186 | expect(spends()).toBe(s); | |
| 187 | expect(asked).toBe(2); | |
| 188 | expect(TALK_WORDS.sandbox[1]).toContain("requires the agent sandbox"); | |
| 189 | // The sentence names the cause a failed AppArmor profile leaves, and the footer an admin of | |
| 190 | // that forge sees says the same and that runs are refused. | |
| 191 | expect(sandboxRefusal(app)).toContain("user namespaces refused (bwrap: setting up uid map: Permission denied)"); | |
| 192 | noteProtection(app, "crew shells", { ok: false, reason: NO_USERNS }, "its runs are refused (FORGE_CREW_SANDBOX=require)"); | |
| 193 | expect(protectionNotice(app)).toBe(`Reduced protection: crew shells (${NO_USERNS}) its runs are refused (FORGE_CREW_SANDBOX=require).`); | |
| 194 | }); | |
| 195 | ||
| 196 | test("required and available: nothing is refused", () => { | |
| 197 | noteSandbox(app, true, { ok: true }, () => { | |
| 198 | throw new Error("a working sandbox is not probed again"); | |
| 199 | }); | |
| 200 | expect(sandboxRefusal(app)).toBeUndefined(); | |
| 201 | }); | |
| 202 | }); | |
| 203 | ||
| 204 | describe("the probe is taken again, at most once a minute and one at a time", () => { | |
| 205 | test("a host that was fixed is heard without a restart", async () => { | |
| 206 | let clock = 1_000_000; | |
| 207 | let works = false; | |
| 208 | let probes = 0; | |
| 209 | const heard: SandboxProbe[] = []; | |
| 210 | let release: () => void = () => {}; | |
| 211 | const again = reprober({ | |
| 212 | last: clock, | |
| 213 | now: () => clock, | |
| 214 | heard: (p) => heard.push(p), | |
| 215 | probe: () => | |
| 216 | new Promise<SandboxProbe>((resolve) => { | |
| 217 | probes++; | |
| 218 | release = () => resolve(works ? { ok: true } : { ok: false, reason: "bwrap is not installed" }); | |
| 219 | }), | |
| 220 | }); | |
| 221 | // Asked at once and for the rest of the minute: no probe. | |
| 222 | expect(again()).toBe(false); | |
| 223 | clock += SANDBOX_REPROBE_MS - 1; | |
| 224 | expect(again()).toBe(false); | |
| 225 | expect(probes).toBe(0); | |
| 226 | // A minute on: one probe, and asking while it runs starts no second. | |
| 227 | clock += 1; | |
| 228 | expect(again()).toBe(true); | |
| 229 | expect(again()).toBe(false); | |
| 230 | expect(probes).toBe(1); | |
| 231 | release(); | |
| 232 | await Promise.resolve(); | |
| 233 | await Promise.resolve(); | |
| 234 | expect(heard).toEqual([{ ok: false, reason: "bwrap is not installed" }]); | |
| 235 | // The minute counts from that answer. | |
| 236 | expect(again()).toBe(false); | |
| 237 | works = true; | |
| 238 | clock += SANDBOX_REPROBE_MS; | |
| 239 | expect(again()).toBe(true); | |
| 240 | release(); | |
| 241 | await Promise.resolve(); | |
| 242 | await Promise.resolve(); | |
| 243 | expect(heard.at(-1)).toEqual({ ok: true }); | |
| 244 | expect(probes).toBe(2); | |
| 245 | }); | |
| 246 | ||
| 247 | test("a probe that throws is an answer of 'unavailable', never a stuck asker", async () => { | |
| 248 | let clock = 0; | |
| 249 | const heard: SandboxProbe[] = []; | |
| 250 | const again = reprober({ last: -SANDBOX_REPROBE_MS, now: () => clock, heard: (p) => heard.push(p), probe: () => Promise.reject(new Error("spawn failed")) }); | |
| 251 | expect(again()).toBe(true); | |
| 252 | await Promise.resolve(); | |
| 253 | await Promise.resolve(); | |
| 254 | await Promise.resolve(); | |
| 255 | expect(heard).toEqual([{ ok: false, reason: "spawn failed" }]); | |
| 256 | clock += SANDBOX_REPROBE_MS; | |
| 257 | expect(again()).toBe(true); | |
| 258 | }); | |
| 259 | }); |
test/engine-crossing.test.ts +1
| @@ -211,6 +211,7 @@ const whole = (dataDir: string): Required<ForgeConfig> => ({ | ||
| 211 | 211 | memory: () => 1, |
| 212 | 212 | codeBudgetMs: 30, |
| 213 | 213 | port: 8080, |
| 214 | bind: "127.0.0.1", | |
| 214 | 215 | host: "0.0.0.0", |
| 215 | 216 | url: "https://forge.test", |
| 216 | 217 | edgeToken: "not-a-token", |
test/helpers/places-fixture.ts +33
| @@ -1,3 +1,7 @@ | ||
| 1 | import type { Database } from "bun:sqlite"; | |
| 2 | import { readPlaces } from "../../src/cloud/places_read.ts"; | |
| 3 | import { refreshRate } from "../../src/cloud/rates.ts"; | |
| 4 | ||
| 1 | 5 | /** What Hetzner and DigitalOcean answer, as much as places read (#16203). */ |
| 2 | 6 | export const hetzner = { |
| 3 | 7 | server_types: [ |
| @@ -20,3 +24,32 @@ export const ocean = { | ||
| 20 | 24 | ], |
| 21 | 25 | }; |
| 22 | 26 | |
| 27 | ||
| 28 | /** | |
| 29 | * The catalog the pinned-forge tests deploy against, kept as a real read keeps it: DigitalOcean's | |
| 30 | * `s-1vcpu-2gb` in nyc3 ($12 + the $1 volume = $13.00 a month) and Hetzner's CX line in nbg1 in | |
| 31 | * euros (cx23: 5.99 + 0.572 volume + 0.50 address = 7.062, at 1.2 and rounded up $8.48), with the | |
| 32 | * day's rate. The spend ceiling prices every create from it, and refuses one it has no price for. | |
| 33 | */ | |
| 34 | export async function seedPlaces(db: Database): Promise<void> { | |
| 35 | const json = (o: unknown): Response => new Response(JSON.stringify(o), { status: 200 }); | |
| 36 | const eur = (gross: string) => [{ location: "nbg1", price_monthly: { gross } }]; | |
| 37 | const types = [ | |
| 38 | { id: 1, name: "cx22", cores: 2, memory: 4, disk: 40, architecture: "x86", prices: eur("4.50") }, | |
| 39 | { id: 2, name: "cx23", cores: 2, memory: 4, disk: 40, architecture: "x86", prices: eur("5.99") }, | |
| 40 | { id: 5, name: "cx33", cores: 4, memory: 8, disk: 80, architecture: "x86", prices: eur("8.99") }, | |
| 41 | ]; | |
| 42 | await readPlaces(db, "digitalocean", async (url) => json(String(url).includes("/sizes") ? { sizes: ocean.sizes } : { regions: ocean.regions }), "t"); | |
| 43 | await readPlaces( | |
| 44 | db, | |
| 45 | "hetzner", | |
| 46 | async (url) => { | |
| 47 | const u = String(url); | |
| 48 | if (u.includes("/server_types")) return json({ server_types: types }); | |
| 49 | if (u.includes("/datacenters")) return json({ datacenters: [{ location: { name: "nbg1", city: "Nuremberg", country: "DE" }, server_types: { available: [1, 2, 5] } }] }); | |
| 50 | return json({ pricing: { currency: "EUR", volume: { price_per_gb_month: { gross: "0.0572" } }, primary_ips: [{ type: "ipv4", prices: [{ location: "nbg1", price_monthly: { gross: "0.50" } }] }] } }); | |
| 51 | }, | |
| 52 | "t", | |
| 53 | ); | |
| 54 | await refreshRate(db, async () => new Response("<Cube time='2026-11-23'><Cube currency='USD' rate='1.2'/></Cube>", { status: 200 })); | |
| 55 | } |
test/openapi-errors.test.ts +1 −1
| @@ -29,7 +29,7 @@ const BASE = "http://localhost"; | ||
| 29 | 29 | /** Not called: these would end the session, stop the forge or reach beyond the test's own data. */ |
| 30 | 30 | const NOT_CALLED = /\/(sessions|maintenance|migrate|first-admin|heartbeat|release|fleet-ops|drills|forges|sandbox|broker|admin\/(pinned|releases|accounts|settings))/; |
| 31 | 31 | /** How many routes NOT_CALLED leaves out; a change to it changes this on purpose. */ |
| 32 | const SKIPPED = 54; | |
| 32 | const SKIPPED = 55; | |
| 33 | 33 | |
| 34 | 34 | let dataDir: string; |
| 35 | 35 | let app: App; |
test/pinned-canary.test.ts +1 −1
| @@ -3,7 +3,7 @@ import { canary, invalid, leftovers, table } from "../scripts/pinned-canary.ts"; | ||
| 3 | 3 | |
| 4 | 4 | const A = "a".repeat(40); |
| 5 | 5 | const B = "b".repeat(40); |
| 6 | const o = { name: "c", account: "do", app: "o/n", source: "https://x/y.git", version: A, next: B, budget: 600 }; | |
| 6 | const o = { name: "c", host: "c.forge.test", account: "do", app: "o/n", source: "https://x/y.git", version: A, next: B, budget: 600 }; | |
| 7 | 7 | |
| 8 | 8 | function fake(opts: { rollbackTo?: string; status?: number } = {}) { |
| 9 | 9 | const seen: string[] = []; |
test/pinned-ceiling.test.ts added +358
| @@ -0,0 +1,358 @@ | ||
| 1 | /** | |
| 2 | * The spend ceiling of a cloud account: $50 a month for every account until an admin changes it, | |
| 3 | * reckoned from the forge's own pinned rows at list prices, and enforced before anything is made. | |
| 4 | */ | |
| 5 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 6 | import { readdirSync, readFileSync } from "node:fs"; | |
| 7 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { createApp, type App } from "../src/app.ts"; | |
| 11 | import { addAccount, allowWrite, net as cloudNet } from "../src/actions/cloud.ts"; | |
| 12 | import { setCeiling } from "../src/actions/cloud_ceiling.ts"; | |
| 13 | import { claimPinned, deployPinned, net, updatePinned } from "../src/actions/pinned.ts"; | |
| 14 | import { cloudOverview } from "../src/cloud/overview.ts"; | |
| 15 | import { priced } from "../src/cloud/ceiling.ts"; | |
| 16 | import { keptPlaces } from "../src/cloud/places_read.ts"; | |
| 17 | import { keptRate } from "../src/cloud/rates.ts"; | |
| 18 | import { getCloudAccount } from "../src/core/cloud_account.ts"; | |
| 19 | import { getPinned } from "../src/core/pinned.ts"; | |
| 20 | import { createUser, getUserByName } from "../src/core/users.ts"; | |
| 21 | import { quietLogs } from "./helpers/globals.ts"; | |
| 22 | import { seedPlaces } from "./helpers/places-fixture.ts"; | |
| 23 | ||
| 24 | quietLogs(); | |
| 25 | ||
| 26 | const V1 = "a".repeat(40); | |
| 27 | const V2 = "b".repeat(40); | |
| 28 | const SOURCE = "https://forge.example.org/trevato/forge"; | |
| 29 | ||
| 30 | describe("cloud account ceiling", () => { | |
| 31 | let dataDir = ""; | |
| 32 | let app: App; | |
| 33 | const calls: string[] = []; | |
| 34 | let hetznerType = "cx23"; | |
| 35 | let seq = 1000; | |
| 36 | ||
| 37 | const admin = () => getUserByName(app.db, "alice")!; | |
| 38 | const input = (name: string, over: Record<string, unknown> = {}) => ({ | |
| 39 | name, host: `${name}.forge.test`, target: "digitalocean", account: "main", app: "alice/shop", source: SOURCE, version: V1, config: {}, ...over, | |
| 40 | }); | |
| 41 | const error = (r: unknown) => String((r as { error: unknown }).error); | |
| 42 | ||
| 43 | beforeAll(async () => { | |
| 44 | dataDir = await mkdtemp(join(tmpdir(), "forge-ceiling-")); | |
| 45 | app = createApp({ dataDir, port: 0 }); | |
| 46 | await seedPlaces(app.db); | |
| 47 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 48 | if (!made.ok) throw new Error(made.error); | |
| 49 | cloudNet.fetch = async () => new Response(JSON.stringify({ account: { email: "[email protected]", status: "active" }, servers: [], meta: { pagination: { total_entries: 0 } } }), { status: 200 }); | |
| 50 | for (const [provider, token] of [["digitalocean", "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5"], ["hetzner", "hcloud_Zq4TxLm7Kp2Vb8nWcR5Yd3Fg6Hj9"]] as const) { | |
| 51 | const added = await addAccount(app, admin(), provider, "main", token); | |
| 52 | if (!added.ok) throw new Error(String(added.error)); | |
| 53 | allowWrite(app, admin(), provider, "main", true); | |
| 54 | } | |
| 55 | net.fetch = async (url, init) => { | |
| 56 | const u = new URL(url); | |
| 57 | const method = init?.method ?? "GET"; | |
| 58 | calls.push(`${method} ${u.host}${u.pathname}`); | |
| 59 | const json = (o: unknown, status = 200) => new Response(JSON.stringify(o), { status }); | |
| 60 | if (u.pathname === "/v1/server_types") return json({ server_types: [{ id: 9, name: hetznerType, architecture: "x86", memory: 4, prices: [{ location: "nbg1", price_monthly: { gross: "5.0" } }] }] }); | |
| 61 | if (u.pathname === "/v1/datacenters") return json({ datacenters: [{ location: { name: "nbg1" }, server_types: { available: [9] } }] }); | |
| 62 | if (u.pathname === "/v2/volumes" || u.pathname === "/v1/volumes") return json({ volume: { id: ++seq } }, 201); | |
| 63 | // Each machine is made with a throwaway SSH key, deleted after the call (#16218). | |
| 64 | if (u.pathname === "/v2/account/keys" || u.pathname === "/v1/ssh_keys") return json({ ssh_key: { id: 4242 } }, 201); | |
| 65 | if (method === "DELETE") return new Response(null, { status: 204 }); | |
| 66 | if (u.pathname === "/v1/servers") return json({ server: { id: ++seq } }, 201); | |
| 67 | return json({ droplet: { id: ++seq } }, 202); | |
| 68 | }; | |
| 69 | }, 30_000); | |
| 70 | ||
| 71 | afterAll(async () => { | |
| 72 | app.close(); | |
| 73 | await rm(dataDir, { recursive: true, force: true }); | |
| 74 | }); | |
| 75 | ||
| 76 | test("every account has a $50 ceiling with no setup, and nothing reckoned yet", () => { | |
| 77 | expect(getCloudAccount(app.db, "digitalocean", "main")?.ceilingDollars).toBe(50); | |
| 78 | const o = cloudOverview(app, admin()); | |
| 79 | expect(o.ok && o.value.accounts.find((a) => a.provider === "digitalocean")).toMatchObject({ ceilingDollars: 50, monthlyCents: 0, leftCents: 5000 }); | |
| 80 | }); | |
| 81 | ||
| 82 | test("a forge is priced from the Places catalog, where the drivers order it: euros at the day's rate, rounded up; what it does not list has no price", () => { | |
| 83 | const p = priced(app.db); | |
| 84 | // DigitalOcean: $12 machine + $1 volume, in dollars as the provider says. | |
| 85 | expect(p.forge("digitalocean", "s-1vcpu-2gb")).toBe(1300); | |
| 86 | // Hetzner cx23 in nbg1: 5.99 + 0.572 (10 GiB) + 0.50 (address) = 7.062 EUR, at 1.2 = 8.4744, up. | |
| 87 | expect(p.forge("hetzner", "cx23")).toBe(848); | |
| 88 | expect(p.forge("hetzner", "cx33")).toBe(1208); | |
| 89 | expect(p.dearest("hetzner")).toBe(1208); | |
| 90 | // The catalog's own figure for the same place rounds to the nearest cent; the ceiling's never | |
| 91 | // rounds in favour of spending. | |
| 92 | expect(keptPlaces(app.db, keptRate(app.db, "EUR")).find((x) => x.id === "hetzner:nbg1:cx23")?.costCents).toBe(847); | |
| 93 | for (const [cloud, size] of [["digitalocean", "s-9vcpu"], ["hetzner", "cx99"], ["aws", "t4g.small"], ["hetzner", ""]] as const) | |
| 94 | expect(p.forge(cloud, size)).toBeUndefined(); | |
| 95 | expect(p.dearest("aws")).toBeUndefined(); | |
| 96 | }); | |
| 97 | ||
| 98 | test("no catalog, no rate, or a place with no price is never a price of zero", async () => { | |
| 99 | const dir = await mkdtemp(join(tmpdir(), "forge-ceiling-none-")); | |
| 100 | const bare = createApp({ dataDir: dir, port: 0 }); | |
| 101 | try { | |
| 102 | // Never read: nothing has a price. | |
| 103 | expect(priced(bare.db).forge("digitalocean", "s-1vcpu-2gb")).toBeUndefined(); | |
| 104 | await seedPlaces(bare.db); | |
| 105 | expect(priced(bare.db).forge("hetzner", "cx23")).toBe(848); | |
| 106 | // The rate gone: a euro place has no dollars, and so no price; a dollar place keeps its own. | |
| 107 | bare.db.run("DELETE FROM fx_rate"); | |
| 108 | expect(priced(bare.db).forge("hetzner", "cx23")).toBeUndefined(); | |
| 109 | expect(priced(bare.db).dearest("hetzner")).toBeUndefined(); | |
| 110 | expect(priced(bare.db).forge("digitalocean", "s-1vcpu-2gb")).toBe(1300); | |
| 111 | } finally { | |
| 112 | bare.close(); | |
| 113 | await rm(dir, { recursive: true, force: true }); | |
| 114 | } | |
| 115 | }); | |
| 116 | ||
| 117 | test("deploys under the ceiling pass, and the page-ready reckoning counts them", async () => { | |
| 118 | for (const n of ["one", "two", "three"]) expect((await deployPinned(app, admin(), input(n))).ok).toBe(true); | |
| 119 | const o = cloudOverview(app, admin()); | |
| 120 | expect(o.ok && o.value.accounts.find((a) => a.provider === "digitalocean")).toMatchObject({ monthlyCents: 3900, leftCents: 1100 }); | |
| 121 | }); | |
| 122 | ||
| 123 | test("the deploy that would cross the ceiling is refused before any provider call", async () => { | |
| 124 | calls.length = 0; | |
| 125 | const r = await deployPinned(app, admin(), input("four")); | |
| 126 | expect(r).toMatchObject({ ok: false }); | |
| 127 | expect(error(r)).toBe( | |
| 128 | "digitalocean/main is held to $50 a month and runs $39.00 now; this would add $13.00, which is over it, so nothing was made. " + | |
| 129 | "Raise the ceiling at /settings/cloud if you mean to spend more. This is the forge's own reckoning from list prices; the provider's bill is the truth.", | |
| 130 | ); | |
| 131 | expect(calls).toHaveLength(0); | |
| 132 | }); | |
| 133 | ||
| 134 | test("raising the ceiling lets it through", async () => { | |
| 135 | expect(setCeiling(app, admin(), "digitalocean", "main", 52).ok).toBe(true); | |
| 136 | expect((await deployPinned(app, admin(), input("four"))).ok).toBe(true); | |
| 137 | expect(getPinned(app.db, "four")?.state).toBe("running"); | |
| 138 | }); | |
| 139 | ||
| 140 | test("a replace of a same-size machine passes at the ceiling", async () => { | |
| 141 | const o = cloudOverview(app, admin()); | |
| 142 | expect(o.ok && o.value.accounts.find((a) => a.provider === "digitalocean")?.leftCents).toBe(0); | |
| 143 | const r = await updatePinned(app, admin(), "one", { version: V2 }); | |
| 144 | expect(r.ok).toBe(true); | |
| 145 | expect(calls.filter((c) => c.startsWith("DELETE")).length).toBeGreaterThan(0); | |
| 146 | }); | |
| 147 | ||
| 148 | test("a ceiling is whole dollars, and only an admin sets it", () => { | |
| 149 | for (const bad of [1.5, -1, "50", 1e9]) expect(setCeiling(app, admin(), "digitalocean", "main", bad).ok).toBe(false); | |
| 150 | expect(setCeiling(app, undefined, "digitalocean", "main", 10)).toMatchObject({ ok: false, error: "not_found" }); | |
| 151 | expect(setCeiling(app, admin(), "digitalocean", "nope", 10)).toMatchObject({ ok: false }); | |
| 152 | }); | |
| 153 | ||
| 154 | test("a size with no price is refused, never counted as free", async () => { | |
| 155 | hetznerType = "cx99"; | |
| 156 | calls.length = 0; | |
| 157 | const r = await deployPinned(app, admin(), input("odd", { target: "hetzner" })); | |
| 158 | expect(r).toMatchObject({ ok: false }); | |
| 159 | expect(error(r)).toContain("The forge has no price for cx99 in nbg1 on hetzner, so it cannot hold hetzner/main to its ceiling; nothing was made."); | |
| 160 | expect(calls.every((c) => c.startsWith("GET"))).toBe(true); | |
| 161 | hetznerType = "cx23"; | |
| 162 | }); | |
| 163 | ||
| 164 | test("Hetzner is reckoned in dollars at the day's rate, rounded up: a cx23 forge is $8.48", async () => { | |
| 165 | expect((await deployPinned(app, admin(), input("het", { target: "hetzner" }))).ok).toBe(true); | |
| 166 | const o = cloudOverview(app, admin()); | |
| 167 | expect(o.ok && o.value.accounts.find((a) => a.provider === "hetzner")).toMatchObject({ monthlyCents: 848, ceilingDollars: 50 }); | |
| 168 | }); | |
| 169 | ||
| 170 | test("a new claim link is a create like any other: over the ceiling it is refused before anything is made", async () => { | |
| 171 | // "het" runs a cx23 ($8.48). Hetzner now offers only the cx33 ($12.08), so its replacement | |
| 172 | // would add $3.60, and the account is held to $10. | |
| 173 | expect(setCeiling(app, admin(), "hetzner", "main", 10).ok).toBe(true); | |
| 174 | const was = getPinned(app.db, "het")!; | |
| 175 | hetznerType = "cx33"; | |
| 176 | calls.length = 0; | |
| 177 | const r = await claimPinned(app, admin(), "het"); | |
| 178 | expect(r).toMatchObject({ ok: false }); | |
| 179 | expect(error(r)).toContain("hetzner/main is held to $10 a month and runs $8.48 now; this would add $3.60, which is over it, so nothing was made."); | |
| 180 | expect(calls.filter((c) => !c.startsWith("GET"))).toEqual([]); | |
| 181 | expect(JSON.stringify(r)).not.toContain("first-admin#"); | |
| 182 | expect(getPinned(app.db, "het")).toMatchObject({ claimHash: was.claimHash, remote: was.remote, state: "running" }); | |
| 183 | // With room for it, the same request makes the machine, and the forge is counted at its new size. | |
| 184 | expect(setCeiling(app, admin(), "hetzner", "main", 50).ok).toBe(true); | |
| 185 | expect((await claimPinned(app, admin(), "het")).ok).toBe(true); | |
| 186 | hetznerType = "cx23"; | |
| 187 | const o = cloudOverview(app, admin()); | |
| 188 | expect(o.ok && o.value.accounts.find((x) => x.provider === "hetzner")).toMatchObject({ monthlyCents: 1208 }); | |
| 189 | // A forge whose machine is gone and whose volume waits is still counted whole, so finishing | |
| 190 | // it adds nothing: it passes a ceiling it already fills. | |
| 191 | app.db.run("UPDATE pinned_forge SET remote = '', address = '', state = 'failed' WHERE name = 'two'"); | |
| 192 | expect(cloudOverview(app, admin())).toMatchObject({ ok: true }); | |
| 193 | expect((await claimPinned(app, admin(), "two")).ok).toBe(true); | |
| 194 | }); | |
| 195 | ||
| 196 | test("two deploys asked together cannot both fit under a ceiling with room for one", async () => { | |
| 197 | // $52 is spent to the cent; $65 leaves room for exactly one more machine and volume ($13). | |
| 198 | expect(setCeiling(app, admin(), "digitalocean", "main", 65).ok).toBe(true); | |
| 199 | const [a, b] = await Promise.all([deployPinned(app, admin(), input("racea")), deployPinned(app, admin(), input("raceb"))]); | |
| 200 | expect([a.ok, b.ok].sort()).toEqual([false, true]); | |
| 201 | expect(error(a.ok ? b : a)).toContain("is held to $65 a month and runs $65.00 now"); | |
| 202 | const o = cloudOverview(app, admin()); | |
| 203 | expect(o.ok && o.value.accounts.find((x) => x.provider === "digitalocean")).toMatchObject({ monthlyCents: 6500, leftCents: 0 }); | |
| 204 | // The turn is given back on a refusal: the next create is answered, not left waiting. | |
| 205 | expect((await deployPinned(app, admin(), input("racec"))).ok).toBe(false); | |
| 206 | }); | |
| 207 | ||
| 208 | test("two new claim links asked together for one forge run one after the other: no machine is left behind", async () => { | |
| 209 | const before = getPinned(app.db, "three")!.remote; | |
| 210 | calls.length = 0; | |
| 211 | const [a, b] = await Promise.all([claimPinned(app, admin(), "three"), claimPinned(app, admin(), "three")]); | |
| 212 | expect(a.ok && b.ok).toBe(true); | |
| 213 | const droplets = calls.filter((c) => /^(DELETE|POST) api\.digitalocean\.com\/v2\/droplets/.test(c)).map((c) => c.split(" ")[0]); | |
| 214 | // Never two deletes or two creates in a row: each replacement finished before the next began. | |
| 215 | expect(droplets).toEqual(["DELETE", "POST", "DELETE", "POST"]); | |
| 216 | const deleted = calls.filter((c) => c.startsWith("DELETE api.digitalocean.com/v2/droplets/")).map((c) => c.split("/").at(-1)!); | |
| 217 | const now = getPinned(app.db, "three")!.remote; | |
| 218 | // The first deleted the machine there was; the second deleted the first's; the row holds the | |
| 219 | // last. | |
| 220 | expect(deleted[0]).toBe(before); | |
| 221 | expect(deleted).not.toContain(now); | |
| 222 | expect(new Set([...deleted, now]).size).toBe(3); | |
| 223 | // And the row's claim is the second link's, the only one that still works. | |
| 224 | expect(a.ok && b.ok && a.value.claim.link).not.toBe(b.ok && b.value.claim.link); | |
| 225 | }); | |
| 226 | ||
| 227 | test("a turn is given back however a create ends: refused by the ceiling, refused by the cloud, or cut off; the next one completes", async () => { | |
| 228 | const real = net.fetch; | |
| 229 | let how: "" | "500" | "throw" = ""; | |
| 230 | net.fetch = async (url, init) => { | |
| 231 | if (how !== "" && init?.method === "POST" && new URL(url).pathname === "/v2/droplets") { | |
| 232 | const was = how; | |
| 233 | how = ""; | |
| 234 | if (was === "throw") throw new Error("socket closed"); | |
| 235 | return new Response("{}", { status: 500 }); | |
| 236 | } | |
| 237 | return real(url, init); | |
| 238 | }; | |
| 239 | try { | |
| 240 | // The account's turn: a ceiling refusal, then the cloud's refusal, then a cut connection, | |
| 241 | // each followed by a create on the same account that is answered. | |
| 242 | expect((await deployPinned(app, admin(), input("turna"))).ok).toBe(false); | |
| 243 | expect(setCeiling(app, admin(), "digitalocean", "main", 500).ok).toBe(true); | |
| 244 | for (const end of ["500", "throw"] as const) { | |
| 245 | how = end; | |
| 246 | const failed = await deployPinned(app, admin(), input(`turn${end === "500" ? "b" : "c"}`)); | |
| 247 | expect(failed).toMatchObject({ ok: false }); | |
| 248 | expect(error(failed)).toContain("The cloud refused"); | |
| 249 | } | |
| 250 | expect((await deployPinned(app, admin(), input("turnd"))).ok).toBe(true); | |
| 251 | // The forge's turn: an Update and a new claim link that each fail, then each asked again. | |
| 252 | how = "500"; | |
| 253 | expect((await updatePinned(app, admin(), "turnd", { version: V2 })).ok).toBe(false); | |
| 254 | expect((await updatePinned(app, admin(), "turnd", { version: V2 })).ok).toBe(true); | |
| 255 | how = "throw"; | |
| 256 | expect((await claimPinned(app, admin(), "turnd")).ok).toBe(false); | |
| 257 | expect((await claimPinned(app, admin(), "turnd")).ok).toBe(true); | |
| 258 | // A refusal before anything is asked gives it back too. | |
| 259 | expect((await claimPinned(app, admin(), "nope")).ok).toBe(false); | |
| 260 | expect((await updatePinned(app, admin(), "turnd", { version: "main" })).ok).toBe(false); | |
| 261 | expect((await updatePinned(app, admin(), "turnd", { version: V1 })).ok).toBe(true); | |
| 262 | expect(getPinned(app.db, "turnd")).toMatchObject({ state: "running", version: V1 }); | |
| 263 | } finally { | |
| 264 | net.fetch = real; | |
| 265 | } | |
| 266 | }); | |
| 267 | ||
| 268 | test("a create refused before anything was changed leaves a running forge running; one that lost its machine is failed", async () => { | |
| 269 | // Refused at the plan (a size the forge has no price for): nothing was asked of the cloud but | |
| 270 | // reads. | |
| 271 | expect(getPinned(app.db, "het")).toMatchObject({ state: "running" }); | |
| 272 | const server = getPinned(app.db, "het")!.remote; | |
| 273 | hetznerType = "cx99"; | |
| 274 | calls.length = 0; | |
| 275 | const refused = await updatePinned(app, admin(), "het", { version: V2 }); | |
| 276 | hetznerType = "cx23"; | |
| 277 | expect(error(refused)).toContain("has no price for cx99"); | |
| 278 | expect(calls.filter((c) => !c.startsWith("GET"))).toEqual([]); | |
| 279 | // Nothing moved: not the machine, not its state, not the pin, and no change is recorded. | |
| 280 | expect(getPinned(app.db, "het")).toMatchObject({ state: "running", remote: server, version: V1 }); | |
| 281 | expect(app.db.query("SELECT count(*) AS n FROM pinned_change WHERE pinned_id = (SELECT id FROM pinned_forge WHERE name = 'het')").get()).toEqual({ n: 1 }); | |
| 282 | // A new claim link refused the same way leaves it running too. | |
| 283 | hetznerType = "cx99"; | |
| 284 | expect((await claimPinned(app, admin(), "het")).ok).toBe(false); | |
| 285 | hetznerType = "cx23"; | |
| 286 | expect(getPinned(app.db, "het")).toMatchObject({ state: "running", remote: server }); | |
| 287 | ||
| 288 | const real = net.fetch; | |
| 289 | const machine = getPinned(app.db, "turnd")!.remote; | |
| 290 | expect(getPinned(app.db, "turnd")?.state).toBe("running"); | |
| 291 | // The cloud refuses the delete of a new claim link's replacement: nothing was recorded for it | |
| 292 | // and the old machine still runs, so the forge is as it was. | |
| 293 | net.fetch = async (url, init) => (init?.method === "DELETE" && new URL(url).pathname.startsWith("/v2/droplets/") ? new Response("{}", { status: 500 }) : real(url, init)); | |
| 294 | try { | |
| 295 | expect((await claimPinned(app, admin(), "turnd")).ok).toBe(false); | |
| 296 | expect(getPinned(app.db, "turnd")).toMatchObject({ state: "running", remote: machine }); | |
| 297 | // An Update's pin moved before the cloud was asked: the row no longer says what runs, so it | |
| 298 | // is failed, and asking again for the same version finishes it. | |
| 299 | expect((await updatePinned(app, admin(), "turnd", { version: V2 })).ok).toBe(false); | |
| 300 | expect(getPinned(app.db, "turnd")).toMatchObject({ state: "failed", remote: machine, version: V2 }); | |
| 301 | } finally { | |
| 302 | net.fetch = real; | |
| 303 | } | |
| 304 | // The delete went through and the create did not: no machine, so failed, and asked again it is | |
| 305 | // made. | |
| 306 | net.fetch = async (url, init) => (init?.method === "POST" && new URL(url).pathname === "/v2/droplets" ? new Response("{}", { status: 500 }) : real(url, init)); | |
| 307 | try { | |
| 308 | expect((await updatePinned(app, admin(), "turnd", { version: V2 })).ok).toBe(false); | |
| 309 | expect(getPinned(app.db, "turnd")).toMatchObject({ state: "failed", remote: "" }); | |
| 310 | } finally { | |
| 311 | net.fetch = real; | |
| 312 | } | |
| 313 | expect((await updatePinned(app, admin(), "turnd", { version: V2 })).ok).toBe(true); | |
| 314 | expect(getPinned(app.db, "turnd")).toMatchObject({ state: "running", version: V2 }); | |
| 315 | ||
| 316 | // The cloud refuses the read of the machine, the first thing a change asks: refused with the | |
| 317 | // cloud's answer, nothing recorded, nothing changed. A machine that is gone (404) is replaced. | |
| 318 | const reads = (status: number): void => | |
| 319 | void (net.fetch = async (url, init) => ((init?.method ?? "GET") === "GET" && new URL(url).pathname.startsWith("/v2/droplets/") ? new Response("{}", { status }) : real(url, init))); | |
| 320 | const changes = () => app.db.query("SELECT count(*) AS n FROM pinned_change WHERE pinned_id = (SELECT id FROM pinned_forge WHERE name = 'turnd')").get() as { n: number }; | |
| 321 | const recorded = changes().n; | |
| 322 | try { | |
| 323 | reads(500); | |
| 324 | for (const refused of [await updatePinned(app, admin(), "turnd", { version: V1 }), await claimPinned(app, admin(), "turnd")]) | |
| 325 | expect(refused).toMatchObject({ ok: false, error: "The cloud refused: api.digitalocean.com answered 500" }); | |
| 326 | expect(getPinned(app.db, "turnd")).toMatchObject({ state: "running", version: V2 }); | |
| 327 | expect(changes().n).toBe(recorded); | |
| 328 | reads(404); | |
| 329 | expect((await updatePinned(app, admin(), "turnd", { version: V1 })).ok).toBe(true); | |
| 330 | } finally { | |
| 331 | net.fetch = real; | |
| 332 | } | |
| 333 | }); | |
| 334 | ||
| 335 | test("every use of a cloud driver that can make something is held to the ceiling", () => { | |
| 336 | // A driver is only ever taken through `capped`, or handed to `read`, which makes nothing. A new | |
| 337 | // call site that provisions or replaces with a bare driver fails here. | |
| 338 | const files = (dir: string): string[] => | |
| 339 | readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? files(join(dir, e.name)) : e.name.endsWith(".ts") ? [join(dir, e.name)] : [])); | |
| 340 | const src = join(import.meta.dir, "../src"); | |
| 341 | const bare: string[] = []; | |
| 342 | let uses = 0; | |
| 343 | for (const file of files(src)) { | |
| 344 | if (file.endsWith("cloud/drivers.ts")) continue; | |
| 345 | const text = readFileSync(file, "utf8"); | |
| 346 | for (const m of text.matchAll(/\bdriverOf\(/g)) { | |
| 347 | if (/^import\b[^\n]*$/.test(text.slice(text.lastIndexOf("\n", m.index) + 1, m.index))) continue; | |
| 348 | uses++; | |
| 349 | const before = text.slice(Math.max(0, m.index - 80), m.index); | |
| 350 | if (!/\bcapped\(app, [\w.]+, $/.test(before) && !/\bread\($/.test(before)) bare.push(`${file.slice(src.length + 1)}: …${before.slice(-40)}driverOf(`); | |
| 351 | } | |
| 352 | } | |
| 353 | expect(bare).toEqual([]); | |
| 354 | // Deploy, update or rollback (asked, then made), a new claim link, and the read: the five there | |
| 355 | // are. | |
| 356 | expect(uses).toBe(5); | |
| 357 | }); | |
| 358 | }); |
test/pinned-claim.test.ts +1171 −174
| @@ -1,201 +1,1198 @@ | ||
| 1 | 1 | /** |
| 2 | * After the claim the selling forge refuses Update and Rollback, and says plainly what the host can | |
| 3 | * still do (#16204). | |
| 2 | * A deployed forge is claimed by one person (#16217). The forge that deploys | |
| 3 | * it shows its deployer a one-time claim link; the machine is booted with the | |
| 4 | * link's sha256 and a deadline and nothing else, and takes that as its | |
| 5 | * first-admin code (`core/first_admin.ts`), redeemed at the doors that | |
| 6 | * already exist. Proved end to end with two forges in one process and a | |
| 7 | * recorded fetch for the cloud: the boot config the seller sends is read back | |
| 8 | * as the deployed forge's environment, and the link the seller showed is | |
| 9 | * tried at the deployed forge's door. | |
| 4 | 10 | */ |
| 5 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 11 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 6 | 12 | import { mkdtemp, rm } from "node:fs/promises"; |
| 7 | 13 | import { tmpdir } from "node:os"; |
| 8 | 14 | import { join } from "node:path"; |
| 15 | import { | |
| 16 | addAccount, | |
| 17 | allowWrite, | |
| 18 | net as cloudNet, | |
| 19 | } from "../src/actions/cloud.ts"; | |
| 20 | import { | |
| 21 | checkPinned, | |
| 22 | claimPinned, | |
| 23 | deployPinned, | |
| 24 | net, | |
| 25 | pinnedForges, | |
| 26 | rollbackPinned, | |
| 27 | updatePinned, | |
| 28 | } from "../src/actions/pinned.ts"; | |
| 29 | import { setCeiling } from "../src/actions/cloud_ceiling.ts"; | |
| 9 | 30 | import { createApp, type App } from "../src/app.ts"; |
| 10 | import { addAccount, allowWrite, net as cloudNet } from "../src/actions/cloud.ts"; | |
| 11 | import { claimPinned, deployPinned, pinnedForges, net, rollbackPinned, updatePinned } from "../src/actions/pinned.ts"; | |
| 12 | import { HOST_CAN, getPinned } from "../src/core/pinned.ts"; | |
| 31 | import { bootConfig } from "../src/cloud/droplet.ts"; | |
| 32 | import { proxyConfig, servedEnv } from "../src/cloud/machine.ts"; | |
| 33 | import { | |
| 34 | FIRST_ADMIN_SEED_TTL_MS, | |
| 35 | FIRST_ADMIN_TTL_MS, | |
| 36 | burnFirstAdmin, | |
| 37 | firstAdminSeed, | |
| 38 | mintFirstAdmin, | |
| 39 | newFirstAdminCode, | |
| 40 | readFirstAdmin, | |
| 41 | readSeed, | |
| 42 | seedFirstAdmin, | |
| 43 | seedState, | |
| 44 | } from "../src/core/first_admin.ts"; | |
| 45 | import { | |
| 46 | BOOT_NAMES, | |
| 47 | CLAIMED_REFUSAL, | |
| 48 | HOST_CAN, | |
| 49 | checkConfig, | |
| 50 | getPinned, | |
| 51 | validHost, | |
| 52 | } from "../src/core/pinned.ts"; | |
| 13 | 53 | import { createToken } from "../src/core/tokens.ts"; |
| 14 | 54 | import { createUser, getUserByName } from "../src/core/users.ts"; |
| 15 | 55 | import { serve, type Servers } from "../src/http/server.ts"; |
| 16 | import { Session } from "../src/tui/session.ts"; | |
| 17 | import { pinnedScreen } from "../src/tui/screens/pinned.ts"; | |
| 56 | import { sha256 } from "../src/kernel/hash.ts"; | |
| 18 | 57 | import type { Ctx, Screen } from "../src/tui/app/app.ts"; |
| 19 | import { quietCtx } from "./helpers/tui-text.ts"; | |
| 20 | import { createToken as mkToken } from "../src/core/tokens.ts"; | |
| 58 | import { pinnedScreen } from "../src/tui/screens/pinned.ts"; | |
| 59 | import { pinnedListPage } from "../src/web/pages/pinned.ts"; | |
| 60 | import { deployPage } from "../src/web/pinned.ts"; | |
| 61 | import { Session } from "../src/tui/session.ts"; | |
| 21 | 62 | import { quietLogs } from "./helpers/globals.ts"; |
| 63 | import { seedPlaces } from "./helpers/places-fixture.ts"; | |
| 64 | import { waitFor } from "./helpers/poll.ts"; | |
| 65 | import { quietCtx } from "./helpers/tui-text.ts"; | |
| 22 | 66 | |
| 23 | 67 | quietLogs(); |
| 24 | const V = "a".repeat(40); | |
| 68 | ||
| 69 | const V1 = "a".repeat(40); | |
| 25 | 70 | const V2 = "b".repeat(40); |
| 26 | let dir = ""; | |
| 27 | let app: App; | |
| 28 | let servers: Servers; | |
| 29 | let tok = ""; | |
| 71 | const SOURCE = "https://forge.example.org/trevato/forge"; | |
| 72 | const HOST = "acme.forge.test"; | |
| 73 | const LINK = /^https:\/\/([a-z0-9.-]+)\/first-admin#([A-Za-z0-9_-]{43})$/; | |
| 30 | 74 | |
| 31 | beforeAll(async () => { | |
| 32 | dir = await mkdtemp(join(tmpdir(), "forge-pinned-claim-")); | |
| 33 | app = createApp({ dataDir: dir, port: 0 }); | |
| 34 | servers = await serve(app); | |
| 35 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "a@f.test", password: "a-good-passphrase", adminIfFirst: true }); | |
| 36 | if (!made.ok) throw new Error(made.error); | |
| 37 | tok = createToken(app.db, getUserByName(app.db, "alice")!.id, "admin", "admin").token; | |
| 38 | cloudNet.fetch = async () => new Response(JSON.stringify({ account: { email: "[email protected]", status: "active" } }), { status: 200 }); | |
| 39 | const alice = getUserByName(app.db, "alice"); | |
| 40 | await addAccount(app, alice, "digitalocean", "main", "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5"); | |
| 41 | allowWrite(app, alice, "digitalocean", "main", true); | |
| 42 | net.fetch = async (url, init) => { | |
| 43 | if (new URL(url).pathname === "/v2/volumes") return new Response(JSON.stringify({ volume: { id: "vol-1" } }), { status: 201 }); | |
| 44 | if (init?.method === "DELETE") return new Response(null, { status: 204 }); | |
| 45 | return new Response(JSON.stringify({ droplet: { id: 7 } }), { status: 202 }); | |
| 46 | }; | |
| 47 | }, 30_000); | |
| 75 | const dirs: string[] = []; | |
| 76 | const fresh = async (opts: { bind?: string } = {}): Promise<App> => { | |
| 77 | const dir = await mkdtemp(join(tmpdir(), "forge-pinned-claim-")); | |
| 78 | dirs.push(dir); | |
| 79 | const app = createApp({ dataDir: dir, port: 0, passkeyOnlySignup: true, ...opts }); | |
| 80 | // Every create is priced from the Places catalog; a forge with none refuses to make anything. | |
| 81 | await seedPlaces(app.db); | |
| 82 | return app; | |
| 83 | }; | |
| 48 | 84 | afterAll(async () => { |
| 49 | await servers.stop(); | |
| 50 | await rm(dir, { recursive: true, force: true }); | |
| 85 | for (const d of dirs) await rm(d, { recursive: true, force: true }); | |
| 51 | 86 | }); |
| 52 | 87 | |
| 53 | test("a claimed forge refuses update and rollback, once, and says what the host can still do", async () => { | |
| 54 | const alice = getUserByName(app.db, "alice"); | |
| 55 | const d = await deployPinned(app, alice, { name: "acme", target: "digitalocean", account: "main", app: "alice/shop", source: "https://forge.example.org/trevato/forge", version: V }); | |
| 56 | expect(d.ok).toBe(true); | |
| 57 | expect((await updatePinned(app, alice, "acme", { version: V2 })).ok).toBe(true); | |
| 58 | ||
| 59 | const page = async () => (await fetch(servers.url + "/pinned", { headers: { authorization: `Bearer ${tok}` } })).text(); | |
| 60 | const before = await page(); | |
| 61 | expect(before).toContain("Update"); | |
| 62 | expect(before).not.toContain("snapshot its disk"); | |
| 63 | ||
| 64 | expect(claimPinned(app, undefined, "acme").ok).toBe(false); | |
| 65 | expect(claimPinned(app, alice, "acme").ok).toBe(true); | |
| 66 | expect(getPinned(app.db, "acme")!.claimedAt).not.toBe(""); | |
| 67 | const again = claimPinned(app, alice, "acme"); | |
| 68 | expect(again.ok).toBe(false); | |
| 69 | ||
| 70 | const u = await updatePinned(app, alice, "acme", { version: V }); | |
| 71 | const r = await rollbackPinned(app, alice, "acme"); | |
| 72 | expect(u.ok || r.ok).toBe(false); | |
| 73 | expect(u.ok ? "" : u.error).toContain("handed to its buyer"); | |
| 74 | expect(r.ok ? "" : r.error).toContain("handed to its buyer"); | |
| 75 | expect(getPinned(app.db, "acme")!.version).toBe(V2); | |
| 76 | ||
| 77 | const after = await page(); | |
| 78 | expect(after).toContain("snapshot its disk"); | |
| 79 | expect(after).not.toContain("no access"); | |
| 80 | expect(after.split("snapshot its disk").length).toBe(2); | |
| 81 | expect(after).not.toContain(">Roll back<"); | |
| 82 | expect(HOST_CAN).toContain("own cloud account"); | |
| 88 | /** The machine's environment file, read back out of the cloud-config the seller sent. */ | |
| 89 | const envOf = (userData: string): Record<string, string> => { | |
| 90 | const content = | |
| 91 | /- path: \/etc\/forge\/env\n\s+permissions: "0600"\n\s+content: (".*")\n/.exec( | |
| 92 | userData, | |
| 93 | )?.[1]; | |
| 94 | if (content === undefined) | |
| 95 | throw new Error("no /etc/forge/env in the boot config"); | |
| 96 | return Object.fromEntries( | |
| 97 | (JSON.parse(content) as string) | |
| 98 | .trim() | |
| 99 | .split("\n") | |
| 100 | .map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1)]), | |
| 101 | ); | |
| 102 | }; | |
| 103 | /** Every byte the database holds, as text: where a stored secret would show. */ | |
| 104 | const everything = (app: App): string => | |
| 105 | Buffer.from(app.db.serialize()).toString("latin1"); | |
| 106 | const redeem = (base: string, body: Record<string, unknown>) => | |
| 107 | fetch(`${base}/api/v1/first-admin`, { | |
| 108 | method: "POST", | |
| 109 | headers: { "content-type": "application/json" }, | |
| 110 | body: JSON.stringify(body), | |
| 111 | }); | |
| 112 | const who = (n: number) => ({ | |
| 113 | username: `buyer${n}`, | |
| 114 | email: `buyer${n}@x.test`, | |
| 115 | scope: "admin", | |
| 83 | 116 | }); |
| 84 | 117 | |
| 85 | test("the deploy page says it and points to the buyer's own account", async () => { | |
| 86 | const t = await (await fetch(servers.url + "/deploy-to", { headers: { authorization: `Bearer ${tok}` } })).text(); | |
| 87 | expect(t).toContain("boot it into rescue"); | |
| 88 | expect(t).toContain("own cloud account"); | |
| 89 | expect(t.split("boot it into rescue").length).toBe(2); | |
| 90 | }); | |
| 118 | describe("a deployed forge is claimed with the link its deployer was shown, and by nothing else", () => { | |
| 119 | let seller: App; | |
| 120 | let sellerServers: Servers; | |
| 121 | let deployed: App; | |
| 122 | let servers: Servers; | |
| 123 | /** Every machine the seller asked its cloud for, newest last. */ | |
| 124 | const machines: { user_data: string }[] = []; | |
| 125 | const calls: string[] = []; | |
| 126 | let said: string | undefined; | |
| 127 | /** The cloud refuses the next machine it is asked for. */ | |
| 128 | let refuseMachine = false; | |
| 129 | let code = ""; | |
| 130 | const admin = () => getUserByName(seller.db, "alice")!; | |
| 131 | const input = (over: Record<string, unknown> = {}) => ({ | |
| 132 | name: "acme", | |
| 133 | host: HOST, | |
| 134 | target: "digitalocean", | |
| 135 | account: "main", | |
| 136 | app: "alice/shop", | |
| 137 | source: SOURCE, | |
| 138 | version: V1, | |
| 139 | config: { PORT: "8080" }, | |
| 140 | ...over, | |
| 141 | }); | |
| 91 | 142 | |
| 92 | const mkForge = (name: string) => | |
| 93 | deployPinned(app, getUserByName(app.db, "alice"), { name, target: "digitalocean", account: "main", app: "alice/shop", source: "https://forge.example.org/trevato/forge", version: V }); | |
| 94 | ||
| 95 | test("web: Hand to buyer confirms first, posts same-origin, is admin only and shows the result", async () => { | |
| 96 | expect((await mkForge("web1")).ok).toBe(true); | |
| 97 | await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" }); | |
| 98 | const bob = mkToken(app.db, getUserByName(app.db, "bob")!.id, "admin", "admin").token; | |
| 99 | const hdr = (t: string, origin = servers.url) => ({ authorization: `Bearer ${t}`, origin, "content-type": "application/x-www-form-urlencoded" }); | |
| 100 | const post = (t: string, origin?: string) => fetch(servers.url + "/pinned/web1/claim", { method: "POST", redirect: "manual", headers: hdr(t, origin), body: "" }); | |
| 101 | ||
| 102 | const list = await (await fetch(servers.url + "/pinned", { headers: { authorization: `Bearer ${tok}` } })).text(); | |
| 103 | expect(list).toContain("/pinned/web1/claim"); | |
| 104 | const conf = await (await fetch(servers.url + "/-/confirm?to=/pinned/web1/claim", { headers: { authorization: `Bearer ${tok}` } })).text(); | |
| 105 | expect(conf).toContain("Hand web1 to its buyer?"); | |
| 106 | expect(conf).toContain('action="/pinned/web1/claim"'); | |
| 107 | ||
| 108 | expect((await post(bob)).status).toBeGreaterThanOrEqual(403); | |
| 109 | expect((await post(tok, "https://evil.example")).status).toBe(403); | |
| 110 | expect(getPinned(app.db, "web1")!.claimedAt).toBe(""); | |
| 111 | expect((await fetch(servers.url + "/pinned", { headers: { authorization: `Bearer ${bob}` } })).status).toBeGreaterThanOrEqual(403); | |
| 112 | ||
| 113 | expect((await post(tok)).status).toBe(303); | |
| 114 | expect(getPinned(app.db, "web1")!.claimedAt).not.toBe(""); | |
| 115 | const again = await post(tok); | |
| 116 | expect(again.status).toBe(303); | |
| 117 | expect(getPinned(app.db, "web1")!.claimedAt).not.toBe(""); | |
| 118 | }); | |
| 119 | ||
| 120 | test("HTTP API: claim is admin-scope only, once, and 404s an unknown forge", async () => { | |
| 121 | expect((await mkForge("api1")).ok).toBe(true); | |
| 122 | const bob = mkToken(app.db, getUserByName(app.db, "bob")!.id, "admin", "admin").token; | |
| 123 | const post = (name: string, t?: string) => | |
| 124 | fetch(`${servers.url}/api/v1/admin/pinned/${name}/claim`, { method: "POST", headers: { "content-type": "application/json", ...(t ? { authorization: `Bearer ${t}` } : {}) }, body: "{}" }); | |
| 125 | expect((await post("api1")).status).toBeGreaterThanOrEqual(401); | |
| 126 | expect((await post("api1", bob)).status).toBe(403); | |
| 127 | expect(getPinned(app.db, "api1")!.claimedAt).toBe(""); | |
| 128 | const ok = await post("api1", tok); | |
| 129 | expect(ok.status).toBe(200); | |
| 130 | expect(getPinned(app.db, "api1")!.claimedAt).not.toBe(""); | |
| 131 | expect((await post("api1", tok)).status).toBe(422); | |
| 132 | expect((await post("nope", tok)).status).toBe(404); | |
| 133 | }); | |
| 134 | ||
| 135 | test("MCP: the claim verb hands a forge over, and a read-only token cannot", async () => { | |
| 136 | expect((await mkForge("mcp1")).ok).toBe(true); | |
| 137 | const call = async (t: string, args: Record<string, unknown>) => { | |
| 138 | const res = await fetch(`${servers.url}/mcp`, { | |
| 139 | method: "POST", | |
| 140 | headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${t}` }, | |
| 141 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "pinned_forge", arguments: args } }), | |
| 143 | beforeAll(async () => { | |
| 144 | seller = await fresh(); | |
| 145 | sellerServers = await serve(seller); | |
| 146 | deployed = await fresh(); | |
| 147 | servers = await serve(deployed); | |
| 148 | const made = await createUser(seller.db, { | |
| 149 | origin: "seed", | |
| 150 | trusted: true, | |
| 151 | username: "alice", | |
| 152 | email: "[email protected]", | |
| 153 | password: "a-good-passphrase", | |
| 154 | adminIfFirst: true, | |
| 142 | 155 | }); |
| 143 | return ((await res.json()) as any).result.content[0].text as string; | |
| 144 | }; | |
| 145 | const ro = mkToken(app.db, getUserByName(app.db, "alice")!.id, "ro", "ro").token; | |
| 146 | await call(ro, { verb: "claim", name: "mcp1" }); | |
| 147 | expect(getPinned(app.db, "mcp1")!.claimedAt).toBe(""); | |
| 148 | const said = await call(tok, { verb: "claim", name: "mcp1" }); | |
| 149 | expect(said).toContain("claim mcp1"); | |
| 150 | expect(getPinned(app.db, "mcp1")!.claimedAt).not.toBe(""); | |
| 151 | expect(await call(tok, { verb: "claim", name: "mcp1" })).toContain("handed"); | |
| 156 | if (!made.ok) throw new Error(made.error); | |
| 157 | cloudNet.fetch = async () => | |
| 158 | new Response( | |
| 159 | JSON.stringify({ account: { email: "[email protected]", status: "active" } }), | |
| 160 | { status: 200 }, | |
| 161 | ); | |
| 162 | const added = await addAccount( | |
| 163 | seller, | |
| 164 | admin(), | |
| 165 | "digitalocean", | |
| 166 | "main", | |
| 167 | "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5", | |
| 168 | ); | |
| 169 | if (!added.ok) throw new Error(String(added.error)); | |
| 170 | allowWrite(seller, admin(), "digitalocean", "main", true); | |
| 171 | // These tests put five forges on the account ($13 a month each); the default ceiling of $50 | |
| 172 | // would refuse the fourth, which is the ceiling's test to make (test/pinned-ceiling.test.ts). | |
| 173 | if (!setCeiling(seller, admin(), "digitalocean", "main", 500).ok) | |
| 174 | throw new Error("the ceiling was not set"); | |
| 175 | net.fetch = async (url, init) => { | |
| 176 | const path = new URL(url).pathname; | |
| 177 | const method = init?.method ?? "GET"; | |
| 178 | calls.push(`${method} ${path}`); | |
| 179 | if (path === "/v2/volumes") | |
| 180 | return new Response(JSON.stringify({ volume: { id: "vol-1" } }), { | |
| 181 | status: 201, | |
| 182 | }); | |
| 183 | if (method === "DELETE") return new Response(null, { status: 204 }); | |
| 184 | // Each machine is made with a throwaway SSH key, deleted after the call (#16218). | |
| 185 | if (path === "/v2/account/keys") | |
| 186 | return new Response(JSON.stringify({ ssh_key: { id: 4242 } }), { | |
| 187 | status: 201, | |
| 188 | }); | |
| 189 | if (method === "POST" && refuseMachine) { | |
| 190 | refuseMachine = false; | |
| 191 | return new Response("{}", { status: 500 }); | |
| 192 | } | |
| 193 | if (method === "POST") | |
| 194 | machines.push(JSON.parse(String(init?.body)) as { user_data: string }); | |
| 195 | return new Response( | |
| 196 | JSON.stringify({ | |
| 197 | droplet: { | |
| 198 | id: 100 + machines.length, | |
| 199 | status: "active", | |
| 200 | networks: { v4: [{ type: "public", ip_address: "203.0.113.7" }] }, | |
| 201 | }, | |
| 202 | }), | |
| 203 | { status: 202 }, | |
| 204 | ); | |
| 205 | }; | |
| 206 | net.resolve = async () => ["203.0.113.7"]; | |
| 207 | // The deployed forge, asked on its name: the claim question is answered by the real route. | |
| 208 | net.probe = async (url) => { | |
| 209 | const u = new URL(url); | |
| 210 | if (u.pathname !== "/api/v1/first-admin/claim") | |
| 211 | return new Response("ok", { status: 200 }); | |
| 212 | if (said !== undefined) | |
| 213 | return new Response(JSON.stringify({ state: said }), { status: 200 }); | |
| 214 | return fetch(`${servers.url}${u.pathname}${u.search}`); | |
| 215 | }; | |
| 216 | }, 30_000); | |
| 217 | ||
| 218 | afterAll(async () => { | |
| 219 | await sellerServers.stop(); | |
| 220 | await servers.stop(); | |
| 221 | seller.close(); | |
| 222 | deployed.close(); | |
| 223 | }); | |
| 224 | ||
| 225 | test("the deploy answers once with a link on the forge's own name; the machine is given its hash and never the link", async () => { | |
| 226 | const r = await deployPinned(seller, admin(), input()); | |
| 227 | if (!r.ok) throw new Error(r.error); | |
| 228 | const link = LINK.exec(r.value.claim.link); | |
| 229 | expect(link?.[1]).toBe(HOST); | |
| 230 | code = link![2]!; | |
| 231 | expect(r.value.url).toBe(`https://${HOST}/`); | |
| 232 | expect(r.value.dns).toBe(`${HOST} A 203.0.113.7`); | |
| 233 | expect( | |
| 234 | Date.parse(r.value.claim.expiresAt) - Date.now(), | |
| 235 | ).toBeLessThanOrEqual(FIRST_ADMIN_SEED_TTL_MS); | |
| 236 | expect(Date.parse(r.value.claim.expiresAt) - Date.now()).toBeGreaterThan( | |
| 237 | FIRST_ADMIN_SEED_TTL_MS - 60_000, | |
| 238 | ); | |
| 239 | ||
| 240 | const sent = machines.at(-1)!.user_data; | |
| 241 | const env = envOf(sent); | |
| 242 | expect(env["FORGE_FIRST_ADMIN_SEED"]).toBe( | |
| 243 | firstAdminSeed(sha256(code), r.value.claim.expiresAt), | |
| 244 | ); | |
| 245 | // No form of the link is in the boot config: not as it is, not re-encoded. | |
| 246 | const raw = Buffer.from(code, "base64url"); | |
| 247 | for (const form of [ | |
| 248 | code, | |
| 249 | raw.toString("base64"), | |
| 250 | raw.toString("hex"), | |
| 251 | encodeURIComponent(r.value.claim.link), | |
| 252 | ]) | |
| 253 | expect(sent).not.toContain(form); | |
| 254 | // And it could not be: the boot config is a function of the stored row, and the row holds only | |
| 255 | // the hash. | |
| 256 | const row = getPinned(seller.db, "acme")!; | |
| 257 | expect(sent).toBe(bootConfig(row)); | |
| 258 | expect(row.claimHash).toBe(sha256(code)); | |
| 259 | expect(JSON.stringify(row)).not.toContain(code); | |
| 260 | expect(everything(seller)).not.toContain(code); | |
| 261 | // Nor does the list any door reads, which leaves the hash out as well. | |
| 262 | const listed = pinnedForges(seller, admin()); | |
| 263 | expect(JSON.stringify(listed)).not.toContain(code); | |
| 264 | expect(JSON.stringify(listed)).not.toContain(row.claimHash); | |
| 265 | }); | |
| 266 | ||
| 267 | test("the deployed forge takes the seed at boot: a visitor without the link gets the refusal any wrong code gets", async () => { | |
| 268 | const env = envOf(machines.at(-1)!.user_data); | |
| 269 | expect(seedFirstAdmin(deployed.db, env["FORGE_FIRST_ADMIN_SEED"])).toBe( | |
| 270 | "seeded", | |
| 271 | ); | |
| 272 | expect(everything(deployed)).not.toContain(code); | |
| 273 | const wrong = newFirstAdminCode().code; | |
| 274 | const answers: unknown[] = []; | |
| 275 | for (const guess of [ | |
| 276 | wrong, | |
| 277 | "", | |
| 278 | sha256(code), | |
| 279 | env["FORGE_FIRST_ADMIN_SEED"]!, | |
| 280 | ]) { | |
| 281 | const res = await redeem(servers.url, { code: guess, ...who(0) }); | |
| 282 | expect(res.status).toBe(403); | |
| 283 | answers.push(await res.json()); | |
| 284 | } | |
| 285 | // One answer for all of them: nothing says whether a claim stands, or what was wrong. | |
| 286 | expect(new Set(answers.map((a) => JSON.stringify(a))).size).toBe(1); | |
| 287 | expect(getUserByName(deployed.db, "buyer0")).toBeUndefined(); | |
| 288 | // The page shows a form to anyone and nothing of the claim. | |
| 289 | const page = await (await fetch(`${servers.url}/first-admin`)).text(); | |
| 290 | expect(page).not.toContain(sha256(code)); | |
| 291 | // The claim question is answered only to the hash the machine was booted with. | |
| 292 | expect( | |
| 293 | (await fetch(`${servers.url}/api/v1/first-admin/claim`)).status, | |
| 294 | ).toBe(404); | |
| 295 | expect( | |
| 296 | ( | |
| 297 | await fetch( | |
| 298 | `${servers.url}/api/v1/first-admin/claim?seed=${sha256(wrong)}`, | |
| 299 | ) | |
| 300 | ).status, | |
| 301 | ).toBe(404); | |
| 302 | expect( | |
| 303 | (await fetch(`${servers.url}/api/v1/first-admin/claim?seed=${code}`)) | |
| 304 | .status, | |
| 305 | ).toBe(404); | |
| 306 | expect(await checkPinned(seller, admin(), "acme")).toMatchObject({ | |
| 307 | ok: true, | |
| 308 | value: { healthy: true, claim: "waiting" }, | |
| 309 | }); | |
| 310 | }); | |
| 311 | ||
| 312 | test("the link works once: it makes the first admin, and a second use is refused", async () => { | |
| 313 | const res = await redeem(servers.url, { code, ...who(1) }); | |
| 314 | expect(res.status).toBe(201); | |
| 315 | expect(getUserByName(deployed.db, "buyer1")?.isAdmin).toBe(true); | |
| 316 | expect((await redeem(servers.url, { code, ...who(2) })).status).toBe(403); | |
| 317 | expect(getUserByName(deployed.db, "buyer2")).toBeUndefined(); | |
| 318 | expect(await checkPinned(seller, admin(), "acme")).toMatchObject({ | |
| 319 | ok: true, | |
| 320 | value: { claim: "claimed" }, | |
| 321 | }); | |
| 322 | }); | |
| 323 | ||
| 324 | test("a restart with the same boot config revives nothing", async () => { | |
| 325 | const env = envOf(machines.at(-1)!.user_data); | |
| 326 | expect(seedFirstAdmin(deployed.db, env["FORGE_FIRST_ADMIN_SEED"])).toBe( | |
| 327 | "kept", | |
| 328 | ); | |
| 329 | expect((await redeem(servers.url, { code, ...who(3) })).status).toBe(403); | |
| 330 | }); | |
| 331 | ||
| 332 | test("once the forge says it was claimed it is its buyer's: recorded once, and Update, Roll back and a new claim link are refused", async () => { | |
| 333 | // The check above learnt it from the deployed forge; nobody here said so by hand. | |
| 334 | const row = getPinned(seller.db, "acme")!; | |
| 335 | expect(row.claimedAt).not.toBe(""); | |
| 336 | const claimed = () => | |
| 337 | seller.db | |
| 338 | .query("SELECT payload FROM event WHERE kind = 'pinned.claimed'") | |
| 339 | .all() as { payload: string }[]; | |
| 340 | expect(claimed().map((e) => JSON.parse(e.payload))).toEqual([ | |
| 341 | { name: "acme" }, | |
| 342 | ]); | |
| 343 | expect(await checkPinned(seller, admin(), "acme")).toMatchObject({ | |
| 344 | ok: true, | |
| 345 | value: { claim: "claimed", claimedAt: row.claimedAt }, | |
| 346 | }); | |
| 347 | expect(claimed()).toHaveLength(1); | |
| 348 | const n = machines.length; | |
| 349 | for (const refused of [ | |
| 350 | await updatePinned(seller, admin(), "acme", { version: V2 }), | |
| 351 | await rollbackPinned(seller, admin(), "acme"), | |
| 352 | await claimPinned(seller, admin(), "acme"), | |
| 353 | ]) | |
| 354 | expect(refused).toMatchObject({ ok: false, error: CLAIMED_REFUSAL }); | |
| 355 | expect(machines.length).toBe(n); | |
| 356 | expect(getPinned(seller.db, "acme")).toMatchObject({ | |
| 357 | version: V1, | |
| 358 | claimHash: row.claimHash, | |
| 359 | }); | |
| 360 | // At the door itself: /pinned says what the host can still do and offers the claimed forge | |
| 361 | // only Check, and /deploy-to says it too. | |
| 362 | const tok = createToken(seller.db, admin().id, "admin", "admin").token; | |
| 363 | const get = async (path: string) => | |
| 364 | (await fetch(sellerServers.url + path, { headers: { authorization: `Bearer ${tok}` } })).text(); | |
| 365 | const list = await get("/pinned"); | |
| 366 | expect(list.split("snapshot its disk").length - 1).toBe(1); | |
| 367 | expect(list).not.toContain("no access"); | |
| 368 | expect(list).toContain('value="/pinned/acme/check"'); | |
| 369 | for (const act of ["update", "rollback", "claim"]) | |
| 370 | expect(list).not.toContain(`value="/pinned/acme/${act}"`); | |
| 371 | const form = await get("/deploy-to"); | |
| 372 | expect(form.split("boot it into rescue").length - 1).toBe(1); | |
| 373 | expect(form).toContain("own cloud account"); | |
| 374 | }); | |
| 375 | ||
| 376 | test("a new claim the cloud refuses issues nothing: the row keeps the hash its machine was booted with", async () => { | |
| 377 | const made = await deployPinned( | |
| 378 | seller, | |
| 379 | admin(), | |
| 380 | input({ name: "held", host: "held.forge.test" }), | |
| 381 | ); | |
| 382 | if (!made.ok) throw new Error(made.error); | |
| 383 | const was = getPinned(seller.db, "held")!; | |
| 384 | const events = () => | |
| 385 | seller.db | |
| 386 | .query("SELECT count(*) AS n FROM event WHERE kind = 'pinned.claim_issued'") | |
| 387 | .get() as { n: number }; | |
| 388 | const before = events().n; | |
| 389 | said = "waiting"; | |
| 390 | refuseMachine = true; | |
| 391 | const refused = await claimPinned(seller, admin(), "held"); | |
| 392 | said = undefined; | |
| 393 | expect(refused).toMatchObject({ ok: false }); | |
| 394 | expect(JSON.stringify(refused)).not.toContain("first-admin#"); | |
| 395 | expect(getPinned(seller.db, "held")).toMatchObject({ | |
| 396 | state: "failed", | |
| 397 | claimHash: was.claimHash, | |
| 398 | claimExpires: was.claimExpires, | |
| 399 | }); | |
| 400 | expect(events().n).toBe(before); | |
| 401 | // Finishing the replacement boots the machine with the claim that still stands. | |
| 402 | expect( | |
| 403 | (await updatePinned(seller, admin(), "held", { version: V1 })).ok, | |
| 404 | ).toBe(true); | |
| 405 | expect(envOf(machines.at(-1)!.user_data)["FORGE_FIRST_ADMIN_SEED"]).toBe( | |
| 406 | firstAdminSeed(was.claimHash, was.claimExpires), | |
| 407 | ); | |
| 408 | }); | |
| 409 | ||
| 410 | test("a new claim replaces the machine with the new hash; the old link is dead and the new one works once", async () => { | |
| 411 | // A second forge nobody has claimed, on a deployed forge of its own. | |
| 412 | const other = await fresh(); | |
| 413 | const otherServers = await serve(other); | |
| 414 | try { | |
| 415 | const first = await deployPinned( | |
| 416 | seller, | |
| 417 | admin(), | |
| 418 | input({ name: "second", host: "second.forge.test" }), | |
| 419 | ); | |
| 420 | if (!first.ok) throw new Error(first.error); | |
| 421 | const old = LINK.exec(first.value.claim.link)![2]!; | |
| 422 | expect( | |
| 423 | seedFirstAdmin( | |
| 424 | other.db, | |
| 425 | envOf(machines.at(-1)!.user_data)["FORGE_FIRST_ADMIN_SEED"], | |
| 426 | ), | |
| 427 | ).toBe("seeded"); | |
| 428 | ||
| 429 | said = "waiting"; | |
| 430 | calls.length = 0; | |
| 431 | const again = await claimPinned(seller, admin(), "second"); | |
| 432 | if (!again.ok) throw new Error(again.error); | |
| 433 | // The forge is asked whether it was claimed, at the address read back; then the machine is | |
| 434 | // replaced on the volume it had: nothing else carries a hash to it. | |
| 435 | expect(calls.slice(0, 5)).toEqual([ | |
| 436 | "GET /v2/droplets/" + first.value.remote, | |
| 437 | "DELETE /v2/droplets/" + first.value.remote, | |
| 438 | "POST /v2/account/keys", | |
| 439 | "POST /v2/droplets", | |
| 440 | "DELETE /v2/account/keys/4242", | |
| 441 | ]); | |
| 442 | const next = LINK.exec(again.value.claim.link)![2]!; | |
| 443 | expect(next).not.toBe(old); | |
| 444 | const sent = machines.at(-1)!.user_data; | |
| 445 | expect(envOf(sent)["FORGE_FIRST_ADMIN_SEED"]).toBe( | |
| 446 | firstAdminSeed(sha256(next), again.value.claim.expiresAt), | |
| 447 | ); | |
| 448 | expect(sent).not.toContain(sha256(old)); | |
| 449 | expect(sent).not.toContain(next); | |
| 450 | expect(everything(seller)).not.toContain(next); | |
| 451 | expect(everything(seller)).not.toContain(sha256(old)); | |
| 452 | ||
| 453 | // The replaced machine boots on the same volume, so the same database, with the new seed. | |
| 454 | expect( | |
| 455 | seedFirstAdmin(other.db, envOf(sent)["FORGE_FIRST_ADMIN_SEED"]), | |
| 456 | ).toBe("seeded"); | |
| 457 | expect( | |
| 458 | (await redeem(otherServers.url, { code: old, ...who(4) })).status, | |
| 459 | ).toBe(403); | |
| 460 | expect(seedState(other.db, sha256(old))).toBeUndefined(); | |
| 461 | expect(seedState(other.db, sha256(next))).toBe("waiting"); | |
| 462 | expect( | |
| 463 | (await redeem(otherServers.url, { code: next, ...who(5) })).status, | |
| 464 | ).toBe(201); | |
| 465 | expect( | |
| 466 | (await redeem(otherServers.url, { code: next, ...who(6) })).status, | |
| 467 | ).toBe(403); | |
| 468 | expect(seedState(other.db, sha256(next))).toBe("claimed"); | |
| 469 | // A name does not change with a claim, and a new claim is the admin's alone. | |
| 470 | expect( | |
| 471 | await claimPinned(seller, admin(), "second", { | |
| 472 | host: "elsewhere.forge.test", | |
| 473 | }), | |
| 474 | ).toMatchObject({ ok: false }); | |
| 475 | expect(await claimPinned(seller, undefined, "second")).toMatchObject({ | |
| 476 | ok: false, | |
| 477 | error: "not_found", | |
| 478 | }); | |
| 479 | expect(await claimPinned(seller, admin(), "nope")).toMatchObject({ | |
| 480 | ok: false, | |
| 481 | error: "No such pinned forge.", | |
| 482 | }); | |
| 483 | } finally { | |
| 484 | said = undefined; | |
| 485 | await otherServers.stop(); | |
| 486 | other.close(); | |
| 487 | } | |
| 488 | }); | |
| 489 | ||
| 490 | test("a forge deployed before forges had names is not replaced until it is given one, with a claim", async () => { | |
| 491 | seller.db.run( | |
| 492 | "UPDATE pinned_forge SET host = '', claim_hash = '', claim_expires = '' WHERE name = 'second'", | |
| 493 | ); | |
| 494 | const n = machines.length; | |
| 495 | expect( | |
| 496 | await updatePinned(seller, admin(), "second", { version: V2 }), | |
| 497 | ).toMatchObject({ ok: false }); | |
| 498 | expect(await rollbackPinned(seller, admin(), "second")).toMatchObject({ | |
| 499 | ok: false, | |
| 500 | }); | |
| 501 | expect(await claimPinned(seller, admin(), "second")).toMatchObject({ | |
| 502 | ok: false, | |
| 503 | }); | |
| 504 | expect(await checkPinned(seller, admin(), "second")).toMatchObject({ | |
| 505 | ok: true, | |
| 506 | value: { healthy: false, waiting: "name", url: "" }, | |
| 507 | }); | |
| 508 | expect(machines.length).toBe(n); | |
| 509 | // One forge a name: another's is refused; its own is taken, once. | |
| 510 | expect( | |
| 511 | await claimPinned(seller, admin(), "second", { host: HOST }), | |
| 512 | ).toMatchObject({ | |
| 513 | ok: false, | |
| 514 | error: "Another pinned forge is served on that name.", | |
| 515 | }); | |
| 516 | const named = await claimPinned(seller, admin(), "second", { | |
| 517 | host: "Second.Forge.Test", | |
| 518 | }); | |
| 519 | expect(named).toMatchObject({ | |
| 520 | ok: true, | |
| 521 | value: { host: "second.forge.test", url: "https://second.forge.test/" }, | |
| 522 | }); | |
| 523 | expect(envOf(machines.at(-1)!.user_data)["FORGE_URL"]).toBe( | |
| 524 | "https://second.forge.test", | |
| 525 | ); | |
| 526 | }); | |
| 527 | ||
| 528 | test("HTTP and MCP: deploy and claim answer with the link once, uncached; a member and a read-only token get nothing", async () => { | |
| 529 | const tok = createToken(seller.db, admin().id, "admin", "admin").token; | |
| 530 | const h = (t: string) => ({ | |
| 531 | authorization: `Bearer ${t}`, | |
| 532 | "content-type": "application/json", | |
| 533 | }); | |
| 534 | const dep = await fetch(`${sellerServers.url}/api/v1/admin/pinned`, { | |
| 535 | method: "POST", | |
| 536 | headers: h(tok), | |
| 537 | body: JSON.stringify(input({ name: "third", host: "third.forge.test" })), | |
| 538 | }); | |
| 539 | expect(dep.status).toBe(201); | |
| 540 | expect(dep.headers.get("cache-control")).toBe("no-store"); | |
| 541 | const body = (await dep.json()) as { | |
| 542 | claim: { link: string }; | |
| 543 | claimHash?: string; | |
| 544 | dns: string; | |
| 545 | }; | |
| 546 | expect(LINK.exec(body.claim.link)?.[1]).toBe("third.forge.test"); | |
| 547 | expect(body.claimHash).toBeUndefined(); | |
| 548 | expect(body.dns).toBe("third.forge.test A 203.0.113.7"); | |
| 549 | expect( | |
| 550 | ( | |
| 551 | await fetch(`${sellerServers.url}/api/v1/admin/pinned`, { | |
| 552 | method: "POST", | |
| 553 | headers: h(tok), | |
| 554 | body: JSON.stringify(input({ name: "nohost", host: "" })), | |
| 555 | }) | |
| 556 | ).status, | |
| 557 | ).toBe(422); | |
| 558 | ||
| 559 | said = "waiting"; | |
| 560 | const again = await fetch( | |
| 561 | `${sellerServers.url}/api/v1/admin/pinned/third/claim`, | |
| 562 | { method: "POST", headers: h(tok), body: "{}" }, | |
| 563 | ); | |
| 564 | expect(again.status).toBe(200); | |
| 565 | expect(again.headers.get("cache-control")).toBe("no-store"); | |
| 566 | const fresher = ((await again.json()) as { claim: { link: string } }).claim | |
| 567 | .link; | |
| 568 | expect(fresher).not.toBe(body.claim.link); | |
| 569 | expect(getPinned(seller.db, "third")!.claimHash).toBe( | |
| 570 | sha256(LINK.exec(fresher)![2]!), | |
| 571 | ); | |
| 572 | // The list afterwards holds neither link. | |
| 573 | const list = await ( | |
| 574 | await fetch(`${sellerServers.url}/api/v1/admin/pinned`, { | |
| 575 | headers: h(tok), | |
| 576 | }) | |
| 577 | ).text(); | |
| 578 | expect(list).not.toContain("first-admin#"); | |
| 579 | ||
| 580 | const made = await createUser(seller.db, { | |
| 581 | origin: "seed", | |
| 582 | trusted: true, | |
| 583 | username: "bob", | |
| 584 | email: "[email protected]", | |
| 585 | password: "a-good-passphrase", | |
| 586 | }); | |
| 587 | if (!made.ok) throw new Error(made.error); | |
| 588 | const bob = createToken(seller.db, made.value.id, "admin", "admin").token; | |
| 589 | expect( | |
| 590 | ( | |
| 591 | await fetch(`${sellerServers.url}/api/v1/admin/pinned/third/claim`, { | |
| 592 | method: "POST", | |
| 593 | headers: h(bob), | |
| 594 | body: "{}", | |
| 595 | }) | |
| 596 | ).status, | |
| 597 | ).toBeGreaterThanOrEqual(403); | |
| 598 | expect( | |
| 599 | ( | |
| 600 | await fetch(`${sellerServers.url}/api/v1/admin/pinned/third/claim`, { | |
| 601 | method: "POST", | |
| 602 | headers: { "content-type": "application/json" }, | |
| 603 | body: "{}", | |
| 604 | }) | |
| 605 | ).status, | |
| 606 | ).toBeGreaterThanOrEqual(401); | |
| 607 | ||
| 608 | const call = async (t: string, args: Record<string, unknown>) => { | |
| 609 | const res = await fetch(`${sellerServers.url}/mcp`, { | |
| 610 | method: "POST", | |
| 611 | headers: { | |
| 612 | "content-type": "application/json", | |
| 613 | accept: "application/json, text/event-stream", | |
| 614 | authorization: `Bearer ${t}`, | |
| 615 | }, | |
| 616 | body: JSON.stringify({ | |
| 617 | jsonrpc: "2.0", | |
| 618 | id: 1, | |
| 619 | method: "tools/call", | |
| 620 | params: { name: "pinned_forge", arguments: args }, | |
| 621 | }), | |
| 622 | }); | |
| 623 | const text = ( | |
| 624 | (await res.json()) as { result: { content: { text: string }[] } } | |
| 625 | ).result.content[0]!.text; | |
| 626 | const answer: { says?: string; claim?: { link: string }; text?: string } = | |
| 627 | text.startsWith("{") ? JSON.parse(text) : { text }; | |
| 628 | return answer; | |
| 629 | }; | |
| 630 | const viaMcp = await call(tok, { verb: "claim", name: "third" }); | |
| 631 | expect(LINK.exec(viaMcp.claim?.link ?? "")?.[1]).toBe("third.forge.test"); | |
| 632 | expect(viaMcp.says).toContain( | |
| 633 | "Create the DNS record third.forge.test A 203.0.113.7", | |
| 634 | ); | |
| 635 | expect(viaMcp.says).toContain("shown only now"); | |
| 636 | const ro = createToken(seller.db, admin().id, "ro", "ro").token; | |
| 637 | expect( | |
| 638 | JSON.stringify(await call(ro, { verb: "claim", name: "third" })), | |
| 639 | ).not.toContain("first-admin#"); | |
| 640 | said = undefined; | |
| 641 | }); | |
| 642 | ||
| 643 | test("terminal: a deploy shows its link in the one dialog that holds it; n asks before it replaces the machine", async () => { | |
| 644 | const f = new Session(seller, { | |
| 645 | sshUsername: "t", | |
| 646 | remoteAddress: "127.0.0.1", | |
| 647 | user: admin(), | |
| 648 | }); | |
| 649 | const pushed: Screen[] = []; | |
| 650 | // The link dialog takes the mouse while it is open, so this context has one to give. | |
| 651 | const ctx: Ctx = { ...quietCtx(), mouse() {}, push: (s) => void pushed.push(s) }; | |
| 652 | const key = (s: Screen, k: string) => | |
| 653 | s.key?.({ type: "key", key: k, ctrl: false, alt: false, shift: false }); | |
| 654 | const screen = pinnedScreen(f, ctx); | |
| 655 | key(screen, "d"); | |
| 656 | const prompt = pushed[0]!; | |
| 657 | prompt.paste?.( | |
| 658 | `tty tty.forge.test digitalocean/main alice/shop ${SOURCE} ${V1}`, | |
| 659 | ); | |
| 660 | key(prompt, "enter"); | |
| 661 | await waitFor(() => pushed.some((s) => s.title === "Link")); | |
| 662 | expect(getPinned(seller.db, "tty")).toMatchObject({ | |
| 663 | host: "tty.forge.test", | |
| 664 | state: "running", | |
| 665 | }); | |
| 666 | // n on the first forge asks; nothing is replaced by the key alone. | |
| 667 | const n = machines.length; | |
| 668 | key(screen, "n"); | |
| 669 | expect(pushed.at(-1)!.title).toContain("A new claim link for"); | |
| 670 | expect(machines.length).toBe(n); | |
| 671 | }); | |
| 152 | 672 | }); |
| 153 | 673 | |
| 154 | test("terminal: h asks first, hands over only on Hand over, and the view follows a claim made elsewhere", async () => { | |
| 155 | expect((await mkForge("tui1")).ok).toBe(true); | |
| 156 | expect((await mkForge("tui2")).ok).toBe(true); | |
| 157 | const alice = getUserByName(app.db, "alice")!; | |
| 158 | const mk = (u: typeof alice) => new Session(app, { sshUsername: "t", remoteAddress: "127.0.0.1", user: u }); | |
| 159 | const pushed: Screen[] = []; | |
| 160 | let invalidated = 0; | |
| 161 | let wake: () => void = () => {}; | |
| 162 | const ctx: Ctx = { ...quietCtx(), push: (s: Screen) => void pushed.push(s), invalidate: () => { invalidated++; wake(); } }; | |
| 163 | const key = (s: Screen, k: string) => s.key?.({ type: "key", key: k, ctrl: false, alt: false, shift: false }); | |
| 164 | const abort = new AbortController(); | |
| 165 | const screen = pinnedScreen(mk(alice), ctx); | |
| 166 | await screen.load!(abort.signal); | |
| 167 | // The cursor starts on the first forge in the list; find it by claiming whichever it is. | |
| 168 | const listed = pinnedForges(app, alice); | |
| 169 | const first = listed.ok ? listed.value.find((p) => p.claimedAt === "")! : undefined; | |
| 170 | expect(first).toBeDefined(); | |
| 171 | // Move the cursor onto it. | |
| 172 | for (let i = 0; i < 10; i++) { | |
| 173 | const row = listed.ok ? listed.value[i] : undefined; | |
| 174 | if (row?.name === first!.name) break; | |
| 175 | key(screen, "j"); | |
| 176 | } | |
| 177 | expect(key(screen, "h")).toBe(true); | |
| 178 | expect(pushed.length).toBe(1); | |
| 179 | expect(getPinned(app.db, first!.name)!.claimedAt).toBe(""); | |
| 180 | const dialog = pushed[0]!; | |
| 181 | // Escape dismisses: nothing claimed. | |
| 182 | key(dialog, "esc"); | |
| 183 | expect(getPinned(app.db, first!.name)!.claimedAt).toBe(""); | |
| 184 | // Enter on the first action hands it over. | |
| 185 | expect(key(screen, "h")).toBe(true); | |
| 186 | key(pushed[1]!, "enter"); | |
| 187 | expect(getPinned(app.db, first!.name)!.claimedAt).not.toBe(""); | |
| 674 | describe("claimed is what the deployed forge says, never what the seller says (#16220)", () => { | |
| 675 | test("a check that hears 'claimed' records it once; a reissue that hears it records it and is refused; nothing else can", async () => { | |
| 676 | const app = await fresh(); | |
| 677 | const made = await createUser(app.db, { | |
| 678 | origin: "seed", | |
| 679 | trusted: true, | |
| 680 | username: "alice", | |
| 681 | email: "[email protected]", | |
| 682 | password: "a-good-passphrase", | |
| 683 | adminIfFirst: true, | |
| 684 | }); | |
| 685 | if (!made.ok) throw new Error(made.error); | |
| 686 | const alice = made.value; | |
| 687 | const kept = { fetch: net.fetch, probe: net.probe, resolve: net.resolve }; | |
| 688 | const cloud = cloudNet.fetch; | |
| 689 | let says = "waiting"; | |
| 690 | let machines = 0; | |
| 691 | cloudNet.fetch = async () => | |
| 692 | new Response( | |
| 693 | JSON.stringify({ account: { email: "a@b.c", status: "active" } }), | |
| 694 | { status: 200 }, | |
| 695 | ); | |
| 696 | net.fetch = async (url, init) => { | |
| 697 | const path = new URL(url).pathname; | |
| 698 | const method = init?.method ?? "GET"; | |
| 699 | if (path === "/v2/volumes") | |
| 700 | return new Response(JSON.stringify({ volume: { id: "vol-1" } }), { | |
| 701 | status: 201, | |
| 702 | }); | |
| 703 | if (path === "/v2/account/keys") | |
| 704 | return new Response(JSON.stringify({ ssh_key: { id: 4242 } }), { | |
| 705 | status: 201, | |
| 706 | }); | |
| 707 | if (method === "DELETE") return new Response(null, { status: 204 }); | |
| 708 | if (method === "POST") machines++; | |
| 709 | return new Response( | |
| 710 | JSON.stringify({ | |
| 711 | droplet: { | |
| 712 | id: 100 + machines, | |
| 713 | networks: { v4: [{ type: "public", ip_address: "203.0.113.7" }] }, | |
| 714 | }, | |
| 715 | }), | |
| 716 | { status: 202 }, | |
| 717 | ); | |
| 718 | }; | |
| 719 | net.resolve = async () => ["203.0.113.7"]; | |
| 720 | net.probe = async (url) => | |
| 721 | new URL(url).pathname === "/api/v1/first-admin/claim" | |
| 722 | ? new Response(JSON.stringify({ state: says }), { status: 200 }) | |
| 723 | : new Response("ok", { status: 200 }); | |
| 724 | try { | |
| 725 | await addAccount(app, alice, "digitalocean", "main", "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5"); | |
| 726 | allowWrite(app, alice, "digitalocean", "main", true); | |
| 727 | // Five forges are deployed here; the default ceiling has room for three. | |
| 728 | setCeiling(app, alice, "digitalocean", "main", 500); | |
| 729 | const deploy = (name: string) => | |
| 730 | deployPinned(app, alice, { | |
| 731 | name, | |
| 732 | host: `${name}.forge.test`, | |
| 733 | target: "digitalocean", | |
| 734 | account: "main", | |
| 735 | app: "alice/shop", | |
| 736 | source: SOURCE, | |
| 737 | version: V1, | |
| 738 | }); | |
| 739 | const events = () => | |
| 740 | ( | |
| 741 | app.db | |
| 742 | .query("SELECT payload FROM event WHERE kind = 'pinned.claimed' ORDER BY seq") | |
| 743 | .all() as { payload: string }[] | |
| 744 | ).map((e) => JSON.parse(e.payload) as { name: string }); | |
| 188 | 745 | |
| 189 | // A claim at another door reaches the live view. | |
| 190 | const other = pinnedForges(app, alice); | |
| 191 | const next = other.ok ? other.value.find((p) => p.claimedAt === "")! : undefined; | |
| 192 | const n = invalidated; | |
| 193 | const woke = new Promise<void>((r) => (wake = r)); | |
| 194 | claimPinned(app, alice, next!.name); | |
| 195 | await woke; | |
| 196 | expect(invalidated).toBeGreaterThan(n); | |
| 746 | // While the forge says waiting, expired or nothing, the seller still holds it. | |
| 747 | expect((await deploy("one")).ok).toBe(true); | |
| 748 | for (const not of ["waiting", "expired", "handed over"]) { | |
| 749 | says = not; | |
| 750 | expect(await checkPinned(app, alice, "one")).toMatchObject({ ok: true, value: { claimedAt: "" } }); | |
| 751 | } | |
| 752 | says = "waiting"; | |
| 753 | expect((await updatePinned(app, alice, "one", { version: V2 })).ok).toBe(true); | |
| 754 | expect(events()).toEqual([]); | |
| 755 | // The pages, drawn from the rows every door reads (#16220's assertions, kept). | |
| 756 | const page = (): string => { | |
| 757 | const rows = pinnedForges(app, alice); | |
| 758 | return rows.ok ? String(pinnedListPage(rows.value, { names: new Map(), checks: new Map() })) : ""; | |
| 759 | }; | |
| 760 | const offered = (name: string): string[] => | |
| 761 | ["update", "rollback", "claim", "check"].filter((act) => page().includes(`value="/pinned/${name}/${act}"`)); | |
| 762 | // Nothing is claimed yet: every control is offered, and the list does not say the sentence. | |
| 763 | expect(offered("one")).toEqual(["update", "rollback", "claim", "check"]); | |
| 764 | expect(page()).not.toContain("snapshot its disk"); | |
| 197 | 765 | |
| 198 | // A member does nothing. | |
| 199 | expect(key(pinnedScreen(mk(getUserByName(app.db, "bob")!), ctx), "h")).toBeFalsy(); | |
| 200 | abort.abort(); | |
| 766 | // The forge says claimed: recorded with the check, once. | |
| 767 | says = "claimed"; | |
| 768 | const seen = await checkPinned(app, alice, "one"); | |
| 769 | expect(seen.ok && seen.value.claimedAt).not.toBe(""); | |
| 770 | await checkPinned(app, alice, "one"); | |
| 771 | expect(events()).toEqual([{ name: "one" }]); | |
| 772 | const n = machines; | |
| 773 | for (const refused of [ | |
| 774 | await updatePinned(app, alice, "one", { version: V1 }), | |
| 775 | await rollbackPinned(app, alice, "one"), | |
| 776 | await claimPinned(app, alice, "one"), | |
| 777 | ]) | |
| 778 | expect(refused).toMatchObject({ ok: false, error: CLAIMED_REFUSAL }); | |
| 779 | expect(machines).toBe(n); | |
| 780 | expect(getPinned(app.db, "one")!.version).toBe(V2); | |
| 781 | const listed = pinnedForges(app, alice); | |
| 782 | expect(listed.ok && listed.value.find((p) => p.name === "one")!.claimedAt).not.toBe(""); | |
| 783 | ||
| 784 | // A reissue that hears it: recorded then, refused, and no machine is replaced. | |
| 785 | says = "waiting"; | |
| 786 | expect((await deploy("two")).ok).toBe(true); | |
| 787 | says = "claimed"; | |
| 788 | const before = machines; | |
| 789 | expect(await claimPinned(app, alice, "two")).toMatchObject({ ok: false, error: CLAIMED_REFUSAL }); | |
| 790 | expect(machines).toBe(before); | |
| 791 | expect(getPinned(app.db, "two")!.claimedAt).not.toBe(""); | |
| 792 | expect(events()).toEqual([{ name: "one" }, { name: "two" }]); | |
| 793 | ||
| 794 | // A forge that cannot be asked is never taken as claimed. | |
| 795 | says = "waiting"; | |
| 796 | expect((await deploy("three")).ok).toBe(true); | |
| 797 | says = "claimed"; | |
| 798 | net.resolve = async () => []; | |
| 799 | expect(await checkPinned(app, alice, "three")).toMatchObject({ ok: true, value: { waiting: "dns", claimedAt: "" } }); | |
| 800 | expect((await updatePinned(app, alice, "three", { version: V2 })).ok).toBe(true); | |
| 801 | ||
| 802 | // Every change asks the forge first. One whose machine has never answered (still booting, | |
| 803 | // its DNS not pointed, a first boot that failed) is replaced in silence, or it could never | |
| 804 | // be recovered. | |
| 805 | const dns = (works: boolean): void => void (net.resolve = async () => (works ? ["203.0.113.7"] : [])); | |
| 806 | dns(true); | |
| 807 | says = "waiting"; | |
| 808 | expect((await deploy("four")).ok).toBe(true); | |
| 809 | dns(false); | |
| 810 | expect((await updatePinned(app, alice, "four", { version: V2 })).ok).toBe(true); | |
| 811 | // It answers once from this machine, and the row keeps that. | |
| 812 | dns(true); | |
| 813 | expect(await checkPinned(app, alice, "four")).toMatchObject({ ok: true, value: { claim: "waiting" } }); | |
| 814 | expect(getPinned(app.db, "four")!.reached).toBe(getPinned(app.db, "four")!.remote); | |
| 815 | // Then it goes silent (a broken DNS record, or an answer that is no answer): nothing replaces | |
| 816 | // its machine on a guess that nobody claimed it. | |
| 817 | const stands = machines; | |
| 818 | for (const silent of [() => dns(false), () => void (says = "handed over")]) { | |
| 819 | dns(true); | |
| 820 | says = "waiting"; | |
| 821 | silent(); | |
| 822 | for (const refused of [ | |
| 823 | await updatePinned(app, alice, "four", { version: V1 }), | |
| 824 | await rollbackPinned(app, alice, "four"), | |
| 825 | await claimPinned(app, alice, "four"), | |
| 826 | ]) { | |
| 827 | expect(refused.ok ? "" : refused.error).toContain("cannot confirm that nobody has claimed it; nothing was changed"); | |
| 828 | expect(refused.ok ? "" : refused.error).toContain("four.forge.test must resolve to 203.0.113.7"); | |
| 829 | } | |
| 830 | } | |
| 831 | expect(machines).toBe(stands); | |
| 832 | expect(getPinned(app.db, "four")).toMatchObject({ state: "running", version: V2, claimedAt: "" }); | |
| 833 | // Reachable and unclaimed, the change goes through; its new machine has not answered yet, so | |
| 834 | // silence does not hold that one. | |
| 835 | dns(true); | |
| 836 | says = "waiting"; | |
| 837 | expect((await updatePinned(app, alice, "four", { version: V1 })).ok).toBe(true); | |
| 838 | expect(getPinned(app.db, "four")!.reached).not.toBe(getPinned(app.db, "four")!.remote); | |
| 839 | dns(false); | |
| 840 | expect((await rollbackPinned(app, alice, "four")).ok).toBe(true); | |
| 841 | // Claimed with no Check in between: the Update itself hears it, records it and is refused. | |
| 842 | dns(true); | |
| 843 | says = "waiting"; | |
| 844 | expect((await deploy("five")).ok).toBe(true); | |
| 845 | says = "claimed"; | |
| 846 | const kept = machines; | |
| 847 | expect(await updatePinned(app, alice, "five", { version: V2 })).toMatchObject({ ok: false, error: CLAIMED_REFUSAL }); | |
| 848 | expect(machines).toBe(kept); | |
| 849 | expect(getPinned(app.db, "five")).toMatchObject({ version: V1 }); | |
| 850 | expect(getPinned(app.db, "five")!.claimedAt).not.toBe(""); | |
| 851 | expect(events().at(-1)).toEqual({ name: "five" }); | |
| 852 | says = "claimed"; | |
| 853 | ||
| 854 | // A claimed forge is offered Check and nothing that would change it: no Update, no Roll | |
| 855 | // back, no new claim link. One the seller still holds keeps all four. | |
| 856 | expect(offered("one")).toEqual(["check"]); | |
| 857 | expect(offered("two")).toEqual(["check"]); | |
| 858 | expect(offered("three")).toEqual(["update", "rollback", "claim", "check"]); | |
| 859 | // And the list says, once, what the host can still do as owner of the machine; never "no | |
| 860 | // access". | |
| 861 | expect(HOST_CAN).toContain("own cloud account"); | |
| 862 | for (const words of ["open a forge", "boot it into rescue", "snapshot its disk", "read its boot data", "own cloud account"]) | |
| 863 | expect(page().split(words).length - 1).toBe(1); | |
| 864 | expect(page()).not.toContain("no access"); | |
| 865 | // The deploy page says it before anything is sold, once, and points at the buyer's own | |
| 866 | // account. | |
| 867 | const form = String(deployPage([], { name: "", account: "", app: "", source: "", version: "", host: "" })); | |
| 868 | for (const words of ["boot it into rescue", "snapshot its disk", "gives the host none of that"]) expect(form.split(words).length - 1).toBe(1); | |
| 869 | expect(form).not.toContain("no access"); | |
| 870 | } finally { | |
| 871 | Object.assign(net, kept); | |
| 872 | cloudNet.fetch = cloud; | |
| 873 | app.close(); | |
| 874 | } | |
| 875 | }); | |
| 876 | }); | |
| 877 | ||
| 878 | describe("the seed", () => { | |
| 879 | test("is a hash and a deadline: the code itself, a bare hash and anything else are refused, and nothing is written", async () => { | |
| 880 | const app = await fresh(); | |
| 881 | const { code, hash } = newFirstAdminCode(); | |
| 882 | const at = new Date(Date.now() + 60_000).toISOString(); | |
| 883 | for (const bad of [ | |
| 884 | code, | |
| 885 | hash, | |
| 886 | `${hash}@`, | |
| 887 | `${hash}@tomorrow`, | |
| 888 | `${hash.toUpperCase()}@${at}`, | |
| 889 | `${hash}@${at} x`, | |
| 890 | `${hash}@${at}\nFORGE_SIGNUP=open`, | |
| 891 | `${code}@${at}`, | |
| 892 | ]) | |
| 893 | expect(seedFirstAdmin(app.db, bad)).toBe("invalid"); | |
| 894 | expect(seedFirstAdmin(app.db, undefined)).toBe("none"); | |
| 895 | expect(seedFirstAdmin(app.db, " ")).toBe("none"); | |
| 896 | expect( | |
| 897 | app.db | |
| 898 | .query( | |
| 899 | "SELECT count(*) AS n FROM forge_setting WHERE key LIKE 'first_admin.%'", | |
| 900 | ) | |
| 901 | .get(), | |
| 902 | ).toEqual({ n: 0 }); | |
| 903 | expect(readSeed(firstAdminSeed(hash, at))).toEqual({ | |
| 904 | hash, | |
| 905 | expires: Date.parse(at), | |
| 906 | }); | |
| 907 | app.close(); | |
| 908 | }); | |
| 909 | ||
| 910 | test("stands until its deadline and never past the longest a seed may stand", async () => { | |
| 911 | const app = await fresh(); | |
| 912 | const now = Date.parse("2026-11-24T00:00:00.000Z"); | |
| 913 | const { code, hash } = newFirstAdminCode(); | |
| 914 | const at = new Date(now + 60 * 60_000).toISOString(); | |
| 915 | expect(seedFirstAdmin(app.db, firstAdminSeed(hash, at), now)).toBe( | |
| 916 | "seeded", | |
| 917 | ); | |
| 918 | // Longer than a terminal's code, which is the point: a buyer may not open the link today. | |
| 919 | expect(readFirstAdmin(app.db, code, now + FIRST_ADMIN_TTL_MS + 1)).toBe( | |
| 920 | "ok", | |
| 921 | ); | |
| 922 | expect(readFirstAdmin(app.db, code, Date.parse(at) - 1)).toBe("ok"); | |
| 923 | expect(readFirstAdmin(app.db, code, Date.parse(at))).toBe("refused"); | |
| 924 | expect(burnFirstAdmin(app.db, code, Date.parse(at) + 1)).toBe("refused"); | |
| 925 | expect(seedState(app.db, hash, Date.parse(at) + 1)).toBe("expired"); | |
| 926 | expect(seedState(app.db, hash, now)).toBe("waiting"); | |
| 927 | ||
| 928 | // A deadline a year out is cut to the constant. | |
| 929 | const far = newFirstAdminCode(); | |
| 930 | expect( | |
| 931 | seedFirstAdmin( | |
| 932 | app.db, | |
| 933 | firstAdminSeed( | |
| 934 | far.hash, | |
| 935 | new Date(now + 365 * 86_400_000).toISOString(), | |
| 936 | ), | |
| 937 | now, | |
| 938 | ), | |
| 939 | ).toBe("seeded"); | |
| 940 | expect( | |
| 941 | readFirstAdmin(app.db, far.code, now + FIRST_ADMIN_SEED_TTL_MS - 1), | |
| 942 | ).toBe("ok"); | |
| 943 | expect( | |
| 944 | readFirstAdmin(app.db, far.code, now + FIRST_ADMIN_SEED_TTL_MS), | |
| 945 | ).toBe("refused"); | |
| 946 | // The seed before it is gone. | |
| 947 | expect(readFirstAdmin(app.db, code, now)).toBe("refused"); | |
| 948 | // One already out of time is taken and never works. | |
| 949 | const late = newFirstAdminCode(); | |
| 950 | expect( | |
| 951 | seedFirstAdmin( | |
| 952 | app.db, | |
| 953 | firstAdminSeed(late.hash, new Date(now - 1).toISOString()), | |
| 954 | now, | |
| 955 | ), | |
| 956 | ).toBe("seeded"); | |
| 957 | expect(readFirstAdmin(app.db, late.code, now)).toBe("refused"); | |
| 958 | app.close(); | |
| 959 | }); | |
| 960 | ||
| 961 | test("is taken once: a restart leaves a code the operator minted since, and a forge with an admin takes none", async () => { | |
| 962 | const app = await fresh(); | |
| 963 | const { code, hash } = newFirstAdminCode(); | |
| 964 | const seed = firstAdminSeed( | |
| 965 | hash, | |
| 966 | new Date(Date.now() + 60_000).toISOString(), | |
| 967 | ); | |
| 968 | expect(seedFirstAdmin(app.db, seed)).toBe("seeded"); | |
| 969 | const minted = mintFirstAdmin(app.db)!; | |
| 970 | expect(readFirstAdmin(app.db, code)).toBe("refused"); | |
| 971 | expect(seedFirstAdmin(app.db, seed)).toBe("kept"); | |
| 972 | expect(readFirstAdmin(app.db, minted.code)).toBe("ok"); | |
| 973 | expect(readFirstAdmin(app.db, code)).toBe("refused"); | |
| 974 | expect(seedState(app.db, hash)).toBe("expired"); | |
| 975 | ||
| 976 | const made = await createUser(app.db, { | |
| 977 | origin: "seed", | |
| 978 | trusted: true, | |
| 979 | username: "olive", | |
| 980 | email: "[email protected]", | |
| 981 | isAdmin: true, | |
| 982 | }); | |
| 983 | if (!made.ok) throw new Error(made.error); | |
| 984 | const later = newFirstAdminCode(); | |
| 985 | expect( | |
| 986 | seedFirstAdmin( | |
| 987 | app.db, | |
| 988 | firstAdminSeed(later.hash, new Date(Date.now() + 60_000).toISOString()), | |
| 989 | ), | |
| 990 | ).toBe("owned"); | |
| 991 | expect(readFirstAdmin(app.db, later.code)).toBe("refused"); | |
| 992 | expect(seedState(app.db, later.hash)).toBe("claimed"); | |
| 993 | app.close(); | |
| 994 | }); | |
| 995 | }); | |
| 996 | ||
| 997 | describe("the name and the boot config", () => { | |
| 998 | const booted = (over: Record<string, unknown> = {}) => ({ | |
| 999 | name: "acme", | |
| 1000 | source: SOURCE, | |
| 1001 | version: V1, | |
| 1002 | config: {}, | |
| 1003 | host: HOST, | |
| 1004 | claimHash: "c".repeat(64), | |
| 1005 | claimExpires: "2026-12-01T00:00:00.000Z", | |
| 1006 | ...over, | |
| 1007 | }); | |
| 1008 | ||
| 1009 | test("a hostname is a full lowercase DNS name and nothing a shell, YAML or the proxy could read as more", () => { | |
| 1010 | for (const good of [ | |
| 1011 | "forge.example.com", | |
| 1012 | "a.io", | |
| 1013 | "x-1.eu-west.example.org", | |
| 1014 | `${"a".repeat(63)}.example.com`, | |
| 1015 | ]) | |
| 1016 | expect(validHost(good)).toBe(true); | |
| 1017 | const bad = [ | |
| 1018 | "", | |
| 1019 | "localhost", | |
| 1020 | "example", | |
| 1021 | "1.2.3.4", | |
| 1022 | "203.0.113.7", | |
| 1023 | "[::1]", | |
| 1024 | "a.b", | |
| 1025 | "Example.com", | |
| 1026 | "example.COM", | |
| 1027 | "example.com.", | |
| 1028 | ".example.com", | |
| 1029 | "a..example.com", | |
| 1030 | "*.example.com", | |
| 1031 | "-a.example.com", | |
| 1032 | "a-.example.com", | |
| 1033 | "exa_mple.com", | |
| 1034 | "example.c0m", | |
| 1035 | "example.123", | |
| 1036 | "example.com:443", | |
| 1037 | "example.com/path", | |
| 1038 | "https://example.com", | |
| 1039 | "[email protected]", | |
| 1040 | "ex ample.com", | |
| 1041 | " example.com", | |
| 1042 | "example.com ", | |
| 1043 | "example.com\n", | |
| 1044 | "example.com\nFORGE_SIGNUP=open", | |
| 1045 | "example.com;reboot", | |
| 1046 | "$(id).example.com", | |
| 1047 | "`id`.example.com", | |
| 1048 | "example.com{", | |
| 1049 | "a.com, b.com", | |
| 1050 | "example.com#x", | |
| 1051 | '"example.com"', | |
| 1052 | "exämple.com", | |
| 1053 | `${"a".repeat(64)}.example.com`, | |
| 1054 | `${"a.".repeat(126)}com`, | |
| 1055 | ]; | |
| 1056 | for (const b of bad) expect([b, validHost(b)]).toEqual([b, false]); | |
| 1057 | }); | |
| 1058 | ||
| 1059 | test("a deploy with no hostname, or a bad one, is refused before anything is recorded or asked of the cloud", async () => { | |
| 1060 | const app = await fresh(); | |
| 1061 | const made = await createUser(app.db, { | |
| 1062 | origin: "seed", | |
| 1063 | trusted: true, | |
| 1064 | username: "alice", | |
| 1065 | email: "[email protected]", | |
| 1066 | password: "a-good-passphrase", | |
| 1067 | adminIfFirst: true, | |
| 1068 | }); | |
| 1069 | if (!made.ok) throw new Error(made.error); | |
| 1070 | const asked: string[] = []; | |
| 1071 | const before = net.fetch; | |
| 1072 | net.fetch = async (url) => { | |
| 1073 | asked.push(url); | |
| 1074 | return new Response("{}", { status: 500 }); | |
| 1075 | }; | |
| 1076 | try { | |
| 1077 | for (const host of [ | |
| 1078 | "", | |
| 1079 | "203.0.113.7", | |
| 1080 | "example.com:8443", | |
| 1081 | "example.com\nX=1", | |
| 1082 | ]) { | |
| 1083 | const r = await deployPinned(app, made.value, { | |
| 1084 | name: "acme", | |
| 1085 | host, | |
| 1086 | target: "digitalocean", | |
| 1087 | account: "main", | |
| 1088 | app: "alice/shop", | |
| 1089 | source: SOURCE, | |
| 1090 | version: V1, | |
| 1091 | }); | |
| 1092 | expect(r).toMatchObject({ ok: false }); | |
| 1093 | expect(r.ok ? "" : r.error).toContain("A hostname is a full DNS name"); | |
| 1094 | } | |
| 1095 | expect(asked).toEqual([]); | |
| 1096 | expect(getPinned(app.db, "acme")).toBeUndefined(); | |
| 1097 | } finally { | |
| 1098 | net.fetch = before; | |
| 1099 | app.close(); | |
| 1100 | } | |
| 1101 | }); | |
| 1102 | ||
| 1103 | test("the forge listens on loopback behind a proxy that serves its one name; config cannot say otherwise", () => { | |
| 1104 | const MOUNT = "/mnt/forge_acme_data"; | |
| 1105 | expect(proxyConfig(booted({ config: { PORT: "8080" } }), MOUNT)).toBe( | |
| 1106 | `{\n\tstorage file_system ${MOUNT}/caddy\n}\n${HOST} {\n\treverse_proxy 127.0.0.1:8080\n}\n`, | |
| 1107 | ); | |
| 1108 | expect(proxyConfig(booted(), MOUNT)).toContain( | |
| 1109 | "reverse_proxy 127.0.0.1:3000", | |
| 1110 | ); | |
| 1111 | expect(() => proxyConfig(booted(), "/mnt/x\n}\nevil.test {")).toThrow(); | |
| 1112 | const script = bootConfig( | |
| 1113 | booted({ | |
| 1114 | config: { | |
| 1115 | FORGE_URL: "http://elsewhere.test", | |
| 1116 | FORGE_BIND: "0.0.0.0", | |
| 1117 | FORGE_FIRST_ADMIN_SEED: "x", | |
| 1118 | FORGE_TRUSTED_PROXIES: "0.0.0.0/0", | |
| 1119 | PUBLIC_NAME: "Acme", | |
| 1120 | }, | |
| 1121 | }), | |
| 1122 | ); | |
| 1123 | const env = envOf(script); | |
| 1124 | expect(env).toMatchObject({ | |
| 1125 | FORGE_URL: `https://${HOST}`, | |
| 1126 | FORGE_HOST: HOST, | |
| 1127 | FORGE_BIND: "127.0.0.1", | |
| 1128 | FORGE_TRUSTED_PROXIES: "127.0.0.1/32", | |
| 1129 | FORGE_SSH_PORT: "0", | |
| 1130 | FORGE_CREW_SANDBOX: "require", | |
| 1131 | FORGE_FIRST_ADMIN_SEED: `${"c".repeat(64)}@2026-12-01T00:00:00.000Z`, | |
| 1132 | PUBLIC_NAME: "Acme", | |
| 1133 | }); | |
| 1134 | // What the boot sets comes after the config, the data directory last of all. | |
| 1135 | expect(Object.keys(env).at(-1)).toBe("FORGE_APP_DATA"); | |
| 1136 | expect(Object.keys(env).indexOf("PUBLIC_NAME")).toBeLessThan( | |
| 1137 | Object.keys(env).indexOf("FORGE_URL"), | |
| 1138 | ); | |
| 1139 | // And none of it is a setting a deploy may name: every name the boot sets is refused. | |
| 1140 | for (const name of [...Object.keys(servedEnv(booted())), "FORGE_APP_DATA"]) { | |
| 1141 | expect(BOOT_NAMES).toContain(name); | |
| 1142 | const r = checkConfig({ [name]: "x" }); | |
| 1143 | expect(r.ok ? "" : r.error).toContain("is set by the deploy itself"); | |
| 1144 | } | |
| 1145 | for (const once of [ | |
| 1146 | "FORGE_URL=", | |
| 1147 | "FORGE_BIND=", | |
| 1148 | "FORGE_FIRST_ADMIN_SEED=", | |
| 1149 | "FORGE_TRUSTED_PROXIES=", | |
| 1150 | ]) | |
| 1151 | expect(script.split(once).length - 1).toBe(1); | |
| 1152 | expect(script).not.toContain("elsewhere.test"); | |
| 1153 | expect(script).not.toContain("0.0.0.0"); | |
| 1154 | // The proxy comes from the distribution's own packages and is handed the one-site config. | |
| 1155 | expect(script).toMatch(/^packages:\n(?: - \S+\n)* - caddy\n/m); | |
| 1156 | // Each top-level key is there once: one package list, one set of files, one run list. | |
| 1157 | for (const key of ["packages:", "write_files:", "runcmd:"]) | |
| 1158 | expect(script.split(`\n${key}\n`).length - 1).toBe(1); | |
| 1159 | // The one-site config is written where the package reads it, and keeps its certificates on | |
| 1160 | // the volume. | |
| 1161 | expect(script).toContain( | |
| 1162 | ` - path: /etc/caddy/Caddyfile\n content: ${JSON.stringify(proxyConfig(booted(), MOUNT))}`, | |
| 1163 | ); | |
| 1164 | expect(script).toContain(`chown -R caddy:caddy ${MOUNT}/caddy`); | |
| 1165 | // No address and no plain-HTTP origin is written anywhere in it. | |
| 1166 | expect(script).not.toMatch(/http:\/\/(?!127\.0\.0\.1)/); | |
| 1167 | }); | |
| 1168 | ||
| 1169 | test("a row with no name, a bad name or a claim that is not a hash makes no boot config", () => { | |
| 1170 | for (const over of [ | |
| 1171 | { host: "" }, | |
| 1172 | { host: "example.com\n - path: /etc/x" }, | |
| 1173 | { claimHash: "not-a-hash" }, | |
| 1174 | { claimHash: newFirstAdminCode().code }, | |
| 1175 | { claimExpires: "soon" }, | |
| 1176 | { claimExpires: "" }, | |
| 1177 | ]) | |
| 1178 | expect(() => bootConfig(booted(over))).toThrow(); | |
| 1179 | // A forge with no claim issued is still served on its name, and takes no seed. | |
| 1180 | expect( | |
| 1181 | servedEnv(booted({ claimHash: "", claimExpires: "" }))[ | |
| 1182 | "FORGE_FIRST_ADMIN_SEED" | |
| 1183 | ], | |
| 1184 | ).toBeUndefined(); | |
| 1185 | }); | |
| 1186 | ||
| 1187 | test("a forge told to bind one address answers there", async () => { | |
| 1188 | const app = await fresh({ bind: "127.0.0.1" }); | |
| 1189 | const servers = await serve(app); | |
| 1190 | try { | |
| 1191 | expect(new URL(servers.url).hostname).toBe("127.0.0.1"); | |
| 1192 | expect((await fetch(`${servers.url}/healthz`)).status).toBe(200); | |
| 1193 | } finally { | |
| 1194 | await servers.stop(); | |
| 1195 | app.close(); | |
| 1196 | } | |
| 1197 | }); | |
| 201 | 1198 | }); |
test/pinned-forge-address.test.ts +60 −17
| @@ -1,7 +1,9 @@ | ||
| 1 | 1 | /** |
| 2 | * A pinned forge's droplet address is read back (#8745): shown as a URL, and a | |
| 3 | * health check lets a failed forge recover. Tried at every door: the action, | |
| 4 | * the HTTP route, the MCP verb and the terminal key. | |
| 2 | * A pinned forge's droplet address is read back (#8745) and is what its DNS | |
| 3 | * record points at; the forge itself is served on its name over HTTPS and | |
| 4 | * nowhere else (#16217). A health check says what it waits for, and lets a | |
| 5 | * failed forge recover. Tried at every door: the action, the HTTP route, the | |
| 6 | * MCP verb and the terminal key. | |
| 5 | 7 | */ |
| 6 | 8 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; |
| 7 | 9 | import { mkdtemp, rm } from "node:fs/promises"; |
| @@ -9,16 +11,17 @@ import { tmpdir } from "node:os"; | ||
| 9 | 11 | import { join } from "node:path"; |
| 10 | 12 | import { createApp, type App } from "../src/app.ts"; |
| 11 | 13 | import { addAccount, allowWrite, net as cloudNet } from "../src/actions/cloud.ts"; |
| 12 | import { checkPinned, deployPinned, net, pinnedForges } from "../src/actions/pinned.ts"; | |
| 14 | import { checkPinned, checkWords, deployPinned, net, pinnedForges } from "../src/actions/pinned.ts"; | |
| 13 | 15 | import { digitalocean } from "../src/cloud/droplet.ts"; |
| 14 | 16 | import { read } from "../src/cloud/machine.ts"; |
| 15 | import { getPinned, portOf, setRemote } from "../src/core/pinned.ts"; | |
| 17 | import { getPinned, portOf, setRemote, urlOf } from "../src/core/pinned.ts"; | |
| 16 | 18 | import { createToken } from "../src/core/tokens.ts"; |
| 17 | 19 | import { createUser, getUserByName } from "../src/core/users.ts"; |
| 18 | 20 | import { serve, type Servers } from "../src/http/server.ts"; |
| 19 | 21 | import { Session } from "../src/tui/session.ts"; |
| 20 | 22 | import { pinnedScreen } from "../src/tui/screens/pinned.ts"; |
| 21 | 23 | import { quietLogs } from "./helpers/globals.ts"; |
| 24 | import { seedPlaces } from "./helpers/places-fixture.ts"; | |
| 22 | 25 | |
| 23 | 26 | quietLogs(); |
| 24 | 27 | |
| @@ -31,14 +34,19 @@ describe("pinned forge address", () => { | ||
| 31 | 34 | let networks: unknown = { v4: [{ type: "private", ip_address: "10.0.0.2" }, { type: "public", ip_address: "203.0.113.7" }] }; |
| 32 | 35 | let probeStatus = 200; |
| 33 | 36 | let readStatus = 200; |
| 37 | // What DNS says the forge's name points at, and what the deployed forge says of its claim. | |
| 38 | let resolved = ["203.0.113.7"]; | |
| 39 | let claimSaid = "waiting"; | |
| 34 | 40 | const probed: string[] = []; |
| 41 | const URL_ = "https://acme.forge.test/"; | |
| 35 | 42 | const admin = () => getUserByName(app.db, "alice")!; |
| 36 | 43 | const deploy = (name: string) => |
| 37 | deployPinned(app, admin(), { name, target: "digitalocean", account: "main", app: "alice/shop", source: "https://forge.example.org/trevato/forge", version: "a".repeat(40), config: { PORT: "8080" } }); | |
| 44 | deployPinned(app, admin(), { name, host: `${name}.forge.test`, target: "digitalocean", account: "main", app: "alice/shop", source: "https://forge.example.org/trevato/forge", version: "a".repeat(40), config: { PORT: "8080" } }); | |
| 38 | 45 | |
| 39 | 46 | beforeAll(async () => { |
| 40 | 47 | dataDir = await mkdtemp(join(tmpdir(), "forge-pinned-addr-")); |
| 41 | 48 | app = createApp({ dataDir, port: 0 }); |
| 49 | await seedPlaces(app.db); | |
| 42 | 50 | servers = await serve(app); |
| 43 | 51 | for (const [username, adminIfFirst] of [["alice", true], ["bob", false]] as const) { |
| 44 | 52 | const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@f.test`, password: "a-good-passphrase", adminIfFirst }); |
| @@ -49,6 +57,7 @@ describe("pinned forge address", () => { | ||
| 49 | 57 | allowWrite(app, admin(), "digitalocean", "main", true); |
| 50 | 58 | net.fetch = async (url, init) => { |
| 51 | 59 | const path = new URL(url).pathname; |
| 60 | if (path === "/v2/account/keys" && init?.method === "POST") return new Response(JSON.stringify({ ssh_key: { id: 4242 } }), { status: 201 }); | |
| 52 | 61 | if (path === "/v2/volumes") return new Response(JSON.stringify({ volume: { id: "vol-1" } }), { status: 201 }); |
| 53 | 62 | if ((init?.method ?? "GET") === "GET") |
| 54 | 63 | return readStatus === 200 |
| @@ -56,7 +65,11 @@ describe("pinned forge address", () => { | ||
| 56 | 65 | : new Response("{}", { status: readStatus }); |
| 57 | 66 | return new Response(JSON.stringify({ droplet: { id: 77 } }), { status: 202 }); |
| 58 | 67 | }; |
| 59 | net.probe = async (url) => { probed.push(url); return new Response("ok", { status: probeStatus }); }; | |
| 68 | net.probe = async (url) => { | |
| 69 | probed.push(url); | |
| 70 | return new URL(url).pathname === "/api/v1/first-admin/claim" ? new Response(JSON.stringify({ state: claimSaid }), { status: 200 }) : new Response("ok", { status: probeStatus }); | |
| 71 | }; | |
| 72 | net.resolve = async () => resolved; | |
| 60 | 73 | }, 30_000); |
| 61 | 74 | |
| 62 | 75 | afterAll(async () => { |
| @@ -65,12 +78,40 @@ describe("pinned forge address", () => { | ||
| 65 | 78 | await rm(dataDir, { recursive: true, force: true }); |
| 66 | 79 | }); |
| 67 | 80 | |
| 68 | test("a deploy has no address yet; the check reads the public IPv4 back and the view carries the served URL", async () => { | |
| 81 | test("the URL is HTTPS on the forge's name, never an address or a port; the address read back is its DNS record", async () => { | |
| 82 | expect(urlOf({ host: "acme.forge.test" })).toBe(URL_); | |
| 83 | expect(urlOf({ host: "" })).toBe(""); | |
| 69 | 84 | const r = await deploy("acme"); |
| 70 | expect(r).toMatchObject({ ok: true, value: { address: "", url: "" } }); | |
| 71 | expect(await checkPinned(app, admin(), "acme")).toMatchObject({ ok: true, value: { address: "203.0.113.7", url: "http://203.0.113.7:8080/" } }); | |
| 85 | expect(r).toMatchObject({ ok: true, value: { address: "203.0.113.7", url: URL_, dns: "acme.forge.test A 203.0.113.7" } }); | |
| 86 | expect(await checkPinned(app, admin(), "acme")).toMatchObject({ ok: true, value: { address: "203.0.113.7", url: URL_, healthy: true, waiting: "", claim: "waiting" } }); | |
| 72 | 87 | const listed = pinnedForges(app, admin()); |
| 73 | expect(listed.ok && listed.value[0]!.url).toBe("http://203.0.113.7:8080/"); | |
| 88 | expect(listed.ok && listed.value[0]!.url).toBe(URL_); | |
| 89 | expect(probed.every((u) => u.startsWith(URL_))).toBe(true); | |
| 90 | }); | |
| 91 | ||
| 92 | test("until the name resolves to the machine the check says 'waiting for DNS', names the record, and sends nothing", async () => { | |
| 93 | const before = probed.length; | |
| 94 | for (const elsewhere of [[], ["198.51.100.1"]]) { | |
| 95 | resolved = elsewhere; | |
| 96 | const r = await checkPinned(app, admin(), "acme"); | |
| 97 | expect(r).toMatchObject({ ok: true, value: { healthy: false, waiting: "dns", claim: "unknown", dns: "acme.forge.test A 203.0.113.7" } }); | |
| 98 | expect(r.ok && checkWords(r.value)).toContain("waiting for DNS: create the record acme.forge.test A 203.0.113.7"); | |
| 99 | } | |
| 100 | expect(probed.length).toBe(before); | |
| 101 | resolved = ["198.51.100.1", "203.0.113.7"]; | |
| 102 | expect(await checkPinned(app, admin(), "acme")).toMatchObject({ ok: true, value: { healthy: true, waiting: "" } }); | |
| 103 | resolved = ["203.0.113.7"]; | |
| 104 | }); | |
| 105 | ||
| 106 | test("the check says what became of the claim, as the deployed forge reports it; nonsense is unknown", async () => { | |
| 107 | for (const [said, want] of [["claimed", "claimed"], ["expired", "expired"], ["owned", "unknown"], ["waiting", "waiting"]] as const) { | |
| 108 | claimSaid = said; | |
| 109 | expect(await checkPinned(app, admin(), "acme")).toMatchObject({ ok: true, value: { healthy: true, claim: want } }); | |
| 110 | } | |
| 111 | // The question carries the hash the machine was booted with, never the link. | |
| 112 | const asked = new URL(probed.at(-1)!); | |
| 113 | expect(asked.pathname).toBe("/api/v1/first-admin/claim"); | |
| 114 | expect(asked.searchParams.get("seed")).toBe(getPinned(app.db, "acme")!.claimHash); | |
| 74 | 115 | }); |
| 75 | 116 | |
| 76 | 117 | test("only a well-formed public IPv4 is taken", async () => { |
| @@ -97,7 +138,7 @@ describe("pinned forge address", () => { | ||
| 97 | 138 | expect(await checkPinned(app, admin(), "acme")).toMatchObject({ ok: true, value: { healthy: false, state: "failed" } }); |
| 98 | 139 | probeStatus = 200; |
| 99 | 140 | expect(await checkPinned(app, admin(), "acme")).toMatchObject({ ok: true, value: { healthy: true, state: "running" } }); |
| 100 | expect(probed.at(-1)).toBe("http://203.0.113.7:8080/"); | |
| 141 | expect(probed).toContain(URL_); | |
| 101 | 142 | off(); |
| 102 | 143 | expect(seen).toEqual([ |
| 103 | 144 | { name: "acme", address: "203.0.113.7", state: "failed", healthy: false }, |
| @@ -110,7 +151,9 @@ describe("pinned forge address", () => { | ||
| 110 | 151 | test("the probe is audited like the other calls made for the account", () => { |
| 111 | 152 | const rows = app.db.query("SELECT target FROM cloud_audit WHERE purpose = 'pinned:probe'").all() as { target: string }[]; |
| 112 | 153 | expect(rows.length).toBeGreaterThan(0); |
| 113 | expect(rows[0]!.target).toBe("203.0.113.7:8080/"); | |
| 154 | expect(rows[0]!.target).toBe("acme.forge.test/"); | |
| 155 | // The claim question is audited by its path alone: the hash is no part of a row. | |
| 156 | expect(JSON.stringify(rows)).not.toContain(getPinned(app.db, "acme")!.claimHash); | |
| 114 | 157 | }); |
| 115 | 158 | |
| 116 | 159 | test("a refused read is returned, not turned into 'no address'; a read-only account may still check", async () => { |
| @@ -142,7 +185,7 @@ describe("pinned forge address", () => { | ||
| 142 | 185 | fetch(`${servers.url}/api/v1/admin/pinned/${name}/check`, { method: "POST", headers: t ? h(t) : { "content-type": "application/json" }, body: "{}" }); |
| 143 | 186 | const ok = await post("acme", tok); |
| 144 | 187 | expect(ok.status).toBe(200); |
| 145 | expect(await ok.json()).toMatchObject({ healthy: true, url: "http://203.0.113.7:8080/" }); | |
| 188 | expect(await ok.json()).toMatchObject({ healthy: true, url: URL_, waiting: "", claim: "waiting" }); | |
| 146 | 189 | expect((await post("acme", bob)).status).toBe(403); |
| 147 | 190 | expect((await post("acme")).status).toBeGreaterThanOrEqual(401); |
| 148 | 191 | expect((await post("nope", tok)).status).toBe(404); |
| @@ -161,7 +204,7 @@ describe("pinned forge address", () => { | ||
| 161 | 204 | }; |
| 162 | 205 | const tok = createToken(app.db, admin().id, "admin", "admin").token; |
| 163 | 206 | const done = await call(tok, { verb: "check", name: "acme" }); |
| 164 | expect(done.says).toBe("check acme: now " + "a".repeat(40) + ", running at http://203.0.113.7:8080/."); | |
| 207 | expect(done.says).toBe(`check acme: now ${"a".repeat(40)}. acme answers at ${URL_}; it is running. Its claim link has not been used; it works until ${getPinned(app.db, "acme")!.claimExpires}.`); | |
| 165 | 208 | expect(done.forge).toMatchObject({ healthy: true }); |
| 166 | 209 | const ro = createToken(app.db, admin().id, "ro", "ro").token; |
| 167 | 210 | expect((await call(ro, { verb: "check", name: "acme" })).text ?? "").not.toContain("running at"); |
| @@ -182,10 +225,10 @@ describe("pinned forge address", () => { | ||
| 182 | 225 | const n = invalidated; |
| 183 | 226 | expect(key(screen, "c")).toBe(true); |
| 184 | 227 | await new Promise((r) => setTimeout(r, 150)); |
| 185 | expect(probed.length).toBe(before + 1); | |
| 228 | expect(probed.length).toBeGreaterThan(before); | |
| 186 | 229 | expect(invalidated).toBeGreaterThan(n); |
| 187 | 230 | const list = pinnedForges(app, admin()); |
| 188 | expect(list.ok && list.value[0]!.url).toBe("http://203.0.113.7:8080/"); | |
| 231 | expect(list.ok && list.value[0]!.url).toBe(URL_); | |
| 189 | 232 | abort.abort(); |
| 190 | 233 | }); |
| 191 | 234 | }); |
test/pinned-forge-recovery.test.ts +8 −5
| @@ -16,6 +16,7 @@ import { createUser, getUserByName } from "../src/core/users.ts"; | ||
| 16 | 16 | import { Session } from "../src/tui/session.ts"; |
| 17 | 17 | import { entry, pinnedScreen } from "../src/tui/screens/pinned.ts"; |
| 18 | 18 | import { quietLogs } from "./helpers/globals.ts"; |
| 19 | import { seedPlaces } from "./helpers/places-fixture.ts"; | |
| 19 | 20 | |
| 20 | 21 | quietLogs(); |
| 21 | 22 | |
| @@ -32,13 +33,14 @@ describe("pinned forge recovery", () => { | ||
| 32 | 33 | let deleted = new Set<string>(); |
| 33 | 34 | |
| 34 | 35 | const admin = () => getUserByName(app.db, "alice")!; |
| 35 | const input = (over: Record<string, unknown> = {}) => ({ | |
| 36 | name: "acme", target: "digitalocean", account: "main", app: "alice/shop", source: SOURCE, version: V1, config: {}, ...over, | |
| 36 | const input = (over: { name?: string } = {}) => ({ | |
| 37 | name: "acme", host: `${over.name ?? "acme"}.forge.test`, target: "digitalocean", account: "main", app: "alice/shop", source: SOURCE, version: V1, config: {}, ...over, | |
| 37 | 38 | }); |
| 38 | 39 | |
| 39 | 40 | beforeAll(async () => { |
| 40 | 41 | dataDir = await mkdtemp(join(tmpdir(), "forge-pinned-rec-")); |
| 41 | 42 | app = createApp({ dataDir, port: 0 }); |
| 43 | await seedPlaces(app.db); | |
| 42 | 44 | for (const [username, adminIfFirst] of [["alice", true], ["bob", false]] as const) { |
| 43 | 45 | const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@f.test`, password: "a-good-passphrase", adminIfFirst }); |
| 44 | 46 | if (!made.ok) throw new Error(made.error); |
| @@ -54,6 +56,7 @@ describe("pinned forge recovery", () => { | ||
| 54 | 56 | const key = `${method} ${path.replace(/\/\d+$/, "")}`; |
| 55 | 57 | const status = fail.get(key); |
| 56 | 58 | if (status !== undefined) { fail.delete(key); return new Response("{}", { status }); } |
| 59 | if (path === "/v2/account/keys" && method === "POST") return new Response(JSON.stringify({ ssh_key: { id: 4242 } }), { status: 201 }); | |
| 57 | 60 | if (path === "/v2/volumes") return new Response(JSON.stringify({ volume: { id: "vol-9" } }), { status: 201 }); |
| 58 | 61 | if (method === "DELETE") { |
| 59 | 62 | if (deleted.has(path)) return new Response("{}", { status: 404 }); |
| @@ -78,7 +81,7 @@ describe("pinned forge recovery", () => { | ||
| 78 | 81 | calls.length = 0; |
| 79 | 82 | const again = await deployPinned(app, admin(), input()); |
| 80 | 83 | expect(again.ok).toBe(true); |
| 81 | expect(calls).toEqual(["POST /v2/droplets"]); | |
| 84 | expect(calls).toEqual(["POST /v2/account/keys", "POST /v2/droplets", "DELETE /v2/account/keys/4242", "GET /v2/droplets/2002"]); | |
| 82 | 85 | expect(getPinned(app.db, "acme")).toMatchObject({ state: "running", volume: "vol-9" }); |
| 83 | 86 | // A running forge still owns its name. |
| 84 | 87 | expect(await deployPinned(app, admin(), input())).toMatchObject({ ok: false, error: "A pinned forge has that name already." }); |
| @@ -92,7 +95,7 @@ describe("pinned forge recovery", () => { | ||
| 92 | 95 | // The old droplet is not deleted a second time. |
| 93 | 96 | const back = await rollbackPinned(app, admin(), "acme"); |
| 94 | 97 | expect(back.ok).toBe(true); |
| 95 | expect(calls).toEqual(["POST /v2/droplets"]); | |
| 98 | expect(calls).toEqual(["POST /v2/account/keys", "POST /v2/droplets", "DELETE /v2/account/keys/4242"]); | |
| 96 | 99 | expect(getPinned(app.db, "acme")).toMatchObject({ state: "running", version: V1 }); |
| 97 | 100 | }); |
| 98 | 101 | |
| @@ -110,7 +113,7 @@ describe("pinned forge recovery", () => { | ||
| 110 | 113 | }); |
| 111 | 114 | |
| 112 | 115 | test("the boot script installs the Bun version it names, not whatever is latest", () => { |
| 113 | const script = bootConfig({ name: "acme", source: SOURCE, version: V1, config: {} }); | |
| 116 | const script = bootConfig({ name: "acme", source: SOURCE, version: V1, config: {}, host: "acme.forge.test", claimHash: "", claimExpires: "" }); | |
| 114 | 117 | expect(script).toContain(`bash -s "bun-v${BUN_VERSION}"`); |
| 115 | 118 | expect(BUN_VERSION).toMatch(/^\d+\.\d+\.\d+$/); |
| 116 | 119 | }); |
test/pinned-forge.test.ts +34 −10
| @@ -18,6 +18,7 @@ import { createToken } from "../src/core/tokens.ts"; | ||
| 18 | 18 | import { createUser, getUserByName } from "../src/core/users.ts"; |
| 19 | 19 | import { serve, type Servers } from "../src/http/server.ts"; |
| 20 | 20 | import { quietLogs } from "./helpers/globals.ts"; |
| 21 | import { seedPlaces } from "./helpers/places-fixture.ts"; | |
| 21 | 22 | |
| 22 | 23 | quietLogs(); |
| 23 | 24 | |
| @@ -32,15 +33,19 @@ describe("pinned forge", () => { | ||
| 32 | 33 | let servers: Servers; |
| 33 | 34 | const calls: { method: string; url: string; auth: string | null; body: any }[] = []; |
| 34 | 35 | let failNext = false; |
| 36 | /** The cloud refuses the next machine it is asked to make, after any delete went through. */ | |
| 37 | let failCreate = false; | |
| 35 | 38 | |
| 36 | 39 | const admin = () => getUserByName(app.db, "alice")!; |
| 37 | const input = (over: Record<string, unknown> = {}) => ({ | |
| 38 | name: "acme", target: "digitalocean", account: "main", app: "alice/shop", source: SOURCE, version: V1, config: { PUBLIC_NAME: "Acme" }, ...over, | |
| 40 | // Each forge is served on a name of its own: one forge a name. | |
| 41 | const input = (over: { name?: string; target?: string } = {}) => ({ | |
| 42 | name: "acme", host: `${over.name ?? "acme"}.forge.test`, target: "digitalocean", account: "main", app: "alice/shop", source: SOURCE, version: V1, config: { PUBLIC_NAME: "Acme" }, ...over, | |
| 39 | 43 | }); |
| 40 | 44 | |
| 41 | 45 | beforeAll(async () => { |
| 42 | 46 | dataDir = await mkdtemp(join(tmpdir(), "forge-pinned-")); |
| 43 | 47 | app = createApp({ dataDir, port: 0 }); |
| 48 | await seedPlaces(app.db); | |
| 44 | 49 | servers = await serve(app); |
| 45 | 50 | for (const [username, adminIfFirst] of [["alice", true], ["bob", false]] as const) { |
| 46 | 51 | const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@f.test`, password: "a-good-passphrase", adminIfFirst }); |
| @@ -52,7 +57,9 @@ describe("pinned forge", () => { | ||
| 52 | 57 | net.fetch = async (url, init) => { |
| 53 | 58 | const u = new URL(url); |
| 54 | 59 | calls.push({ method: init?.method ?? "GET", url, auth: new Headers(init?.headers).get("authorization"), body: init?.body ? JSON.parse(String(init.body)) : undefined }); |
| 60 | if (u.pathname === "/v2/account/keys" && init?.method === "POST") return new Response(JSON.stringify({ ssh_key: { id: 4242 } }), { status: 201 }); | |
| 55 | 61 | if (failNext) { failNext = false; return new Response("{}", { status: 500 }); } |
| 62 | if (failCreate && init?.method === "POST" && u.pathname === "/v2/droplets") { failCreate = false; return new Response("{}", { status: 500 }); } | |
| 56 | 63 | if (u.pathname === "/v2/volumes") return new Response(JSON.stringify({ volume: { id: "vol-1" } }), { status: 201 }); |
| 57 | 64 | if (init?.method === "DELETE") return new Response(null, { status: 204 }); |
| 58 | 65 | return new Response(JSON.stringify({ droplet: { id: 1000 + calls.length } }), { status: 202 }); |
| @@ -79,9 +86,9 @@ describe("pinned forge", () => { | ||
| 79 | 86 | allowWrite(app, admin(), "digitalocean", "main", true); |
| 80 | 87 | const r = await deployPinned(app, admin(), input()); |
| 81 | 88 | expect(r.ok).toBe(true); |
| 82 | expect(calls.map((c) => `${c.method} ${new URL(c.url).pathname}`)).toEqual(["POST /v2/volumes", "POST /v2/droplets"]); | |
| 89 | expect(calls.map((c) => `${c.method} ${new URL(c.url).pathname}`)).toEqual(["POST /v2/volumes", "POST /v2/account/keys", "POST /v2/droplets", "DELETE /v2/account/keys/4242", "GET /v2/droplets/1003"]); | |
| 83 | 90 | expect(calls.every((c) => c.auth === `Bearer ${TOKEN}`)).toBe(true); |
| 84 | const droplet = calls[1]!.body; | |
| 91 | const droplet = calls[2]!.body; | |
| 85 | 92 | expect(droplet.volumes).toEqual(["vol-1"]); |
| 86 | 93 | expect(JSON.stringify(calls.map((c) => c.body))).not.toContain(TOKEN); |
| 87 | 94 | expect(droplet.user_data).toContain(`checkout --detach ${V1}`); |
| @@ -128,9 +135,13 @@ describe("pinned forge", () => { | ||
| 128 | 135 | calls.length = 0; |
| 129 | 136 | const r = await updatePinned(app, admin(), "acme", { version: V2, config: { PUBLIC_NAME: "Acme Ltd" } }); |
| 130 | 137 | expect(r.ok).toBe(true); |
| 131 | expect(calls.map((c) => `${c.method} ${new URL(c.url).pathname}`)).toEqual([expect.stringMatching(/^DELETE \/v2\/droplets\/\d+$/), "POST /v2/droplets"]); | |
| 132 | expect(calls[1]!.body.volumes).toEqual(["vol-1"]); | |
| 133 | expect(calls[1]!.body.user_data).toContain(`checkout --detach ${V2}`); | |
| 138 | expect(calls.map((c) => `${c.method} ${new URL(c.url).pathname}`)).toEqual([ | |
| 139 | // The machine's address is read first, to ask the forge there whether it was claimed. | |
| 140 | expect.stringMatching(/^GET \/v2\/droplets\/\d+$/), | |
| 141 | expect.stringMatching(/^DELETE \/v2\/droplets\/\d+$/), "POST /v2/account/keys", "POST /v2/droplets", "DELETE /v2/account/keys/4242", | |
| 142 | ]); | |
| 143 | expect(calls[3]!.body.volumes).toEqual(["vol-1"]); | |
| 144 | expect(calls[3]!.body.user_data).toContain(`checkout --detach ${V2}`); | |
| 134 | 145 | const [latest] = changesOf(app.db, getPinned(app.db, "acme")!.id); |
| 135 | 146 | expect(latest).toMatchObject({ kind: "update", fromVersion: V1, toVersion: V2, by: admin().id }); |
| 136 | 147 | expect(Date.parse(latest!.at)).toBeGreaterThan(0); |
| @@ -154,11 +165,24 @@ describe("pinned forge", () => { | ||
| 154 | 165 | expect(latest).toMatchObject({ kind: "rollback", fromVersion: V2, toVersion: V1 }); |
| 155 | 166 | }); |
| 156 | 167 | |
| 157 | test("a cloud failure leaves the change recorded and the forge marked failed", async () => { | |
| 168 | test("a cloud failure before anything is asked of the machine refuses the change and records nothing", async () => { | |
| 169 | // The first call of an Update reads the machine; the cloud refusing it is not "all is well". | |
| 170 | const before = getPinned(app.db, "acme")!; | |
| 171 | const changes = changesOf(app.db, before.id).length; | |
| 158 | 172 | failNext = true; |
| 173 | calls.length = 0; | |
| 174 | const r = await updatePinned(app, admin(), "acme", { version: V2 }); | |
| 175 | expect(r).toMatchObject({ ok: false, error: "The cloud refused: api.digitalocean.com answered 500" }); | |
| 176 | expect(calls.map((c) => c.method)).toEqual(["GET"]); | |
| 177 | expect(getPinned(app.db, "acme")).toMatchObject({ version: V1, state: before.state, remote: before.remote }); | |
| 178 | expect(changesOf(app.db, before.id)).toHaveLength(changes); | |
| 179 | }); | |
| 180 | ||
| 181 | test("a cloud failure after the old machine is deleted leaves the change recorded and the forge marked failed", async () => { | |
| 182 | failCreate = true; | |
| 159 | 183 | const r = await updatePinned(app, admin(), "acme", { version: V2 }); |
| 160 | 184 | expect(r).toMatchObject({ ok: false }); |
| 161 | expect(getPinned(app.db, "acme")).toMatchObject({ version: V2, state: "failed" }); | |
| 185 | expect(getPinned(app.db, "acme")).toMatchObject({ version: V2, state: "failed", remote: "" }); | |
| 162 | 186 | expect(changesOf(app.db, getPinned(app.db, "acme")!.id)[0]).toMatchObject({ kind: "update", toVersion: V2 }); |
| 163 | 187 | }); |
| 164 | 188 | |
| @@ -182,7 +206,7 @@ describe("pinned forge", () => { | ||
| 182 | 206 | expect(checkConfig({ A: "x\nB=1" }).ok).toBe(false); |
| 183 | 207 | expect(checkConfig({ A: 'x"y' }).ok).toBe(false); |
| 184 | 208 | expect(checkConfig({ "a b": "x" }).ok).toBe(false); |
| 185 | const script = bootConfig({ name: "acme", source: SOURCE, version: V1, config: { A: "b" } }); | |
| 209 | const script = bootConfig({ name: "acme", source: SOURCE, version: V1, config: { A: "b" }, host: "acme.forge.test", claimHash: "", claimExpires: "" }); | |
| 186 | 210 | expect(script).toContain("A=b"); |
| 187 | 211 | expect(script.startsWith("#cloud-config")).toBe(true); |
| 188 | 212 | }); |
test/pinned-harden.test.ts added +368
| @@ -0,0 +1,368 @@ | ||
| 1 | /** | |
| 2 | * What a sold forge's machine is (#16218): the boot config and the create calls, read as plain data | |
| 3 | * with no network. The things only a real boot can prove (that the firewall is up, that bubblewrap | |
| 4 | * runs under the unit) are listed in docs/features/pinned-forge.md, not claimed here. | |
| 5 | */ | |
| 6 | import { describe, expect, test } from "bun:test"; | |
| 7 | import { | |
| 8 | bootConfig as digitaloceanBoot, | |
| 9 | digitalocean, | |
| 10 | } from "../src/cloud/droplet.ts"; | |
| 11 | import { PUBLIC_PORTS } from "../src/cloud/harden.ts"; | |
| 12 | import { hetzner, bootConfig as hetznerBoot } from "../src/cloud/hetzner.ts"; | |
| 13 | import type { Call } from "../src/cloud/machine.ts"; | |
| 14 | import { throwawayPublicKey } from "../src/cloud/throwaway_key.ts"; | |
| 15 | import { checkConfig, type Pinned } from "../src/core/pinned.ts"; | |
| 16 | ||
| 17 | const V1 = "a".repeat(40); | |
| 18 | const SOURCE = "https://forge.example.org/trevato/forge"; | |
| 19 | const forge = { | |
| 20 | name: "acme", | |
| 21 | source: SOURCE, | |
| 22 | version: V1, | |
| 23 | config: { PUBLIC_NAME: "Acme" }, | |
| 24 | host: "acme.forge.test", | |
| 25 | claimHash: "c".repeat(64), | |
| 26 | claimExpires: "2026-12-01T00:00:00.000Z", | |
| 27 | }; | |
| 28 | ||
| 29 | interface Doc { | |
| 30 | ssh_pwauth: boolean; | |
| 31 | disable_root: boolean; | |
| 32 | package_update: boolean; | |
| 33 | package_upgrade: boolean; | |
| 34 | packages: string[]; | |
| 35 | write_files: { path: string; permissions?: string; content: string }[]; | |
| 36 | runcmd: string[]; | |
| 37 | } | |
| 38 | const parse = (text: string): Doc => Bun.YAML.parse(text) as Doc; | |
| 39 | const file = (d: Doc, path: string) => | |
| 40 | d.write_files.find((f) => f.path === path)?.content ?? ""; | |
| 41 | ||
| 42 | const boots = { | |
| 43 | digitalocean: () => digitaloceanBoot(forge), | |
| 44 | hetzner: () => hetznerBoot(forge, "77"), | |
| 45 | }; | |
| 46 | ||
| 47 | describe.each(Object.entries(boots))("the %s machine", (_name, boot) => { | |
| 48 | const doc = parse(boot()); | |
| 49 | const unit = file(doc, "/etc/systemd/system/forge.service"); | |
| 50 | ||
| 51 | test("is valid cloud-config", () => { | |
| 52 | expect(boot().startsWith("#cloud-config\n")).toBe(true); | |
| 53 | expect(doc.runcmd.every((c) => typeof c === "string")).toBe(true); | |
| 54 | expect(file(doc, "/etc/forge/env")).toContain("FORGE_APP_DATA="); | |
| 55 | }); | |
| 56 | ||
| 57 | test("the forge runs as its own user, from a Bun root owns, never as root", () => { | |
| 58 | expect(unit).toContain("User=forge\n"); | |
| 59 | expect(unit).toContain("Group=forge\n"); | |
| 60 | expect(unit).toContain("ExecStart=/opt/bun/bin/bun run src/main.ts"); | |
| 61 | expect(boot()).not.toContain("/root"); | |
| 62 | expect( | |
| 63 | doc.runcmd.some( | |
| 64 | (c) => | |
| 65 | c.startsWith("useradd --system") && | |
| 66 | c.includes("/usr/sbin/nologin") && | |
| 67 | c.endsWith(" forge"), | |
| 68 | ), | |
| 69 | ).toBe(true); | |
| 70 | expect(doc.runcmd.find((c) => c.includes("bun.sh/install"))).toContain( | |
| 71 | "BUN_INSTALL=/opt/bun", | |
| 72 | ); | |
| 73 | expect(doc.runcmd).toContain("chown -R forge:forge /opt/forge"); | |
| 74 | // The checkout is made before it is handed over, and the service starts last. | |
| 75 | const at = (s: string) => doc.runcmd.findIndex((c) => c.includes(s)); | |
| 76 | expect(at("git clone")).toBeLessThan(at("chown -R forge:forge /opt/forge")); | |
| 77 | expect(at("chown -R forge:forge /opt/forge")).toBeLessThan( | |
| 78 | at("systemctl enable --now forge.service"), | |
| 79 | ); | |
| 80 | }); | |
| 81 | ||
| 82 | test("the unit is locked down and keeps only the data directory and the forge's home writable", () => { | |
| 83 | for (const line of [ | |
| 84 | "NoNewPrivileges=yes", | |
| 85 | "PrivateTmp=yes", | |
| 86 | "ProtectSystem=strict", | |
| 87 | "ProtectHome=yes", | |
| 88 | "RestrictSUIDSGID=yes", | |
| 89 | ]) | |
| 90 | expect(unit.split("\n")).toContain(line); | |
| 91 | const rw = unit.split("\n").find((l) => l.startsWith("ReadWritePaths="))!; | |
| 92 | expect(rw).toMatch(/^ReadWritePaths=\/mnt\/\S+ \/var\/lib\/forge$/); | |
| 93 | // What the sandbox and the cells need is not taken away (no namespace, syscall or JIT limit). | |
| 94 | // Nor is any part of /proc or /sys hidden: a sandbox mounts its own /proc, and may only when | |
| 95 | // the unit's is whole. | |
| 96 | for (const never of [ | |
| 97 | "ProtectKernelLogs", | |
| 98 | "ProtectKernelTunables", | |
| 99 | "ProtectControlGroups", | |
| 100 | "ProtectProc", | |
| 101 | "ProcSubset", | |
| 102 | "InaccessiblePaths", | |
| 103 | "RestrictNamespaces", | |
| 104 | "PrivateUsers", | |
| 105 | "SystemCallFilter", | |
| 106 | "MemoryDenyWriteExecute", | |
| 107 | "PrivateDevices", | |
| 108 | "CapabilityBoundingSet", | |
| 109 | ]) | |
| 110 | expect(unit).not.toContain(never); | |
| 111 | // The data volume's mount point is the forge's, on every start, including a volume an older | |
| 112 | // root forge wrote. | |
| 113 | expect(unit).toMatch( | |
| 114 | /ExecStartPre=\+\/bin\/sh -c 'mkdir -p (\/mnt\/\S+) && find \1 -xdev -path \1\/caddy -prune -o ! -user forge -exec chown -h forge:forge \{\} \+'/, | |
| 115 | ); | |
| 116 | }); | |
| 117 | ||
| 118 | test("the firewall is on and opens exactly 80 and 443", () => { | |
| 119 | expect(PUBLIC_PORTS).toEqual([80, 443]); | |
| 120 | const ufw = doc.runcmd.filter((c) => c.startsWith("ufw ")); | |
| 121 | expect(ufw).toEqual([ | |
| 122 | "ufw default deny incoming", | |
| 123 | "ufw default allow outgoing", | |
| 124 | "ufw allow 80/tcp", | |
| 125 | "ufw allow 443/tcp", | |
| 126 | "ufw --force enable", | |
| 127 | ]); | |
| 128 | expect(doc.packages).toContain("ufw"); | |
| 129 | // What listens on the two is the packaged proxy, a service of its own; the forge is on | |
| 130 | // loopback. | |
| 131 | expect(doc.packages).toContain("caddy"); | |
| 132 | expect(boot()).not.toContain("apt-get"); | |
| 133 | expect(file(doc, "/etc/forge/env")).toContain("FORGE_BIND=127.0.0.1\n"); | |
| 134 | const dir = /^FORGE_APP_DATA=(\/mnt\/\S+)$/m.exec(file(doc, "/etc/forge/env"))![1]!; | |
| 135 | // Its config is where the package reads it before the package exists, so its first start is | |
| 136 | // on this and never on a welcome page; nothing copies a config in afterwards. | |
| 137 | expect(file(doc, "/etc/caddy/Caddyfile")).toBe(`{\n\tstorage file_system ${dir}/caddy\n}\nacme.forge.test {\n\treverse_proxy 127.0.0.1:3000\n}\n`); | |
| 138 | expect(doc.write_files.filter((f) => f.path.endsWith("Caddyfile"))).toHaveLength(1); | |
| 139 | expect(doc.runcmd.some((c) => c.includes("Caddyfile"))).toBe(false); | |
| 140 | // Its certificates live on the data volume, the proxy's own, so a replaced machine reuses them: | |
| 141 | // it waits for the mount, the directory is made its own before it is restarted, and the | |
| 142 | // forge's walk of the volume leaves it alone. | |
| 143 | expect(file(doc, "/etc/systemd/system/caddy.service.d/forge.conf")).toBe(`[Unit]\nRequiresMountsFor=${dir}\n`); | |
| 144 | const at = (c: string) => doc.runcmd.indexOf(c); | |
| 145 | expect(at(`install -d -m 0700 -o caddy -g caddy ${dir}/caddy`)).toBeGreaterThan(at("systemctl enable --now forge.service")); | |
| 146 | expect(at(`chown -R caddy:caddy ${dir}/caddy`)).toBeGreaterThan(at(`install -d -m 0700 -o caddy -g caddy ${dir}/caddy`)); | |
| 147 | expect(at("systemctl restart caddy.service")).toBeGreaterThan(at(`chown -R caddy:caddy ${dir}/caddy`)); | |
| 148 | expect(at("systemctl restart caddy.service")).toBeGreaterThan(at("systemctl daemon-reload")); | |
| 149 | expect(unit).toContain(`-path ${dir}/caddy -prune`); | |
| 150 | // The forge's unit runs nothing of the proxy: its one mention is the store its walk skips. | |
| 151 | expect(unit.replace(/-path \S+\/caddy -prune/, "")).not.toContain("caddy"); | |
| 152 | // The proxy is handed its config only after the firewall is up and the forge is started. | |
| 153 | expect(doc.runcmd.indexOf("ufw --force enable")).toBeLessThan(doc.runcmd.indexOf("systemctl restart caddy.service")); | |
| 154 | // Nothing is opened before the rules are in: the firewall precedes the Bun download and the | |
| 155 | // clone. | |
| 156 | expect(doc.runcmd.indexOf("ufw --force enable")).toBeLessThan( | |
| 157 | doc.runcmd.findIndex((c) => c.includes("bun.sh")), | |
| 158 | ); | |
| 159 | }); | |
| 160 | ||
| 161 | test("nobody logs in with a password, as root, or at all by default", () => { | |
| 162 | expect(doc.ssh_pwauth).toBe(false); | |
| 163 | expect(doc.disable_root).toBe(true); | |
| 164 | const sshd = file(doc, "/etc/ssh/sshd_config.d/00-forge.conf").split("\n"); | |
| 165 | for (const line of [ | |
| 166 | "PasswordAuthentication no", | |
| 167 | "KbdInteractiveAuthentication no", | |
| 168 | "PermitRootLogin no", | |
| 169 | "AuthenticationMethods publickey", | |
| 170 | ]) | |
| 171 | expect(sshd).toContain(line); | |
| 172 | expect(doc.runcmd.some((c) => /ufw allow (22|ssh)/.test(c))).toBe(false); | |
| 173 | }); | |
| 174 | ||
| 175 | test("security updates install themselves", () => { | |
| 176 | expect(doc.package_update).toBe(true); | |
| 177 | expect(doc.package_upgrade).toBe(true); | |
| 178 | expect(doc.packages).toContain("unattended-upgrades"); | |
| 179 | const auto = file(doc, "/etc/apt/apt.conf.d/20auto-upgrades"); | |
| 180 | expect(auto).toContain('APT::Periodic::Update-Package-Lists "1";'); | |
| 181 | expect(auto).toContain('APT::Periodic::Unattended-Upgrade "1";'); | |
| 182 | }); | |
| 183 | ||
| 184 | test("the sandbox has what it needs: bubblewrap, socat, and a profile letting bwrap, and only bwrap, make a user namespace", () => { | |
| 185 | expect(doc.packages).toEqual( | |
| 186 | expect.arrayContaining(["bubblewrap", "socat", "git", "curl", "unzip"]), | |
| 187 | ); | |
| 188 | const profile = file(doc, "/etc/apparmor.d/forge-bwrap"); | |
| 189 | expect(profile).toContain( | |
| 190 | "profile forge-bwrap /usr/bin/bwrap flags=(unconfined) {", | |
| 191 | ); | |
| 192 | expect(profile).toContain("userns,"); | |
| 193 | expect(doc.runcmd).toContain( | |
| 194 | "apparmor_parser -r /etc/apparmor.d/forge-bwrap || true", | |
| 195 | ); | |
| 196 | // The system-wide restriction is left on. | |
| 197 | expect(boot()).not.toContain("apparmor_restrict_unprivileged_userns"); | |
| 198 | expect(boot()).not.toContain("sysctl"); | |
| 199 | }); | |
| 200 | ||
| 201 | test("the forge's own data directory is applied last, after anything config said", () => { | |
| 202 | const env = file(parse(boot().replace("PUBLIC_NAME=Acme", "FORGE_APP_DATA=/evil\\nPUBLIC_NAME=Acme")), "/etc/forge/env"); | |
| 203 | expect(env.trim().split("\n").at(-1)).toMatch(/^FORGE_APP_DATA=\/mnt\//); | |
| 204 | }); | |
| 205 | }); | |
| 206 | ||
| 207 | describe("a data directory that is not a plain mount point is refused", () => { | |
| 208 | test.each(["x y", "../x", "a;b", "a'b", "a\nb"])("volume %j", (volume) => { | |
| 209 | expect(() => hetznerBoot(forge, volume)).toThrow(/plain mount point/); | |
| 210 | }); | |
| 211 | }); | |
| 212 | ||
| 213 | describe("config that steers the process is refused", () => { | |
| 214 | test.each([ | |
| 215 | "LD_PRELOAD", | |
| 216 | "LD_LIBRARY_PATH", | |
| 217 | "LD_AUDIT", | |
| 218 | "DYLD_INSERT_LIBRARIES", | |
| 219 | "NODE_OPTIONS", | |
| 220 | "NODE_PATH", | |
| 221 | "BUN_CONFIG_REGISTRY", | |
| 222 | "BUN_INSTALL", | |
| 223 | "PATH", | |
| 224 | "HOME", | |
| 225 | "SHELL", | |
| 226 | "USER", | |
| 227 | "LOGNAME", | |
| 228 | "IFS", | |
| 229 | "ENV", | |
| 230 | "BASH_ENV", | |
| 231 | "CDPATH", | |
| 232 | "TMPDIR", | |
| 233 | "GIT_SSH_COMMAND", | |
| 234 | "GIT_EXEC_PATH", | |
| 235 | "PYTHONPATH", | |
| 236 | ])("%s", (k) => { | |
| 237 | const r = checkConfig({ [k]: "x" }); | |
| 238 | expect(r.ok).toBe(false); | |
| 239 | expect(!r.ok && r.error).toContain( | |
| 240 | "steers the loader, the runtime or the path", | |
| 241 | ); | |
| 242 | }); | |
| 243 | ||
| 244 | test.each([ | |
| 245 | "ADMIN_PASSWORD", | |
| 246 | "DB_PASSPHRASE", | |
| 247 | "BASIC_AUTH", | |
| 248 | "OAUTH_CLIENT", | |
| 249 | "SESSION_COOKIE", | |
| 250 | "CREDENTIALS", | |
| 251 | "PRIVATE_SEED", | |
| 252 | "SIGNING_KEY", | |
| 253 | "KEY", | |
| 254 | "KEYS", | |
| 255 | "STRIPE_API_KEY", | |
| 256 | "WEBHOOK_SECRET", | |
| 257 | "API_TOKEN", | |
| 258 | ])("%s looks like a secret", (k) => { | |
| 259 | const r = checkConfig({ [k]: "x" }); | |
| 260 | expect(r.ok).toBe(false); | |
| 261 | expect(!r.ok && r.error).toContain("looks like a secret"); | |
| 262 | }); | |
| 263 | ||
| 264 | test("ordinary settings still pass", () => { | |
| 265 | const r = checkConfig({ | |
| 266 | PUBLIC_NAME: "Acme", | |
| 267 | PORT: "3000", | |
| 268 | FORGE_SIGNUP: "invite", | |
| 269 | AUTHOR_NAME: "Ada", | |
| 270 | MONKEY_COUNT: "3", | |
| 271 | }); | |
| 272 | expect(r.ok).toBe(true); | |
| 273 | }); | |
| 274 | }); | |
| 275 | ||
| 276 | /** A Call that records what it was asked and answers the way each cloud does. */ | |
| 277 | function recorder() { | |
| 278 | const asked: { method: string; path: string; body: any }[] = []; | |
| 279 | const call: Call = async (method, path, body) => { | |
| 280 | asked.push({ method, path, body }); | |
| 281 | if (path.endsWith("/keys") || path.endsWith("/ssh_keys")) | |
| 282 | return { ssh_key: { id: 4242 } }; | |
| 283 | if (path === "/droplets") return { droplet: { id: 7 } }; | |
| 284 | if (path === "/servers") return { server: { id: 8 } }; | |
| 285 | return {}; | |
| 286 | }; | |
| 287 | return { asked, call }; | |
| 288 | } | |
| 289 | const row = { | |
| 290 | claimedAt: "", | |
| 291 | reached: "", | |
| 292 | id: "x", | |
| 293 | target: "t", | |
| 294 | account: "a", | |
| 295 | app: "o/n", | |
| 296 | remote: "", | |
| 297 | volume: "", | |
| 298 | address: "", | |
| 299 | state: "", | |
| 300 | createdAt: "", | |
| 301 | ...forge, | |
| 302 | } as Pinned; | |
| 303 | ||
| 304 | describe("no root password is ever made", () => { | |
| 305 | test("a throwaway key is a well-formed OpenSSH ed25519 public key, new each time", async () => { | |
| 306 | const [a, b] = [await throwawayPublicKey(), await throwawayPublicKey()]; | |
| 307 | expect(a).not.toBe(b); | |
| 308 | const [type, b64, extra] = a.split(" "); | |
| 309 | expect(type).toBe("ssh-ed25519"); | |
| 310 | expect(extra).toBeUndefined(); | |
| 311 | const blob = Buffer.from(b64!, "base64"); | |
| 312 | expect(blob.readUInt32BE(0)).toBe(11); | |
| 313 | expect(blob.subarray(4, 15).toString()).toBe("ssh-ed25519"); | |
| 314 | expect(blob.readUInt32BE(15)).toBe(32); | |
| 315 | expect(blob.length).toBe(51); | |
| 316 | }); | |
| 317 | ||
| 318 | test("DigitalOcean: the droplet is created with a key, and the key is deleted after", async () => { | |
| 319 | const { asked, call } = recorder(); | |
| 320 | await digitalocean.createMachine(call, row, "vol-1", undefined); | |
| 321 | expect(asked.map((a) => `${a.method} ${a.path}`)).toEqual([ | |
| 322 | "POST /account/keys", | |
| 323 | "POST /droplets", | |
| 324 | "DELETE /account/keys/4242", | |
| 325 | ]); | |
| 326 | expect(asked[0]!.body.public_key).toMatch(/^ssh-ed25519 [A-Za-z0-9+/=]+$/); | |
| 327 | expect(asked[1]!.body.ssh_keys).toEqual([4242]); | |
| 328 | expect(asked[1]!.body.user_data).toContain("ufw allow 443/tcp"); | |
| 329 | }); | |
| 330 | ||
| 331 | test("Hetzner: the server is created with a key, and the key is deleted after", async () => { | |
| 332 | const { asked, call } = recorder(); | |
| 333 | await hetzner.createMachine(call, row, "77", "cx23"); | |
| 334 | expect(asked.map((a) => `${a.method} ${a.path}`)).toEqual([ | |
| 335 | "POST /ssh_keys", | |
| 336 | "POST /servers", | |
| 337 | "DELETE /ssh_keys/4242", | |
| 338 | ]); | |
| 339 | expect(asked[0]!.body.public_key).toMatch(/^ssh-ed25519 /); | |
| 340 | expect(asked[1]!.body.ssh_keys).toEqual([4242]); | |
| 341 | expect(asked[1]!.body.user_data).toContain("PermitRootLogin no"); | |
| 342 | }); | |
| 343 | ||
| 344 | test("the private half is never in anything sent", async () => { | |
| 345 | const { asked, call } = recorder(); | |
| 346 | await hetzner.createMachine(call, row, "77", "cx23"); | |
| 347 | expect(JSON.stringify(asked)).not.toMatch(/PRIVATE KEY|BEGIN OPENSSH/); | |
| 348 | }); | |
| 349 | ||
| 350 | test("a failed create still deletes the key, and a failed key makes no machine", async () => { | |
| 351 | const { asked, call } = recorder(); | |
| 352 | const failing: Call = async (m, p, b) => { | |
| 353 | if (p === "/servers") throw new Error("api.hetzner.cloud answered 500"); | |
| 354 | return call(m, p, b); | |
| 355 | }; | |
| 356 | await expect( | |
| 357 | hetzner.createMachine(failing, row, "77", "cx23"), | |
| 358 | ).rejects.toThrow("answered 500"); | |
| 359 | expect(asked.at(-1)).toMatchObject({ | |
| 360 | method: "DELETE", | |
| 361 | path: "/ssh_keys/4242", | |
| 362 | }); | |
| 363 | const none: Call = async () => ({}); | |
| 364 | await expect( | |
| 365 | hetzner.createMachine(none, row, "77", "cx23"), | |
| 366 | ).rejects.toThrow("no SSH key"); | |
| 367 | }); | |
| 368 | }); |
test/pinned-hetzner-doors.test.ts +12 −6
| @@ -19,6 +19,7 @@ import { Session } from "../src/tui/session.ts"; | ||
| 19 | 19 | import type { Ctx, Screen } from "../src/tui/app/app.ts"; |
| 20 | 20 | import { pinnedScreen } from "../src/tui/screens/pinned.ts"; |
| 21 | 21 | import { quietLogs } from "./helpers/globals.ts"; |
| 22 | import { seedPlaces } from "./helpers/places-fixture.ts"; | |
| 22 | 23 | import { quietCtx } from "./helpers/tui-text.ts"; |
| 23 | 24 | import { waitFor } from "./helpers/poll.ts"; |
| 24 | 25 | |
| @@ -42,10 +43,12 @@ describe("Hetzner at the existing doors", () => { | ||
| 42 | 43 | body: new URLSearchParams(body), |
| 43 | 44 | }); |
| 44 | 45 | const good = { app: "alice/shop", source: SOURCE, version: V }; |
| 46 | const named = (name: string) => ({ ...good, name, host: `${name}.forge.test` }); | |
| 45 | 47 | |
| 46 | 48 | beforeAll(async () => { |
| 47 | 49 | dataDir = await mkdtemp(join(tmpdir(), "forge-hetzner-doors-")); |
| 48 | 50 | app = createApp({ dataDir, port: 0 }); |
| 51 | await seedPlaces(app.db); | |
| 49 | 52 | servers = await serve(app); |
| 50 | 53 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); |
| 51 | 54 | if (!made.ok) throw new Error(made.error); |
| @@ -66,9 +69,11 @@ describe("Hetzner at the existing doors", () => { | ||
| 66 | 69 | if (u.pathname === "/v1/server_types") return json({ server_types: [{ id: 2, name: "cx23", architecture: "x86", memory: 4, prices: [price("nbg1", "5.99")] }] }); |
| 67 | 70 | if (u.pathname === "/v1/datacenters") return json({ datacenters: [{ location: { name: "nbg1" }, server_types: { available: [2] } }] }); |
| 68 | 71 | if (u.pathname === "/v1/volumes") return json({ volume: { id: 77 } }, 201); |
| 72 | if (u.pathname === "/v1/ssh_keys" && method === "POST") return json({ ssh_key: { id: 4242 } }, 201); | |
| 69 | 73 | return json({ server: { id: 501 } }, 201); |
| 70 | 74 | } |
| 71 | 75 | if (u.pathname === "/v2/volumes") return json({ volume: { id: "vol-1" } }, 201); |
| 76 | if (u.pathname === "/v2/account/keys" && method === "POST") return json({ ssh_key: { id: 4242 } }, 201); | |
| 72 | 77 | return json({ droplet: { id: 7 } }, 202); |
| 73 | 78 | }; |
| 74 | 79 | }, 30_000); |
| @@ -94,20 +99,21 @@ describe("Hetzner at the existing doors", () => { | ||
| 94 | 99 | }); |
| 95 | 100 | |
| 96 | 101 | test("a posted hetzner/main deploys to Hetzner", async () => { |
| 97 | const r = await post({ ...good, name: "eu", account: "hetzner/main" }); | |
| 98 | expect(r.status).toBe(303); | |
| 102 | const r = await post({ ...named("eu"), account: "hetzner/main" }); | |
| 103 | // The answer is the page that shows the claim link once, not a redirect. | |
| 104 | expect(r.status).toBe(200); | |
| 99 | 105 | expect(getPinned(app.db, "eu")).toMatchObject({ target: "hetzner", state: "running" }); |
| 100 | 106 | expect(paths.some((p) => p.startsWith("api.hetzner.cloud POST /v1/servers"))).toBe(true); |
| 101 | 107 | }); |
| 102 | 108 | |
| 103 | 109 | test("a bare account name is a DigitalOcean account, as the form used to say", async () => { |
| 104 | const r = await post({ ...good, name: "old", account: "main" }); | |
| 105 | expect(r.status).toBe(303); | |
| 110 | const r = await post({ ...named("old"), account: "main" }); | |
| 111 | expect(r.status).toBe(200); | |
| 106 | 112 | expect(getPinned(app.db, "old")).toMatchObject({ target: "digitalocean" }); |
| 107 | 113 | }); |
| 108 | 114 | |
| 109 | 115 | test("more than one slash is refused, and deploys nothing", async () => { |
| 110 | const r = await post({ ...good, name: "odd", account: "hetzner/main/extra" }); | |
| 116 | const r = await post({ ...named("odd"), account: "hetzner/main/extra" }); | |
| 111 | 117 | expect(r.status).toBe(422); |
| 112 | 118 | expect(await r.text()).toContain("Pick a cloud account from the list."); |
| 113 | 119 | expect(getPinned(app.db, "odd")).toBeUndefined(); |
| @@ -120,7 +126,7 @@ describe("Hetzner at the existing doors", () => { | ||
| 120 | 126 | const key = (s: Screen, k: string) => s.key?.({ type: "key", key: k, ctrl: false, alt: false, shift: false }); |
| 121 | 127 | key(pinnedScreen(f, ctx), "d"); |
| 122 | 128 | const prompt = pushed[0]!; |
| 123 | prompt.paste?.(`tty hetzner/main alice/shop ${SOURCE} ${V}`); | |
| 129 | prompt.paste?.(`tty tty.forge.test hetzner/main alice/shop ${SOURCE} ${V}`); | |
| 124 | 130 | key(prompt, "enter"); |
| 125 | 131 | await waitFor(() => getPinned(app.db, "tty")?.state === "running"); |
| 126 | 132 | expect(getPinned(app.db, "tty")).toMatchObject({ target: "hetzner", state: "running" }); |
test/pinned-hetzner.test.ts +20 −7
| @@ -16,6 +16,7 @@ import { verify } from "../src/cloud/providers.ts"; | ||
| 16 | 16 | import { getPinned } from "../src/core/pinned.ts"; |
| 17 | 17 | import { createUser, getUserByName } from "../src/core/users.ts"; |
| 18 | 18 | import { quietLogs } from "./helpers/globals.ts"; |
| 19 | import { seedPlaces } from "./helpers/places-fixture.ts"; | |
| 19 | 20 | |
| 20 | 21 | quietLogs(); |
| 21 | 22 | |
| @@ -42,20 +43,23 @@ describe("hetzner target", () => { | ||
| 42 | 43 | let serverSeq = 500; |
| 43 | 44 | |
| 44 | 45 | const admin = () => getUserByName(app.db, "alice")!; |
| 45 | const input = (over: Record<string, unknown> = {}) => ({ | |
| 46 | name: "acme", target: "hetzner", account: "main", app: "alice/shop", source: SOURCE, version: V1, config: { PUBLIC_NAME: "Acme" }, ...over, | |
| 46 | const input = (over: { name?: string; version?: string } = {}) => ({ | |
| 47 | name: "acme", host: `${over.name ?? "acme"}.forge.test`, target: "hetzner", account: "main", app: "alice/shop", source: SOURCE, version: V1, config: { PUBLIC_NAME: "Acme" }, ...over, | |
| 47 | 48 | }); |
| 48 | 49 | const seen = () => calls.map((c) => `${c.method} ${c.path}`); |
| 49 | 50 | |
| 50 | 51 | beforeAll(async () => { |
| 51 | 52 | dataDir = await mkdtemp(join(tmpdir(), "forge-hetzner-")); |
| 52 | 53 | app = createApp({ dataDir, port: 0 }); |
| 54 | await seedPlaces(app.db); | |
| 53 | 55 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); |
| 54 | 56 | if (!made.ok) throw new Error(made.error); |
| 55 | 57 | cloudNet.fetch = async () => new Response(JSON.stringify({ servers: [], meta: { pagination: { total_entries: 0 } } }), { status: 200 }); |
| 56 | 58 | const added = await addAccount(app, admin(), "hetzner", "main", TOKEN); |
| 57 | 59 | if (!added.ok) throw new Error(String(added.error)); |
| 58 | 60 | allowWrite(app, admin(), "hetzner", "main", true); |
| 61 | // The forge's name resolves nowhere here: nothing in this file asks a deployed forge. | |
| 62 | net.resolve = async () => []; | |
| 59 | 63 | net.fetch = async (url, init) => { |
| 60 | 64 | const u = new URL(url); |
| 61 | 65 | expect(u.host).toBe("api.hetzner.cloud"); |
| @@ -65,6 +69,7 @@ describe("hetzner target", () => { | ||
| 65 | 69 | if (u.pathname === "/v1/server_types") return json({ server_types: TYPES }); |
| 66 | 70 | if (u.pathname === "/v1/datacenters") return json({ datacenters: [{ location: { name: LOCATION }, server_types: { available: stocked } }, { location: { name: "ash" }, server_types: { available: [1, 2, 3, 4, 5] } }] }); |
| 67 | 71 | if (u.pathname === "/v1/volumes") return json({ volume: { id: 77 } }, 201); |
| 72 | if (u.pathname === "/v1/ssh_keys" && method === "POST") return json({ ssh_key: { id: 4242 } }, 201); | |
| 68 | 73 | if (u.pathname === "/v1/servers" && method === "POST") { |
| 69 | 74 | if (failServer > 0) { failServer--; return json({}, 500); } |
| 70 | 75 | return json({ server: { id: ++serverSeq } }, 201); |
| @@ -83,10 +88,11 @@ describe("hetzner target", () => { | ||
| 83 | 88 | test("deploy reads the types, picks the cheapest CX in stock with 2 GiB in an EU location, and mounts the volume by its id", async () => { |
| 84 | 89 | const r = await deployPinned(app, admin(), input()); |
| 85 | 90 | expect(r.ok).toBe(true); |
| 86 | expect(seen()).toEqual(["GET /v1/server_types", "GET /v1/datacenters", "POST /v1/volumes", "POST /v1/servers"]); | |
| 91 | // The last call reads the new server's address, so the answer can name the DNS record. | |
| 92 | expect(seen()).toEqual(["GET /v1/server_types", "GET /v1/datacenters", "POST /v1/volumes", "POST /v1/ssh_keys", "POST /v1/servers", "DELETE /v1/ssh_keys/4242", "GET /v1/servers/501"]); | |
| 87 | 93 | expect(calls.every((c) => c.auth === `Bearer ${TOKEN}`)).toBe(true); |
| 88 | 94 | expect(JSON.stringify(calls.map((c) => c.body))).not.toContain(TOKEN); |
| 89 | const [volume, server] = [calls[2]!.body, calls[3]!.body]; | |
| 95 | const [volume, server] = [calls[2]!.body, calls[4]!.body]; | |
| 90 | 96 | expect(["nbg1", "fsn1", "hel1"]).toContain(volume.location); |
| 91 | 97 | expect(server).toMatchObject({ server_type: "cx23", location: volume.location, volumes: [77], automount: true }); |
| 92 | 98 | expect(server.user_data).toContain("FORGE_APP_DATA=/mnt/HC_Volume_77"); |
| @@ -106,9 +112,16 @@ describe("hetzner target", () => { | ||
| 106 | 112 | calls.length = 0; |
| 107 | 113 | const r = await updatePinned(app, admin(), "acme", { version: V2 }); |
| 108 | 114 | expect(r.ok).toBe(true); |
| 109 | expect(seen()).toEqual(["GET /v1/server_types", "GET /v1/datacenters", "DELETE /v1/servers/501", "POST /v1/servers"]); | |
| 110 | expect(calls[3]!.body.volumes).toEqual([77]); | |
| 111 | expect(calls[3]!.body.user_data).toContain(`checkout --detach ${V2}`); | |
| 115 | // The address is read to ask the forge whether it was claimed; what would be ordered is asked | |
| 116 | // before the pin moves; then the server is replaced. | |
| 117 | expect(seen()).toEqual([ | |
| 118 | "GET /v1/servers/501", | |
| 119 | "GET /v1/server_types", "GET /v1/datacenters", | |
| 120 | "GET /v1/server_types", "GET /v1/datacenters", "DELETE /v1/servers/501", "POST /v1/ssh_keys", "POST /v1/servers", "DELETE /v1/ssh_keys/4242", | |
| 121 | ]); | |
| 122 | const made = calls.find((c) => c.method === "POST" && c.path === "/v1/servers")!; | |
| 123 | expect(made.body.volumes).toEqual([77]); | |
| 124 | expect(made.body.user_data).toContain(`checkout --detach ${V2}`); | |
| 112 | 125 | expect(getPinned(app.db, "acme")).toMatchObject({ volume: "77", remote: "502", version: V2 }); |
| 113 | 126 | }); |
| 114 | 127 |
test/pinned-page.test.ts +42 −7
| @@ -10,8 +10,10 @@ import { getPinned } from "../src/core/pinned.ts"; | ||
| 10 | 10 | import { createToken } from "../src/core/tokens.ts"; |
| 11 | 11 | import { createUser, getUserByName } from "../src/core/users.ts"; |
| 12 | 12 | import { serve, type Servers } from "../src/http/server.ts"; |
| 13 | import { sha256 } from "../src/kernel/hash.ts"; | |
| 13 | 14 | import { deployToHref } from "../src/web/pinned.ts"; |
| 14 | 15 | import { quietLogs } from "./helpers/globals.ts"; |
| 16 | import { seedPlaces } from "./helpers/places-fixture.ts"; | |
| 15 | 17 | |
| 16 | 18 | quietLogs(); |
| 17 | 19 | |
| @@ -33,11 +35,12 @@ describe("deploy-to page", () => { | ||
| 33 | 35 | headers: { authorization: `Bearer ${tok}`, origin, "content-type": "application/x-www-form-urlencoded" }, |
| 34 | 36 | body: new URLSearchParams(body), |
| 35 | 37 | }); |
| 36 | const good = { name: "acme", account: "main", app: "alice/shop", source: SOURCE, version: V }; | |
| 38 | const good = { name: "acme", host: "acme.forge.test", account: "main", app: "alice/shop", source: SOURCE, version: V }; | |
| 37 | 39 | |
| 38 | 40 | beforeAll(async () => { |
| 39 | 41 | dataDir = await mkdtemp(join(tmpdir(), "forge-pinned-page-")); |
| 40 | 42 | app = createApp({ dataDir, port: 0 }); |
| 43 | await seedPlaces(app.db); | |
| 41 | 44 | servers = await serve(app); |
| 42 | 45 | for (const [username, adminIfFirst] of [["alice", true], ["bob", false]] as const) { |
| 43 | 46 | const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@f.test`, password: "a-good-passphrase", adminIfFirst }); |
| @@ -50,6 +53,7 @@ describe("deploy-to page", () => { | ||
| 50 | 53 | if (!added.ok) throw new Error(String(added.error)); |
| 51 | 54 | net.fetch = async (url, init) => { |
| 52 | 55 | if (new URL(url).pathname === "/v2/volumes") return new Response(JSON.stringify({ volume: { id: "vol-1" } }), { status: 201 }); |
| 56 | if (new URL(url).pathname === "/v2/account/keys" && init?.method === "POST") return new Response(JSON.stringify({ ssh_key: { id: 4242 } }), { status: 201 }); | |
| 53 | 57 | if (init?.method === "DELETE") return new Response(null, { status: 204 }); |
| 54 | 58 | return new Response(JSON.stringify({ droplet: { id: 7 } }), { status: 202 }); |
| 55 | 59 | }; |
| @@ -101,8 +105,15 @@ describe("deploy-to page", () => { | ||
| 101 | 105 | allowWrite(app, getUserByName(app.db, "alice"), "digitalocean", "main", true); |
| 102 | 106 | expect(await (await get("/deploy-to", adminTok)).text()).toContain("DigitalOcean / main"); |
| 103 | 107 | const r = await post(good, adminTok); |
| 104 | expect(r.status).toBe(303); | |
| 108 | // The answer is the page that shows the claim link once: no redirect, no flash, no cache. | |
| 109 | expect(r.status).toBe(200); | |
| 110 | expect(r.headers.get("cache-control")).toBe("no-store"); | |
| 111 | expect(r.headers.get("set-cookie") ?? "").not.toContain("first-admin"); | |
| 112 | const text = await r.text(); | |
| 113 | const link = /https:\/\/acme\.forge\.test\/first-admin#([A-Za-z0-9_-]{43})/.exec(text); | |
| 114 | expect(link).not.toBeNull(); | |
| 105 | 115 | const p = getPinned(app.db, "acme")!; |
| 116 | expect(p.claimHash).toBe(sha256(link![1]!)); | |
| 106 | 117 | expect(p.version).toBe(V); |
| 107 | 118 | expect(p.state).toBe("running"); |
| 108 | 119 | }); |
| @@ -112,6 +123,7 @@ describe("pinned list page", () => { | ||
| 112 | 123 | test("renders none, then one forge; a non-admin gets 403", async () => { |
| 113 | 124 | const dataDir = await mkdtemp(join(tmpdir(), "forge-pinned-list-")); |
| 114 | 125 | const app = createApp({ dataDir, port: 0 }); |
| 126 | await seedPlaces(app.db); | |
| 115 | 127 | const servers = await serve(app); |
| 116 | 128 | try { |
| 117 | 129 | for (const [username, adminIfFirst] of [["alice", true], ["bob", false]] as const) { |
| @@ -132,13 +144,13 @@ describe("pinned list page", () => { | ||
| 132 | 144 | if (!added.ok) throw new Error(String(added.error)); |
| 133 | 145 | allowWrite(app, getUserByName(app.db, "alice"), "digitalocean", "main", true); |
| 134 | 146 | net.fetch = async (url) => |
| 135 | new Response(JSON.stringify(new URL(url).pathname === "/v2/volumes" ? { volume: { id: "vol-1" } } : { droplet: { id: 7 } }), { status: 202 }); | |
| 147 | new Response(JSON.stringify(new URL(url).pathname === "/v2/volumes" ? { volume: { id: "vol-1" } } : new URL(url).pathname === "/v2/account/keys" ? { ssh_key: { id: 4242 } } : { droplet: { id: 7 } }), { status: 202 }); | |
| 136 | 148 | const r = await fetch(servers.url + "/deploy-to", { |
| 137 | 149 | method: "POST", redirect: "manual", |
| 138 | 150 | headers: { authorization: `Bearer ${adminTok}`, origin: servers.url, "content-type": "application/x-www-form-urlencoded" }, |
| 139 | body: new URLSearchParams({ name: "acme", account: "main", app: "alice/shop", source: SOURCE, version: V }), | |
| 151 | body: new URLSearchParams({ name: "acme", host: "acme.forge.test", account: "main", app: "alice/shop", source: SOURCE, version: V }), | |
| 140 | 152 | }); |
| 141 | expect(r.status).toBe(303); | |
| 153 | expect(r.status).toBe(200); | |
| 142 | 154 | const t = await (await get(adminTok)).text(); |
| 143 | 155 | expect(t).toContain("acme"); |
| 144 | 156 | expect(t).toContain("alice/shop"); |
| @@ -146,6 +158,11 @@ describe("pinned list page", () => { | ||
| 146 | 158 | expect(t).toContain("deploy to"); |
| 147 | 159 | expect(t).toContain("alice"); |
| 148 | 160 | expect(t).toContain("never checked"); |
| 161 | expect(t).toContain("https://acme.forge.test/"); | |
| 162 | expect(t).toContain("/pinned/acme/claim"); | |
| 163 | // The list never holds the claim: not the link, not its hash. | |
| 164 | expect(t).not.toContain("first-admin#"); | |
| 165 | expect(t).not.toContain(getPinned(app.db, "acme")!.claimHash); | |
| 149 | 166 | expect(t).not.toContain("<table"); |
| 150 | 167 | app.bus.append({ kind: "pinned.check", actorId: getUserByName(app.db, "alice")!.id, payload: { name: "acme", state: "running", healthy: true } }); |
| 151 | 168 | const checked = await (await get(adminTok)).text(); |
| @@ -163,6 +180,7 @@ describe("pinned list page actions", () => { | ||
| 163 | 180 | test("Update, Roll back and Check go through a confirm, are admin only and same-origin, and show refusals", async () => { |
| 164 | 181 | const dataDir = await mkdtemp(join(tmpdir(), "forge-pinned-acts-")); |
| 165 | 182 | const app = createApp({ dataDir, port: 0 }); |
| 183 | await seedPlaces(app.db); | |
| 166 | 184 | const servers = await serve(app); |
| 167 | 185 | const V2 = "b".repeat(40); |
| 168 | 186 | try { |
| @@ -181,6 +199,7 @@ describe("pinned list page actions", () => { | ||
| 181 | 199 | const path = new URL(url).pathname; |
| 182 | 200 | calls.push(`${init?.method ?? "GET"} ${path}`); |
| 183 | 201 | if (path === "/v2/volumes") return new Response(JSON.stringify({ volume: { id: "vol-1" } }), { status: 201 }); |
| 202 | if (path === "/v2/account/keys" && init?.method === "POST") return new Response(JSON.stringify({ ssh_key: { id: 4242 } }), { status: 201 }); | |
| 184 | 203 | if (init?.method === "DELETE") return new Response(null, { status: 204 }); |
| 185 | 204 | return new Response(JSON.stringify({ droplet: { id: 7, networks: { v4: [{ type: "public", ip_address: "203.0.113.9" }] } } }), { status: 202 }); |
| 186 | 205 | }; |
| @@ -191,8 +210,9 @@ describe("pinned list page actions", () => { | ||
| 191 | 210 | const get = (path: string, tok: string) => fetch(servers.url + path, { redirect: "manual", headers: { authorization: `Bearer ${tok}` } }); |
| 192 | 211 | const after = async (r: Response) => |
| 193 | 212 | (await fetch(servers.url + r.headers.get("location")!, { headers: { authorization: `Bearer ${adminTok}`, cookie: (r.headers.get("set-cookie") ?? "").split(";")[0]! } })).text(); |
| 194 | const dep = await act("/deploy-to", adminTok, { name: "acme", account: "main", app: "alice/shop", source: SOURCE, version: V }); | |
| 195 | expect(dep.status).toBe(303); | |
| 213 | net.resolve = async () => ["203.0.113.9"]; | |
| 214 | const dep = await act("/deploy-to", adminTok, { name: "acme", host: "acme.forge.test", account: "main", app: "alice/shop", source: SOURCE, version: V }); | |
| 215 | expect(dep.status).toBe(200); | |
| 196 | 216 | |
| 197 | 217 | const list = await (await get("/pinned", adminTok)).text(); |
| 198 | 218 | for (const w of ["/pinned/acme/update", "/pinned/acme/rollback", "/pinned/acme/check"]) expect(list).toContain(w); |
| @@ -203,6 +223,21 @@ describe("pinned list page actions", () => { | ||
| 203 | 223 | expect(conf).toContain(`value="${V2}"`); |
| 204 | 224 | expect((await get("/-/confirm?to=/pinned/Bad_Name/update", adminTok)).status).toBe(404); |
| 205 | 225 | |
| 226 | // A new claim link is confirmed too, and its answer is the page that shows the link once. | |
| 227 | const ask = await (await get(`/-/confirm?to=${encodeURIComponent("/pinned/acme/claim")}`, adminTok)).text(); | |
| 228 | expect(ask).toContain('action="/pinned/acme/claim"'); | |
| 229 | expect(ask).toContain("stops working"); | |
| 230 | const was = getPinned(app.db, "acme")!.claimHash; | |
| 231 | expect((await act("/pinned/acme/claim", bobTok)).status).toBe(403); | |
| 232 | expect((await act("/pinned/acme/claim", adminTok, {}, "https://evil.example")).status).toBe(403); | |
| 233 | expect(getPinned(app.db, "acme")!.claimHash).toBe(was); | |
| 234 | const fresh = await act("/pinned/acme/claim", adminTok); | |
| 235 | expect(fresh.status).toBe(200); | |
| 236 | expect(fresh.headers.get("cache-control")).toBe("no-store"); | |
| 237 | const shownLink = /https:\/\/acme\.forge\.test\/first-admin#([A-Za-z0-9_-]{43})/.exec(await fresh.text()); | |
| 238 | expect(getPinned(app.db, "acme")!.claimHash).toBe(sha256(shownLink![1]!)); | |
| 239 | expect(getPinned(app.db, "acme")!.claimHash).not.toBe(was); | |
| 240 | ||
| 206 | 241 | // Not an admin: 404 and nothing moves. Cross-origin: 403. |
| 207 | 242 | for (const a of ["update", "rollback", "check"]) expect((await act(`/pinned/acme/${a}`, bobTok, { version: V2 })).status).toBe(403); |
| 208 | 243 | expect((await act("/pinned/acme/update", adminTok, { version: V2 }, "https://evil.example")).status).toBe(403); |
test/private-by-default.test.ts +1 −1
| @@ -62,7 +62,7 @@ const DOORS: Readonly<Record<string, Door>> = { | ||
| 62 | 62 | "POST /:owner/:name/pulls/new": { noRepository: "a pull" }, |
| 63 | 63 | "POST /admin/agent-start": { noRepository: "the setting that opens the start call" }, |
| 64 | 64 | "POST /api/v1/admin/app-templates": { noRepository: "marks a repository a template; its copies are walked as a template" }, |
| 65 | "POST /api/v1/admin/pinned/:name/claim": { noRepository: "marks a pinned forge handed to its buyer" }, | |
| 65 | "POST /api/v1/admin/pinned/:name/claim": { noRepository: "issues a new claim link for a pinned forge nobody has claimed" }, | |
| 66 | 66 | "POST /api/v1/apps": { walked: API }, |
| 67 | 67 | "POST /api/v1/forges": { walked: SPAWN }, |
| 68 | 68 | "POST /api/v1/migrate": { proven: "test/migrate-trail.test.ts", says: "a migration that asks for no visibility is private" }, |
new above
offline