llm-host/tests/test_newt.py
neil e814a2359d install-newt: optional internet access via a Pangolin tunnel, with OIDC sign-in on the dashboard
A plain install is unchanged: LAN-only, dashboard behind the API key. `llmhost install-newt`
is the upgrade path. It installs a pinned, sha256-checked newt as a third user service and
switches the dashboard to an OIDC authorization-code + PKCE sign-in limited to allowed groups
or users. The API still takes the key. Secrets live in 0600 files, never in config.json, a
service file or argv. `llmhost remove-newt` undoes it; setup/update keep it; `logs --newt`
shows the tunnel (and `logs -f` now follows the service it was asked for).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 21:44:09 -08:00

163 lines
7.3 KiB
Python

"""install-newt / remove-newt: pinned download, secrets kept out of config and output,
OIDC switched on with the tunnel and off again, all against fake services."""
import contextlib
import hashlib
import io
import json
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import harness
ROOT = harness.setup()
from llmhost import cli, newt, 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()))
sys.stdin = io.StringIO() # no terminal: missing values are errors, not prompts
def run(argv, env=None):
import os
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 = io.StringIO(), 0
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:
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)
ARGS = ["install-newt", "--endpoint", "https://pangolin.example.test", "--newt-id", "site123",
"--public-url", "https://dash.example.test", "--issuer", ISSUER, "--allow-group", "llm-admins"]
SECRETS = {"LLMHOST_NEWT_SECRET": NEWT_SECRET, "LLMHOST_OIDC_SECRET": OIDC_SECRET}
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("version recorded", newt.installed_version() == newt.VERSION)
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 needs everything, without a terminal")
code, out = run(ARGS)
check("missing secrets -> error", code != 0 and "LLMHOST_NEWT_SECRET" in out, out)
code, out = run([a for a in ARGS if a not in ("--allow-group", "llm-admins")], SECRETS)
check("no allow list -> error", code != 0 and "allow" in out, out)
code, out = run([*ARGS[:6], "http://dash.example.test", *ARGS[7:]], SECRETS)
check("an http:// public URL is refused", code != 0 and "https" in out, out)
check("nothing configured by the failures", "newt" not in paths.load_config() and not installed)
print("\n4. install-newt")
calls.clear()
code, out = run(ARGS, SECRETS)
c = paths.load_config()
check("succeeds", code == 0, out)
check("newt config saved", c.get("newt") == {"endpoint": "https://pangolin.example.test", "id": "site123"}, c.get("newt"))
check("dashboard switched to OIDC", c["dashboard_auth"]["mode"] == "oidc" and c["dashboard_auth"]["issuer"] == ISSUER)
check("allow list saved", c["dashboard_auth"]["allowed_groups"] == ["llm-admins"])
check("newt service installed and started", ("install", "newt") in calls and ("restart", "newt") in calls, calls)
check("dashboard restarted to pick up sign-in", ("restart", "web") in calls, calls)
check("secrets saved 0600", all((f.stat().st_mode & 0o777) == 0o600
for f in (paths.NEWT_SECRET_FILE, paths.OIDC_SECRET_FILE)))
check("secrets read back", paths.NEWT_SECRET_FILE.read_text().strip() == NEWT_SECRET
and paths.oidc_secret() == OIDC_SECRET)
cfg_text = paths.CONFIG_FILE.read_text()
check("no secret in config.json", NEWT_SECRET not in cfg_text and OIDC_SECRET not in cfg_text)
check("no secret in the output", NEWT_SECRET not in out and OIDC_SECRET not in out)
check("prints the redirect URI", "https://dash.example.test/auth/callback" in out, out)
print("\n5. a re-run keeps what it isn't given")
code, out = run(["install-newt", "--newt-id", "site456"])
c = paths.load_config()
check("re-run without secrets succeeds", code == 0, out)
check("changed value updated", c["newt"]["id"] == "site456")
check("other values kept", c["newt"]["endpoint"] == "https://pangolin.example.test"
and c["dashboard_auth"]["allowed_groups"] == ["llm-admins"])
check("secrets kept", paths.NEWT_SECRET_FILE.read_text().strip() == NEWT_SECRET and paths.oidc_secret() == OIDC_SECRET)
print("\n6. newt starts with its credentials in the environment, not its arguments")
seen = {}
import os
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("runs the installed binary", seen["exe"] == str(newt.binary()))
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("\n7. setup/update keep it")
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("\n8. remove-newt")
calls.clear()
code, out = run(["remove-newt"])
c = paths.load_config()
check("succeeds", code == 0, out)
check("service removed", ("uninstall", "newt") in calls and "newt" not in installed, calls)
check("config back to LAN", "newt" not in c and "dashboard_auth" not in c)
check("secrets deleted", not paths.NEWT_SECRET_FILE.exists() and not paths.OIDC_SECRET_FILE.exists())
check("binary deleted", not newt.binary().exists())
check("dashboard restarted", ("restart", "web") in calls)
check("rest of the config untouched", c.get("api_port") == cfg.get("api_port") and c.get("models") == cfg.get("models"))
code, out = run(["remove-newt"])
check("running it again is harmless", code == 0 and "wasn't installed" in out, out)
check.done(ROOT)