diff --git a/pm-stack/console/README.md b/pm-stack/console/README.md index 2d4f66cbf0..55b2f3953b 100644 --- a/pm-stack/console/README.md +++ b/pm-stack/console/README.md @@ -162,6 +162,10 @@ bun run scripts/demo.ts # the app with made-up state, on this host alon bun run scripts/edge-demo.ts # the same behind the edge ``` +The app's own switches for what this script sets up are under More: +Sign-in (the Google client) and Laptop away (whether Cloudflare acts +by itself while the laptop cannot be reached; see edge/README.md). + The owner's address is given once with `--owner` and remembered in the console's environment file; it is not written in the script. diff --git a/pm-stack/console/edge/README.md b/pm-stack/console/edge/README.md index d407230f4f..52ca30e5f9 100644 --- a/pm-stack/console/edge/README.md +++ b/pm-stack/console/edge/README.md @@ -81,7 +81,11 @@ laptop: pm-console (../src/server.ts), reporting through ../src/sync.ts `via: edge-held` with who took it and when. Three secrets are optional, put there by the laptop's -`scripts/expose.py --edge-direct on` (off by default, remembered): +`scripts/expose.py --edge-direct on` (off by default, remembered). The +owner turns it on and off in the app, under More, Laptop away, which +runs that script on the laptop; `--edge-direct off` takes the two +tokens away again. They travel through Cloudflare's API with the token +the script already holds, so nothing is installed on the laptop for it: `GITHUB_TOKEN` (the repository automation token), `QUEUE_TOKEN` (the queue store token), and `EDGE_DIRECT`, the explicit opt-in that must read `on` for either to be used. With them, the edge reads the board, diff --git a/pm-stack/console/public/app.js b/pm-stack/console/public/app.js index ad5503f0e2..1bf7a2a36d 100644 --- a/pm-stack/console/public/app.js +++ b/pm-stack/console/public/app.js @@ -835,6 +835,7 @@ function viewMore() { tile("more/notify", "Notifications", "choose what reaches this device"), tile("more/phone", "Phones", "the Android app and its home-screen widget"), tile("more/signin", "Sign-in", "Google first, the emailed code as the fallback"), + tile("more/away", "Laptop away", "what Cloudflare does by itself when the laptop cannot be reached"), ), ]; for (const g of ops.more || []) { @@ -984,6 +985,99 @@ function collectUrl() { /** Sign-in: what is on, and the one part only the owner can do to put * Google first. Google lets nobody but a signed-in person make the * client its sign-in runs on; everything after that is done here. */ +/** What the edge says of acting by itself, read from its public health + * answer. `served` is false when the app is coming straight from the + * laptop and there is no edge to ask. */ +export function awayState(health) { + if (!health || health.edge !== true) return { served: false }; + const kinds = health.selfCheck?.kinds || {}; + const names = { board: "The board", prs: "Pull requests", priorities: "Ranked issues", asks: "Your prompts" }; + return { + served: true, + on: health.directEnabled === true, + // On, and holding both tokens with a laptop new enough to have said + // where things are: it will act once the laptop has been quiet. + ready: health.directEnabled === true && health.directReady === true, + checkedAt: typeof health.selfCheck?.at === "number" ? health.selfCheck.at : null, + checks: Object.keys(names) + .filter((kind) => kinds[kind]) + .map((kind) => ({ what: names[kind], ok: kinds[kind].ok === true, error: String(kinds[kind].error || "") })), + }; +} + +/** Laptop away: whether Cloudflare acts by itself when the laptop cannot + * be reached, what that covers, and the switch. The switch is the + * owner's because turning it on hands the Worker two of his tokens. */ +async function viewAway() { + let health = null; + try { + const res = await fetch("/console/health", { cache: "no-store" }); + health = res.ok ? await res.json() : null; + } catch { + health = null; + } + const s = awayState(health); + if (!s.served) { + return [ + card( + h("h3", {}, "The app is coming straight from the laptop"), + h("p", { class: "meta" }, "It is not being served from Cloudflare right now, so nothing there can act while the laptop is away."), + ), + ]; + } + const flip = async (e) => { + const done = await act( + "edge.direct", + { on: !s.on }, + s.on ? "Cloudflare no longer acts by itself" : "Cloudflare will act while the laptop is away", + e.target, + ); + if (!done) return; + // The Worker restarts with what it was given; ask it again shortly. + await new Promise((resolve) => setTimeout(resolve, 5000)); + draw(); + }; + const checked = s.on + ? s.checks.length > 0 + ? h( + "ul", + { class: "plain" }, + s.checks.map((c) => h("li", {}, `${c.what}: ${c.ok ? "read from Cloudflare" : `could not be read (${c.error || "no reason given"})`}`)), + ) + : h("p", { class: "meta" }, "Not tried yet. It tries one read of each kind within a minute of being turned on.") + : null; + return [ + card( + h("h3", {}, s.on ? "Cloudflare acts by itself while the laptop is away" : "While the laptop is away, Cloudflare only waits"), + h( + "p", + { class: "meta" }, + s.on + ? s.ready + ? "It starts once the laptop has been quiet for a minute, and stops when the laptop reports again." + : "It is on, but the Worker does not have everything it needs yet. Turning it off and on again gives it the tokens afresh." + : "The app still opens and shows what the laptop last reported. What you send is kept and done when the laptop is back.", + ), + checked, + s.on && s.checkedAt ? h("p", { class: "meta" }, `Tried ${ago(new Date(s.checkedAt).toISOString())}.`) : null, + ), + h("h2", {}, s.on ? "Turn it off" : "Turn it on"), + card( + h( + "p", + { class: "meta" }, + "On, Cloudflare reads the board, pull requests, ranked issues and your prompts itself, and does these at once: reply to or close a prompt, comment, rank an issue, move a task. A new prompt is filed at once and queued for the fleet when the laptop is back.", + ), + h( + "p", + { class: "meta" }, + "Turning it on gives the Worker two tokens from your secret store: the repository automation token and the queue store token. They are kept as the Worker's secrets in your Cloudflare account. Turning it off takes them away again. The laptop has to be reachable for either.", + ), + h("div", { class: "row end" }, h("button", { class: s.on ? "ghost" : "", onclick: flip }, s.on ? "Turn off" : "Turn on")), + ), + ]; +} + async function viewSignin() { let s; try { @@ -1399,6 +1493,7 @@ const VIEWS = { "more/notify": ["Notifications", viewNotify], "more/phone": ["Phones", viewPhone], "more/signin": ["Sign-in", viewSignin], + "more/away": ["Laptop away", viewAway], }; let route = "now"; let drawSeq = 0; diff --git a/pm-stack/console/scripts/expose.py b/pm-stack/console/scripts/expose.py index f398602240..123c73ea6c 100755 --- a/pm-stack/console/scripts/expose.py +++ b/pm-stack/console/scripts/expose.py @@ -36,10 +36,13 @@ to act itself while the laptop is away (the repository automation token and the queue store token) and the explicit opt-in that lets it use them. Off by default, remembered like `--edge`, and nothing is - uploaded on a run that does not change the choice. Turning it off - turns the opt-in off; the tokens stay on the Worker, inert without - it. The Worker says in /console/health whether the flag is on and - whether each token is there. + uploaded on a run that does not change the choice (unless the Worker + has lost one of them, and then it gets them again). Turning it off + turns the opt-in off and takes the two tokens away again. They go + through Cloudflare's API with the token this script already holds, so + nothing has to be installed here for it. The Worker says in + /console/health whether the flag is on and whether each token is + there. The gate comes first and the routes last, so the origin is never reachable without sign-in in front of it. If the console does not come @@ -68,18 +71,18 @@ --edge-direct on let the edge Worker act itself while the laptop is away: upload the GitHub and queue tokens and turn the opt-in - on; remembered by later runs until --edge-direct off. - Off by default. + on; remembered by later runs until --edge-direct off, + which also takes the tokens away. Off by default. """ from __future__ import annotations import argparse +import contextlib +import fcntl import json -import os import pathlib import re -import shutil import subprocess import sys import time @@ -119,6 +122,21 @@ QUEUE_TOKEN_DEFAULT = "turso.fleet-queue-rw-token" +@contextlib.contextmanager +def one_at_a_time(state: pathlib.Path): + """Hold this for a run that may change something: a second run waits + for the first. The timer's run and one started from the app would + otherwise each read what is so, then both act on it (one deleting a + token the other has just uploaded).""" + state.mkdir(parents=True, exist_ok=True, mode=0o700) + with open(state / "expose.lock", "w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + try: + yield + finally: + fcntl.flock(lock, fcntl.LOCK_UN) + + def secret(name: str) -> str: return subprocess.run( ["fleet", "secrets", "get", name], capture_output=True, text=True, check=False @@ -259,62 +277,56 @@ def ensure_edge_direct( check: bool, ) -> None: """Upload the two tokens the edge Worker acts with, and its opt-in, - or turn the opt-in off. Nothing is uploaded on a run that does not - change the choice, so the timer's runs leave the secrets alone. - A secret is read by name through `fleet secrets get` and piped to - `wrangler secret put`; it is never printed or written to a file. - The choice is remembered only after the Worker has it: a run that - fails part-way leaves the old marker, so the next run tries again - instead of assuming the mode is already set.""" + or turn the opt-in off and take the tokens away again. + + A secret is read by name through `fleet secrets get` and sent to + Cloudflare's API as a Worker secret; it is never printed, written to + a file or put on a command line. + + The choice is remembered only once the Worker has it. Turning it on + either gets all three there or leaves none: an attempt that fails + part-way takes away what it uploaded. Turning it off puts the opt-in + off first, so the Worker stops at once, and then removes the tokens; + if that stops part-way the mode is still off and a later run + finishes. A run that changes nothing uploads nothing, with one + exception: a mode that is on gets back whatever the Worker has lost.""" state = env.parent - # Read what is remembered before the choice overwrites it: only a - # change uploads anything. Nothing is written here: the marker moves - # only once the remote changes below have succeeded. + # Read what is remembered before the choice overwrites it. Nothing is + # written here: the marker moves only once the Worker has the change. marker = state / "edge-direct" current = marker.exists() and marker.read_text().strip() == "on" wanted = direct_choice(state, choice, keep=False) - if wanted == current: - return - if wanted: - what = ( - "edge direct: upload the GitHub and queue tokens and turn direct actions on" - ) - else: - what = "edge direct: turn direct actions off" - cf.changes.append(what) - if check: - return - edge_dir = pathlib.Path(__file__).resolve().parent.parent / "edge" - wrangler = shutil.which("wrangler") or str( - edge_dir / "node_modules" / ".bin" / "wrangler" - ) - if not wrangler or not pathlib.Path(wrangler).exists(): - raise SystemExit( - "wrangler is not installed here; run `npm ci` in pm-stack/console/edge, then rerun" - ) - envs = { - **os.environ, - "CLOUDFLARE_API_TOKEN": cf.token, - "CLOUDFLARE_ACCOUNT_ID": account, - } + # Straight to Cloudflare's API, with the token this script already + # holds: nothing to install on this host, and the value travels in + # the request body, never on a command line. + secrets_path = f"/accounts/{account}/workers/scripts/{WORKER}/secrets" + all_three = ("GITHUB_TOKEN", "QUEUE_TOKEN", "EDGE_DIRECT") def put(name: str, value: str) -> None: - done = subprocess.run( - [wrangler, "secret", "put", name], - input=value, - capture_output=True, - text=True, - cwd=edge_dir, - env=envs, - check=False, + cf.call( + "PUT", secrets_path, {"name": name, "text": value, "type": "secret_text"} ) - if done.returncode != 0: - raise SystemExit( - f"wrangler secret put {name} failed ({(done.stderr or '').strip()[:200]}); " - "the edge Worker was not given its secrets" - ) - if wanted: + def held() -> set[str]: + return {s.get("name") for s in cf.get(secrets_path)} + + def remember(mode: str) -> None: + state.mkdir(parents=True, exist_ok=True, mode=0o700) + marker.write_text(mode + "\n") + + def take_tokens_away() -> None: + """Off means the Worker holds nothing it could act with.""" + names = held() + for name in ("GITHUB_TOKEN", "QUEUE_TOKEN"): + if name in names: + cf.change( + f"edge direct: take {name} away from the Worker", + "DELETE", + f"{secrets_path}/{name}", + None, + ) + + def upload() -> None: github = secret(GITHUB_TOKEN_SECRET) queue_name = ( env_values(env).get("PM_CONSOLE_QUEUE_TOKEN_NAME") or QUEUE_TOKEN_DEFAULT @@ -324,17 +336,69 @@ def put(name: str, value: str) -> None: raise SystemExit(f"secret {GITHUB_TOKEN_SECRET} is not readable here") if not queue: raise SystemExit(f"secret {queue_name} is not readable here") - put("GITHUB_TOKEN", github) - put("QUEUE_TOKEN", queue) - put("EDGE_DIRECT", "on") - else: - # The tokens stay, inert without the opt-in; only the flag moves. + try: + put("GITHUB_TOKEN", github) + put("QUEUE_TOKEN", queue) + put("EDGE_DIRECT", "on") + except SystemExit: + # Part-way is not on. What did get there is taken away again, + # so a failed attempt leaves the Worker holding nothing. + if not current: + try: + take_tokens_away() + except SystemExit: + pass + raise + + if wanted and current: + # On already. A timer's run uploads nothing, unless the Worker + # has lost one of the three, and then it gets them again. + try: + lost = sorted(set(all_three) - held()) + except SystemExit as error: + print(f"note: could not see what the Worker holds: {error}") + return + if lost: + cf.changes.append( + f"edge direct: give the Worker back what it has lost ({', '.join(lost)})" + ) + if not check: + upload() + return + if wanted: + cf.changes.append( + "edge direct: upload the GitHub and queue tokens and turn direct actions on" + ) + if check: + return + upload() + # The Worker has all three now, so the choice is remembered; a + # failure above raises before this line and leaves no marker. + remember("on") + return + if current: + cf.changes.append("edge direct: turn direct actions off") + if check: + return + # The opt-in goes first, so the Worker stops acting at once, and + # the mode is off from here whatever happens to the tidying. put("EDGE_DIRECT", "off") - # The Worker has the change now, so the choice is remembered; a - # failure above raises before this line and leaves the old marker. - if choice is not None: - state.mkdir(parents=True, exist_ok=True, mode=0o700) - marker.write_text(choice + "\n") + remember("off") + take_tokens_away() + return + if choice == "off": + # Asked for off while already off, or after an attempt to turn it + # on that never finished: make sure nothing was left behind. + take_tokens_away() + return + if marker.exists(): + # Off, after having been on, and nobody asking: a token left by a + # run that stopped part-way is taken away now. This is tidying; + # it never fails a run that changes nothing else. + try: + take_tokens_away() + except SystemExit as error: + print(f"note: could not look for tokens left on the Worker: {error}") def worker_ready(cf: Cloudflare, account: str, host: str) -> bool: @@ -703,6 +767,15 @@ def ensure_console( def main() -> int: + # A run that only looks needs no turn. One that may change something + # waits for any other such run to finish first. + if {"--status", "--check"} & set(sys.argv[1:]): + return configure() + with one_at_a_time(pathlib.Path.home() / ".local/state/pm-console"): + return configure() + + +def configure() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--check", action="store_true") parser.add_argument("--host", default="pm.security.cab") diff --git a/pm-stack/console/scripts/test_expose.py b/pm-stack/console/scripts/test_expose.py index 857f5da514..4f1d2322f3 100755 --- a/pm-stack/console/scripts/test_expose.py +++ b/pm-stack/console/scripts/test_expose.py @@ -51,6 +51,13 @@ def __init__(self, check=False): # its next health checks get no answer. self.worker_host = HOST self.health_misses = 0 + # What the Worker holds as secrets, and how many of the next + # uploads Cloudflare refuses. + self.worker_secrets = {} + # Uploads made so far, and which one (counted from 1) is refused. + self.uploads = 0 + self.fail_upload = 0 + self.delete_failures = 0 def call(self, method, path, body=None): path, _, query = path.partition("?") @@ -103,6 +110,24 @@ def call(self, method, path, body=None): elif path == "/zones": name = query.partition("name=")[2] result = [{"id": self.zones[name]}] if name in self.zones else [] + elif path.endswith(f"/workers/scripts/{expose.WORKER}/secrets"): + # The Worker's secrets: names can be listed, values never read back. + if method == "PUT": + self.uploads += 1 + if self.uploads == self.fail_upload: + raise SystemExit("cloudflare PUT secrets: refused") + self.worker_secrets[body["name"]] = body["text"] + result = [ + {"name": name, "type": "secret_text"} for name in self.worker_secrets + ] + elif ( + f"/workers/scripts/{expose.WORKER}/secrets/" in path and method == "DELETE" + ): + if self.delete_failures > 0: + self.delete_failures -= 1 + raise SystemExit("cloudflare DELETE secret: refused") + self.worker_secrets.pop(path.split("/")[-1], None) + result = None elif path.endswith("/workers/subdomain"): result = {"subdomain": "acct"} elif "/workers/routes" in path: @@ -152,12 +177,10 @@ def run( owner=OWNER, stdin=None, secrets=None, - wrangler_path=None, ): """One run of the script. What it printed is left in account.printed.""" argv = ["expose.py", *(["--owner", owner] if owner else []), *args] machine = machine or Machine() - real_which = expose.shutil.which def secret(name): if secrets is not None and name in secrets: @@ -178,13 +201,6 @@ def health(url): with ( mock.patch.object(expose, "Cloudflare", lambda token, check: account), mock.patch.object(expose, "secret", secret), - mock.patch.object( - expose.shutil, - "which", - lambda cmd, *a, **k: ( - wrangler_path if wrangler_path is not None else real_which(cmd, *a, **k) - ), - ), mock.patch.object(expose.pathlib.Path, "home", lambda: pathlib.Path(home)), mock.patch.object(expose.subprocess, "run", machine.systemctl), mock.patch.object(expose, "console_up", machine.up), @@ -523,68 +539,223 @@ def test_edge_off_is_remembered_and_edge_on_brings_it_back(self): ) self.assertEqual(self.env()["PM_CONSOLE_EDGE_URL"], f"https://{HOST}") - def test_direct_choice_is_remembered_only_after_it_is_applied(self): + def test_direct_mode_gives_the_worker_its_tokens_and_takes_them_away_again(self): account = Account() run(account, self.home) marker = pathlib.Path(self.home) / ".local/state/pm-console/edge-direct" - fake = pathlib.Path(self.home) / "wrangler" - fake.write_text("#!/bin/sh\n") + path = f"/accounts/acc/workers/scripts/{expose.WORKER}/secrets" + # Off by default: an ordinary run uploads nothing. + self.assertEqual(account.worker_secrets, {}) + # Asked what turning it on would change: said, and nothing done. + account.order.clear() + self.assertEqual(run(account, self.home, "--check", "--edge-direct", "on"), 1) + self.assertEqual(len(account.changes), 1) + self.assertEqual(account.order, []) + self.assertFalse(marker.exists()) # The tokens cannot be read here: the run fails, and nothing is # remembered, so a later run still tries to turn direct mode on. with self.assertRaisesRegex(SystemExit, "is not readable here"): - run(account, self.home, "--edge-direct", "on", wrangler_path=str(fake)) + run(account, self.home, "--edge-direct", "on") self.assertFalse(marker.exists()) - # Readable now: the tokens are uploaded and the choice is remembered. + self.assertEqual(account.worker_secrets, {}) secrets = { - expose.GITHUB_TOKEN_SECRET: "gh-test", - expose.QUEUE_TOKEN_DEFAULT: "queue-test", + expose.GITHUB_TOKEN_SECRET: "gh-test-value", + expose.QUEUE_TOKEN_DEFAULT: "queue-test-value", } - machine = Machine() + # Cloudflare takes the first token and refuses the second: nothing + # is remembered, and the one that got there is taken away again, + # so a failed attempt leaves the Worker holding nothing. + account.fail_upload = account.uploads + 2 + with self.assertRaisesRegex(SystemExit, "refused"): + run(account, self.home, "--edge-direct", "on", secrets=secrets) + self.assertFalse(marker.exists()) + self.assertEqual(account.worker_secrets, {}) + # If even that tidying fails, asking for off finishes it, though + # the mode was never on and nothing says it was. + account.fail_upload = account.uploads + 2 + account.delete_failures = 1 + with self.assertRaisesRegex(SystemExit, "refused"): + run(account, self.home, "--edge-direct", "on", secrets=secrets) + self.assertEqual(list(account.worker_secrets), ["GITHUB_TOKEN"]) + self.assertFalse(marker.exists()) self.assertEqual( - run( - account, - self.home, - "--edge-direct", - "on", - machine=machine, - secrets=secrets, - wrangler_path=str(fake), - ), - 0, + run(account, self.home), 0 + ) # the timer leaves it: not its to judge + self.assertEqual(list(account.worker_secrets), ["GITHUB_TOKEN"]) + self.assertEqual(run(account, self.home, "--edge-direct", "off"), 0) + self.assertEqual(account.worker_secrets, {}) + self.assertEqual( + account.changes, ["edge direct: take GITHUB_TOKEN away from the Worker"] + ) + # Readable and accepted: the two tokens and the opt-in are the + # Worker's, through Cloudflare's API and nothing installed here. + account.order.clear() + self.assertEqual( + run(account, self.home, "--edge-direct", "on", secrets=secrets), 0 ) + self.assertEqual( + account.worker_secrets, + { + "GITHUB_TOKEN": "gh-test-value", + "QUEUE_TOKEN": "queue-test-value", + "EDGE_DIRECT": "on", + }, + ) + self.assertEqual(account.order, [f"PUT {path}"] * 3) self.assertEqual(marker.read_text().strip(), "on") - self.assertEqual(machine.commands.count("put"), 3) - # A later run with the same choice uploads nothing again. - machine = Machine() + # Neither value is in anything it printed, said it changed, or wrote. + said = "\n".join(account.printed + account.changes) + for value in secrets.values(): + self.assertNotIn(value, said) + for kept in pathlib.Path(self.home).rglob("*"): + if kept.is_file(): + self.assertNotIn(value, kept.read_text()) + # A later run with the same choice, or with none (the timer's), + # uploads nothing again. + for again in (("--edge-direct", "on"), ()): + account.order.clear() + self.assertEqual(run(account, self.home, *again, secrets=secrets), 0) + self.assertEqual(account.changes, []) + self.assertEqual(account.order, []) + # Off: the opt-in first, then the two tokens are taken away. + account.order.clear() + self.assertEqual(run(account, self.home, "--edge-direct", "off"), 0) + self.assertEqual(account.worker_secrets, {"EDGE_DIRECT": "off"}) self.assertEqual( - run( - account, - self.home, - "--edge-direct", - "on", - machine=machine, - secrets=secrets, - wrangler_path=str(fake), - ), - 0, + account.order, + [ + f"PUT {path}", + f"DELETE {path}/GITHUB_TOKEN", + f"DELETE {path}/QUEUE_TOKEN", + ], + ) + self.assertEqual(marker.read_text().strip(), "off") + # Off again, or the timer's run: nothing left to do. + account.order.clear() + self.assertEqual(run(account, self.home), 0) + self.assertEqual(account.changes, []) + self.assertEqual(account.order, []) + + def test_turning_direct_mode_off_is_finished_by_a_later_run_if_it_stopped_part_way( + self, + ): + account = Account() + run(account, self.home) + marker = pathlib.Path(self.home) / ".local/state/pm-console/edge-direct" + secrets = { + expose.GITHUB_TOKEN_SECRET: "gh-test-value", + expose.QUEUE_TOKEN_DEFAULT: "queue-test-value", + } + run(account, self.home, "--edge-direct", "on", secrets=secrets) + # Cloudflare takes the opt-in off and then refuses a delete. + account.delete_failures = 1 + with self.assertRaisesRegex(SystemExit, "refused"): + run(account, self.home, "--edge-direct", "off") + # The mode is off and remembered as off, so it can be turned on again. + self.assertEqual(account.worker_secrets["EDGE_DIRECT"], "off") + self.assertEqual(marker.read_text().strip(), "off") + self.assertIn("GITHUB_TOKEN", account.worker_secrets) + # Asked what the next run would do: take what was left behind away. + self.assertEqual(run(account, self.home, "--check"), 1) + self.assertEqual( + account.changes, + [ + "edge direct: take GITHUB_TOKEN away from the Worker", + "edge direct: take QUEUE_TOKEN away from the Worker", + ], + ) + self.assertIn("GITHUB_TOKEN", account.worker_secrets) + # The timer's next run does it. + self.assertEqual(run(account, self.home), 0) + self.assertEqual(account.worker_secrets, {"EDGE_DIRECT": "off"}) + # Tidying that cannot be done never fails a run. + account.worker_secrets["QUEUE_TOKEN"] = "left behind" + account.delete_failures = 1 + self.assertEqual(run(account, self.home), 0) + self.assertTrue( + any("could not look for tokens" in line for line in account.printed) + ) + # And on again works from here. + self.assertEqual( + run(account, self.home, "--edge-direct", "on", secrets=secrets), 0 ) + self.assertEqual(account.worker_secrets["EDGE_DIRECT"], "on") + self.assertEqual(marker.read_text().strip(), "on") + + def test_direct_mode_that_is_on_gets_back_what_the_worker_has_lost(self): + account = Account() + run(account, self.home) + secrets = { + expose.GITHUB_TOKEN_SECRET: "gh-test-value", + expose.QUEUE_TOKEN_DEFAULT: "queue-test-value", + } + run(account, self.home, "--edge-direct", "on", secrets=secrets) + # Something took a token off the Worker (a hand in the dashboard, + # another run's tidying): the mode says on and cannot work. + del account.worker_secrets["QUEUE_TOKEN"] + self.assertEqual(run(account, self.home, "--check"), 1) + self.assertEqual( + account.changes, + ["edge direct: give the Worker back what it has lost (QUEUE_TOKEN)"], + ) + self.assertNotIn("QUEUE_TOKEN", account.worker_secrets) + # The timer's next run puts it right, and the one after has nothing to do. + self.assertEqual(run(account, self.home, secrets=secrets), 0) + self.assertEqual(account.worker_secrets["QUEUE_TOKEN"], "queue-test-value") + account.order.clear() + self.assertEqual(run(account, self.home, secrets=secrets), 0) self.assertEqual(account.changes, []) - self.assertNotIn("put", machine.commands) - # Turning it off is remembered the same way, once the Worker has it. + self.assertEqual(account.order, []) + # A repair that fails part-way takes nothing away: the mode was on. + del account.worker_secrets["EDGE_DIRECT"] + account.fail_upload = account.uploads + 2 + with self.assertRaisesRegex(SystemExit, "refused"): + run(account, self.home, secrets=secrets) + self.assertIn("GITHUB_TOKEN", account.worker_secrets) + + def test_runs_that_may_change_something_take_turns(self): + import threading + + state = pathlib.Path(self.home) / ".local/state/pm-console" + order = [] + inside = threading.Event() + release = threading.Event() + + def first(): + with expose.one_at_a_time(state): + order.append("first in") + inside.set() + release.wait(5) + order.append("first out") + + def second(): + inside.wait(5) + order.append("second waiting") + with expose.one_at_a_time(state): + order.append("second in") + + a = threading.Thread(target=first) + b = threading.Thread(target=second) + a.start() + b.start() + inside.wait(5) + # Give the second every chance to barge in; it must not. + for _ in range(50): + if "second waiting" in order: + break + threading.Event().wait(0.01) + threading.Event().wait(0.05) + self.assertNotIn("second in", order) + release.set() + a.join(5) + b.join(5) self.assertEqual( - run( - account, - self.home, - "--edge-direct", - "off", - machine=machine, - secrets=secrets, - wrangler_path=str(fake), - ), - 0, + order, ["first in", "second waiting", "first out", "second in"] ) - self.assertEqual(marker.read_text().strip(), "off") - self.assertEqual(machine.commands.count("put"), 1) + # A run that only looks does not wait for a turn, or leave a lock. + fresh = tempfile.mkdtemp() + self.assertEqual(run(Account(), fresh, "--status", owner=None), 0) + self.assertFalse((pathlib.Path(fresh) / ".local").exists()) def test_another_workers_route_on_the_hostname_is_left_alone(self): for foreign in ( diff --git a/pm-stack/console/src/actions.ts b/pm-stack/console/src/actions.ts index 60e0d09699..c29563a431 100644 --- a/pm-stack/console/src/actions.ts +++ b/pm-stack/console/src/actions.ts @@ -138,6 +138,9 @@ export function actions(ops: Ops, work: Work, push?: Push, devices?: Devices): R // written to the record of what was done, and the action is never // held anywhere to be done late. "sso.google": { run: (a) => ops.googleSignin(a.clientId, a.clientSecret), touch: [], audit: () => ({}) }, + // The owner's switch for the edge acting by itself while the laptop + // is away. Done on the laptop, where the tokens are, and never held. + "edge.direct": { run: (a) => ops.edgeDirect(a.on), touch: [], audit: (a) => ({ on: a.on === true }) }, "message.send": { run: (a) => ops.send(a.to, a.text, a.command), touch: [], diff --git a/pm-stack/console/src/ops.ts b/pm-stack/console/src/ops.ts index f0e85a68f2..24baf0b32c 100644 --- a/pm-stack/console/src/ops.ts +++ b/pm-stack/console/src/ops.ts @@ -541,6 +541,27 @@ export class Ops { return { google: true, changed: said.filter((line) => line.startsWith("changed: ")).map((line) => line.slice(9)) }; } + /** Let the edge act by itself while this host is away, or stop it. + * Turning it on gives the Worker the repository automation token and + * the queue store token, read from the secret store by the setup + * script and sent to Cloudflare; turning it off takes them away. It + * can only be done here, where the secret store is. */ + async edgeDirect(on: unknown) { + if (typeof on !== "boolean") throw new OpError(400, "on: true or false"); + const r = await this.expose(["--edge-direct", on ? "on" : "off"]); + const said = `${r.stdout}\n${r.stderr}` + .split("\n") + .map((line) => line.trim()) + .filter((line) => line !== ""); + if (r.code !== 0) { + throw new OpError( + 502, + `Cloudflare was not ${on ? "given" : "relieved of"} the tokens: ${(said.pop() ?? "the setup script failed").slice(0, 300)}`, + ); + } + return { on, changed: said.filter((line) => line.startsWith("changed: ")).map((line) => line.slice(9)) }; + } + // ---- services ---------------------------------------------------------- async services(): Promise { diff --git a/pm-stack/console/test/app.test.ts b/pm-stack/console/test/app.test.ts index 63d62a0a60..1099accf40 100644 --- a/pm-stack/console/test/app.test.ts +++ b/pm-stack/console/test/app.test.ts @@ -3,7 +3,7 @@ // Oracles: the elapsed-time phrases and the device labels are written // out here by hand for real inputs (two real browser names). import { expect, test } from "bun:test"; -import { ago, band, deviceLabel, endpointMark, subscriptionState } from "../public/app.js"; +import { ago, awayState, band, deviceLabel, endpointMark, subscriptionState } from "../public/app.js"; import { contact, endpointMark as serverMark } from "../src/push.ts"; test("elapsed time reads as a phrase on its own, never 'just now ago'", () => { @@ -66,3 +66,42 @@ test("a device with notifications on tells whether the sender still has it, and test("the contact given to push services is the project's page, never a person's address", () => { expect(contact("developing-today/code")).toBe("https://github.com/developing-today/code"); }); + +test("the Laptop away screen reads the edge's own account of itself", () => { + // Straight from the laptop, or no answer: there is no edge to ask. + expect(awayState(null)).toEqual({ served: false }); + expect(awayState({ ok: true })).toEqual({ served: false }); + // Served from the edge, the switch never touched. + expect(awayState({ ok: true, edge: true, directEnabled: false, directReady: false, selfCheck: null })).toEqual({ + served: true, + on: false, + ready: false, + checkedAt: null, + checks: [], + }); + // On and holding its tokens: each kind of read it tried, in the owner's words. + expect( + awayState({ + edge: true, + directEnabled: true, + directReady: true, + selfCheck: { + at: 1_700_000_000_000, + kinds: { board: { ok: true }, asks: { ok: false, error: "queue store answered http 401" } }, + }, + }), + ).toEqual({ + served: true, + on: true, + ready: true, + checkedAt: 1_700_000_000_000, + checks: [ + { what: "The board", ok: true, error: "" }, + { what: "Your prompts", ok: false, error: "queue store answered http 401" }, + ], + }); + // The flag is on but a token is missing: on, and not ready. + expect(awayState({ edge: true, directEnabled: true, directReady: false }).ready).toBe(false); + // Ready without the flag is not ready: the flag is what the owner turned. + expect(awayState({ edge: true, directEnabled: false, directReady: true })).toMatchObject({ on: false, ready: false }); +}); diff --git a/pm-stack/console/test/signin.test.ts b/pm-stack/console/test/signin.test.ts index 319540cf6e..9de318034c 100644 --- a/pm-stack/console/test/signin.test.ts +++ b/pm-stack/console/test/signin.test.ts @@ -114,6 +114,45 @@ describe("sign-in", () => { expect(w.calls).toEqual([]); }); + test("the owner's switch for the edge acting by itself runs the setup script here, on or off", async () => { + const w = setup((argv) => ({ + stdout: argv.includes("on") + ? "changed: edge direct: upload the GitHub and queue tokens and turn direct actions on\n" + : "changed: edge direct: turn direct actions off and take the two tokens away\n", + })); + const docs = new Docs( + Object.fromEntries(SECTION_NAMES.map((name) => [name, { ttlMs: 1000, load: async () => ({}) }])), + ); + expect(await perform(w.table, docs, "edge.direct", { on: true })).toEqual({ + on: true, + changed: ["edge direct: upload the GitHub and queue tokens and turn direct actions on"], + }); + expect(await perform(w.table, docs, "edge.direct", { on: false })).toMatchObject({ on: false }); + expect(w.calls.map((c) => c.argv.slice(2))).toEqual([ + ["--edge-direct", "on"], + ["--edge-direct", "off"], + ]); + // Nothing is handed to it: the tokens are read by the script, by name. + expect(w.calls.every((c) => c.stdin === undefined)).toBe(true); + // What it records is the choice. It is the laptop's to do, so it is never held for later. + expect(w.table["edge.direct"].audit({ on: true })).toEqual({ on: true }); + expect(HOLDABLE.has("edge.direct")).toBe(false); + // Anything but true or false is refused before the script is run. + for (const on of ["on", 1, undefined, null]) { + const refused = await w.ops.edgeDirect(on).catch((error) => error); + expect(refused).toBeInstanceOf(OpError); + expect(refused.status).toBe(400); + } + expect(w.calls).toHaveLength(2); + // A script that fails says why. + const failing = setup(() => ({ code: 1, stderr: "secret turso.fleet-queue-rw-token is not readable here\n" })); + const failed = await failing.ops.edgeDirect(true).catch((error) => error); + expect(failed.status).toBe(502); + expect(failed.message).toBe( + "Cloudflare was not given the tokens: secret turso.fleet-queue-rw-token is not readable here", + ); + }); + test("a script that fails says why, without either value even if the script printed one", async () => { const w = setup(() => ({ code: 1,