Public: anyone can read this; the crew can change it.
The shell refuses -f only where it follows, and a refused command is in its list #17792
Merged 9h 32m ago, live in production
sold/shell-refusals-2 → main 0 commits 1 thread · 1 unresolved
4 files
changed +140
−13
docs/features/game-box.md +1 −1
| @@ -38,7 +38,7 @@ experiment. | ||
| 38 | 38 | - **DNS:** an A record, not proxied, for the box's `host` in any Cloudflare zone a connected token can write; with none, the plan says to set it by hand. |
| 39 | 39 | |
| 40 | 40 | Code: `src/games/store.ts` (the `game_box` row and its token, the games store's), `src/games/boot.ts` (the boot config), `src/games/agent.sh`, `gameWant` in `src/actions/infra.ts`, and `bootRow` in `src/actions/pinned.ts`. |
| 41 | - **Console (owner only):** `/games/<box>` has a Console for the box's owner (forge admins are owners): a command is queued like an rcon (`kind: "shell"`, no service), and the agent runs it with `bash -lc` under `capped`, beside the sync: at most 30 s, no terminal and no input, at most 16 KB of output back at the next sync, streamed into the console over the box's own sync. It runs as root (the agent's unit names no user), and both doors say so. Each command is a block (`src/terminal/blocks.ts`): what was typed, its state in words (waiting, the box has it, done, failed, no answer came back) and what it printed; the page replaces a block in place as its state changes, and up and down in the input walk the commands of the blocks on the page, each once; a block's Edit puts its command in the input, for a phone with no arrows. Each answer keeps the last line of its service's log that the forge held when it was recorded (`game_command.after_log`, 0 for none, null for one from before it was kept), sent as `after` in the stream's `blocks` event, so a reader can place it among the lines. A program that waits on a person (an editor, a pager, `top`, a bare shell or REPL, a `-f` follow) is refused before it is queued, saying what to run instead. Every command (`game.shell.asked`) and its output (`game.shell.done`) go to the audit, the owner's to read, so a secret a command prints stays there: one line at the input says it. In the terminal, `!` on a box's row opens the same console (`:` runs a command). `src/games/shell.ts`. | |
| 41 | - **Console (owner only):** `/games/<box>` has a Console for the box's owner (forge admins are owners): a command is queued like an rcon (`kind: "shell"`, no service), and the agent runs it with `bash -lc` under `capped`, beside the sync: at most 30 s, no terminal and no input, at most 16 KB of output back at the next sync, streamed into the console over the box's own sync. It runs as root (the agent's unit names no user), and both doors say so. Each command is a block (`src/terminal/blocks.ts`): what was typed, its state in words (waiting, the box has it, done, failed, no answer came back) and what it printed; the page replaces a block in place as its state changes, and up and down in the input walk the commands of the blocks on the page, each once; a block's Edit puts its command in the input, for a phone with no arrows. Each answer keeps the last line of its service's log that the forge held when it was recorded (`game_command.after_log`, 0 for none, null for one from before it was kept), sent as `after` in the stream's `blocks` event, so a reader can place it among the lines. A program that waits on a person (an editor, a pager, `top`, a bare shell or REPL, a `-f` follow) is refused before it is queued, saying what to run instead, in the notice and as a block of the list (`docker … -f` only with `logs`: elsewhere it is a format, a filter or a file; what runs inside an `exec`, a `run` or `sh -c` is looked at the same way). A refused command never reaches the box or the audit, but the forge keeps its text (up to 1,000 characters, a secret typed into it too) in `game_command` for 30 days, like any answered command's; only this list shows it, to the box's owner. Every command (`game.shell.asked`) and its output (`game.shell.done`) go to the audit, the owner's to read, so a secret a command prints stays there: one line at the input says it. In the terminal, `!` on a box's row opens the same console (`:` runs a command). `src/games/shell.ts`. | |
| 42 | 42 | |
| 43 | 43 | - **Spare while servers sleep (#17576):** `/games/<box>` has two `dl` rows (the `status-rows` of the security page), and the terminal's box screen (`b` on a service) the same two as its first line: "Spare while servers sleep: N core-hours a week, M GB (samples of 7 days). Forge checks, same week: C core-hours." (`src/games/spare.ts`, read by `spare_row.ts`, which keeps the pair a minute per box so a redraw or reload reads nothing). Spare memory = the box's memory − what is awake − a reserve that always fits the largest sleeping server (its highest memory seen awake in the window); spare core-hours = the idle cores (the box's vCPUs − awake servers' CPU, 100 % being a core) of each minute a server sleeps, scaled from the minutes sampled to a week. A box with everything awake has 0. Fewer than 24 hours of samples, or a size or sleeper's memory not known, says "unknown", never 0. The checks' figure is the `cpu_s` of the cost ledger's `check` entries that ended in the last 7 days (read from the end of the month files, stopping at the window's start, at most 4 MiB, not walking the chain; "not measured" when none carried it). A server counts as asleep in a minute that it held no memory. |
| 44 | 44 | - **Run checks while servers sleep (#17577):** the box's owner (forge admins own every box) sees a switch on `/games/<box>` (`POST /games/<box>/lend`, same-origin) and as `l` on the terminal's box screen, off by default, in the same words (`src/games/lend.ts`). Switching it on enrols a scoped `lent-box-<name>` runner for the box ([](lent-runners.md)); switching it off revokes it at once. Its authors are the people who write the box's repository (its owner, teams and crew), read at each claim (a writer removed later is out at once), never a box owner who does not write it; a box with none names nobody, never anyone. The runner's token is not kept: it is held in the forge's memory until the box's next sync carries it over, once (see below). |
src/games/shell.ts +64 −11
| @@ -10,7 +10,7 @@ | ||
| 10 | 10 | import type { App } from "../app.ts"; |
| 11 | 11 | import type { User } from "../core/users.ts"; |
| 12 | 12 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 13 | import { commandOf, mayDo, queueCommand, roleOn, type GameBox } from "./store.ts"; | |
| 13 | import { commandOf, keepRefused, mayDo, queueCommand, roleOn, type GameBox } from "./store.ts"; | |
| 14 | 14 | |
| 15 | 15 | /** Shell commands are the box's: they carry this service, which no compose service can have. */ |
| 16 | 16 | export const SHELL_SERVICE = ""; |
| @@ -62,25 +62,74 @@ const REPLS = new Set([ | ||
| 62 | 62 | "rcon-cli", |
| 63 | 63 | ]); |
| 64 | 64 | |
| 65 | /** Docker's and kubectl's options before the subcommand that take the next word: `docker compose -f x.yml logs`. */ | |
| 66 | const TAKES_A_WORD = /^(-[fpcHnl]|--(file|project-name|project-directory|profile|env-file|context|host|config|log-level|namespace|kubeconfig|cluster|user))$/; | |
| 67 | ||
| 68 | /** Options of `exec` and `run` with no word after them; any other takes the next word, unless it carries its value. */ | |
| 69 | const ALONE = /^(-[ditPqT]+|--(detach|interactive|tty|stdin|rm|init|privileged|publish-all|read-only|quiet|quiet-pull|no-deps|no-TTY|service-ports|use-aliases|build|remove-orphans))$/; | |
| 70 | const takesNext = (w: string): boolean => !ALONE.test(w) && (w.startsWith("--") ? !w.includes("=") : /^-[ditPqT]*[a-zA-Z]$/.test(w)); | |
| 71 | ||
| 72 | /** The words from the program on: without the assignments, `sudo` and `exec` before it. */ | |
| 73 | function programOf(words: readonly string[]): string[] { | |
| 74 | const at = words.findIndex((w) => !/^[A-Za-z_][A-Za-z0-9_]*=/.test(w) && w !== "sudo" && w !== "exec"); | |
| 75 | return at === -1 ? [] : words.slice(at); | |
| 76 | } | |
| 77 | const nameOf = (words: readonly string[]): string => (words[0] ?? "").split("/").at(-1) ?? ""; | |
| 78 | ||
| 79 | /** What `docker exec`, `docker run`, compose's and kubectl's run inside: the words after the container. */ | |
| 80 | function inside(words: readonly string[], kubectl: boolean): readonly string[] { | |
| 81 | const dashes = kubectl ? words.indexOf("--") : -1; | |
| 82 | if (dashes !== -1) return words.slice(dashes + 1); | |
| 83 | let i = 0; | |
| 84 | const skip = () => { | |
| 85 | while (words[i]?.startsWith("-") === true) i += takesNext(words[i]!) ? 2 : 1; | |
| 86 | }; | |
| 87 | skip(); | |
| 88 | i++; | |
| 89 | if (kubectl) skip(); | |
| 90 | return words.slice(i); | |
| 91 | } | |
| 92 | ||
| 93 | /** | |
| 94 | * Whether a command follows: `tail -f`, `journalctl -f`, the `logs -f` of docker, compose and | |
| 95 | * kubectl, and any of these inside an `exec`, a `run` or a shell's `-c`. With another subcommand | |
| 96 | * `-f` is a format, a filter or a file. | |
| 97 | */ | |
| 98 | function follows(line: readonly string[]): boolean { | |
| 99 | const words = programOf(line); | |
| 100 | const head = nameOf(words); | |
| 101 | if (head === "tail" || head === "journalctl") return words.some((w) => w === "-f" || w === "--follow" || (head === "tail" && /^-[a-zA-Z]*f[a-zA-Z]*$/.test(w))); | |
| 102 | if (head === "bash" || head === "sh") { | |
| 103 | const c = words.findIndex((w) => /^-[a-z]*c$/.test(w)); | |
| 104 | return c !== -1 && follows(words.slice(c + 1)); | |
| 105 | } | |
| 106 | if (head !== "docker" && head !== "docker-compose" && head !== "kubectl") return false; | |
| 107 | let i = 1; | |
| 108 | while (i < words.length) { | |
| 109 | const w = words[i]!; | |
| 110 | if (w.startsWith("-")) i += TAKES_A_WORD.test(w) ? 2 : 1; | |
| 111 | else if (["compose", "container", "service"].includes(w)) i++; | |
| 112 | else break; | |
| 113 | } | |
| 114 | const rest = words.slice(i + 1); | |
| 115 | if (words[i] === "logs") return rest.some((w) => /^(-[tp]*f[a-z]*|--follow(=true)?)$/.test(w)); | |
| 116 | return (words[i] === "exec" || words[i] === "run") && follows(inside(rest, head === "kubectl")); | |
| 117 | } | |
| 118 | ||
| 65 | 119 | /** Why a command would wait on a person, or undefined when it runs and ends by itself. */ |
| 66 | 120 | export function shellRefusal(text: string): string | undefined { |
| 67 | 121 | const line = text.trim(); |
| 68 | 122 | if (line === "") return "Type a command."; |
| 69 | 123 | if (line.length > 1_000) return "A command is at most 1,000 characters."; |
| 70 | 124 | for (const part of line.split(/&&|\|\||;|\|/)) { |
| 71 | const words = part | |
| 72 | .trim() | |
| 73 | .split(/\s+/) | |
| 74 | .filter((w) => !/^[A-Za-z_][A-Za-z0-9_]*=/.test(w) && w !== "sudo" && w !== "exec"); | |
| 75 | const head = (words[0] ?? "").split("/").at(-1) ?? ""; | |
| 125 | const words = programOf(part.trim().split(/\s+/)); | |
| 126 | const head = nameOf(words); | |
| 76 | 127 | if (INTERACTIVE.has(head)) |
| 77 | 128 | return `${head} waits on a person, and the console has no terminal: run something that ends by itself (cat, head, ps, df).`; |
| 78 | 129 | if (REPLS.has(head) && words.length === 1) |
| 79 | 130 | return `${head} alone waits for input: give it something to run (${head === "bash" || head === "sh" ? `${head} -c '…'` : `${head} -c '…' or a file`}).`; |
| 80 | if ( | |
| 81 | (head === "tail" || head === "journalctl" || head === "docker" || head === "kubectl") && | |
| 82 | words.some((w) => w === "-f" || w === "--follow" || (/^-[a-zA-Z]*f[a-zA-Z]*$/.test(w) && head === "tail")) | |
| 83 | ) | |
| 131 | // Quotes are only dropped to look: `sh -c 'tail -f x'`. | |
| 132 | if (follows(words.map((w) => w.replace(/['"]/g, "")))) | |
| 84 | 133 | return "Following never ends, and a command here stops at 30 s: drop -f, or ask for the last lines (-n 100)."; |
| 85 | 134 | } |
| 86 | 135 | return undefined; |
| @@ -90,7 +139,11 @@ export function shellRefusal(text: string): string | undefined { | ||
| 90 | 139 | export function queueShell(app: App, actor: User | undefined, box: GameBox, text: string): Result<string, string> { |
| 91 | 140 | if (actor === undefined || !mayDo(roleOn(app.db, actor, box.id), "owner")) return err("Only the box's owner runs a shell on it."); |
| 92 | 141 | const refused = shellRefusal(text); |
| 93 | if (refused !== undefined) return err(refused); | |
| 142 | if (refused !== undefined) { | |
| 143 | // In the owner's list like any other answer, with why, and as long; the box and the audit never get it. | |
| 144 | if (text.trim() !== "") keepRefused(app.db, box.id, SHELL_SERVICE, "shell", text.trim(), actor.id, `Not sent to the box: ${refused}`); | |
| 145 | return err(refused); | |
| 146 | } | |
| 94 | 147 | const id = queueCommand(app.db, box.id, SHELL_SERVICE, "shell", text.trim(), actor.id); |
| 95 | 148 | app.bus.append({ kind: "game.shell.asked", actorId: actor.id, payload: { box: box.name, command: id, text: text.trim() } }); |
| 96 | 149 | return ok(id); |
src/games/store.ts +7
| @@ -352,6 +352,13 @@ export function queueCommand(db: Database, boxId: string, service: string, kind: | ||
| 352 | 352 | return id; |
| 353 | 353 | } |
| 354 | 354 | |
| 355 | /** A command refused before it was queued, kept as a failed one that says why: never in the queue, so never handed out. */ | |
| 356 | export function keepRefused(db: Database, boxId: string, service: string, kind: CommandKind, text: string, by: string, why: string): void { | |
| 357 | db.query( | |
| 358 | "INSERT INTO game_command (id, box_id, service, kind, text, by, created_at, handed_at, done_at, ok, output) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?7, ?7, 0, ?8)", | |
| 359 | ).run(newId(), boxId, service, kind, text.slice(0, 1_000), by, new Date().toISOString(), why); | |
| 360 | } | |
| 361 | ||
| 355 | 362 | /** The most lines one reply in game has. */ |
| 356 | 363 | export const LINES_OUT = 6; |
| 357 | 364 |
test/game-console.test.ts +68 −1
| @@ -15,7 +15,8 @@ import { requestConsole } from "../src/cloud/provider_console.ts"; | ||
| 15 | 15 | import { createSession } from "../src/core/sessions.ts"; |
| 16 | 16 | import { createUser, type User } from "../src/core/users.ts"; |
| 17 | 17 | import { queueShell, shellRefusal } from "../src/games/shell.ts"; |
| 18 | import { boxNamed, commandOf, createGameBox, grant, rotateGameBoxToken } from "../src/games/store.ts"; | |
| 18 | import { pruneGameCommands } from "../src/system/retention_games.ts"; | |
| 19 | import { boxNamed, commandOf, createGameBox, grant, recentCommands, recordSync, rotateGameBoxToken } from "../src/games/store.ts"; | |
| 19 | 20 | import { serve, type Servers } from "../src/http/server.ts"; |
| 20 | 21 | import { createForgeApp } from "../src/tui/forge.ts"; |
| 21 | 22 | import { gameShellScreen } from "../src/tui/screens/games.ts"; |
| @@ -41,6 +42,51 @@ describe("what the console refuses", () => { | ||
| 41 | 42 | expect(shellRefusal("python3 -c 'print(1)'")).toBeUndefined(); |
| 42 | 43 | expect(shellRefusal(" ")).toBe("Type a command."); |
| 43 | 44 | }); |
| 45 | ||
| 46 | test.each([ | |
| 47 | "docker logs -f hub", | |
| 48 | "docker logs --follow hub", | |
| 49 | "docker logs -tf hub", | |
| 50 | "docker container logs -f hub", | |
| 51 | "docker service logs -f hub", | |
| 52 | "docker compose logs -f hub", | |
| 53 | "docker compose -f /opt/forge-game/compose.yml logs -f hub", | |
| 54 | "docker-compose logs -f", | |
| 55 | "kubectl logs -f pod/hub", | |
| 56 | "kubectl -n games logs --follow=true hub", | |
| 57 | "docker exec hub tail -f x", | |
| 58 | "docker exec -it -u root hub tail -f x", | |
| 59 | "docker exec -e A=b hub tail -n 5 -f x", | |
| 60 | "docker exec hub journalctl -f", | |
| 61 | "docker exec hub sh -c 'tail -f x'", | |
| 62 | "docker compose -f /opt/forge-game/compose.yml exec -T hub tail -f x", | |
| 63 | "docker run --rm -v /srv:/srv alpine tail -f /srv/x", | |
| 64 | "kubectl exec pod -- tail -f x", | |
| 65 | "kubectl exec pod -c hub -- journalctl -f", | |
| 66 | "sudo docker exec hub tail -f x", | |
| 67 | ])("%s follows, and is refused", (line) => { | |
| 68 | expect(shellRefusal(line)).toStartWith("Following never ends"); | |
| 69 | }); | |
| 70 | ||
| 71 | test.each([ | |
| 72 | 'docker inspect -f "{{.State.Status}}" hub', | |
| 73 | "docker ps -f name=hub", | |
| 74 | "docker rm -f old", | |
| 75 | "docker compose -f /opt/forge-game/compose.yml ps", | |
| 76 | "docker compose -f logs ps", | |
| 77 | "docker compose -f /opt/forge-game/compose.yml logs --tail 20 hub", | |
| 78 | "docker logs --tail 20 hub", | |
| 79 | "docker exec hub ls logs -f", | |
| 80 | "docker exec hub tail -n 5 x", | |
| 81 | "docker exec -w /f hub rm -f tail", | |
| 82 | "docker exec hub sh -c 'rm -f x'", | |
| 83 | "docker run --rm alpine rm -f tail", | |
| 84 | "kubectl exec pod -- rm -f x", | |
| 85 | "kubectl get -f pod.yml", | |
| 86 | "kubectl logs --follow=false hub", | |
| 87 | ])("%s ends by itself, and runs", (line) => { | |
| 88 | expect(shellRefusal(line)).toBeUndefined(); | |
| 89 | }); | |
| 44 | 90 | }); |
| 45 | 91 | |
| 46 | 92 | describe("on a forge", () => { |
| @@ -93,6 +139,12 @@ describe("on a forge", () => { | ||
| 93 | 139 | ok: false, |
| 94 | 140 | error: expect.stringContaining("less waits on a person"), |
| 95 | 141 | }); |
| 142 | // The refused one is in the list with why, and the box is never handed it. | |
| 143 | expect(recentCommands(app.db, box.id, "")).toEqual([ | |
| 144 | expect.objectContaining({ text: "less /etc/os-release", done: true, ok: false, output: expect.stringContaining("Not sent to the box: less waits on a person") }), | |
| 145 | ]); | |
| 146 | expect(recordSync(app.db, box, { light: true })).toEqual([]); | |
| 147 | expect(events("game.shell.asked")).toEqual([]); | |
| 96 | 148 | const queued = queueShell(app, alice, box, "df -h /"); |
| 97 | 149 | if (!queued.ok) throw new Error(queued.error); |
| 98 | 150 | expect(commandOf(app.db, queued.value)).toMatchObject({ kind: "shell", service: "", text: "df -h /" }); |
| @@ -150,6 +202,21 @@ describe("on a forge", () => { | ||
| 150 | 202 | expect(text).toContain("$ df -h /"); |
| 151 | 203 | expect(text).toContain("$ cat /var/log/big"); |
| 152 | 204 | }); |
| 205 | ||
| 206 | test("a refused command's text: the owner's list alone shows it, the audit has none of it, and it goes after 30 days", async () => { | |
| 207 | const box = boxNamed(app.db, "mc")!; | |
| 208 | expect(queueShell(app, alice, box, "less typed-secret-7").ok).toBe(false); | |
| 209 | const id = recentCommands(app.db, box.id, "").find((c) => c.text === "less typed-secret-7")!.id; | |
| 210 | const page = async (who: User, path: string) => | |
| 211 | (await fetch(`${servers.url}${path}`, { headers: { cookie: `forge_session=${createSession(app.db, who.id).token}` } })).text(); | |
| 212 | expect(await page(alice, "/games/mc")).toContain("typed-secret-7"); | |
| 213 | expect(await page(bob, "/games/mc")).not.toContain("typed-secret-7"); | |
| 214 | expect(app.db.query("SELECT kind FROM event WHERE payload LIKE '%typed-secret-7%'").all()).toEqual([]); | |
| 215 | pruneGameCommands(app.db, Date.now() + 29 * 86_400_000); | |
| 216 | expect(commandOf(app.db, id)).toBeDefined(); | |
| 217 | pruneGameCommands(app.db, Date.now() + 31 * 86_400_000); | |
| 218 | expect(commandOf(app.db, id)).toBeUndefined(); | |
| 219 | }); | |
| 153 | 220 | }); |
| 154 | 221 | |
| 155 | 222 | describe("the agent", () => { |
new above
offline
Only
logsis checked, sodocker exec <c> tail -f xanddocker exec <c> journalctl -fnow run and hang to the 30 s cap; the old code refused them. Also refuse a follow flag on atail/journalctlafterexec/run, with a test.