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

@ -50,9 +50,11 @@ PYTHONPATH=. python3 -P -m llmhost plan --simulate apple:64 # a 64 GB Mac
| `llmhost switch <model>` | serve a different model (downloads it first if needed) |
| `llmhost download <model>` | download ahead of time |
| `llmhost watch` | download and loading progress, until the model is ready |
| `llmhost logs -f` | follow the model server log |
| `llmhost logs -f` | follow the model server log (`--web` for the dashboard's, `--newt` for the tunnel's) |
| `llmhost start` / `stop` / `restart` | control the model server (stop frees the GPU) |
| `llmhost key` | print the API key |
| `llmhost install-newt` | optional: reach this server from the internet through a Pangolin tunnel, with OIDC sign-in on the dashboard (see [Reaching it from the internet](#reaching-it-from-the-internet)) |
| `llmhost remove-newt` | undo `install-newt`: back to LAN-only, dashboard back to the API key |
| `llmhost opencode-setup` | install opencode here if needed and connect it to this server |
| `llmhost opencode-config` | print what to add to opencode on another machine |
| `llmhost opencode-remove` | take llm-host back out of this machine's opencode config (`--host` for a retired remote server, `--all` for every one) |
@ -67,6 +69,86 @@ prompt tokens with the seconds and rate of the prefill, then generated tokens wi
the generation. A request that didn't stream has no first-token mark, so its prompt seconds read `—` and its
whole duration counts as generation.
## Reaching it from the internet
A plain install is LAN-only, and the dashboard asks for the API key. To let people use it from
anywhere, `llmhost install-newt` adds two things on top:
- **A tunnel.** [newt](https://github.com/fosrl/newt) dials out to your [Pangolin](https://github.com/fosrl/pangolin)
server, which serves HTTPS on your domain. Nothing on this machine is opened to the internet, and no port is forwarded.
newt runs as a third user service, in userspace (no root). It's a pinned release, checked against its sha256 before it's installed.
- **OIDC sign-in on the dashboard, replacing the API key there.** Whoever holds the key can also stop or
switch the model from the dashboard, which is too much to hand out with the key. The API itself is
unchanged and still takes the key.
You need a Pangolin server with a Newt site (Pangolin: *Sites → Add Site → Newt*, which gives an endpoint, ID and
secret) and an OIDC client registered with your identity provider:
- a confidential client using `client_secret_basic`
- the authorization-code flow with PKCE (S256)
- scopes `openid profile email groups`
- the redirect URI `https://<dashboard host>/auth/callback`
Then:
```bash
llmhost install-newt \
--endpoint https://pangolin.example.com --newt-id <site id> \
--public-url https://llm-dash.example.com \
--issuer https://auth.example.com --client-id llm-host \
--allow-group llm-admins # and/or --allow-user <username>; repeatable
```
It asks for anything left out. The two secrets are always prompted for, or read from `$LLMHOST_NEWT_SECRET` and
`$LLMHOST_OIDC_SECRET`, and never taken as flags, so they stay out of shell history. They're stored in
`~/.config/llm-host/` with mode 600 and handed to the services at start; they're never written into a service
file or `config.json`. Running it again changes only what you give it.
It ends by printing the two Pangolin HTTP resources to create, both pointing at this machine's LAN address (not
`localhost`, which llm-host treats as local), and **with Pangolin's own SSO off**:
| resource | target | who checks |
|---|---|---|
| dashboard, at the `--public-url` host | `<LAN IP>:<web port>` | llm-host, through your OIDC provider |
| API, at a host of your choice | `<LAN IP>:<API port>` | llm-host, with the API key |
Clients then use `https://<API host>/v1` with the key from `llmhost key`.
For Authelia, the client looks like this:
```yaml
identity_providers:
oidc:
clients:
- client_id: llm-host
client_name: llm-host dashboard
client_secret: '$pbkdf2-sha512$...' # authelia crypto hash generate pbkdf2 --random
public: false
authorization_policy: two_factor
require_pkce: true
pkce_challenge_method: S256
redirect_uris: ['https://llm-dash.example.com/auth/callback']
scopes: [openid, profile, email, groups]
response_types: [code]
grant_types: [authorization_code]
token_endpoint_auth_method: client_secret_basic
```
How the dashboard's sign-in behaves:
- **Only listed people get in.** A person must be in an allowed group or have an allowed username
(`preferred_username`, falling back to email). Groups come from userinfo.
- **Sessions are HttpOnly, Secure, `SameSite=Lax` cookies.** They last 12 hours and are held in memory, so
restarting the dashboard signs everyone out. State-changing requests must come from the dashboard's own origin.
- **The ID token is checked.** Its issuer, audience, expiry and nonce must match. It arrives directly from the
token endpoint over TLS, which OIDC allows in place of verifying its signature.
- **Other addresses redirect to the public URL.** A visit to any other name for the machine
(`http://<host>.local:11340`) is sent there, because that's the only host the session cookie exists on.
`llmhost status` shows the tunnel and sign-in settings. `setup` and `update` keep them, and `update` moves newt to
a newly pinned release. `llmhost remove-newt` undoes it all: it removes the service, the binary and both secrets,
and switches the dashboard back to the key.
## Connecting opencode
**On the server itself**, setup handles it: if opencode isn't installed it offers to install it (official
@ -204,6 +286,8 @@ python3 tests/test_opencode.py # or run one directly
| `tests/test_opencode.py` | provider naming and ownership, removal, the credential cache |
| `tests/test_proxy.py` | model names, dropping client reasoning settings, upstream key, streamed-run counting, against a fake server |
| `tests/test_dashboard.py` | KV parsing, per-run summaries, log collapsing |
| `tests/test_dashboard_auth.py` | API-key mode, and OIDC sign-in against a fake provider: PKCE, state/nonce/aud/iss/exp checks, allow list, origin check, sign-out |
| `tests/test_newt.py` | `install-newt`/`remove-newt` against fake services: pinned checksum, secrets kept out of config, output and argv, re-runs, undo |
| `tests/test_reasoning.py` | effort options matching the real chat templates; the setting surviving an update |
## Continuing on an NVIDIA box
@ -248,6 +332,9 @@ suites are hermetic and don't need a GPU), so run that first.
| `~/.local/share/llm-host/` | this repo (`src/`), backend venvs, the assembled CUDA toolkit |
| `~/.config/llm-host/config.json` | the plan: backend, fitting models, active model, ports |
| `~/.config/llm-host/api_key` | API key (mode 600) |
| `~/.config/llm-host/oidc_secret` | dashboard sign-in client secret (mode 600), after `install-newt` |
| `~/.config/llm-host/newt_secret` | Pangolin site secret (mode 600), after `install-newt` |
| `~/.local/share/llm-host/newt/` | the newt binary, after `install-newt` |
| `~/.cache/huggingface/hub/` | downloaded models |
| Linux: `~/.config/systemd/user/llm-host-{model,web}.service` | services (`journalctl --user -u llm-host-model`) |
| macOS: `~/Library/LaunchAgents/dev.llm-host.{model,web}.plist` | services; logs in `~/Library/Logs/llm-host/` |
@ -262,4 +349,6 @@ On macOS the services are launchd agents, so they run while you're logged in.
`reasoning_effort` (top-level or in `chat_template_kwargs`) is dropped and the dashboard's
setting applied instead.
- AMD (ROCm), Intel and CPU-only machines aren't supported yet.
- The API and dashboard use plain HTTP and are meant for a trusted LAN. Don't expose them to the internet.
- The API and dashboard use plain HTTP and are meant for a trusted LAN. Don't forward their ports to the internet;
use [`llmhost install-newt`](#reaching-it-from-the-internet), which puts HTTPS in front and OIDC sign-in on the dashboard.
- Everyone using the API shares one key, with no per-person revocation or rate limits.

View file

@ -117,7 +117,11 @@ def carried_settings(old, names):
`llmhost update` would quietly put every model back to "Model default". Models that no
longer fit lose their setting along with their plan."""
kept = {k: v for k, v in (old.get("reasoning") or {}).items() if k in names}
return {"reasoning": kept} if kept else {}
out = {"reasoning": kept} if kept else {}
for k in ("newt", "dashboard_auth"): # set by `llmhost install-newt`, not by the plan
if old.get(k):
out[k] = old[k]
return out
def cmd_setup(a):
@ -190,6 +194,10 @@ def cmd_setup(a):
if not a.no_start:
service.restart("web")
service.restart("model")
if cfg.get("newt") and service.installed("newt"):
from . import newt
if newt.ensure_binary(say):
service.restart("newt")
host = default_host()
say(f"""
Done.
@ -328,7 +336,7 @@ def _service_check():
def cmd_status(a):
cfg = _service_check()
host = default_host()
for name in service.NAMES:
for name in service.NAMES + tuple(n for n in service.OPTIONAL if service.installed(n)):
st, up = service.state(name)
upt = f" (up {int(up // 3600)}h{int(up % 3600 // 60):02d}m)" if up else ""
say(f"{name:6} {st}{upt}")
@ -340,6 +348,12 @@ def cmd_status(a):
except Exception:
say(f"active model {cfg['active']} is not answering yet")
say(f"api http://{host}:{cfg['api_port']}/v1\ndashboard http://{host}:{cfg['web_port']}")
d = cfg.get("dashboard_auth") or {}
if d.get("mode") == "oidc":
who = ", ".join([f"group {g}" for g in d.get("allowed_groups", [])] + [f"user {u}" for u in d.get("allowed_users", [])])
say(f"public {d['public_url']} (sign-in via {d['issuer']}; {who})")
if cfg.get("newt"):
say(f"tunnel newt -> {cfg['newt']['endpoint']}")
def cmd_models(a):
@ -375,9 +389,10 @@ def cmd_ctl(a):
def cmd_logs(a):
_service_check()
name = "newt" if a.newt else "web" if a.web else "model"
if a.follow:
os.execvp(service.log_command("model")[0], service.log_command("model"))
for line in service.logs("web" if a.web else "model", a.n):
os.execvp(service.log_command(name)[0], service.log_command(name))
for line in service.logs(name, a.n):
say(line)
@ -466,6 +481,139 @@ def cmd_key(a):
say(paths.api_key())
def _restart_if_running(name):
if service.state(name)[0] in ("active", "activating"):
if not service.restart(name):
say(f"Couldn't restart the {name} service; see `llmhost logs --{name}`.")
def lan_ip():
"""This machine's address on its default route -- what newt, running here, should dial
to reach the services. Connecting a UDP socket sends nothing."""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(("192.0.2.1", 9)) # TEST-NET-1: never routed anywhere
return s.getsockname()[0]
except OSError:
return "127.0.0.1"
finally:
s.close()
def _ask(label, given, default=None, flag=None, secret=False, env=None):
"""A value from its flag, its env var, or a prompt (keeping `default` on Enter).
Without a terminal, a value that's still missing is an error naming the flag."""
if given:
return given
if env and os.environ.get(env):
return os.environ[env]
if not sys.stdin.isatty():
if default:
return default
sys.exit(f"missing {flag or ('$' + env)}" + (f" (or ${env})" if flag and env else ""))
hint = " [keep current]" if secret and default else (f" [{default}]" if default else "")
if secret:
import getpass
v = getpass.getpass(f"{label}{hint}: ").strip()
else:
v = input(f"{label}{hint}: ").strip()
v = v or default
if not v:
sys.exit(f"{label} is required")
return v
def _check_url(label, url, bare=True):
import urllib.parse
u = urllib.parse.urlsplit(url)
if u.scheme not in ("http", "https") or not u.netloc or (bare and u.path.strip("/")):
sys.exit(f"{label} should look like https://host.example.com, not {url!r}")
if u.scheme != "https":
sys.exit(f"{label} must be https:// -- this is the address people reach from the internet")
return url.rstrip("/")
def cmd_install_newt(a):
"""Upgrade a LAN install for the internet: newt tunnel + OIDC sign-in on the dashboard."""
from . import newt
from .web import oidc
cfg = _service_check()
old_n, old_d = cfg.get("newt") or {}, cfg.get("dashboard_auth") or {}
newt.platform_tag() # fail before asking anything on a platform newt doesn't ship for
say("Pangolin site (Pangolin: Sites -> Add Site -> Newt):")
endpoint = _check_url("Pangolin endpoint", _ask(" Pangolin endpoint", a.endpoint, old_n.get("endpoint"), "--endpoint"))
site_id = _ask(" Newt ID", a.newt_id, old_n.get("id"), "--newt-id")
have_newt_secret = paths.NEWT_SECRET_FILE.exists() and old_n
newt_secret = _ask(" Newt secret", None, "keep" if have_newt_secret else None, secret=True, env="LLMHOST_NEWT_SECRET")
say("\nDashboard sign-in (an OIDC client registered with your provider):")
public_url = _check_url("Dashboard URL", _ask(" Dashboard's public URL", a.public_url, old_d.get("public_url"), "--public-url"))
issuer = _check_url("Issuer", _ask(" OIDC issuer", a.issuer, old_d.get("issuer"), "--issuer"), bare=False)
client_id = _ask(" Client ID", a.client_id, old_d.get("client_id") or "llm-host", "--client-id")
have_oidc_secret = paths.OIDC_SECRET_FILE.exists() and old_d
oidc_secret = _ask(" Client secret", None, "keep" if have_oidc_secret else None, secret=True, env="LLMHOST_OIDC_SECRET")
groups, users = a.allow_group or [], a.allow_user or []
if not (groups or users):
# A re-run keeps the allow list unless it's given again.
groups, users = old_d.get("allowed_groups", []), old_d.get("allowed_users", [])
if not (groups or users):
groups = [g.strip() for g in _ask(" Groups allowed in (comma-separated)", None, None,
"--allow-group").split(",") if g.strip()]
if not (groups or users):
sys.exit("say who may sign in: --allow-group <group> and/or --allow-user <username>")
dash = {"mode": "oidc", "issuer": issuer, "client_id": client_id, "public_url": public_url,
"allowed_groups": sorted(set(groups)), "allowed_users": sorted(set(users))}
secret_for_check = paths.oidc_secret() if oidc_secret == "keep" else oidc_secret
try:
oidc.OIDC(dash, secret_for_check).discovery()
except oidc.AuthError as e:
sys.exit(str(e))
newt.ensure_binary(say)
if newt_secret != "keep":
paths.save_secret(paths.NEWT_SECRET_FILE, newt_secret)
if oidc_secret != "keep":
paths.save_secret(paths.OIDC_SECRET_FILE, oidc_secret)
cfg["newt"] = {"endpoint": endpoint, "id": site_id}
cfg["dashboard_auth"] = dash
paths.save_config(cfg)
service.install("newt")
if not service.restart("newt"):
say("newt didn't start; see `llmhost logs --newt`.")
_restart_if_running("web")
ip = lan_ip()
say(f"""
Done. newt is running and the dashboard now signs in through {issuer};
the API key no longer opens it (the API itself still uses the key).
In Pangolin, add two HTTP resources on this site, with Pangolin's own SSO off on both
(llm-host checks the API key on one and signs people in on the other):
dashboard {public_url} -> http://{ip}:{cfg['web_port']}
API <a host of your choice> -> http://{ip}:{cfg['api_port']}
Point them at {ip}, not localhost: requests from localhost count as local here.
Register this redirect URI with your OIDC client: {public_url}/auth/callback
Clients use https://<API host>/v1 with the API key (`llmhost key`).
Undo all of this with: llmhost remove-newt""")
def cmd_remove_newt(a):
"""Back to a LAN-only install: stop newt, and the dashboard takes the API key again."""
cfg = _service_check()
if service.installed("newt"):
service.uninstall("newt")
shutil.rmtree(paths.NEWT_DIR, ignore_errors=True)
paths.NEWT_SECRET_FILE.unlink(missing_ok=True)
paths.OIDC_SECRET_FILE.unlink(missing_ok=True)
had = bool(cfg.pop("newt", None)) | bool(cfg.pop("dashboard_auth", None))
paths.save_config(cfg)
_restart_if_running("web")
say("Removed newt; the dashboard takes the API key again." if had else "newt wasn't installed.")
def cmd_download(a):
cfg = _service_check()
m = next((x for x in cfg["models"] if x["name"] == a.model), None)
@ -554,7 +702,7 @@ def cmd_uninstall(a):
# Read the catalog now: --purge deletes it along with the rest of llm-host.
cached = cached_catalog_models()
cfg = paths.load_config() or {}
for name in service.NAMES:
for name in service.NAMES + tuple(n for n in service.OPTIONAL if service.installed(n)):
service.uninstall(name)
# Stopping returns before the processes have exited (launchd especially). Wait, so a
# reinstall right after this finds the ports free instead of moving to other ones.
@ -563,7 +711,7 @@ def cmd_uninstall(a):
ours = list(range(cfg["api_port"], cfg["api_port"] + span)) + ([cfg["web_port"]] if cfg.get("web_port") else [])
with Spinner("Waiting for the services to exit"):
wait_ports_free(ours, timeout=30)
for d in ("venv-vllm", "venv-mlx", "cuda", "nvcc-test"):
for d in ("venv-vllm", "venv-mlx", "cuda", "nvcc-test", "newt"):
shutil.rmtree(paths.DATA / d, ignore_errors=True)
say("Removed services and backend environments.")
# Before the --purge below: the provider is identified by its reference to KEY_FILE.
@ -637,6 +785,11 @@ def cmd_run_model(a):
mlx.run_server(cfg, entry, choice, plan.mlx_args(entry, choice, cfg["api_port"] + 1))
def cmd_run_newt(a):
from . import newt
newt.run()
def cmd_run_web(a):
_service_check()
service.trim_log("web")
@ -679,10 +832,22 @@ def main(argv=None):
s.add_argument("-f", "--follow", action="store_true")
s.add_argument("-n", type=int, default=100)
s.add_argument("--web", action="store_true", help="dashboard logs instead")
s.add_argument("--newt", action="store_true", help="tunnel logs instead")
s.set_defaults(fn=cmd_logs)
sub.add_parser("watch", help="show download and loading progress until the model is ready"
).set_defaults(fn=cmd_watch)
sub.add_parser("key", help="print the API key").set_defaults(fn=cmd_key)
s = sub.add_parser("install-newt", help="reach this server from the internet: newt tunnel + OIDC sign-in on the dashboard")
s.add_argument("--endpoint", help="Pangolin server, e.g. https://pangolin.example.com")
s.add_argument("--newt-id", help="the site's Newt ID (its secret: prompted, or $LLMHOST_NEWT_SECRET)")
s.add_argument("--public-url", help="the dashboard's public address, e.g. https://llm-dash.example.com")
s.add_argument("--issuer", help="OIDC provider, e.g. https://auth.example.com")
s.add_argument("--client-id", help="OIDC client ID (default llm-host; secret: prompted, or $LLMHOST_OIDC_SECRET)")
s.add_argument("--allow-group", action="append", metavar="GROUP", help="provider group allowed into the dashboard (repeatable)")
s.add_argument("--allow-user", action="append", metavar="USER", help="username allowed into the dashboard (repeatable)")
s.set_defaults(fn=cmd_install_newt)
sub.add_parser("remove-newt", help="undo install-newt: stop the tunnel, dashboard back to the API key"
).set_defaults(fn=cmd_remove_newt)
s = sub.add_parser("download", help="download a model ahead of time")
s.add_argument("model")
s.set_defaults(fn=cmd_download)
@ -710,6 +875,7 @@ def main(argv=None):
s.set_defaults(fn=cmd_uninstall)
sub.add_parser("run-model").set_defaults(fn=cmd_run_model)
sub.add_parser("run-web").set_defaults(fn=cmd_run_web)
sub.add_parser("run-newt").set_defaults(fn=cmd_run_newt)
a = ap.parse_args(argv)
a.fn(a)

89
llmhost/newt.py Normal file
View file

@ -0,0 +1,89 @@
"""Optional internet access through a Pangolin tunnel (newt). Stdlib only.
`llmhost install-newt` is the upgrade path from a LAN install. It
- downloads a pinned newt release and checks it against the sha256 below,
- runs it as a third user service ("newt", via `llmhost run-newt`), which dials out to
the Pangolin server -- nothing on this machine is opened to the internet,
- and switches the dashboard to OIDC sign-in (web/oidc.py), because once it's public the
API key is too much power to hand out: it also stops and switches the model.
newt runs in userspace (no root, no kernel WireGuard). Its site secret is kept in
~/.config/llm-host/newt_secret (0600) and handed over in its environment at start, never
written into the service file.
"""
import hashlib
import os
import platform
import tempfile
import urllib.request
from . import paths
VERSION = "1.19.0"
# From the GitHub release's asset digests for VERSION.
SHA256 = {
"linux_amd64": "6d40e223fa49d8bcfa9b7094208c58ff616997979bff7c884d0af61fcc1c5376",
"linux_arm64": "2a282e3edda7be17f092ac58aff0ec6dac9ddd152a642e8e61e6d625f2abe696",
"darwin_arm64": "bdc93f811e017affb893eab8d924dfe72ea63e1bdeaf85decec1afb711288ee5",
"darwin_amd64": "d44a4fd5526174788622e4eebea55ef268df19c85fc67766d0f27e23eb8800fa",
}
URL = "https://github.com/fosrl/newt/releases/download/{version}/newt_{plat}"
def platform_tag() -> str:
os_name = {"Linux": "linux", "Darwin": "darwin"}.get(platform.system())
arch = {"x86_64": "amd64", "amd64": "amd64", "aarch64": "arm64", "arm64": "arm64"}.get(platform.machine().lower())
tag = f"{os_name}_{arch}"
if tag not in SHA256:
raise SystemExit(f"newt isn't packaged here for {platform.system()} {platform.machine()}")
return tag
def binary() -> "os.PathLike":
return paths.NEWT_DIR / "newt"
def installed_version():
try:
return (paths.NEWT_DIR / "VERSION").read_text().strip()
except OSError:
return None
def ensure_binary(say=print, fetch=None) -> bool:
"""Install the pinned newt if it isn't there already. Returns True if it changed."""
if installed_version() == VERSION and binary().exists():
return False
tag = platform_tag()
url = URL.format(version=VERSION, plat=tag)
say(f"Downloading newt {VERSION} ({tag})…")
data = (fetch or _fetch)(url)
got = hashlib.sha256(data).hexdigest()
if got != SHA256[tag]:
raise SystemExit(f"newt download didn't match its checksum (got {got}); not installing it")
paths.NEWT_DIR.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=paths.NEWT_DIR, prefix=".newt.")
with os.fdopen(fd, "wb") as f:
f.write(data)
os.chmod(tmp, 0o755)
os.replace(tmp, binary())
(paths.NEWT_DIR / "VERSION").write_text(VERSION + "\n")
return True
def _fetch(url) -> bytes:
with urllib.request.urlopen(url, timeout=300) as r:
return r.read()
def run():
"""The service's entry point: exec newt with its credentials in the environment."""
cfg = paths.load_config()
conf = cfg.get("newt") or {}
if not conf.get("endpoint") or not conf.get("id"):
raise SystemExit("newt isn't configured; run `llmhost install-newt`")
secret = paths.read_secret(paths.NEWT_SECRET_FILE, "newt site secret", "llmhost install-newt")
env = {**os.environ, "PANGOLIN_ENDPOINT": conf["endpoint"], "NEWT_ID": conf["id"],
"NEWT_SECRET": secret, "LOG_LEVEL": conf.get("log_level", "INFO")}
exe = str(binary())
os.execve(exe, [exe], env)

View file

@ -6,6 +6,9 @@ Layout (overridable with LLMHOST_HOME / LLMHOST_CONFIG):
~/.local/share/llm-host/cuda merged CUDA toolkit built from pip wheels (NVIDIA)
~/.config/llm-host/config.json plan + settings
~/.config/llm-host/api_key API key (0600)
~/.local/share/llm-host/newt newt binary, after `llmhost install-newt`
~/.config/llm-host/oidc_secret dashboard sign-in client secret (0600), after install-newt
~/.config/llm-host/newt_secret Pangolin site secret (0600), after install-newt
"""
import json
import os
@ -21,6 +24,9 @@ DATA = Path(os.environ.get("LLMHOST_HOME", HOME / ".local/share/llm-host"))
CONFIG_DIR = Path(os.environ.get("LLMHOST_CONFIG", HOME / ".config/llm-host"))
CONFIG_FILE = CONFIG_DIR / "config.json"
KEY_FILE = CONFIG_DIR / "api_key"
OIDC_SECRET_FILE = CONFIG_DIR / "oidc_secret"
NEWT_SECRET_FILE = CONFIG_DIR / "newt_secret"
NEWT_DIR = DATA / "newt"
LOG_DIR = (HOME / "Library/Logs/llm-host") if IS_MAC else (DATA / "logs")
BIN_DIR = HOME / ".local/bin"
SHIM = BIN_DIR / "llmhost"
@ -66,3 +72,23 @@ def api_key(create: bool = False) -> str:
with os.fdopen(fd, "w") as f:
f.write(key + "\n")
return key
def read_secret(path, what, fix) -> str:
try:
return path.read_text().strip()
except OSError:
raise SystemExit(f"No {what} at {path}; run `{fix}` again.")
def save_secret(path, secret: str) -> None:
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w") as f:
f.write(secret + "\n")
os.chmod(path, 0o600) # O_CREAT's mode doesn't apply to a file that already existed
def oidc_secret() -> str:
return read_secret(OIDC_SECRET_FILE, "dashboard sign-in client secret", "llmhost install-newt")

View file

@ -1,6 +1,7 @@
"""Background services: systemd --user on Linux, launchd agents on macOS.
Two services: "model" (the inference server) and "web" (dashboard). Both run `llmhost run-<name>`.
Two services: "model" (the inference server) and "web" (dashboard), plus "newt" (the
Pangolin tunnel) only after `llmhost install-newt`. Each runs `llmhost run-<name>`.
"""
import os
import re
@ -10,7 +11,8 @@ from pathlib import Path
from . import paths
NAMES = ("model", "web")
NAMES = ("model", "web") # what setup installs
OPTIONAL = ("newt",) # installed by their own command
def _run(cmd, timeout=60):
@ -32,7 +34,8 @@ def _unit_path(name):
def _systemd_install(name):
desc = {"model": "llm-host model server", "web": "llm-host dashboard"}[name]
desc = {"model": "llm-host model server", "web": "llm-host dashboard",
"newt": "llm-host tunnel (newt)"}[name]
extra = "TimeoutStartSec=1800\nTimeoutStopSec=60\n" if name == "model" else ""
p = _unit_path(name)
p.parent.mkdir(parents=True, exist_ok=True)
@ -104,6 +107,10 @@ def install(name):
_run(["systemctl", "--user", "enable", _unit(name)])
def installed(name):
return (_plist_path(name) if paths.IS_MAC else _unit_path(name)).exists()
def enable_linger():
"""Keep user services running without a login session (Linux). Often allowed without sudo."""
if paths.IS_MAC:

View file

@ -76,13 +76,14 @@ button.small { font-size: 12px; padding: 4px 10px; }
}
.effort select:disabled { color: var(--muted); }
.effort .s { color: var(--muted); font-size: 12px; margin-top: 7px; line-height: 1.45; }
button {
button, a.btn {
font: inherit; font-size: 13px; font-weight: 550; padding: 7px 13px; border-radius: 8px; cursor: pointer;
border: 1px solid var(--border); background: var(--panel-2); color: var(--text);
}
button:hover:not(:disabled) { border-color: var(--faint); }
button:disabled { opacity: .45; cursor: default; }
button.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
a.btn { display: inline-block; text-decoration: none; }
button.primary, a.btn.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
button.danger { color: var(--bad); }
.profiles { display: flex; flex-direction: column; gap: 8px; }
@ -169,6 +170,7 @@ pre {
<span id="phase" class="pill">…</span>
<span class="spacer"></span>
<span class="meta" id="uptime"></span>
<span class="meta" id="whoami" hidden></span>
<button id="logout" title="Forget API key">Sign out</button>
</header>
@ -268,6 +270,11 @@ pre {
<div class="err" id="auth-err"></div>
<button class="primary" type="submit">Continue</button>
</form>
<div class="dialog" id="auth-oidc" hidden>
<h3>Sign in</h3>
<p id="auth-oidc-text">This dashboard signs in through your identity provider.</p>
<a class="btn primary" href="/auth/login" id="auth-oidc-go">Sign in</a>
</div>
</div>
<div class="toast" id="toast"></div>
@ -275,6 +282,9 @@ pre {
const $ = (id) => document.getElementById(id);
let KEY = null;
try { KEY = localStorage.getItem("llmhost-key"); } catch (e) {}
// "key": the API key, typed in and kept in this browser. "oidc": a session cookie set by
// signing in at the provider (/auth/login); the key isn't accepted then.
let AUTH = { mode: "key" };
let state = null;
let logTimer = null;
@ -287,14 +297,23 @@ function toast(msg) {
}
async function api(path, opts = {}) {
const r = await fetch(path, { ...opts, headers: { "Authorization": "Bearer " + KEY, "Content-Type": "application/json" } });
if (r.status === 401) { showAuth("That key was rejected."); throw new Error("unauthorized"); }
const headers = { "Content-Type": "application/json" };
if (AUTH.mode === "key") headers["Authorization"] = "Bearer " + KEY;
const r = await fetch(path, { ...opts, headers, credentials: "same-origin" });
if (r.status === 401) { showAuth(AUTH.mode === "key" ? "That key was rejected." : ""); throw new Error("unauthorized"); }
const body = await r.json();
if (!r.ok) throw new Error(body.error || r.statusText);
return body;
}
function showAuth(err = "") { $("auth-err").textContent = err; $("auth").classList.add("show"); $("auth-key").focus(); }
function showAuth(err = "") {
if (AUTH.mode === "oidc") {
$("auth-form").hidden = true; $("auth-oidc").hidden = false;
$("auth").classList.add("show"); $("auth-oidc-go").focus();
return;
}
$("auth-err").textContent = err; $("auth").classList.add("show"); $("auth-key").focus();
}
$("auth-form").addEventListener("submit", (e) => {
e.preventDefault();
KEY = $("auth-key").value.trim();
@ -302,7 +321,14 @@ $("auth-form").addEventListener("submit", (e) => {
$("auth").classList.remove("show");
poll();
});
$("logout").onclick = () => { try { localStorage.removeItem("llmhost-key"); } catch (e) {} KEY = null; showAuth(); };
$("logout").onclick = async () => {
if (AUTH.mode === "oidc") {
try { await fetch("/auth/logout", { method: "POST", credentials: "same-origin" }); } catch (e) {}
AUTH.user = null; $("whoami").hidden = true; clearTimeout(pollTimer); showAuth();
return;
}
try { localStorage.removeItem("llmhost-key"); } catch (e) {} KEY = null; showAuth();
};
const fmt = {
n: (v, d = 0) => v == null ? "—" : v.toLocaleString(undefined, { maximumFractionDigits: d, minimumFractionDigits: d }),
@ -692,12 +718,26 @@ $("logs").addEventListener("toggle", () => {
let pollTimer = null;
async function poll() {
clearTimeout(pollTimer);
if (!KEY) { showAuth(); return; }
if (AUTH.mode === "key" ? !KEY : !AUTH.user) { showAuth(); return; }
try { render(await api("/api/status")); }
catch (e) { if (e.message !== "unauthorized") { $("phase").textContent = "Dashboard unreachable"; $("phase").className = "pill failed"; } }
catch (e) {
if (e.message === "unauthorized" && AUTH.mode === "oidc") return; // session over; wait for sign-in
if (e.message !== "unauthorized") { $("phase").textContent = "Dashboard unreachable"; $("phase").className = "pill failed"; }
}
pollTimer = setTimeout(poll, 2000);
}
poll();
(async () => {
try {
const r = await fetch("/auth/config", { credentials: "same-origin" });
if (r.ok) AUTH = await r.json();
} catch (e) {}
if (AUTH.mode === "oidc") {
$("logout").title = "Sign out of this dashboard";
if (AUTH.user) { $("whoami").textContent = AUTH.name || AUTH.user; $("whoami").hidden = false; }
}
poll();
})();
</script>
</body>
</html>

236
llmhost/web/oidc.py Normal file
View file

@ -0,0 +1,236 @@
"""Dashboard sign-in through an OpenID Connect provider. Stdlib only.
Off unless config.json has a "dashboard_auth" block with mode "oidc" (`llmhost install-newt` sets it); then it replaces the
API key on the dashboard (the API on api_port still takes the key -- that's for clients).
The flow is the authorization-code flow of a confidential client, with PKCE:
/auth/login -> 302 to the provider, with state, nonce and an S256 code challenge.
The state is also set in a short-lived cookie, so a callback only
completes in the browser that started it (no login CSRF).
/auth/callback -> code exchanged at the token endpoint with the client secret, the
ID token's claims checked, groups read from userinfo, the allow
list applied, and a session cookie set.
/auth/logout -> POST; drops the session.
The ID token comes straight from the token endpoint over TLS, which OIDC Core 3.1.3.7 lets
a client rely on in place of checking its signature; its iss/aud/azp/exp/nonce are still
checked. Sessions live in memory, so a dashboard restart signs everyone out.
"""
import base64
import hashlib
import hmac
import json
import secrets
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
SESSION_COOKIE = "llmhost_session"
STATE_COOKIE = "llmhost_oidc_state"
SESSION_TTL = 12 * 3600
LOGIN_TTL = 600 # how long a started sign-in may take to come back
MAX_PENDING = 256 # unfinished sign-ins kept at once
CLOCK_SKEW = 120
SCOPES = "openid profile email groups"
class AuthError(Exception):
"""A sign-in that can't complete; the message is safe to show the user."""
def b64url(raw: bytes) -> str:
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
def jwt_claims(token: str) -> dict:
try:
payload = token.split(".")[1]
return json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4)))
except (IndexError, ValueError):
raise AuthError("the provider sent an unreadable ID token")
def parse_cookies(header: str) -> dict:
out = {}
for part in (header or "").split(";"):
k, sep, v = part.strip().partition("=")
if sep:
out.setdefault(k, v)
return out
def origin_of(url: str) -> str:
u = urllib.parse.urlsplit(url)
return f"{u.scheme}://{u.netloc}".lower()
class OIDC:
def __init__(self, conf: dict, client_secret: str, http=None):
self.issuer = conf["issuer"].rstrip("/")
self.client_id = conf["client_id"]
self.secret = client_secret
self.public_url = conf["public_url"].rstrip("/")
self.redirect_uri = self.public_url + "/auth/callback"
self.origin = origin_of(self.public_url)
self.secure = self.public_url.startswith("https://")
self.allowed_groups = set(conf.get("allowed_groups") or [])
self.allowed_users = set(conf.get("allowed_users") or [])
if not (self.allowed_groups or self.allowed_users):
raise ValueError("dashboard_auth needs allowed_groups or allowed_users")
self.http = http or self._http
self.lock = threading.Lock()
self.pending = {} # state -> {nonce, verifier, t}
self.sessions = {} # sha256(session id) -> {user, name, exp}
self._disco = None
# -- provider ---------------------------------------------------------------------
@staticmethod
def _http(method, url, data=None, headers=None):
req = urllib.request.Request(url, data=data, method=method, headers=headers or {})
try:
with urllib.request.urlopen(req, timeout=10) as r:
return r.status, r.read()
except urllib.error.HTTPError as e:
return e.code, e.read()
def discovery(self) -> dict:
if self._disco is None:
try:
st, body = self.http("GET", self.issuer + "/.well-known/openid-configuration")
d = json.loads(body) if st == 200 else None
except (OSError, ValueError):
d = None
if not d or d.get("issuer", "").rstrip("/") != self.issuer:
raise AuthError(f"couldn't reach the sign-in provider at {self.issuer}")
self._disco = d
return self._disco
# -- sign-in ----------------------------------------------------------------------
def start(self):
"""Begin a sign-in: (provider URL to redirect to, state for the state cookie)."""
d = self.discovery()
state, nonce, verifier = (secrets.token_urlsafe(32) for _ in range(3))
now = time.time()
with self.lock:
for s in [s for s, p in self.pending.items() if now - p["t"] > LOGIN_TTL]:
del self.pending[s]
if len(self.pending) >= MAX_PENDING:
del self.pending[min(self.pending, key=lambda s: self.pending[s]["t"])]
self.pending[state] = {"nonce": nonce, "verifier": verifier, "t": now}
q = urllib.parse.urlencode({
"response_type": "code", "client_id": self.client_id, "redirect_uri": self.redirect_uri,
"scope": SCOPES, "state": state, "nonce": nonce,
"code_challenge": b64url(hashlib.sha256(verifier.encode()).digest()),
"code_challenge_method": "S256"})
return f"{d['authorization_endpoint']}?{q}", state
def finish(self, params: dict, cookie_state: str) -> dict:
"""Complete a sign-in from the callback's query. Returns the new session
{"id", "user", "name"}; raises AuthError for anything that doesn't check out."""
if params.get("error"):
raise AuthError(f"the provider said: {params.get('error_description') or params['error']}")
state = params.get("state", "")
if not state or not cookie_state or not hmac.compare_digest(state, cookie_state):
raise AuthError("this sign-in was started in a different browser or tab; try again")
with self.lock:
p = self.pending.pop(state, None)
if not p or time.time() - p["t"] > LOGIN_TTL:
raise AuthError("this sign-in expired; try again")
d = self.discovery()
if "iss" in params and params["iss"].rstrip("/") != self.issuer:
raise AuthError("the response came from a different provider")
code = params.get("code")
if not code:
raise AuthError("the provider sent no authorization code")
basic = base64.b64encode(f"{urllib.parse.quote(self.client_id, safe='')}:"
f"{urllib.parse.quote(self.secret, safe='')}".encode()).decode()
st, body = self.http("POST", d["token_endpoint"], urllib.parse.urlencode({
"grant_type": "authorization_code", "code": code, "redirect_uri": self.redirect_uri,
"code_verifier": p["verifier"]}).encode(), {
"Authorization": f"Basic {basic}", "Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json"})
try:
tok = json.loads(body)
except ValueError:
tok = {}
if st != 200 or "id_token" not in tok:
raise AuthError(f"the provider refused the code ({tok.get('error') or st})")
c = jwt_claims(tok["id_token"])
now = time.time()
aud = c.get("aud")
auds = aud if isinstance(aud, list) else [aud]
if c.get("iss", "").rstrip("/") != self.issuer:
raise AuthError("the ID token is from a different provider")
if self.client_id not in auds or (len(auds) > 1 and c.get("azp") != self.client_id):
raise AuthError("the ID token was issued to a different client")
if not isinstance(c.get("exp"), (int, float)) or c["exp"] < now - CLOCK_SKEW:
raise AuthError("the ID token has expired")
if not hmac.compare_digest(str(c.get("nonce", "")), p["nonce"]):
raise AuthError("the ID token doesn't belong to this sign-in")
info = dict(c)
if d.get("userinfo_endpoint") and tok.get("access_token"):
st, body = self.http("GET", d["userinfo_endpoint"], None, {
"Authorization": f"Bearer {tok['access_token']}", "Accept": "application/json"})
try:
u = json.loads(body) if st == 200 else {}
except ValueError:
u = {} # a signed/encrypted userinfo isn't JSON; the ID token's claims stand
if u.get("sub") == c.get("sub"):
info.update(u)
user = info.get("preferred_username") or info.get("email") or info.get("sub")
groups = set(info.get("groups") or [])
if user not in self.allowed_users and not (groups & self.allowed_groups):
raise AuthError(f"signed in as {user}, but that account isn't allowed on this dashboard")
sid = secrets.token_urlsafe(32)
with self.lock:
for h in [h for h, s in self.sessions.items() if s["exp"] < now]:
del self.sessions[h]
self.sessions[self._h(sid)] = {"user": user, "name": info.get("name") or user,
"exp": now + SESSION_TTL}
return {"id": sid, "user": user, "name": info.get("name") or user}
# -- sessions ---------------------------------------------------------------------
@staticmethod
def _h(sid: str) -> str:
return hashlib.sha256(sid.encode()).hexdigest()
def session(self, cookie_header: str):
sid = parse_cookies(cookie_header).get(SESSION_COOKIE)
if not sid:
return None
with self.lock:
s = self.sessions.get(self._h(sid))
if s and s["exp"] < time.time():
del self.sessions[self._h(sid)]
s = None
return s
def end(self, cookie_header: str):
sid = parse_cookies(cookie_header).get(SESSION_COOKIE)
if sid:
with self.lock:
self.sessions.pop(self._h(sid), None)
def same_origin(self, headers) -> bool:
"""For state-changing requests: the browser's Origin (or Referer) must be the
dashboard's own. SameSite=Lax already keeps the cookie off cross-site POSTs;
this is the second lock on that door."""
o = headers.get("Origin") or (origin_of(headers["Referer"]) if headers.get("Referer") else "")
return o.lower() == self.origin
def cookie(self, name, value, max_age, path="/"):
attrs = [f"{name}={value}", f"Path={path}", f"Max-Age={max_age}", "HttpOnly", "SameSite=Lax"]
if self.secure:
attrs.append("Secure")
return "; ".join(attrs)

