From 50cc58a0459770c888367a8307b3e8a56585a6d5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 06:05:04 -0600 Subject: [PATCH] feat(pm-console): a Sign-in screen that turns Google sign-in on Google sign-in has waited on one thing only a signed-in person can do: making the OAuth client. Everything around that step is now in the app. More, Sign-in shows which methods are on, the two addresses to give Google (with copy buttons), and takes the client ID and secret. The console hands them to expose.py on its standard input, which gives them to Cloudflare. They are kept nowhere else: not in a file, a log, the record of actions, or the edge (the action is never held). The same screen replaces the client later. expose.py: - --google-stdin creates the Google sign-in method from a client read from standard input, or gives an existing one the new client. What is not a client is refused before Cloudflare is asked anything. - --status prints which sign-in methods are on and changes nothing. - The owner's address is no longer written in the script. It is given once with --owner and remembered in the console's environment file, which every existing install already has. Test fixtures use example addresses. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01YLT5K1QVuzZjfWGFhXSSNF --- pm-stack/console/README.md | 21 +++- pm-stack/console/public/app.css | 17 +++ pm-stack/console/public/app.js | 67 +++++++++++ pm-stack/console/scripts/demo-state.ts | 32 ++++-- pm-stack/console/scripts/expose.py | 111 ++++++++++++++++-- pm-stack/console/scripts/test_expose.py | 145 ++++++++++++++++++++++-- pm-stack/console/src/actions.ts | 4 + pm-stack/console/src/ops.ts | 61 ++++++++++ pm-stack/console/src/server.ts | 1 + pm-stack/console/test/console.test.ts | 8 +- pm-stack/console/test/devices.test.ts | 2 +- pm-stack/console/test/signin.test.ts | 131 +++++++++++++++++++++ pm-stack/console/test/work.test.ts | 2 +- 13 files changed, 565 insertions(+), 37 deletions(-) create mode 100644 pm-stack/console/test/signin.test.ts diff --git a/pm-stack/console/README.md b/pm-stack/console/README.md index 40372d6227..2d4f66cbf0 100644 --- a/pm-stack/console/README.md +++ b/pm-stack/console/README.md @@ -119,10 +119,16 @@ the owner (`PM_CONSOLE_OWNER_EMAILS`). - **Today:** Cloudflare Access at the public edge runs the interactive sign-in and issues the token. The sign-in methods are set on the Access application, not here. -- **Google:** an Access sign-in method. It turns on when - `scripts/expose.py` finds the secrets `google.access-sso.client-id` and - `google.access-sso.client-secret` (an OAuth client whose redirect URI is - `https://.cloudflareaccess.com/cdn-cgi/access/callback`). +- **Google:** an Access sign-in method, offered beside the emailed code. + It needs an OAuth client, which Google lets only a signed-in person + make. The app walks through it under More, Sign-in: it shows the two + addresses to give Google, takes the client ID and secret, and hands + them to `scripts/expose.py --google-stdin`, which gives them to + Cloudflare. They are kept nowhere else: not in a file, a log, the + record of actions, or (the action is never held) the edge. The same + screen replaces the client later. `expose.py` also turns Google on by + itself if it finds the secrets `google.access-sso.client-id` and + `google.access-sso.client-secret`. - **The central OIDC provider (#9077):** either an Access sign-in method (generic OIDC), or trusted directly: add `{name, issuer, jwksUri, audience}` to the file named by @@ -146,14 +152,19 @@ app's link to this origin), and the two phone paths under ```bash bash pm-stack/console/install.sh # user unit pm-console, port 4872, loopback only; and its two timers +python3 pm-stack/console/scripts/expose.py --owner you@example.com # first time: Access, console env, tunnel route, DNS, the edge's route python3 pm-stack/console/scripts/expose.py --check # what public exposure would change -python3 pm-stack/console/scripts/expose.py # Access, console env, tunnel route, DNS, the edge's route +python3 pm-stack/console/scripts/expose.py # later runs (the timer's): the owner is remembered +python3 pm-stack/console/scripts/expose.py --status # which sign-in methods are on, as JSON; changes nothing python3 pm-stack/console/scripts/expose.py --edge off # hostname straight to this host, not through the edge cd pm-stack/console && bun test bun run scripts/demo.ts # the app with made-up state, on this host alone bun run scripts/edge-demo.ts # the same behind the edge ``` +The owner's address is given once with `--owner` and remembered in the +console's environment file; it is not written in the script. + `expose.py` is safe to run again: it changes only what is not already so and refuses to touch DNS records or Access policies it did not write. It puts the sign-in gate in place first and the route last, and stops before diff --git a/pm-stack/console/public/app.css b/pm-stack/console/public/app.css index 2f1812258b..e7b6a820e9 100644 --- a/pm-stack/console/public/app.css +++ b/pm-stack/console/public/app.css @@ -602,3 +602,20 @@ dialog label { min-height: 22px; height: 22px; } + +/* Sign-in: the numbered steps, and a value to copy that may be long. */ +ol.steps { + margin: 0.5rem 0; + padding-left: 1.3rem; + display: grid; + gap: 0.6rem; +} +code.wrap { + flex: 1; + min-width: 0; + overflow-wrap: anywhere; + font-size: 0.85rem; +} +.card input + input { + margin-top: 0.5rem; +} diff --git a/pm-stack/console/public/app.js b/pm-stack/console/public/app.js index d868690e7e..ad5503f0e2 100644 --- a/pm-stack/console/public/app.js +++ b/pm-stack/console/public/app.js @@ -834,6 +834,7 @@ function viewMore() { tile("more/services", "Services", ops.services ? `${ops.services.filter((u) => u.active === "failed").length} failed of ${ops.services.length}` : "start, stop, logs"), 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"), ), ]; for (const g of ops.more || []) { @@ -980,6 +981,71 @@ function collectUrl() { return `intent://finish#Intent;scheme=pmconsole;package=${me.androidPackage || "today.developing.pmconsole"};S.browser_fallback_url=${back};end`; } +/** 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. */ +async function viewSignin() { + let s; + try { + s = await api("signin"); + } catch (error) { + return [empty(`The sign-in settings could not be read just now: ${error.message}`)]; + } + const copy = (text) => + h( + "button", + { + class: "small ghost", + onclick: () => + navigator.clipboard.writeText(text).then( + () => toast("Copied"), + () => toast("Could not copy. Select the text and copy it.", true), + ), + }, + "Copy", + ); + const value = (text) => h("div", { class: "row" }, h("code", { class: "wrap" }, text), copy(text)); + const id = h("input", { type: "text", placeholder: "Client ID", autocomplete: "off", autocapitalize: "none", spellcheck: false }); + const secret = h("input", { type: "password", placeholder: "Client secret", autocomplete: "off" }); + const send = async (e) => { + const done = await act("sso.google", { clientId: id.value.trim(), clientSecret: secret.value.trim() }, "Google sign-in is on", e.target); + secret.value = ""; + if (done) draw(); + else e.target.disabled = false; + }; + return [ + card( + h("h3", {}, s.google ? "Google sign-in is on" : "Google sign-in is not on yet"), + h( + "p", + { class: "meta" }, + s.google + ? "The sign-in page offers Google. The code sent by email stays as the fallback." + : s.pin + ? "For now the sign-in page asks for a code sent by email." + : "No sign-in method is on.", + ), + ), + h("h2", {}, s.google ? "Use a different Google client" : "Turn it on"), + card( + h("p", { class: "meta" }, "Google lets only a signed-in person make the client its sign-in runs on, so this part is yours. A few minutes, once."), + h( + "ol", + { class: "steps" }, + h("li", {}, "Open ", ext("https://console.cloud.google.com/auth/clients", "Google Cloud, Clients"), ". If it asks, set the app up first: any name, audience External."), + h("li", {}, "Create client. Application type: Web application."), + h("li", {}, "Authorized JavaScript origins, add:", value(s.origin)), + h("li", {}, "Authorized redirect URIs, add:", value(s.redirect)), + h("li", {}, "Create, then paste the two values it shows:"), + ), + id, + secret, + h("div", { class: "row end" }, h("button", { onclick: send }, s.google ? "Use this client" : "Turn on Google sign-in")), + h("p", { class: "meta" }, "Both values go to Cloudflare, which runs the sign-in page, and are kept nowhere else."), + ), + ]; +} + async function viewPhone(sub) { if (sub?.startsWith("link=")) { const request = sub.slice(5); @@ -1332,6 +1398,7 @@ const VIEWS = { "more/services": ["Services", viewServices, "ops"], "more/notify": ["Notifications", viewNotify], "more/phone": ["Phones", viewPhone], + "more/signin": ["Sign-in", viewSignin], }; let route = "now"; let drawSeq = 0; diff --git a/pm-stack/console/scripts/demo-state.ts b/pm-stack/console/scripts/demo-state.ts index 18e6bfc8f3..1d4068c3c2 100644 --- a/pm-stack/console/scripts/demo-state.ts +++ b/pm-stack/console/scripts/demo-state.ts @@ -7,7 +7,7 @@ import { readConfig } from "../src/config.ts"; import { Devices, Limiter } from "../src/devices.ts"; import { Docs } from "../src/docs.ts"; import { fileStore } from "../src/file-store.ts"; -import { Ops } from "../src/ops.ts"; +import { Ops, type Run } from "../src/ops.ts"; import { Push } from "../src/push.ts"; import type { Deps } from "../src/server.ts"; @@ -337,6 +337,25 @@ const state = { ], }; +/** The commands the console runs, answered from nothing: every one + * succeeds with an empty list, and the sign-in script remembers whether + * it was handed a Google client. */ +let demoGoogle = false; +const demoRun: Run = async (argv) => { + if (argv.includes("--google-stdin")) { + demoGoogle = true; + return { code: 0, stdout: "changed: access: add Google sign-in\n", stderr: "" }; + } + if (argv.includes("--status")) { + return { + code: 0, + stdout: `${JSON.stringify({ google: demoGoogle, pin: true, team: "your-team.cloudflareaccess.com" })}\n`, + stderr: "", + }; + } + return { code: 0, stdout: "[]", stderr: "" }; +}; + const cfg = readConfig({ HOME: "/tmp", PM_CONSOLE_DASHBOARD_URL: "" }); const docs = new Docs( Object.fromEntries(Object.entries(state).map(([name, data]) => [name, { ttlMs: 3_600_000, load: async () => data }])), @@ -345,15 +364,10 @@ const done = (result: unknown) => ({ run: async () => result, touch: [] as strin // Linking a phone is the real thing, kept in a file under /tmp. const devices = new Devices(fileStore("/tmp/pm-console-demo-devices.json")); const phones = { devices, link: new Limiter(30, 60_000), refused: new Limiter(60, 60_000) }; -const real = realActions( - new Ops(cfg, async () => ({ code: 0, stdout: "[]", stderr: "" })), - undefined as never, - undefined, - devices, -); +const real = realActions(new Ops(cfg, demoRun), undefined as never, undefined, devices); const table = new Proxy({} as Record>, { get: (_t, kind) => - typeof kind === "string" && kind.startsWith("device.") + typeof kind === "string" && (kind.startsWith("device.") || kind === "sso.google") ? real[kind] : done( kind === "ask.send" @@ -369,7 +383,7 @@ const table = new Proxy({} as Record>, { /** The made-up host: canned state, and actions that all succeed. */ export const demoDeps: Deps = { cfg, - ops: new Ops(cfg, async () => ({ code: 0, stdout: "[]", stderr: "" })), + ops: new Ops(cfg, demoRun), docs, phones, push: new Push(fileStore("/tmp/pm-console-demo-push.json"), "mailto:you@example.com", async () => ({ diff --git a/pm-stack/console/scripts/expose.py b/pm-stack/console/scripts/expose.py index 604be33c0a..155b6376b4 100755 --- a/pm-stack/console/scripts/expose.py +++ b/pm-stack/console/scripts/expose.py @@ -40,9 +40,20 @@ Every secret is read by name through `fleet secrets get` and stays in memory. Nothing printed is a secret. -Usage: expose.py [--check] [--edge on|off] [--host pm.security.cab] [--owner EMAIL] +Usage: expose.py [--check] [--edge on|off] [--host pm.security.cab] [--owner ADDRESS] + [--google-stdin] [--status] + --owner whose sign-in is let in. Needed the first time; after that + the console's environment file remembers it. The address + is not written in this script. --check report what would change and exit 1 if anything would; with --edge, what that choice would change, keeping nothing. + --google-stdin + turn Google sign-in on with an OAuth client read from + standard input: the client ID on the first line, the + client secret on the second. They go to Cloudflare and + nowhere else: not to a file, a log or the output. + --status print which sign-in methods are on, as JSON, and change + nothing. --edge off take the hostname off the edge Worker; remembered by later runs (the timer's included) until --edge on. """ @@ -52,6 +63,7 @@ import argparse import json import pathlib +import re import subprocess import sys import time @@ -309,7 +321,43 @@ def ensure_dns(cf: Cloudflare, host: str, tunnel: str, zone: str, needed: bool) ) -def ensure_idps(cf: Cloudflare, account: str) -> list[str]: +def read_google(stream) -> tuple[str, str]: + """A Google OAuth client from standard input: the client ID on the + first line and the client secret on the second. Refused, before + anything is asked of Cloudflare, unless it looks like one. Neither + value is ever printed, in a refusal or otherwise.""" + lines = [line.strip() for line in stream.read().splitlines() if line.strip()] + if len(lines) != 2: + raise SystemExit( + "--google-stdin: expected two lines, the client ID and then the client secret" + ) + client_id, client_secret = lines + if not re.fullmatch(r"[0-9]+-[0-9a-z]+\.apps\.googleusercontent\.com", client_id): + raise SystemExit( + "--google-stdin: the first line is not a Google OAuth client ID " + "(one ends in .apps.googleusercontent.com)" + ) + if not re.fullmatch(r"[\x21-\x7e]{8,200}", client_secret): + raise SystemExit("--google-stdin: the second line is not a client secret") + return client_id, client_secret + + +def owner_address(given: str | None, env: pathlib.Path) -> str: + """Whose sign-in is let in. It is named with --owner the first time; + after that the console's own environment file remembers it, so the + timer's runs need not be told. It is not written in this script.""" + remembered = env_values(env).get("PM_CONSOLE_OWNER_EMAILS", "").split(",")[0] + owner = (given or remembered).strip().lower() + if not re.fullmatch(r"[^@\s,]+@[^@\s,]+\.[^@\s,]+", owner): + raise SystemExit( + f"say whose sign-in is let in: --owner ADDRESS (after the first run, {env} remembers it)" + ) + return owner + + +def ensure_idps( + cf: Cloudflare, account: str, google: tuple[str, str] | None = None +) -> list[str]: idps = cf.get(f"/accounts/{account}/access/identity_providers") by_type = {i["type"]: i for i in idps} ids = [] @@ -324,9 +372,23 @@ def ensure_idps(cf: Cloudflare, account: str) -> list[str]: ids.append(made["id"]) else: ids.append(by_type["onetimepin"]["id"]) - client_id, client_secret = secret(GOOGLE_ID), secret(GOOGLE_SECRET) + # A client handed in now is used; otherwise the two secrets, if they exist. + client_id, client_secret = google or (secret(GOOGLE_ID), secret(GOOGLE_SECRET)) if "google" in by_type: ids.append(by_type["google"]["id"]) + if google: + # Already on, and a client was handed in: it is the one to + # use from here on (a corrected or replaced client). + cf.change( + "access: give Google sign-in the client just supplied", + "PUT", + f"/accounts/{account}/access/identity_providers/{by_type['google']['id']}", + { + "name": by_type["google"].get("name") or "Google", + "type": "google", + "config": {"client_id": client_id, "client_secret": client_secret}, + }, + ) elif client_id and client_secret: made = cf.change( "access: add Google sign-in", @@ -522,7 +584,21 @@ def main() -> 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") - parser.add_argument("--owner", default="drewrypope@gmail.com") + parser.add_argument( + "--owner", + help="whose sign-in is let in; needed the first time, remembered after", + ) + parser.add_argument( + "--google-stdin", + action="store_true", + help="turn Google sign-in on with the OAuth client ID and secret read " + "from standard input, one a line", + ) + parser.add_argument( + "--status", + action="store_true", + help="print which sign-in methods are on, as JSON, and change nothing", + ) parser.add_argument( "--edge", choices=["on", "off"], @@ -530,6 +606,10 @@ def main() -> int: "the choice is kept for later runs (default: on, once the Worker answers)", ) args = parser.parse_args() + env = pathlib.Path.home() / ".local/state/pm-console/.env" + # Refused here, before anything is asked of Cloudflare. + google = read_google(sys.stdin) if args.google_stdin else None + owner = None if args.status else owner_address(args.owner, env) token = secret("cloudflare.api-token-account-wide") if not token: @@ -542,12 +622,25 @@ def main() -> int: raise SystemExit(f"expected one account, found {len(accounts)}") account = accounts[0]["id"] team = cf.get(f"/accounts/{account}/access/organizations")["auth_domain"] + if args.status: + kinds = { + i["type"] for i in cf.get(f"/accounts/{account}/access/identity_providers") + } + print( + json.dumps( + { + "google": "google" in kinds, + "pin": "onetimepin" in kinds, + "team": team, + } + ) + ) + return 0 # Look before changing anything: a hostname that already points # somewhere else stops the run with nothing written. tunnel, tunnel_config = find_tunnel(cf, account) zone, dns_needed = dns_plan(cf, args.host, tunnel) - env = pathlib.Path.home() / ".local/state/pm-console/.env" console = console_origin(env) # Through the edge only if that is wanted and the Worker is really # there; otherwise straight to this host, as before the edge existed. @@ -562,7 +655,7 @@ def main() -> int: # Order matters. The sign-in gate is put in place first and the route # last, so the origin is never reachable without the gate in front. - idps = ensure_idps(cf, account) + idps = ensure_idps(cf, account, google) apps = cf.get(f"/accounts/{account}/access/apps?per_page=200") for path in PUBLIC_PATHS: ensure_app( @@ -582,7 +675,7 @@ def main() -> int: args.host, "PM stack", "allow", - [{"email": {"email": args.owner}}], + [{"email": {"email": owner}}], idps, APP_SETTINGS, ) @@ -592,7 +685,7 @@ def main() -> int: { "PM_CONSOLE_ACCESS_TEAM_DOMAIN": team, "PM_CONSOLE_ACCESS_AUD": aud, - "PM_CONSOLE_OWNER_EMAILS": args.owner, + "PM_CONSOLE_OWNER_EMAILS": owner, # Where this host reports to the edge; absent, it reports # to nobody. "PM_CONSOLE_EDGE_URL": f"https://{args.host}" if edge else None, @@ -616,7 +709,7 @@ def main() -> int: print(("would change: " if args.check else "changed: ") + change) if not cf.changes: print( - f"https://{args.host}/ is set up: dashboard at /, console at /console/, owner {args.owner}" + f"https://{args.host}/ is set up: dashboard at /, console at /console/, owner {owner}" ) return 1 if args.check and cf.changes else 0 diff --git a/pm-stack/console/scripts/test_expose.py b/pm-stack/console/scripts/test_expose.py index 6ca36afe67..5c56062547 100755 --- a/pm-stack/console/scripts/test_expose.py +++ b/pm-stack/console/scripts/test_expose.py @@ -13,7 +13,10 @@ """ import copy +import io +import json import pathlib +import re import sys import tempfile import unittest @@ -23,6 +26,9 @@ import expose HOST = "pm.security.cab" +OWNER = "owner@example.com" +GOOGLE_CLIENT = "123456789012-abc123def456.apps.googleusercontent.com" +GOOGLE_VALUE = "not-a-real-value-0123456789" class Account(expose.Cloudflare): @@ -48,6 +54,7 @@ def __init__(self, check=False): def call(self, method, path, body=None): path, _, query = path.partition("?") + self.asked = getattr(self, "asked", 0) + 1 # every request, reads too if method != "GET": self.order.append(f"{method} {path}") if path == "/accounts": @@ -58,6 +65,10 @@ def call(self, method, path, body=None): if method == "POST": self.idps.append({"id": f"idp-{body['type']}", **body}) result = self.idps[-1] if method == "POST" else self.idps + elif "/access/identity_providers/" in path and method == "PUT": + idp = next(i for i in self.idps if i["id"] == path.split("/")[-1]) + idp.update(body) + result = idp elif "/access/apps/" in path and method == "PUT": app = next(a for a in self.apps if a["id"] == path.split("/")[-1]) app.update(body) @@ -133,8 +144,9 @@ def up(self, origin, seconds=20): return self.running -def run(account, home, *args, machine=None): - argv = ["expose.py", *args] +def run(account, home, *args, machine=None, owner=OWNER, stdin=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() def health(url): @@ -161,11 +173,15 @@ def health(url): mock.patch.object(expose, "fetch_json", health), mock.patch.object(expose.time, "sleep", lambda seconds: None), mock.patch.object(sys, "argv", argv), - mock.patch("builtins.print"), + mock.patch.object(sys, "stdin", io.StringIO(stdin or "")), + mock.patch("builtins.print") as printed, ): account.check = "--check" in args account.changes = [] - return expose.main() + try: + return expose.main() + finally: + account.printed = [str(c.args[0]) for c in printed.call_args_list] class Expose(unittest.TestCase): @@ -187,7 +203,7 @@ def test_the_gate_exists_before_the_route(self): { "name": "allow: PM stack", "decision": "allow", - "include": [{"email": {"email": "drewrypope@gmail.com"}}], + "include": [{"email": {"email": OWNER}}], "precedence": 1, } ], @@ -225,7 +241,7 @@ def test_the_gate_exists_before_the_route(self): ) env = (pathlib.Path(self.home) / ".local/state/pm-console/.env").read_text() self.assertIn("PM_CONSOLE_ACCESS_AUD=" + main["aud"], env) - self.assertIn("PM_CONSOLE_OWNER_EMAILS=drewrypope@gmail.com", env) + self.assertIn(f"PM_CONSOLE_OWNER_EMAILS={OWNER}", env) def test_a_second_run_changes_nothing(self): account = Account() @@ -303,7 +319,7 @@ def test_foreign_records_and_policies_are_left_alone(self): self.assertEqual(len(account.policies["app-x"]), 1) # The owner's own rule with a condition added is not this script's rule. - owner = [{"email": {"email": "drewrypope@gmail.com"}}] + owner = [{"email": {"email": OWNER}}] for extra in ( {"exclude": owner}, {"require": [{"geo": {"country_code": "XX"}}]}, @@ -477,7 +493,7 @@ def test_edge_off_is_remembered_and_edge_on_brings_it_back(self): self.assertEqual(account.routes, []) self.assertNotIn("PM_CONSOLE_EDGE_URL", self.env()) # The sign-in settings are still there: only the edge's went. - self.assertEqual(self.env()["PM_CONSOLE_OWNER_EMAILS"], "drewrypope@gmail.com") + self.assertEqual(self.env()["PM_CONSOLE_OWNER_EMAILS"], OWNER) # A later run with no flag (the timer's) keeps it off. self.assertEqual(run(account, self.home), 0) self.assertEqual(account.changes, []) @@ -572,6 +588,119 @@ def test_one_unanswered_health_check_does_not_take_the_hostname_off_the_edge(sel self.assertEqual(run(account, self.home), 0) self.assertEqual(len(account.routes), 1) + def test_the_owner_is_named_once_and_remembered_and_never_written_in_the_script( + self, + ): + # Never told, on a machine that has not been set up: refused + # before anything is read or changed. + account = Account() + with self.assertRaisesRegex(SystemExit, "say whose sign-in is let in"): + run(account, self.home, owner=None) + with self.assertRaisesRegex(SystemExit, "say whose sign-in"): + run(account, self.home, owner="not an address") + self.assertEqual(getattr(account, "asked", 0), 0) + # Told once: the console's environment file remembers, and a run + # that is not told (the timer's) uses that and changes nothing. + self.assertEqual(run(account, self.home, owner="Owner@Example.com"), 0) + self.assertEqual(self.env()["PM_CONSOLE_OWNER_EMAILS"], OWNER) + self.assertEqual(run(account, self.home, owner=None), 0) + self.assertEqual(account.changes, []) + main = next(a for a in account.apps if a["domain"] == HOST) + self.assertEqual( + account.policies[main["id"]][0]["include"], [{"email": {"email": OWNER}}] + ) + # No address is written in the script itself. + source = pathlib.Path(expose.__file__).read_text() + self.assertIsNone( + re.search(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+\.[a-z]{2,}", source) + ) + + def test_google_sign_in_is_turned_on_from_a_client_handed_in(self): + account = Account() + run(account, self.home) + main = next(a for a in account.apps if a["domain"] == HOST) + self.assertEqual(main["allowed_idps"], ["idp-onetimepin"]) + # Not a client: refused before Cloudflare is asked anything. + for bad in ( + "", + f"{GOOGLE_CLIENT}\n", + f"not-a-client-id\n{GOOGLE_VALUE}\n", + f"{GOOGLE_CLIENT}\nhas a space in it\n", + f"{GOOGLE_CLIENT}\n{GOOGLE_VALUE}\nthird line\n", + ): + account.asked = 0 + with self.assertRaisesRegex(SystemExit, "--google-stdin") as refused: + run(account, self.home, "--google-stdin", stdin=bad) + self.assertEqual(account.asked, 0) + self.assertNotIn(GOOGLE_VALUE, str(refused.exception)) + self.assertNotIn(GOOGLE_VALUE, "\n".join(account.printed)) + # A client: Google is added and the application lets both methods in. + self.assertEqual( + run( + account, + self.home, + "--google-stdin", + stdin=f" {GOOGLE_CLIENT}\n{GOOGLE_VALUE}\n", + ), + 0, + ) + google = next(i for i in account.idps if i["type"] == "google") + self.assertEqual( + google["config"], + {"client_id": GOOGLE_CLIENT, "client_secret": GOOGLE_VALUE}, + ) + self.assertEqual(main["allowed_idps"], ["idp-onetimepin", "idp-google"]) + self.assertEqual(account.changes[0], "access: add Google sign-in") + # Nothing it printed, and nothing it wrote, holds either value. + self.assertNotIn(GOOGLE_VALUE, "\n".join(account.printed)) + self.assertNotIn(GOOGLE_CLIENT, "\n".join(account.printed)) + for kept in pathlib.Path(self.home).rglob("*"): + if kept.is_file(): + self.assertNotIn(GOOGLE_VALUE, kept.read_text()) + # The timer's run, with nothing handed in, keeps it as it is. + self.assertEqual(run(account, self.home), 0) + self.assertEqual(account.changes, []) + # Handed a client again (a corrected one): that is the one used. + other = GOOGLE_VALUE[::-1] + self.assertEqual( + run( + account, + self.home, + "--google-stdin", + stdin=f"{GOOGLE_CLIENT}\n{other}\n", + ), + 0, + ) + self.assertEqual( + account.changes, ["access: give Google sign-in the client just supplied"] + ) + self.assertEqual(google["config"]["client_secret"], other) + self.assertEqual(len([i for i in account.idps if i["type"] == "google"]), 1) + + def test_status_says_which_sign_in_methods_are_on_and_changes_nothing(self): + account = Account() + # Needs no owner, and works before anything is set up. + self.assertEqual(run(account, self.home, "--status", owner=None), 0) + self.assertEqual( + json.loads(account.printed[-1]), + {"google": False, "pin": False, "team": "team.cloudflareaccess.com"}, + ) + self.assertEqual(account.order, []) + self.assertFalse((pathlib.Path(self.home) / ".local").exists()) + run( + account, + self.home, + "--google-stdin", + stdin=f"{GOOGLE_CLIENT}\n{GOOGLE_VALUE}\n", + ) + account.order.clear() + self.assertEqual(run(account, self.home, "--status", owner=None), 0) + self.assertEqual( + json.loads(account.printed[-1]), + {"google": True, "pin": True, "team": "team.cloudflareaccess.com"}, + ) + self.assertEqual(account.order, []) + def test_the_health_check_names_itself(self): # Found live: the edge's health check answered 403 to Python's # default client name, so the Worker looked undeployed. diff --git a/pm-stack/console/src/actions.ts b/pm-stack/console/src/actions.ts index ad6f61be29..ed9f955dab 100644 --- a/pm-stack/console/src/actions.ts +++ b/pm-stack/console/src/actions.ts @@ -105,6 +105,10 @@ export function actions(ops: Ops, work: Work, push?: Push, devices?: Devices): R touch: ["services"], audit: ids("unit", "action"), }, + // The client's two values are in the arguments: nothing of them is + // 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: () => ({}) }, "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 abc7d4f4bd..3f7978a5ff 100644 --- a/pm-stack/console/src/ops.ts +++ b/pm-stack/console/src/ops.ts @@ -164,6 +164,9 @@ function id(value: unknown, name: string): number { return Number(s); } +/** scripts/expose.py, beside this package's sources. */ +const EXPOSE = join(import.meta.dir, "..", "scripts", "expose.py"); + export class Ops { private queueToken: string | null = null; @@ -471,6 +474,64 @@ export class Ops { return { to: targets, command: command === true }; } + // ---- sign-in ------------------------------------------------------------ + + /** The script that keeps the public address as declared. It is the one + * place that talks to the sign-in gate, so sign-in is read and changed + * through it. */ + private expose(args: string[], stdin?: string) { + return this.run(["python3", EXPOSE, ...args], { stdin, timeoutMs: 120_000 }); + } + + /** Which sign-in methods are on, and what Google has to be told to + * let this gate use it. */ + async signin() { + const r = await this.expose(["--status"]); + let status: { google?: unknown; pin?: unknown; team?: unknown } | null = null; + try { + status = JSON.parse(r.stdout.trim().split("\n").pop() ?? ""); + } catch { + status = null; + } + if (r.code !== 0 || !status || typeof status.team !== "string" || !/^[a-z0-9.-]+$/.test(status.team)) { + throw new OpError(502, "could not read the sign-in settings from Cloudflare"); + } + return { + google: status.google === true, + pin: status.pin === true, + // What goes into the Google client: where sign-ins come from, and + // where Google sends them back. + origin: `https://${status.team}`, + redirect: `https://${status.team}/cdn-cgi/access/callback`, + }; + } + + /** Turn Google sign-in on with an OAuth client the owner made. The two + * values go to the script on its standard input and from there to + * Cloudflare; they are not kept here, logged, or returned. */ + async googleSignin(clientId: unknown, clientSecret: unknown) { + const id = text(clientId, "client ID", 200); + const value = text(clientSecret, "client secret", 200); + if (!/^[0-9]+-[0-9a-z]+\.apps\.googleusercontent\.com$/.test(id)) { + throw new OpError(400, "client ID: one from Google ends in .apps.googleusercontent.com"); + } + if (!/^[\x21-\x7e]{8,200}$/.test(value)) throw new OpError(400, "client secret: not a client secret"); + const r = await this.expose(["--google-stdin"], `${id}\n${value}\n`); + // What the script prints is never one of the two values, but nothing + // is passed on that could hold one. + const said = `${r.stdout}\n${r.stderr}` + .split("\n") + .map((line) => line.trim()) + .filter((line) => line && !line.includes(value) && !line.includes(id)); + if (r.code !== 0) { + throw new OpError( + 502, + `Google sign-in was not turned on: ${(said.pop() ?? "the setup script failed").slice(0, 300)}`, + ); + } + return { google: true, changed: said.filter((line) => line.startsWith("changed: ")).map((line) => line.slice(9)) }; + } + // ---- services ---------------------------------------------------------- async services(): Promise { diff --git a/pm-stack/console/src/server.ts b/pm-stack/console/src/server.ts index 4cd11ed899..0ff23b34e3 100644 --- a/pm-stack/console/src/server.ts +++ b/pm-stack/console/src/server.ts @@ -283,6 +283,7 @@ export async function handle(req: Request, deps: Deps, peer: string | null = nul } if (seg.length === 1 && seg[0] === "push" && deps.push) return json(await deps.push.status()); if (seg.length === 1 && seg[0] === "devices" && deps.phones) return json(await deps.phones.devices.list()); + if (seg.length === 1 && seg[0] === "signin") return json(await ops.signin()); if (seg.length === 1 && seg[0] === "question" && deps.work) { return json(await deps.work.question(query.get("set"), query.get("ledger"), query.get("qid"))); } diff --git a/pm-stack/console/test/console.test.ts b/pm-stack/console/test/console.test.ts index ba2ed260b5..70e5342b31 100644 --- a/pm-stack/console/test/console.test.ts +++ b/pm-stack/console/test/console.test.ts @@ -44,7 +44,7 @@ const CENTRAL: Issuer = { audience: "pm-console", source: "bearer", }; -const OWNER = "drewrypope@gmail.com"; +const OWNER = "owner@example.com"; function b64u(bytes: Uint8Array | string): string { const raw = typeof bytes === "string" ? new TextEncoder().encode(bytes) : bytes; @@ -235,7 +235,7 @@ describe("who is the owner", () => { }); expect( await identify( - edge({ cookie: `x=1; CF_Authorization=${await rsa.sign(good(ACCESS, { email: "DrewryPope@Gmail.com" }))}` }), + edge({ cookie: `x=1; CF_Authorization=${await rsa.sign(good(ACCESS, { email: "Owner@Example.COM" }))}` }), cfg, at(keys), ), @@ -256,7 +256,7 @@ describe("who is the owner", () => { expect(await status(edge({ "cf-access-jwt-assertion": "garbage" }))).toBe(401); expect(await status(edge({ "cf-access-jwt-assertion": await other.sign(good(ACCESS)) }))).toBe(401); expect( - await status(edge({ "cf-access-jwt-assertion": await rsa.sign(good(ACCESS, { email: "someone@gmail.com" })) })), + await status(edge({ "cf-access-jwt-assertion": await rsa.sign(good(ACCESS, { email: "someone@example.net" })) })), ).toBe(403); expect( await status(edge({ "cf-access-jwt-assertion": await rsa.sign(good(ACCESS, { email_verified: false })) })), @@ -326,7 +326,7 @@ describe("configuration", () => { const cfg = readConfig( { HOME: "/h", - PM_CONSOLE_OWNER_EMAILS: " DrewryPope@gmail.com ,", + PM_CONSOLE_OWNER_EMAILS: " Owner@Example.com ,", PM_CONSOLE_ACCESS_TEAM_DOMAIN: "team.cloudflareaccess.com", PM_CONSOLE_ACCESS_AUD: "aud-tag", PM_CONSOLE_ISSUERS_FILE: "/x", diff --git a/pm-stack/console/test/devices.test.ts b/pm-stack/console/test/devices.test.ts index e1cedf5e34..41ea9a64c7 100644 --- a/pm-stack/console/test/devices.test.ts +++ b/pm-stack/console/test/devices.test.ts @@ -476,7 +476,7 @@ describe("over HTTP, without the sign-in", () => { const { token, id } = (await (await w.link(VERIFIER)).json()) as { token: string; id: string }; const asOwner = { ...w.deps, - identify: async () => ({ via: "cloudflare-access", email: "drewrypope@gmail.com" }), + identify: async () => ({ via: "cloudflare-access", email: "owner@example.com" }), }; const listed = await handle( new Request("https://pm.security.cab/console/api/devices", { headers: { host: "pm.security.cab" } }), diff --git a/pm-stack/console/test/signin.test.ts b/pm-stack/console/test/signin.test.ts new file mode 100644 index 0000000000..319540cf6e --- /dev/null +++ b/pm-stack/console/test/signin.test.ts @@ -0,0 +1,131 @@ +// Sign-in settings through the console: reading which methods are on, +// and handing a Google client to the setup script. +// +// Stand-in: the setup script (scripts/expose.py, tested on its own in +// scripts/test_expose.py). Everything else is the console's own code. +// The point of most checks here is where the client's two values go: +// to the script's standard input, and nowhere else. +import { describe, expect, test } from "bun:test"; +import { actions, perform } from "../src/actions.ts"; +import { readConfig } from "../src/config.ts"; +import { Docs } from "../src/docs.ts"; +import { HOLDABLE } from "../src/edge-proto.ts"; +import { OpError, Ops, type RunResult } from "../src/ops.ts"; +import { Work } from "../src/work.ts"; + +const CLIENT = "123456789012-abc123def456.apps.googleusercontent.com"; +const VALUE = "not-a-real-value-0123456789"; +const SECTION_NAMES = [ + "board", + "sessions", + "census", + "asks", + "questionCount", + "questions", + "prs", + "priorities", + "agents", + "services", + "more", +]; + +function setup(answer: (argv: string[], stdin?: string) => Partial) { + const calls: { argv: string[]; stdin?: string }[] = []; + const ops = new Ops(readConfig({ HOME: "/h" }), async (argv, opts) => { + calls.push({ argv, stdin: opts?.stdin }); + return { code: 0, stdout: "", stderr: "", ...answer(argv, opts?.stdin) }; + }); + return { ops, calls, table: actions(ops, new Work(ops)) }; +} + +describe("sign-in", () => { + test("which methods are on is read through the setup script, with what Google must be told", async () => { + const w = setup(() => ({ + stdout: 'note: something\n{"google": false, "pin": true, "team": "team-1.cloudflareaccess.com"}\n', + })); + expect(await w.ops.signin()).toEqual({ + google: false, + pin: true, + origin: "https://team-1.cloudflareaccess.com", + redirect: "https://team-1.cloudflareaccess.com/cdn-cgi/access/callback", + }); + expect(w.calls).toHaveLength(1); + expect(w.calls[0].argv[0]).toBe("python3"); + expect(w.calls[0].argv[1]).toMatch(/\/pm-stack\/console\/scripts\/expose\.py$/); + expect(w.calls[0].argv.slice(2)).toEqual(["--status"]); + // A script that failed, or said something that is not a team's domain, is no answer. + for (const bad of [ + { code: 1, stdout: '{"google": true, "pin": true, "team": "t.cloudflareaccess.com"}' }, + { stdout: "not json" }, + { stdout: '{"google": true, "pin": true, "team": "evil.example/x?"}' }, + { stdout: '{"google": true, "pin": true}' }, + ]) { + const failed = await setup(() => bad) + .ops.signin() + .catch((error) => error); + expect(failed).toBeInstanceOf(OpError); + expect(failed.status).toBe(502); + } + }); + + test("a Google client goes to the script's standard input and nowhere else", async () => { + const w = setup(() => ({ + stdout: "changed: access: add Google sign-in\nchanged: access: application for pm.example\n", + })); + const docs = new Docs( + Object.fromEntries(SECTION_NAMES.map((name) => [name, { ttlMs: 1000, load: async () => ({}) }])), + ); + const result = await perform(w.table, docs, "sso.google", { clientId: ` ${CLIENT} `, clientSecret: `${VALUE}\n` }); + expect(result).toEqual({ + google: true, + changed: ["access: add Google sign-in", "access: application for pm.example"], + }); + expect(w.calls).toHaveLength(1); + expect(w.calls[0].argv.slice(2)).toEqual(["--google-stdin"]); + expect(w.calls[0].stdin).toBe(`${CLIENT}\n${VALUE}\n`); + // Not on the command line, where any process listing would show it. + expect(w.calls[0].argv.join(" ")).not.toContain(VALUE); + expect(w.calls[0].argv.join(" ")).not.toContain(CLIENT); + // Not in the record of what was done, and never kept to be done late. + expect(w.table["sso.google"].audit({ clientId: CLIENT, clientSecret: VALUE })).toEqual({}); + expect(HOLDABLE.has("sso.google")).toBe(false); + expect(JSON.stringify(result)).not.toContain(VALUE); + }); + + test("what is not a Google client is refused before the script is run", async () => { + const w = setup(() => ({})); + for (const args of [ + { clientId: "", clientSecret: VALUE }, + { clientId: "my-client", clientSecret: VALUE }, + { clientId: `${CLIENT}.evil.example`, clientSecret: VALUE }, + { clientId: CLIENT, clientSecret: "" }, + { clientId: CLIENT, clientSecret: "short" }, + { clientId: CLIENT, clientSecret: "two words here" }, + { clientId: CLIENT, clientSecret: `${VALUE}\n--status` }, + { clientId: CLIENT }, + ]) { + const refused = await w.ops + .googleSignin((args as { clientId: string }).clientId, (args as { clientSecret?: string }).clientSecret) + .catch((error) => error); + expect(refused).toBeInstanceOf(OpError); + expect(refused.status).toBe(400); + expect(refused.message).not.toContain(VALUE); + } + expect(w.calls).toEqual([]); + }); + + test("a script that fails says why, without either value even if the script printed one", async () => { + const w = setup(() => ({ + code: 1, + stdout: "", + stderr: `cloudflare POST /accounts/a/access/identity_providers: [{"message": "invalid client"}]\nechoed ${VALUE} by mistake\n`, + })); + const failed = await w.ops.googleSignin(CLIENT, VALUE).catch((error) => error); + expect(failed).toBeInstanceOf(OpError); + expect(failed.status).toBe(502); + expect(failed.message).toBe( + 'Google sign-in was not turned on: cloudflare POST /accounts/a/access/identity_providers: [{"message": "invalid client"}]', + ); + expect(failed.message).not.toContain(VALUE); + }); +}); diff --git a/pm-stack/console/test/work.test.ts b/pm-stack/console/test/work.test.ts index 65ae0c90cd..ac22898fd5 100644 --- a/pm-stack/console/test/work.test.ts +++ b/pm-stack/console/test/work.test.ts @@ -726,7 +726,7 @@ describe("the interface's endpoints", () => { docs, actions: actions(w.ops, work), identify: async () => { - if (who === "owner") return { via: "cloudflare-access", email: "drewrypope@gmail.com" }; + if (who === "owner") return { via: "cloudflare-access", email: "owner@example.com" }; throw new (await import("../src/auth.ts")).AuthError(401, "sign-in required"); }, audit: async (e) => {