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>
This commit is contained in:
neil 2026-11-05 21:44:09 -08:00
parent d07a92e5b5
commit e814a2359d
11 changed files with 1155 additions and 26 deletions

View file

@ -40,7 +40,7 @@ def guard(paths, root):
paths.BIN_DIR = Path(root) / ".local/bin"
paths.SHIM = paths.BIN_DIR / "llmhost"
paths.LOG_DIR = Path(root) / "logs"
for name in ("DATA", "CONFIG_DIR", "CONFIG_FILE", "KEY_FILE", "BIN_DIR", "SHIM", "LOG_DIR"):
for name in ("DATA", "CONFIG_DIR", "CONFIG_FILE", "KEY_FILE", "OIDC_SECRET_FILE", "NEWT_SECRET_FILE", "NEWT_DIR", "BIN_DIR", "SHIM", "LOG_DIR"):
value = str(getattr(paths, name))
if not value.startswith(root):
sys.exit(f"ABORT: paths.{name} = {value} is outside the sandbox {root}")

View file

@ -0,0 +1,225 @@
"""Dashboard sign-in: API key mode, and OIDC against a fake provider, through the real handler."""
import base64
import hashlib
import http.client
import json
import sys
import threading
import urllib.parse
from http.server import ThreadingHTTPServer
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import harness
ROOT = harness.setup()
from llmhost import cli, paths
from llmhost.web import oidc as oidc_mod
from llmhost.web import server as web
harness.guard(paths, ROOT)
check = harness.Checks()
ISSUER = "https://auth.example.test"
PUBLIC = "https://dash.example.test"
KEY = "sk-test"
def b64(obj):
return base64.urlsafe_b64encode(json.dumps(obj).encode()).rstrip(b"=").decode()
class FakeProvider:
"""Discovery, token and userinfo endpoints. The test sets what the next token
response's claims and userinfo look like."""
def __init__(self):
self.claims = {}
self.userinfo = {}
self.challenges = {} # code -> code_challenge
self.token_calls = 0
def __call__(self, method, url, data=None, headers=None):
if url == ISSUER + "/.well-known/openid-configuration":
return 200, json.dumps({
"issuer": ISSUER, "authorization_endpoint": ISSUER + "/authorize",
"token_endpoint": ISSUER + "/token", "userinfo_endpoint": ISSUER + "/userinfo"}).encode()
if url == ISSUER + "/token":
self.token_calls += 1
form = {k: v[0] for k, v in urllib.parse.parse_qs(data.decode()).items()}
want = "Basic " + base64.b64encode(b"llm-host:s3cret").decode()
if headers.get("Authorization") != want:
return 401, b'{"error": "invalid_client"}'
verifier = form.get("code_verifier", "")
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()
if self.challenges.get(form.get("code")) != challenge:
return 400, b'{"error": "invalid_grant"}'
if form.get("redirect_uri") != PUBLIC + "/auth/callback":
return 400, b'{"error": "invalid_grant"}'
return 200, json.dumps({"id_token": f"h.{b64(self.claims)}.sig", "access_token": "at"}).encode()
if url == ISSUER + "/userinfo":
return 200, json.dumps(self.userinfo).encode()
return 404, b"{}"
class StubSampler:
def __init__(self):
self.resets = 0
def snapshot(self):
return {"ok": True}
def reset_stats(self):
self.resets += 1
def serve(oidc):
srv = ThreadingHTTPServer(("127.0.0.1", 0), web.make_handler(StubSampler(), KEY, oidc))
threading.Thread(target=srv.serve_forever, daemon=True).start()
return srv
def req(srv, method, path, headers=None, body=None):
c = http.client.HTTPConnection("127.0.0.1", srv.server_address[1], timeout=5)
c.request(method, path, body=body, headers=headers or {})
r = c.getresponse()
data = r.read()
out = (r.status, dict((k.lower(), v) for k, v in r.getheaders()), data,
[v for k, v in r.getheaders() if k.lower() == "set-cookie"])
c.close()
return out
PUB_HOST = {"Host": "dash.example.test"}
print("\n1. API key mode is unchanged")
srv = serve(None)
st, _, body, _ = req(srv, "GET", "/auth/config")
check("config reports key mode", st == 200 and json.loads(body)["mode"] == "key", body)
check("status without key -> 401", req(srv, "GET", "/api/status")[0] == 401)
check("status with key -> 200", req(srv, "GET", "/api/status", {"Authorization": f"Bearer {KEY}"})[0] == 200)
check("no /auth/login without OIDC", req(srv, "GET", "/auth/login")[0] == 404)
srv.shutdown()
print("\n2. OIDC mode refuses the key and unsigned visitors")
prov = FakeProvider()
conf = {"mode": "oidc", "issuer": ISSUER, "client_id": "llm-host", "public_url": PUBLIC,
"allowed_groups": ["llm-admins"], "allowed_users": ["friend"]}
o = oidc_mod.OIDC(conf, "s3cret", http=prov)
srv = serve(o)
st, _, body, _ = req(srv, "GET", "/auth/config", PUB_HOST)
check("config reports oidc, nobody signed in", json.loads(body) == {"mode": "oidc", "user": None, "name": None}, body)
check("status without session -> 401", req(srv, "GET", "/api/status", PUB_HOST)[0] == 401)
check("the API key no longer opens it", req(srv, "GET", "/api/status", {**PUB_HOST, "Authorization": f"Bearer {KEY}"})[0] == 401)
st, h, _, _ = req(srv, "GET", "/", {"Host": "mybox.local:11340"})
check("a LAN name is sent to the public URL", st == 302 and h["location"] == PUBLIC + "/", h.get("location"))
st, h, _, _ = req(srv, "GET", "/auth/login", {"Host": "mybox.local:11340"})
check("login by a LAN name starts on the public URL", st == 302 and h["location"] == PUBLIC + "/auth/login")
try:
oidc_mod.OIDC({**conf, "allowed_groups": [], "allowed_users": []}, "x")
check("an allow list is required", False)
except ValueError:
check("an allow list is required", True)
def login(claims_over=None, userinfo=None, cookie_state=None, tamper_state=None):
"""Run /auth/login then /auth/callback. Returns (callback status, session cookie or None, body)."""
st, h, _, cookies = req(srv, "GET", "/auth/login", PUB_HOST)
assert st == 302, st
q = {k: v[0] for k, v in urllib.parse.parse_qs(urllib.parse.urlsplit(h["location"]).query).items()}
code = "code-" + q["state"][:8]
prov.challenges[code] = q["code_challenge"]
prov.claims = {"iss": ISSUER, "aud": "llm-host", "exp": 9e9, "iat": 1, "sub": "u1",
"nonce": q["nonce"], "preferred_username": "alice", **(claims_over or {})}
prov.userinfo = {"sub": "u1", "preferred_username": "alice", "name": "Alice",
"groups": ["llm-admins"]} if userinfo is None else userinfo
state_cookie = cookies[0].split(";")[0]
if cookie_state is not None:
state_cookie = f"{oidc_mod.STATE_COOKIE}={cookie_state}"
st, h, body, cookies = req(srv, "GET", "/auth/callback?" + urllib.parse.urlencode(
{"code": code, "state": tamper_state or q["state"], "iss": ISSUER}), {**PUB_HOST, "Cookie": state_cookie})
sess = next((c.split(";")[0] for c in cookies if c.startswith(oidc_mod.SESSION_COOKIE + "=")), None)
return st, sess, body, q, h
print("\n3. the authorization request")
st, h, _, cookies = req(srv, "GET", "/auth/login", PUB_HOST)
q = {k: v[0] for k, v in urllib.parse.parse_qs(urllib.parse.urlsplit(h["location"]).query).items()}
check("redirects to the provider", h["location"].startswith(ISSUER + "/authorize?"))
check("PKCE S256", q.get("code_challenge_method") == "S256" and len(q.get("code_challenge", "")) == 43)
check("redirect URI is the public callback", q.get("redirect_uri") == PUBLIC + "/auth/callback")
check("asks for groups", "groups" in q.get("scope", "").split())
check("state cookie is HttpOnly, Secure, Lax, scoped to /auth/",
all(a in cookies[0] for a in ("HttpOnly", "Secure", "SameSite=Lax", "Path=/auth/")), cookies)
print("\n4. a good sign-in")
st, sess, body, q, h = login()
check("callback -> 302 home", st == 302 and h["location"] == "/", (st, body))
check("session cookie set", sess is not None)
st, _, body, _ = req(srv, "GET", "/api/status", {**PUB_HOST, "Cookie": sess})
check("status with session -> 200", st == 200, st)
st, _, body, _ = req(srv, "GET", "/auth/config", {**PUB_HOST, "Cookie": sess})
check("config names the user", json.loads(body)["user"] == "alice" and json.loads(body)["name"] == "Alice", body)
st, _, _, _ = req(srv, "POST", "/api/stats/reset", {**PUB_HOST, "Cookie": sess})
check("POST without Origin -> 403", st == 403, st)
st, _, _, _ = req(srv, "POST", "/api/stats/reset", {**PUB_HOST, "Cookie": sess, "Origin": "https://evil.test"})
check("POST from another origin -> 403", st == 403, st)
st, _, _, _ = req(srv, "POST", "/api/stats/reset", {**PUB_HOST, "Cookie": sess, "Origin": PUBLIC})
check("POST from the dashboard's origin -> 200", st == 200, st)
check("only the session's hash is stored", sess.split("=", 1)[1] not in o.sessions)
print("\n5. sign-ins that must fail")
before = len(o.sessions)
st, sess2, body, *_ = login(cookie_state="someone-elses-state")
check("state cookie mismatch -> 403, no session", st == 403 and sess2 is None, st)
st, sess2, *_ = login(claims_over={"nonce": "wrong"})
check("wrong nonce -> 403", st == 403 and sess2 is None, st)
st, sess2, *_ = login(claims_over={"aud": "other-client"})
check("ID token for another client -> 403", st == 403 and sess2 is None, st)
st, sess2, *_ = login(claims_over={"iss": "https://evil.test"})
check("ID token from another issuer -> 403", st == 403 and sess2 is None, st)
st, sess2, *_ = login(claims_over={"exp": 1})
check("expired ID token -> 403", st == 403 and sess2 is None, st)
st, sess2, body, *_ = login(userinfo={"sub": "u1", "preferred_username": "stranger", "groups": ["users"]},
claims_over={"preferred_username": "stranger"})
check("not in an allowed group -> 403", st == 403 and sess2 is None and b"isn&#x27;t allowed" in body, body[:200])
st, sess2, *_ = login(userinfo={"sub": "u1", "preferred_username": "friend", "groups": []},
claims_over={"preferred_username": "friend"})
check("an allowed username gets in without the group", st == 302 and sess2 is not None, st)
st, sess3, *_ = login(userinfo={"sub": "OTHER", "preferred_username": "x", "groups": ["llm-admins"]},
claims_over={"preferred_username": "stranger"})
check("userinfo for a different sub is ignored", st == 403 and sess3 is None, st)
st, _, _, _ = req(srv, "GET", "/auth/callback?error=access_denied&state=x", {**PUB_HOST, "Cookie": f"{oidc_mod.STATE_COOKIE}=x"})
check("provider error -> 403", st == 403, st)
check("no stray sessions from the failures", len(o.sessions) == before + 1, len(o.sessions))
# A state can be used once.
st, h, _, cookies = req(srv, "GET", "/auth/login", PUB_HOST)
q = {k: v[0] for k, v in urllib.parse.parse_qs(urllib.parse.urlsplit(h["location"]).query).items()}
prov.challenges["c1"] = q["code_challenge"]
prov.claims = {"iss": ISSUER, "aud": "llm-host", "exp": 9e9, "sub": "u1", "nonce": q["nonce"]}
prov.userinfo = {"sub": "u1", "preferred_username": "alice", "groups": ["llm-admins"]}
cb = "/auth/callback?" + urllib.parse.urlencode({"code": "c1", "state": q["state"]})
hdr = {**PUB_HOST, "Cookie": cookies[0].split(";")[0]}
check("first use of a state works", req(srv, "GET", cb, hdr)[0] == 302)
check("replaying it -> 403", req(srv, "GET", cb, hdr)[0] == 403)
print("\n6. sign-out")
st, sess, *_ = login()
check("logout from another origin -> 403", req(srv, "POST", "/auth/logout", {**PUB_HOST, "Cookie": sess, "Origin": "https://evil.test"})[0] == 403)
st, _, _, cookies = req(srv, "POST", "/auth/logout", {**PUB_HOST, "Cookie": sess, "Origin": PUBLIC})
check("logout -> 200 and clears the cookie", st == 200 and "Max-Age=0" in cookies[0], cookies)
check("the old cookie no longer works", req(srv, "GET", "/api/status", {**PUB_HOST, "Cookie": sess})[0] == 401)
srv.shutdown()
print("\n7. setup keeps the dashboard's sign-in setting")
carried = cli.carried_settings({"dashboard_auth": conf, "reasoning": {"m": "low"}}, {"m"})
check("dashboard_auth carried", carried.get("dashboard_auth") == conf, carried)
check("reasoning still carried", carried.get("reasoning") == {"m": "low"})
check("nothing invented when unset", "dashboard_auth" not in cli.carried_settings({}, set()))
print("\n8. the client secret is stored privately")
paths.save_secret(paths.OIDC_SECRET_FILE, "s3cret")
check("secret file is 0600", (paths.OIDC_SECRET_FILE.stat().st_mode & 0o777) == 0o600)
check("reads back", paths.oidc_secret() == "s3cret")
check.done(ROOT)

163
tests/test_newt.py Normal file
View file

@ -0,0 +1,163 @@
"""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)