View file

@ -1,19 +1,23 @@
"""Dashboard: status, metrics and model switching. Stdlib only.
Serves index.html and a JSON API on cfg["web_port"]. /api/* routes need the API key.
Serves index.html and a JSON API on cfg["web_port"]. /api/* routes need the API key, or,
when config.json's "dashboard_auth" is set to OIDC, a signed-in session instead (oidc.py).
"""
import hmac
import html
import json
import re
import socket
import threading
import time
import urllib.parse
import urllib.request
from collections import deque
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from .. import hfcache, hw, opencode, paths, plan, service
from . import oidc as oidc_mod
HERE = Path(__file__).resolve().parent
SAMPLE_SECONDS = 2
@ -408,7 +412,7 @@ class Sampler:
threading.Thread(target=fn, args=("model",), daemon=True).start()
def make_handler(sampler, key):
def make_handler(sampler, key, oidc=None):
class Handler(BaseHTTPRequestHandler):
server_version = "llm-host"
@ -425,6 +429,15 @@ def make_handler(sampler, key):
self.wfile.write(body)
def authed(self):
if oidc:
# Signed in through the provider; the API key isn't accepted here.
if oidc.session(self.headers.get("Cookie", "")) is None:
self.send_json(401, {"error": "unauthorized", "login": "/auth/login"})
return False
if self.command == "POST" and not oidc.same_origin(self.headers):
self.send_json(403, {"error": "cross-origin request refused"})
return False
return True
h = self.headers.get("Authorization", "")
tok = h[7:] if h.startswith("Bearer ") else ""
if hmac.compare_digest(tok.encode(), key.encode()):
@ -432,8 +445,67 @@ def make_handler(sampler, key):
self.send_json(401, {"error": "unauthorized"})
return False
def redirect(self, url, cookies=()):
self.send_response(302)
self.send_header("Location", url)
self.send_header("Cache-Control", "no-store")
for c in cookies:
self.send_header("Set-Cookie", c)
self.send_header("Content-Length", "0")
self.end_headers()
def auth_page(self, code, msg):
body = (f"<!doctype html><meta charset=utf-8><meta name=viewport content='width=device-width'>"
f"<title>llm-host sign-in</title><body style='font:15px system-ui;margin:3em auto;"
f"max-width:32em;padding:0 16px'><h2>Couldn't sign you in</h2><p>{html.escape(msg)}</p>"
f"<p><a href='/auth/login'>Try again</a></p>").encode()
self.send_response(code)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Cache-Control", "no-store")
self.send_header("Set-Cookie", oidc.cookie(oidc_mod.STATE_COOKIE, "", 0, "/auth/"))
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def on_public_host(self):
"""A session cookie only exists on the public URL's host, so a visit by any
other name (mybox.local:11340) is sent there instead of to a login loop."""
host = (self.headers.get("Host") or "").lower()
return host == urllib.parse.urlsplit(oidc.public_url).netloc.lower()
def auth_get(self, path, query):
if path == "/auth/config":
s = oidc.session(self.headers.get("Cookie", "")) if oidc else None
return self.send_json(200, {"mode": "oidc" if oidc else "key",
"user": s and s["user"], "name": s and s["name"]})
if not oidc:
return self.send_json(404, {"error": "not found"})
if path == "/auth/login":
if not self.on_public_host():
return self.redirect(oidc.public_url + "/auth/login")
try:
url, state = oidc.start()
except oidc_mod.AuthError as e:
return self.auth_page(502, str(e))
return self.redirect(url, [oidc.cookie(oidc_mod.STATE_COOKIE, state, oidc_mod.LOGIN_TTL, "/auth/")])
if path == "/auth/callback":
params = {k: v[0] for k, v in urllib.parse.parse_qs(query).items()}
cookie_state = oidc_mod.parse_cookies(self.headers.get("Cookie", "")).get(oidc_mod.STATE_COOKIE, "")
try:
s = oidc.finish(params, cookie_state)
except oidc_mod.AuthError as e:
return self.auth_page(403, str(e))
print(f"llm-host dashboard: {s['user']} signed in", flush=True)
return self.redirect("/", [oidc.cookie(oidc_mod.SESSION_COOKIE, s["id"], oidc_mod.SESSION_TTL),
oidc.cookie(oidc_mod.STATE_COOKIE, "", 0, "/auth/")])
self.send_json(404, {"error": "not found"})
def do_GET(self):
path = self.path.split("?", 1)[0]
path, _, query = self.path.partition("?")
if path.startswith("/auth/"):
return self.auth_get(path, query)
if oidc and path in ("/", "/index.html") and not self.on_public_host():
return self.redirect(oidc.public_url + "/")
if path in ("/", "/index.html"):
body = (HERE / "index.html").read_bytes()
self.send_response(200)
@ -455,6 +527,17 @@ def make_handler(sampler, key):
def do_POST(self):
path = self.path.split("?", 1)[0]
if path == "/auth/logout" and oidc:
if not oidc.same_origin(self.headers):
return self.send_json(403, {"error": "cross-origin request refused"})
oidc.end(self.headers.get("Cookie", ""))
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Set-Cookie", oidc.cookie(oidc_mod.SESSION_COOKIE, "", 0))
self.send_header("Content-Length", "11")
self.end_headers()
self.wfile.write(b'{"ok": true}')
return
if not self.authed():
return
try:
@ -494,6 +577,11 @@ def serve():
key = paths.api_key()
sampler = Sampler(cfg, key)
threading.Thread(target=sampler.loop, daemon=True).start()
srv = ThreadingHTTPServer(("0.0.0.0", cfg["web_port"]), make_handler(sampler, key))
print(f"llm-host dashboard on :{cfg['web_port']}", flush=True)
auth = None
conf = cfg.get("dashboard_auth") or {}
if conf.get("mode") == "oidc":
auth = oidc_mod.OIDC(conf, paths.oidc_secret())
srv = ThreadingHTTPServer(("0.0.0.0", cfg["web_port"]), make_handler(sampler, key, auth))
how = f"sign-in via {auth.issuer}, at {auth.public_url}" if auth else "API key"
print(f"llm-host dashboard on :{cfg['web_port']} ({how})", flush=True)
srv.serve_forever()

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)