"""The internet upgrades, against fake services: install-newt (API only, pinned download, secrets kept out of config/output/argv), install-oidc, install-otp, expose-dashboard, and their remove-* undo commands.""" import contextlib import hashlib import io import json import os import sys import time from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) import harness ROOT = harness.setup() from llmhost import cli, newt, otp, paths, service from llmhost.web import oidc harness.guard(paths, ROOT) check = harness.Checks() ISSUER = "https://auth.example.test" NEWT_SECRET = "newt-site-secret-xyz" OIDC_SECRET = "oidc-client-secret-xyz" # -- fakes ------------------------------------------------------------------------------ calls = [] installed = set() service.install = lambda n: (calls.append(("install", n)), installed.add(n)) service.uninstall = lambda n: (calls.append(("uninstall", n)), installed.discard(n)) service.restart = lambda n: calls.append(("restart", n)) or True service.installed = lambda n: n in installed service.state = lambda n: ("active", 1.0) FAKE_BIN = b"\x7fELF fake newt" newt.SHA256 = {k: hashlib.sha256(FAKE_BIN).hexdigest() for k in newt.SHA256} fetches = [] newt._fetch = lambda url: (fetches.append(url), FAKE_BIN)[1] oidc.OIDC._http = staticmethod(lambda m, url, data=None, headers=None: (200, json.dumps({ "issuer": ISSUER, "authorization_endpoint": ISSUER + "/a", "token_endpoint": ISSUER + "/t"}).encode())) class TTY(io.StringIO): def isatty(self): return True def run(argv, env=None, tty_input=None): """Run the CLI. Without tty_input there's no terminal (missing values are errors, not prompts); with it, stdin/stdout are a terminal and input() reads those lines.""" saved = {k: os.environ.get(k) for k in ("LLMHOST_NEWT_SECRET", "LLMHOST_OIDC_SECRET")} for k in saved: os.environ.pop(k, None) os.environ.update(env or {}) out, code = (TTY() if tty_input is not None else io.StringIO()), 0 old_in = sys.stdin sys.stdin = TTY("".join(l + "\n" for l in tty_input)) if tty_input is not None else io.StringIO() try: with contextlib.redirect_stdout(out): cli.main(argv) except SystemExit as e: code = e.code if isinstance(e.code, int) else (0 if e.code is None else 1) if isinstance(e.code, str): out.write(e.code) finally: sys.stdin = old_in for k, v in saved.items(): os.environ.pop(k, None) if v is not None: os.environ[k] = v return code, out.getvalue() cfg = harness.config() paths.save_config(cfg) paths.api_key(create=True) NEWT_ARGS = ["install-newt", "--api-url", "https://llm-api.example.test", "--endpoint", "https://pangolin.example.test", "--newt-id", "site123"] NEWT_CONF = {"endpoint": "https://pangolin.example.test", "id": "site123", "api_url": "https://llm-api.example.test"} OIDC_ARGS = ["install-oidc", "--public-url", "https://dash.example.test", "--issuer", ISSUER, "--client-id", "client-from-provider", "--allow-group", "llm-admins"] print("\n1. a plain install doesn't include newt") check("setup's services are model and web only", service.NAMES == ("model", "web"), service.NAMES) check("newt is an optional service", "newt" in service.OPTIONAL) print("\n2. the pinned download is checked") real = dict(newt.SHA256) newt.SHA256 = {k: "0" * 64 for k in real} try: newt.ensure_binary(lambda *_: None) check("a bad checksum is refused", False) except SystemExit as e: check("a bad checksum is refused", "checksum" in str(e), e) check("nothing installed after a bad checksum", not newt.binary().exists()) newt.SHA256 = real check("good checksum installs", newt.ensure_binary(lambda *_: None) is True) check("binary is executable", newt.binary().stat().st_mode & 0o111) check("second call is a no-op", newt.ensure_binary(lambda *_: None) is False) check("download URL is the pinned GitHub release", fetches[-1].startswith(f"https://github.com/fosrl/newt/releases/download/{newt.VERSION}/newt_"), fetches) print("\n3. install-newt: the API only") print("\n3a. the client commands before the tunnel: the local network only") code, out = run(["opencode-config"]) check("opencode-config: one command, the LAN address", code == 0 and out.count("opencode-install.sh") == 1 and f"--url http://{cli.default_host()}:{cfg['api_port']}" in out, out) code, out = run(["install-newt", "--endpoint", "https://pangolin.example.test", "--newt-id", "x"], {"LLMHOST_NEWT_SECRET": NEWT_SECRET}) check("the API's public URL is required", code != 0 and "--api-url" in out, out) code, out = run(["install-newt", "--api-url", "https://pangolin.example.test", "--endpoint", "https://pangolin.example.test", "--newt-id", "x"], {"LLMHOST_NEWT_SECRET": NEWT_SECRET}) check("API URL = Pangolin endpoint is refused", code != 0 and "can't be the same" in out, out) code, out = run(NEWT_ARGS) check("missing secret without a terminal -> error", code != 0 and "LLMHOST_NEWT_SECRET" in out, out) calls.clear() code, out = run(NEWT_ARGS, {"LLMHOST_NEWT_SECRET": NEWT_SECRET}) c = paths.load_config() check("succeeds", code == 0, out) check("newt config saved, with the API's public URL", c.get("newt") == NEWT_CONF, c.get("newt")) check("the resource is named by the API's host", f"llm-api.example.test -> http://" in out, out) check("prints the opencode command for the public URL", "opencode-install.sh)\" -- --url https://llm-api.example.test" in out, out) check("dashboard sign-in untouched", "dashboard_auth" not in c and not paths.OIDC_SECRET_FILE.exists()) check("newt service installed and started", ("install", "newt") in calls and ("restart", "newt") in calls, calls) check("dashboard not restarted", ("restart", "web") not in calls, calls) check("only the API resource is described", f":{c['api_port']}" in out and f":{c['web_port']}" not in out, out) check("points to expose-dashboard for the rest", "expose-dashboard" in out and "install-oidc" in out, out) check("secret saved 0600, not in config or output", (paths.NEWT_SECRET_FILE.stat().st_mode & 0o777) == 0o600 and NEWT_SECRET not in paths.CONFIG_FILE.read_text() and NEWT_SECRET not in out) code, out = run(["install-newt", "--newt-id", "site456"]) c = paths.load_config() check("re-run keeps what it isn't given", code == 0 and c["newt"] == {**NEWT_CONF, "id": "site456"} and paths.NEWT_SECRET_FILE.read_text().strip() == NEWT_SECRET, out) code, out = run(["install-newt", "--api-url", "https://llm-api.example.test/v1/"]) check("a trailing /v1 is dropped", code == 0 and paths.load_config()["newt"]["api_url"] == "https://llm-api.example.test", out) print("\n3b. tunnel up, dashboard local: both commands") code, out = run(["opencode-config"]) check("opencode-config: internet first, then local", code == 0 and out.count("opencode-install.sh") == 2 and out.index("--url https://llm-api.example.test") < out.index(f"--url http://{cli.default_host()}"), out) check("by hand: for the public URL", '"baseURL": "https://llm-api.example.test/v1"' in out, out) code, out = run(["status"]) check("status: API URL and a local dashboard", "API at https://llm-api.example.test/v1" in out and "local network only" in out, out) print("\n4. newt starts with its credentials in the environment, not its arguments") seen = {} real_execve = os.execve os.execve = lambda exe, argv, env: seen.update(exe=exe, argv=argv, env=env) newt.run() os.execve = real_execve check("no secret on the command line", seen["argv"] == [str(newt.binary())], seen["argv"]) check("endpoint, id and secret in env", (seen["env"]["PANGOLIN_ENDPOINT"], seen["env"]["NEWT_ID"], seen["env"]["NEWT_SECRET"]) == ("https://pangolin.example.test", "site456", NEWT_SECRET)) print("\n5. expose-dashboard won't publish behind the API key alone without asking") code, out = run(["expose-dashboard", "--public-url", "https://dash.example.test"]) check("refused without a terminal or --force", code != 0 and "install-oidc" in out and "install-otp" in out, out) code, out = run(["expose-dashboard", "--public-url", "https://dash.example.test"], tty_input=["n"]) check("refused when you say no", code != 0 and "Not published" in out, out) code, out = run(["expose-dashboard", "--public-url", "https://dash.example.test", "--force"]) check("--force walks through it anyway", code == 0 and f":{paths.load_config()['web_port']}" in out and "dash.example.test" in out, out) c = paths.load_config() check("records that the dashboard is public, not where", c.get("dashboard_public") is True and "dash.example.test" not in json.dumps({k: v for k, v in c.items() if k != "dashboard_auth"}), c.get("dashboard_public")) code, out = run(["opencode-config"]) check("dashboard public: only the internet command", code == 0 and out.count("opencode-install.sh") == 1 and "--url https://llm-api.example.test" in out and f"http://{cli.default_host()}" not in out.split("Or by hand")[0], out) print("\n6. install-oidc") code, out = run(OIDC_ARGS) check("missing secret -> error", code != 0 and "LLMHOST_OIDC_SECRET" in out, out) code, out = run([a for a in OIDC_ARGS if a not in ("--allow-group", "llm-admins")], {"LLMHOST_OIDC_SECRET": OIDC_SECRET}) check("no allow list -> error", code != 0 and "allow" in out, out) calls.clear() code, out = run(OIDC_ARGS, {"LLMHOST_OIDC_SECRET": OIDC_SECRET}) c = paths.load_config() check("succeeds", code == 0, out) check("dashboard switched to OIDC", c["dashboard_auth"]["mode"] == "oidc" and c["dashboard_auth"]["client_id"] == "client-from-provider") check("newt untouched", c["newt"]["id"] == "site456") check("dashboard restarted", ("restart", "web") in calls, calls) check("prints the redirect URI", "https://dash.example.test/auth/callback" in out, out) check("secret 0600, not in config or output", (paths.OIDC_SECRET_FILE.stat().st_mode & 0o777) == 0o600 and OIDC_SECRET not in paths.CONFIG_FILE.read_text() and OIDC_SECRET not in out) code, out = run(["expose-dashboard"]) check("expose-dashboard with OIDC: no question, URL from OIDC", code == 0 and "dash.example.test" in out and "redirect URI" in out, out) print("\n7. install-otp") code, out = run(["install-otp"]) check("needs a terminal", code != 0 and "terminal" in out, out) FIXED = "JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP" otp.new_secret = lambda: FIXED code, out = run(["install-otp"], tty_input=["000000", "000001", "000002"]) check("wrong codes -> not paired", code != 0 and not paths.OTP_SECRET_FILE.exists(), out) calls.clear() code, out = run(["install-otp"], tty_input=[otp.code_at(FIXED, time.time())]) check("right code -> paired", code == 0 and paths.OTP_SECRET_FILE.read_text().strip() == FIXED, out) check("secret 0600", (paths.OTP_SECRET_FILE.stat().st_mode & 0o777) == 0o600) check("showed a QR code and the manual key", "▀" in out and otp.grouped(FIXED) in out, out[:300]) check("says OIDC takes precedence while it's on", "remove-oidc" in out, out) check("dashboard restarted", ("restart", "web") in calls) code, out = run(["install-otp"], tty_input=["n"]) check("re-running asks before replacing", code != 0 and "kept" in out and paths.OTP_SECRET_FILE.read_text().strip() == FIXED, out) code, out = run(["install-otp", "--show"], tty_input=[]) check("--show shows the existing pairing", code == 0 and otp.grouped(FIXED) in out, out[:200]) print("\n8. status and setup keep it all") code, out = run(["status"]) check("status names the sign-in", "OIDC via " + ISSUER in out, out) carried = cli.carried_settings(paths.load_config(), set()) check("newt and dashboard_auth carried", "newt" in carried and "dashboard_auth" in carried, carried.keys()) print("\n9. remove-oidc, then expose-dashboard with codes") code, out = run(["remove-oidc"]) c = paths.load_config() check("OIDC off, secret deleted", code == 0 and "dashboard_auth" not in c and not paths.OIDC_SECRET_FILE.exists(), out) check("says codes work again", "authenticator code" in out, out) code, out = run(["status"]) check("status: key or code", "API key or authenticator code" in out, out) code, out = run(["expose-dashboard", "--public-url", "https://dash.example.test"], tty_input=["y", ""]) c = paths.load_config() check("offers to turn the key off for the dashboard", code == 0 and c.get("dashboard_key_login") is False, out) code, out = run(["status"]) check("status: codes only", "sign-in authenticator code" in out, out) check("setup keeps the key switched off", cli.carried_settings(c, set()).get("dashboard_key_login") is False) print("\n10. remove-otp and remove-newt") code, out = run(["remove-otp"]) c = paths.load_config() check("unpaired, key back on", code == 0 and not paths.OTP_SECRET_FILE.exists() and "dashboard_key_login" not in c, out) calls.clear() code, out = run(["remove-newt"]) c = paths.load_config() check("newt removed", code == 0 and ("uninstall", "newt") in calls and "newt" not in c and not paths.NEWT_SECRET_FILE.exists() and not newt.binary().exists(), out) check("and the dashboard no longer counts as public", "dashboard_public" not in c) check("rest of the config untouched", c.get("api_port") == cfg.get("api_port") and c.get("models") == cfg.get("models")) code, out = run(["expose-dashboard"]) check("expose-dashboard needs newt first", code != 0 and "install-newt" in out, out) code, out = run(["remove-newt"]) check("running it again is harmless", code == 0 and "wasn't installed" in out, out) check.done(ROOT)