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

On /infra a machine opens to its projects and containers, and a container opens to live logs, stats, restart and stop #18537

opened this

Merged 1h 17m ago, live in production

mason/forge:mason/18487-on-infra-a-machine-opens-to-its-projects → main 0 commits fork 2 threads · 2 unresolved

  • Merged. mason/18487-on-infra-a-machine-opens-to-its-projects was merged into main as 5b0814e.

Review

Sign in to review this change.
6 files changed +145 −9
docs/features/infra.md +2 −1
@@ -115,7 +115,8 @@ Every DigitalOcean and Hetzner account is read into provider ▸ account ▸ pro
115115 - **A resource** is at `/infra/-/<cloud>/<account>/<project>/<id>`, beside the tree, or full width on a phone: cost, state, what it is attached to and what it holds (an address its balancer, NAT gateway or task; an ECS service its balancer and cluster; a balancer the services known behind it, "Shared by" when there are several; a link AWS does not state is not drawn, which does not mean nothing uses it), an AWS list price's day, what it leaves out and whose file it is (or why there is none), the app an AWS resource is part of and how that is known (nothing when it is not), what it was made from, who made it, when it was created, when it was read, and Ask about this (a talk with those facts, fenced as data).
116116 - **Created.** An EC2 instance's is when its primary network interface was attached, which is its first launch: AWS's `launchTime` is its last start and is not shown. "not known" when the cloud does not state a date, or the forge does not read one (an AWS address, function, table, cluster or zone). An S3 bucket's is "Created, or last changed", because AWS moves it when the bucket changes, its policy for one; a filter by `created:` uses that date all the same.
117117 - **Containers.** A machine that is a game box opens into its containers (`src/cloud/containers.ts`), at `/infra/-/<cloud>/<account>/<project>/machine:<id>/container:<name>`: state, health, CPU, memory, how long it has been up, its image (the box owner's only) and a link to its page under /games, where it is changed. It is what the box's last full sync wrote, and nothing is asked of the box. The sync carries `upSince`, `memLimitMiB` and `cpuLimit` for each service, from one `docker inspect` that asks for those fields by name and never the whole answer, which holds the env (`services` in `src/games/agent.sh`): a limit of 0 is "no limit set", and one left out (an older agent) is "not known", as is a value out of its range. Without `upSince` the uptime is the diagnosis' word. "not known" is also said of figures the box could not measure, and of everything once the box is silent for two minutes ("not known: running 3 hours ago"). A container is in no count and no sum. The machine is the one the box's own row names, never found by name. Who sees which follows the games roles, and nobody sees the waker. A held box (docs/features/games.md) says so on its machine: in its row, and first in its facts with the next step. A box whose agent update was put back to the one before (docs/features/games.md, the agent's trial) says so there too: its row reads "On its old agent:" and the agent's own reason, in the terminal's Infra the same words after the row's place, and in the `infra` tool's list as the machine's `agentBack`; a box whose agent is fine has no such field. A machine's pane lists its containers as one table, on the page and in the terminal alike (`CONTAINER_COLUMNS`, `containerCell`): name (a link to the container), state, CPU limit, memory limit and started, as an ago. A value not known, or no limit set, is an em dash, never 0.
118 - **Logs.** A game box's container has a Logs tab with the same live reader and console as its service's page on `/games/<box>/<service>`, with Restart, and Stop and Start under More, for an operator of it (they ask first when someone is on, as there). Someone with no role on the box is told so (`containerConsole` in `src/web/pages/games.ts`).
118 - **Logs.** A game box's container has a Logs tab with the same live reader and console as its service's page on `/games/<box>/<service>`. For an operator of the box, Restart (Start while it is not running) sits beside the container's name, and Stop is a tap further, under More, as on the games page. Each is a form posting, same origin, to `/infra/container/<box>/<container>/<restart|stop|start>`. That asks the box as `/games/<box>/<container>/power` does, and returns to the container (`src/web/pages/container_power.ts`). The games page keeps its own route and posts to it, since it returns to the games page. In the terminal the same request is `s`, `x` and `r` on the container's row in `src/tui/screens/games.ts`. A held box shows the start buttons disabled and says so. Someone with no role on the box is told so (`containerConsole` in `src/web/pages/games.ts`). The container's CPU, memory and uptime are on its Facts tab.
119 - **A machine by name.** `/infra/<machine>` opens the machine in the tree, where its containers are listed. A machine the cloud has not been read for opens the tree's top.
119120 - **File.** A machine has two tabs, Facts and File (`?tab=file`; `[` and `]` in the terminal); a container has a third, Logs (`?tab=logs`): on the page, for someone with a role on its box, the live reader below; otherwise, in the terminal and in the `infra` tool, its newest 200 lines as its box last synced them (nothing is fetched from the box; control characters are dropped, the page escapes the rest), or a sentence saying none were synced and when the box last did. The `infra` tool returns the same lines as `logs` for a container. Only an admin sees the tree. File says which lines of which file declare the thing, links to them, and says whether that agrees with what the forge knows (`src/cloud/declared_in.ts`, `declared_read.ts`). Two kinds of file are read: an app's `infra.json`, against the forge's own record of the machine (the cloud is not asked), and a game box's compose file, against the commit the box last said it runs. When the branch is at another commit the tab says so, since its lines may not be what runs; a silent box is "not known". Of a service it shows the image, ports, volumes and the names of its environment, never a value. A thing in neither file is "in no file the forge reads", one that is part of a stack is "not known", and one in a repository the reader may not read is "in a file you cannot read", with nothing of it shown. The join goes through the forge's own rows and never by a resource's name. On the branch that is followed, the file's own page says to a forge admin "Declares 3: …" with a link to each node; to anyone else it is as before. Nothing is written.
120121 - **Keys.** j and k move, Enter opens, h and l (or the arrows) close and open, `/` filters and Enter goes to the first match.
121122 - **States.** No account (a link to /settings/cloud), not read yet, a failed read (one line: when, why, and how old what is shown is), a kind that could not be read with its reason (on its project and on the account, which says where; under the headline's sum, "Not everything is listed: 1 kind not read" links to that account, and text doors name it; a billed account's gaps count too, and change no sum), and a reading older than three of its duty's intervals. A project's note ("R2 is not switched on for this account") is a plain line and no trouble, on its account too when that has one project. **Check the account** (`a` in the terminal) opens the account: see [Cloud accounts](cloud.md#what-was-not-read-17637).
src/http/infra_routes.ts +42 −3
@@ -23,14 +23,20 @@ import { html, type Html } from "../web/html.ts";
2323 import { flashTo, fragment, page } from "../web/layout.ts";
2424 import { machineView } from "../actions/machine_view.ts";
2525 import { INFRA_CSS, cloudPage, consolePage, endingPage, restoringPage, buildTray, placesRegion, composeForm, infraJs, buildPage, planTray, recordForm, resourcesPage, runningRegion, type ComposeState } from "../web/pages/infra.ts";
26 import { cloudBranch, cloudList, cloudOverview, cloudPane, cloudTotal, cloudTreeJs } from "../web/pages/cloud_tree.ts";
26 import { cloudBranch, cloudHref, cloudList, cloudOverview, cloudPane, cloudTotal, cloudTreeJs } from "../web/pages/cloud_tree.ts";
2727 import { filesByNode } from "../cloud/declared_read.ts";
2828 import { logsOfContainer } from "../cloud/containers.ts";
29 import { nodeAt, tabOf, type CloudNode, type CloudView } from "../cloud/tree.ts";
29 import { nodeAt, resourcesOf, tabOf, type CloudNode, type CloudView } from "../cloud/tree.ts";
3030 import { may } from "../core/may.ts";
3131 import { principalOfUser } from "../core/principal.ts";
3232 import { pinnedBlock } from "./pinned_routes.ts";
3333 import { containerConsole } from "../web/pages/games.ts";
34 import { backOf, isContainerAct } from "../web/pages/container_power.ts";
35 import { askPower } from "../games/power.ts";
36 import { boxNamed, SERVICE_NAME } from "../games/store.ts";
37 import { mayOnGame } from "../games/game_may.ts";
38 import { askingFor } from "./page_may.ts";
39 import { getPinned } from "../core/pinned.ts";
3440 import { LOG_READER_CSS, logReaderJs } from "../web/log_reader.ts";
3541 import { terminalBlocksJs } from "../web/terminal_blocks.ts";
3642 import type { Ctx, Handler } from "./context.ts";
@@ -101,7 +107,7 @@ async function infraResource(ctx: Ctx): Promise<Response> {
101107 if (part === "explorer") return fragment(cloudBranch(tree, node), { request: ctx.request });
102108 // Git is read only when the File tab is what was asked for.
103109 const tab = tabOf(node, ctx.url.searchParams.get("tab"));
104 const game = node.container === undefined ? undefined : containerConsole(ctx, node.container.box, node.name);
110 const game = node.container === undefined ? undefined : containerConsole(ctx, node.container.box, node.name, cloudHref(node.path, tree.q, "logs"));
105111 // A container's live reader needs a role on its box; without one its last synced lines are shown, read only when asked.
106112 const logs = tab === "logs" && node.container !== undefined && game === undefined ? logsOfContainer(ctx.app.db, node.container) : undefined;
107113 const view = logs !== undefined ? { ...tree, logs } : tab !== "file" ? tree : { ...tree, files: await timePhaseAsync(ctx.request, "files", () => filesByNode(ctx.app, ctx.auth.user, tree.whole, tree.now)) };
@@ -363,6 +369,37 @@ async function infraMachine(ctx: Ctx): Promise<Response> {
363369 return flashTo(ctx, "/infra", gone.ok ? { tone: "success", message: retireWords(gone.value) } : { tone: "danger", message: gone.error });
364370 }
365371
372 // GET /infra/:name: a machine opens to what runs on it, its containers (and a Minecraft server is
373 // one of them). It is the machine's own place in the resource tree; one the cloud has not been
374 // read for is the tree's top.
375 function infraMachineOpen(ctx: Ctx): Response {
376 const denied = guard(ctx);
377 if (denied) return denied;
378 const p = getPinned(ctx.app.db, ctx.params.name ?? "");
379 const tree = treeOf(ctx);
380 if (p === undefined || tree === undefined) return notFoundPage(ctx);
381 const at = resourcesOf(tree.whole).find((n) => n.path[0] === p.target && n.path[1] === p.account && n.path.at(-1) === `machine:${p.remote}`);
382 return new Response(null, { status: 303, headers: { location: at === undefined ? "/infra" : cloudHref(at.path, tree.q) } });
383 }
384
385 // POST /infra/container/:box/:service/:act: Restart, Stop or Start a machine's container, as
386 // /games/:box/:service/power asks it, then back to the container. Same origin (readForm), and
387 // `may` decides: the operator of that container, and no one else.
388 async function infraContainerPower(ctx: Ctx): Promise<Response> {
389 const denied = guard(ctx);
390 if (denied) return denied;
391 const box = boxNamed(ctx.app.db, ctx.params.box ?? "");
392 const service = ctx.params.service ?? "";
393 const act = ctx.params.act ?? "";
394 if (box === undefined || !SERVICE_NAME.test(service) || !isContainerAct(act)) return notFoundPage(ctx);
395 if (!mayOnGame(ctx.app.db, askingFor(ctx), box.id, service, "operator")) return notFoundPage(ctx);
396 const form = await readForm(ctx, "rw");
397 if (form instanceof Response) return form;
398 const back = backOf(field(form, "back"), "/infra");
399 const asked = await askPower(ctx.app, ctx.auth.user, box, service, act);
400 return flashTo(ctx, back, asked.ok ? { message: `${act[0]!.toUpperCase()}${act.slice(1)} ${service}: asked. It shows on the container when the machine answers.` } : { tone: "danger", message: asked.error });
401 }
402
366403 // GET /infra/:name/ending: the offer to snapshot before End.
367404 function infraEnding(ctx: Ctx): Response {
368405 const denied = guard(ctx);
@@ -429,6 +466,8 @@ export function infraRoutes(router: Router<Handler>): void {
429466 router.add("POST", "/infra/record", infraRecord);
430467 router.add("POST", "/infra/rebuild", infraRebuild);
431468 router.add("POST", "/infra/projects", infraProjects);
469 router.add("GET", "/infra/:name", infraMachineOpen);
470 router.add("POST", "/infra/container/:box/:service/:act", infraContainerPower);
432471 router.add("GET", "/infra/:name/ending", infraEnding);
433472 router.add("GET", "/infra/:name/cloud", infraCloud);
434473 router.add("POST", "/infra/snapshot/:id/:act", infraSnapshot);
src/http/lazy_lists.ts +2
@@ -657,6 +657,8 @@ export const OPERATIONS_ROUTES = [
657657 ["POST", "/infra/record"],
658658 ["POST", "/infra/rebuild"],
659659 ["POST", "/infra/projects"],
660 ["GET", "/infra/:name"],
661 ["POST", "/infra/container/:box/:service/:act"],
660662 ["GET", "/infra/:name/ending"],
661663 ["GET", "/infra/:name/cloud"],
662664 ["POST", "/infra/snapshot/:id/:act"],
src/web/pages/container_power.ts added +38
@@ -0,0 +1,38 @@
1 /**
2 * A container's power buttons as Infrastructure draws them (#18487): Restart (Start while it is
3 * not running) and Stop, posting to `/infra/container/<machine>/<container>/<act>`, which sends the
4 * person back to the container they were on. The forms are the page's; what they ask is
5 * `askPower`, the same request /games and the terminal make.
6 */
7
8 import { html, type Html } from "../html.ts";
9 import { btn } from "../ui.ts";
10 import { mainPower } from "../../games/gist.ts";
11 import { refusesNow, type Power } from "../../games/power.ts";
12 import type { GameBox, GameService } from "../../games/store.ts";
13
14 /** The acts this route takes: the ones Infrastructure offers. */
15 export const CONTAINER_ACTS = ["start", "stop", "restart"] as const satisfies readonly Power[];
16 export type ContainerAct = (typeof CONTAINER_ACTS)[number];
17 export const isContainerAct = (act: string): act is ContainerAct => (CONTAINER_ACTS as readonly string[]).includes(act);
18
19 /** A return address is a container's own page: under /infra/-/, never another place. */
20 export const backOf = (raw: string, fallback: string): string => (/^\/infra\/-\/[^\s\\]*$/.test(raw) && !raw.includes("//") && !/\/\.\.(\/|$|\?)/.test(raw) ? raw : fallback);
outdated

Low: backOf accepts any /infra/-/ path including '..' segments; harmless today since it stays under /infra, but reject '/..' too, and cover a bad back with a test that checks the fallback for a path like /infra/-/../x.

21
22 const form = (box: GameBox, service: string, act: ContainerAct, back: string, label: string, variant: "primary" | "ghost"): Html =>
23 refusesNow(box, act)
24 ? btn(`${label}: held`, { type: "button", size: "sm", variant: "ghost", disabled: true, label: `${act} ${service}: held` })
25 : html`<form method="post" action="/infra/container/${box.name}/${service}/${act}">
26 <input type="hidden" name="back" value="${back}" />${btn(label, { size: "sm", variant, label: `${act} ${service}` })}
27 </form>`;
28
29 /**
30 * Restart (or Start) as the main button, Stop a tap further under More, as the game page keeps it.
31 */
32 export const containerPower = (box: GameBox, service: string, seen: GameService | undefined, back: string): Html => {
outdated

Principle 8 and 'one way': Stop is a bare ghost button beside Restart with no word on what it does to people on the server. The old menu kept Stop under More; if that was deliberate, say so in the docs. Otherwise keep it under More.

33 const main = mainPower(seen);
34 return html`<span class="game-power">${form(box, service, main, back, main === "start" ? "Start" : "Restart", "primary")}<details class="game-menu">
35 <summary aria-label="More for ${service}">More</summary>
36 <span class="row-fields">${form(box, service, "stop", back, "Stop", "ghost")}</span>
37 </details></span>`;
38 };
src/web/pages/games.ts +5 −3
@@ -73,6 +73,7 @@ import { mapPathOf, mapWords } from "../../games/map_words.ts";
7373 import { notFoundPage, pageHead, signInFirst } from "../chrome.ts";
7474 import { field, readForm, type Form } from "../form.ts";
7575 import { html, type Html } from "../html.ts";
76 import { containerPower } from "./container_power.ts";
7677 import { defaultKind } from "../../kinds/index.ts";
7778 import { answerAfter, gameLogAfter, gameLogAge, gameLogPage } from "../../logs/game.ts";
7879 import { ageWords } from "../../logs/page.ts";
@@ -539,10 +540,11 @@ function grantsBlock(ctx: Ctx, box: GameBox): Html {
539540
540541 /**
541542 * A game box's container as Infrastructure opens it (#17939): the service's own log reader and
542 * console, and its power buttons for an operator, the same parts /games/<box>/<service> draws.
543 * console, and its power buttons for an operator (posting to /infra, back to `back`), the same
544 * reader /games/<box>/<service> draws.
543545 * Undefined for someone with no role on it.
544546 */
545 export function containerConsole(ctx: Ctx, boxName: string, service: string): { readonly power: Html | null; readonly logs: Html } | undefined {
547 export function containerConsole(ctx: Ctx, boxName: string, service: string, back: string): { readonly power: Html | null; readonly logs: Html } | undefined {
546548 const box = boxNamed(ctx.app.db, boxName);
547549 if (box === undefined || !SERVICE_NAME.test(service)) return undefined;
548550 if (!mayOnGame(ctx.app.db, askingFor(ctx), box.id, service, "viewer")) return undefined;
@@ -551,7 +553,7 @@ export function containerConsole(ctx: Ctx, boxName: string, service: string): {
551553 const blocks = serviceBlocks(ctx.app, box.id, service, act);
552554 const seen = servicesOf(ctx.app.db, box.id).find((s) => s.name === service);
553555 return {
554 power: act ? power(box, service, seen) : null,
556 power: act ? containerPower(box, service, seen, back) : null,
555557 logs: html`<p class="game-now" aria-live="polite">${nowWords(seen, powerNow(ctx.app.db, box.id, service))}</p>
556558 ${logReader(logViewOf(ctx.url, base, service), gameLogPage(ctx.app.db, box.id, service), gameLogAge(ctx.app.db, box.id, service), {
557559 stream: `${base}/stream`,
test/cloud-containers.test.ts +56 −2
@@ -278,9 +278,63 @@ test("the page: the machine's row opens, its pane lists them, and one container
278278 const hub = await get(HUB);
279279 expect(hub).toContain('<a href="/games/mc/hub">');
280280 expect(hub).toContain("Its cost is inside its machine&#39;s.");
281 // An operator's power buttons on every tab: the game page's own, which ask first when someone is on.
281 // An operator's Restart and Stop on every tab, posted to /infra and back to the container.
282282 const own = hub.split('id="code-pane"')[1]!.split("</section>")[0]!;
283 expect(own).toContain('action="/games/mc/hub/power"');
283 expect(own).toContain('action="/infra/container/mc/hub/restart"');
284 expect(own).toContain('action="/infra/container/mc/hub/stop"');
285 expect(own.indexOf("More for hub")).toBeLessThan(own.indexOf('action="/infra/container/mc/hub/stop"'));
286 expect(own).toContain('value="/infra/-/hetzner/eu/games/machine:77/container:hub?tab=logs"');
287 });
288
289 const postForm = (path: string, body: string, who: User, origin = servers.url): Promise<Response> =>
290 fetch(`${servers.url}${path}`, { method: "POST", redirect: "manual", headers: { cookie: `forge_session=${createSession(app.db, who.id).token}`, origin, "content-type": "application/x-www-form-urlencoded" }, body });
291 const queued = (): string[] => app.db.query<{ kind: string }, []>("SELECT kind FROM game_command ORDER BY rowid").all().map((r) => r.kind);
292
293 test("/infra/<machine> opens the machine in the tree, to its containers (#18487)", async () => {
294 const res = await fetch(`${servers.url}/infra/mc`, { redirect: "manual", headers: { cookie: `forge_session=${createSession(app.db, alice.id).token}` } });
295 expect(res.status).toBe(303);
296 expect(res.headers.get("location")).toBe("/infra/-/hetzner/eu/games/machine:77");
297 const none = await fetch(`${servers.url}/infra/nobody`, { headers: { cookie: `forge_session=${createSession(app.db, alice.id).token}` } });
298 expect(none.status).toBe(404);
299 expect((await fetch(`${servers.url}/infra/mc`, { redirect: "manual", headers: { cookie: `forge_session=${createSession(app.db, bob.id).token}` } })).status).toBeGreaterThanOrEqual(403);
300 });
301
302 test("/infra/<machine> for a machine the cloud has not been read for goes to the tree's top", async () => {
303 app.db.run("UPDATE pinned_forge SET remote = 'other' WHERE name = 'mc'");
304 const res = await fetch(`${servers.url}/infra/mc`, { redirect: "manual", headers: { cookie: `forge_session=${createSession(app.db, alice.id).token}` } });
305 app.db.run("UPDATE pinned_forge SET remote = '77' WHERE name = 'mc'");
306 expect(res.status).toBe(303);
307 expect(res.headers.get("location")).toBe("/infra");
308 });
309
310 test("Start, a held box's disabled button, and a back with .. segments (#18487)", async () => {
311 app.db.run("DELETE FROM game_command");
312 sync({ ...SYNC, services: SYNC.services!.map((s) => (s.name === "hub" ? { ...s, state: "exited" } : s)) });
313 expect(await get(HUB)).toContain('action="/infra/container/mc/hub/start"');
314 const sent = await postForm("/infra/container/mc/hub/start", `back=${encodeURIComponent("/infra/-/../x")}`, alice);
315 expect(sent.headers.get("location")).toStartWith("/infra");
316 expect(sent.headers.get("location")).not.toContain("..");
317 expect(queued()).toEqual(["start"]);
318 sync({ ...SYNC, diag: { hold: { why: "mount", since: new Date().toISOString() } } } as SyncBody);
319 const held = (await get(HUB)).split('id="code-pane"')[1]!.split("</section>")[0]!;
320 expect(held).not.toContain('action="/infra/container/mc/hub/restart"');
321 expect(held).toContain("held");
322 sync();
323 });
324
325 test("Restart and Stop from the container page: same origin, an operator's, queued as /games queues them (#18487)", async () => {
326 app.db.run("DELETE FROM game_command");
327 const back = encodeURIComponent("/infra/-/hetzner/eu/games/machine:77/container:hub?tab=logs");
328 const sent = await postForm("/infra/container/mc/hub/restart", `back=${back}`, alice);
329 expect(sent.status).toBe(303);
330 expect(sent.headers.get("location")).toStartWith("/infra/-/hetzner/eu/games/machine:77/container:hub");
331 expect((await postForm("/infra/container/mc/hub/stop", "back=https%3A%2F%2Fevil.test%2F", alice)).headers.get("location")).toStartWith("/infra");
332 expect(queued()).toEqual(["restart", "stop"]);
333 // Another origin, an act it does not take, and someone with no operator role change nothing.
334 expect((await postForm("/infra/container/mc/hub/restart", "", alice, "https://evil.test")).status).toBe(403);
335 expect((await postForm("/infra/container/mc/hub/pull", "", alice)).status).toBe(404);
336 expect((await postForm("/infra/container/mc/hub/stop", "", bob)).status).toBeGreaterThanOrEqual(403);
337 expect(queued()).toEqual(["restart", "stop"]);
284338 });
285339
286340 test("the terminal: the same rows and facts, by keys", async () => {

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs