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:
parent
d07a92e5b5
commit
e814a2359d
11 changed files with 1155 additions and 26 deletions
178
llmhost/cli.py
178
llmhost/cli.py
|
|
@ -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)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue