Split the internet upgrades: API-only tunnel, OIDC, authenticator codes, expose-dashboard
install-newt now sets up the tunnel for the API only; the dashboard stays on the LAN. Dashboard sign-in is its own step: install-oidc (the OIDC flow, split out) or install-otp, which pairs authenticator apps with a QR code in the terminal (stdlib QR encoder, TOTP per RFC 6238) so a code also opens the dashboard, with replay and lockout rules. expose-dashboard walks through publishing the dashboard, only after install-newt, and warns while it's protected by the API key alone; with codes it offers to switch the key off for the dashboard. Each install-* has a remove-*. Also opencode-install.sh: a standalone script, fetched from the repo, that installs opencode if needed, saves the API key to a 0600 file and adds the provider to opencode.json for new and existing configs. /v1/models reports whether the model reasons, for that script. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
e6ff4ce909
commit
c8b70afdbf
20 changed files with 1715 additions and 239 deletions
1
tests/fixtures/qr_golden.json
vendored
Normal file
1
tests/fixtures/qr_golden.json
vendored
Normal file
File diff suppressed because one or more lines are too long
|
|
@ -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", "OIDC_SECRET_FILE", "NEWT_SECRET_FILE", "NEWT_DIR", "BIN_DIR", "SHIM", "LOG_DIR"):
|
||||
for name in ("DATA", "CONFIG_DIR", "CONFIG_FILE", "KEY_FILE", "OIDC_SECRET_FILE", "NEWT_SECRET_FILE", "OTP_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}")
|
||||
|
|
|
|||
|
|
@ -109,6 +109,14 @@ check("opencode block is the openai-compatible provider", blk["npm"] == "@ai-sdk
|
|||
check("opencode block offers the one alias", list(blk["models"]) == [cx["model"]] == ["default"], blk["models"])
|
||||
check("opencode block leaves the address to the page", "LABEL" in blk["name"] and "HOST" in blk["options"]["baseURL"], blk)
|
||||
check("the key isn't inlined in the block", KEY not in json.dumps(blk))
|
||||
check("installer URL is a raw file in the repo", cx["installer"].startswith("https://")
|
||||
and cx["installer"].endswith("/opencode-install.sh"), cx["installer"])
|
||||
R = web.raw_file_url
|
||||
check("raw URL for a Gitea/Forgejo repo", R("https://git.example.com/pub/llm-host.git", "main", "f.sh")
|
||||
== "https://git.example.com/pub/llm-host/raw/branch/main/f.sh")
|
||||
check("raw URL for a GitHub repo", R("https://github.com/someone/llm-host", "dev", "f.sh")
|
||||
== "https://raw.githubusercontent.com/someone/llm-host/dev/f.sh")
|
||||
check("no raw URL for an ssh remote", R("git@github.com:someone/llm-host.git", "main", "f.sh") is None)
|
||||
srv.shutdown()
|
||||
|
||||
print("\n2. OIDC mode refuses the key and unsigned visitors")
|
||||
|
|
@ -120,6 +128,7 @@ 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 dashboard doesn't serve the opencode installer", req(srv, "GET", "/opencode-install.sh", PUB_HOST)[0] == 404)
|
||||
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"))
|
||||
|
|
|
|||
|
|
@ -1,17 +1,20 @@
|
|||
"""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."""
|
||||
"""The internet upgrades, against fake services: install-newt (API only, pinned download,
|
||||
secrets kept out of config/output/argv), install-oidc, install-otp, expose-dashboard, and
|
||||
their remove-* undo commands."""
|
||||
import contextlib
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import harness
|
||||
|
||||
ROOT = harness.setup()
|
||||
from llmhost import cli, newt, paths, service
|
||||
from llmhost import cli, newt, otp, paths, service
|
||||
from llmhost.web import oidc
|
||||
|
||||
harness.guard(paths, ROOT)
|
||||
|
|
@ -38,16 +41,22 @@ 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
|
||||
|
||||
class TTY(io.StringIO):
|
||||
def isatty(self):
|
||||
return True
|
||||
|
||||
|
||||
def run(argv, env=None):
|
||||
import os
|
||||
def run(argv, env=None, tty_input=None):
|
||||
"""Run the CLI. Without tty_input there's no terminal (missing values are errors, not
|
||||
prompts); with it, stdin/stdout are a terminal and input() reads those lines."""
|
||||
saved = {k: os.environ.get(k) for k in ("LLMHOST_NEWT_SECRET", "LLMHOST_OIDC_SECRET")}
|
||||
for k in saved:
|
||||
os.environ.pop(k, None)
|
||||
os.environ.update(env or {})
|
||||
out, code = io.StringIO(), 0
|
||||
out, code = (TTY() if tty_input is not None else io.StringIO()), 0
|
||||
old_in = sys.stdin
|
||||
sys.stdin = TTY("".join(l + "\n" for l in tty_input)) if tty_input is not None else io.StringIO()
|
||||
try:
|
||||
with contextlib.redirect_stdout(out):
|
||||
cli.main(argv)
|
||||
|
|
@ -56,6 +65,7 @@ def run(argv, env=None):
|
|||
if isinstance(e.code, str):
|
||||
out.write(e.code)
|
||||
finally:
|
||||
sys.stdin = old_in
|
||||
for k, v in saved.items():
|
||||
os.environ.pop(k, None)
|
||||
if v is not None:
|
||||
|
|
@ -67,9 +77,9 @@ 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}
|
||||
NEWT_ARGS = ["install-newt", "--endpoint", "https://pangolin.example.test", "--newt-id", "site123"]
|
||||
OIDC_ARGS = ["install-oidc", "--public-url", "https://dash.example.test", "--issuer", ISSUER,
|
||||
"--client-id", "client-from-provider", "--allow-group", "llm-admins"]
|
||||
|
||||
print("\n1. a plain install doesn't include newt")
|
||||
check("setup's services are model and web only", service.NAMES == ("model", "web"), service.NAMES)
|
||||
|
|
@ -87,76 +97,121 @@ 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")
|
||||
print("\n3. install-newt: the API only")
|
||||
code, out = run(NEWT_ARGS)
|
||||
check("missing secret without a terminal -> error", code != 0 and "LLMHOST_NEWT_SECRET" in out, out)
|
||||
calls.clear()
|
||||
code, out = run(ARGS, SECRETS)
|
||||
code, out = run(NEWT_ARGS, {"LLMHOST_NEWT_SECRET": NEWT_SECRET})
|
||||
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("dashboard sign-in untouched", "dashboard_auth" not in c and not paths.OIDC_SECRET_FILE.exists())
|
||||
check("newt service installed and started", ("install", "newt") in calls and ("restart", "newt") in calls, calls)
|
||||
check("dashboard 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")
|
||||
check("dashboard not restarted", ("restart", "web") not in calls, calls)
|
||||
check("only the API resource is described", f":{c['api_port']}" in out and f":{c['web_port']}" not in out, out)
|
||||
check("points to expose-dashboard for the rest", "expose-dashboard" in out and "install-oidc" in out, out)
|
||||
check("secret saved 0600, not in config or output",
|
||||
(paths.NEWT_SECRET_FILE.stat().st_mode & 0o777) == 0o600
|
||||
and NEWT_SECRET not in paths.CONFIG_FILE.read_text() and NEWT_SECRET not in out)
|
||||
code, out = run(["install-newt", "--newt-id", "site456"])
|
||||
c = paths.load_config()
|
||||
check("re-run 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)
|
||||
check("re-run keeps what it isn't given", code == 0 and c["newt"] == {"endpoint": "https://pangolin.example.test", "id": "site456"}
|
||||
and paths.NEWT_SECRET_FILE.read_text().strip() == NEWT_SECRET, out)
|
||||
|
||||
print("\n6. newt starts with its credentials in the environment, not its arguments")
|
||||
print("\n4. 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")
|
||||
print("\n5. expose-dashboard won't publish behind the API key alone without asking")
|
||||
code, out = run(["expose-dashboard", "--public-url", "https://dash.example.test"])
|
||||
check("refused without a terminal or --force", code != 0 and "install-oidc" in out and "install-otp" in out, out)
|
||||
code, out = run(["expose-dashboard", "--public-url", "https://dash.example.test"], tty_input=["n"])
|
||||
check("refused when you say no", code != 0 and "Not published" in out, out)
|
||||
code, out = run(["expose-dashboard", "--public-url", "https://dash.example.test", "--force"])
|
||||
check("--force walks through it anyway", code == 0 and f":{paths.load_config()['web_port']}" in out
|
||||
and "dash.example.test" in out, out)
|
||||
|
||||
print("\n6. install-oidc")
|
||||
code, out = run(OIDC_ARGS)
|
||||
check("missing secret -> error", code != 0 and "LLMHOST_OIDC_SECRET" in out, out)
|
||||
code, out = run([a for a in OIDC_ARGS if a not in ("--allow-group", "llm-admins")], {"LLMHOST_OIDC_SECRET": OIDC_SECRET})
|
||||
check("no allow list -> error", code != 0 and "allow" in out, out)
|
||||
calls.clear()
|
||||
code, out = run(OIDC_ARGS, {"LLMHOST_OIDC_SECRET": OIDC_SECRET})
|
||||
c = paths.load_config()
|
||||
check("succeeds", code == 0, out)
|
||||
check("dashboard switched to OIDC", c["dashboard_auth"]["mode"] == "oidc" and c["dashboard_auth"]["client_id"] == "client-from-provider")
|
||||
check("newt untouched", c["newt"]["id"] == "site456")
|
||||
check("dashboard restarted", ("restart", "web") in calls, calls)
|
||||
check("prints the redirect URI", "https://dash.example.test/auth/callback" in out, out)
|
||||
check("secret 0600, not in config or output", (paths.OIDC_SECRET_FILE.stat().st_mode & 0o777) == 0o600
|
||||
and OIDC_SECRET not in paths.CONFIG_FILE.read_text() and OIDC_SECRET not in out)
|
||||
code, out = run(["expose-dashboard"])
|
||||
check("expose-dashboard with OIDC: no question, URL from OIDC", code == 0 and "dash.example.test" in out
|
||||
and "redirect URI" in out, out)
|
||||
|
||||
print("\n7. install-otp")
|
||||
code, out = run(["install-otp"])
|
||||
check("needs a terminal", code != 0 and "terminal" in out, out)
|
||||
FIXED = "JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP"
|
||||
otp.new_secret = lambda: FIXED
|
||||
code, out = run(["install-otp"], tty_input=["000000", "000001", "000002"])
|
||||
check("wrong codes -> not paired", code != 0 and not paths.OTP_SECRET_FILE.exists(), out)
|
||||
calls.clear()
|
||||
code, out = run(["install-otp"], tty_input=[otp.code_at(FIXED, time.time())])
|
||||
check("right code -> paired", code == 0 and paths.OTP_SECRET_FILE.read_text().strip() == FIXED, out)
|
||||
check("secret 0600", (paths.OTP_SECRET_FILE.stat().st_mode & 0o777) == 0o600)
|
||||
check("showed a QR code and the manual key", "▀" in out and otp.grouped(FIXED) in out, out[:300])
|
||||
check("says OIDC takes precedence while it's on", "remove-oidc" in out, out)
|
||||
check("dashboard restarted", ("restart", "web") in calls)
|
||||
code, out = run(["install-otp"], tty_input=["n"])
|
||||
check("re-running asks before replacing", code != 0 and "kept" in out and paths.OTP_SECRET_FILE.read_text().strip() == FIXED, out)
|
||||
code, out = run(["install-otp", "--show"], tty_input=[])
|
||||
check("--show shows the existing pairing", code == 0 and otp.grouped(FIXED) in out, out[:200])
|
||||
|
||||
print("\n8. status and setup keep it all")
|
||||
code, out = run(["status"])
|
||||
check("status names the sign-in", "OIDC via " + ISSUER in out, out)
|
||||
carried = cli.carried_settings(paths.load_config(), set())
|
||||
check("newt and dashboard_auth carried", "newt" in carried and "dashboard_auth" in carried, carried.keys())
|
||||
|
||||
print("\n8. remove-newt")
|
||||
print("\n9. remove-oidc, then expose-dashboard with codes")
|
||||
code, out = run(["remove-oidc"])
|
||||
c = paths.load_config()
|
||||
check("OIDC off, secret deleted", code == 0 and "dashboard_auth" not in c and not paths.OIDC_SECRET_FILE.exists(), out)
|
||||
check("says codes work again", "authenticator code" in out, out)
|
||||
code, out = run(["status"])
|
||||
check("status: key or code", "API key or authenticator code" in out, out)
|
||||
code, out = run(["expose-dashboard", "--public-url", "https://dash.example.test"], tty_input=["y", ""])
|
||||
c = paths.load_config()
|
||||
check("offers to turn the key off for the dashboard", code == 0 and c.get("dashboard_key_login") is False, out)
|
||||
code, out = run(["status"])
|
||||
check("status: codes only", "sign-in authenticator code" in out, out)
|
||||
check("setup keeps the key switched off", cli.carried_settings(c, set()).get("dashboard_key_login") is False)
|
||||
|
||||
print("\n10. remove-otp and remove-newt")
|
||||
code, out = run(["remove-otp"])
|
||||
c = paths.load_config()
|
||||
check("unpaired, key back on", code == 0 and not paths.OTP_SECRET_FILE.exists() and "dashboard_key_login" not in c, out)
|
||||
calls.clear()
|
||||
code, out = run(["remove-newt"])
|
||||
c = paths.load_config()
|
||||
check("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("newt removed", code == 0 and ("uninstall", "newt") in calls and "newt" not in c
|
||||
and not paths.NEWT_SECRET_FILE.exists() and not newt.binary().exists(), out)
|
||||
check("rest of the config untouched", c.get("api_port") == cfg.get("api_port") and c.get("models") == cfg.get("models"))
|
||||
code, out = run(["expose-dashboard"])
|
||||
check("expose-dashboard needs newt first", code != 0 and "install-newt" in out, out)
|
||||
code, out = run(["remove-newt"])
|
||||
check("running it again is harmless", code == 0 and "wasn't installed" in out, out)
|
||||
|
||||
|
|
|
|||
180
tests/test_opencode_install.py
Normal file
180
tests/test_opencode_install.py
Normal file
|
|
@ -0,0 +1,180 @@
|
|||
"""opencode-install.sh against a fake llm-host API, in a throwaway HOME: new and existing
|
||||
opencode configs, the default-model choice, the cached-key cleanup, --remove, and the
|
||||
official installer stood in for by a curl wrapper."""
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import harness
|
||||
|
||||
ROOT = harness.setup()
|
||||
from llmhost import paths
|
||||
|
||||
harness.guard(paths, ROOT)
|
||||
check = harness.Checks()
|
||||
|
||||
SCRIPT = harness.REPO / "opencode-install.sh"
|
||||
KEY = "sk-test-key-for-the-installer"
|
||||
STATE = {"reasoning": True}
|
||||
|
||||
|
||||
class API(BaseHTTPRequestHandler):
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
if self.headers.get("Authorization") != f"Bearer {KEY}":
|
||||
self.send_response(401); self.end_headers(); return
|
||||
if self.path != "/v1/models":
|
||||
self.send_response(404); self.end_headers(); return
|
||||
body = json.dumps({"object": "list", "data": [{"id": "some-model", "max_model_len": 131072,
|
||||
"reasoning": STATE["reasoning"]}]}).encode()
|
||||
self.send_response(200); self.send_header("Content-Length", str(len(body))); self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
|
||||
srv = ThreadingHTTPServer(("127.0.0.1", 0), API)
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
URL = f"http://127.0.0.1:{srv.server_address[1]}"
|
||||
PROV = "llmhost-127" # first label of the host, as the CLI and dashboard name it
|
||||
|
||||
REAL_CURL = subprocess.run(["bash", "-c", "command -v curl"], capture_output=True, text=True).stdout.strip()
|
||||
|
||||
|
||||
def sandbox(with_opencode=True):
|
||||
home = Path(tempfile.mkdtemp(dir=ROOT, prefix="home-"))
|
||||
bin_dir = home / "fakebin"
|
||||
bin_dir.mkdir()
|
||||
# Stand-in for the official installer: drop an `opencode` into ~/.opencode/bin.
|
||||
(bin_dir / "curl").write_text(f"""#!/bin/bash
|
||||
for a in "$@"; do
|
||||
if [ "$a" = "https://opencode.ai/install" ]; then
|
||||
cat <<'EOF'
|
||||
mkdir -p "$HOME/.opencode/bin"
|
||||
cp "$FAKE_OPENCODE" "$HOME/.opencode/bin/opencode"
|
||||
echo "fake opencode installed"
|
||||
EOF
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
exec {REAL_CURL} "$@"
|
||||
""")
|
||||
# A fake opencode whose `models` lists the providers' models from opencode.json.
|
||||
fake_oc = home / "fake-opencode"
|
||||
fake_oc.write_text(f"""#!/bin/bash
|
||||
[ "$1" = models ] || exit 0
|
||||
{sys.executable} -c 'import json,os
|
||||
c=json.load(open(os.path.expanduser("~/.config/opencode/opencode.json")))
|
||||
for p,b in (c.get("provider") or {{}}).items():
|
||||
for m in b.get("models") or {{}}: print(p+"/"+m)'
|
||||
""")
|
||||
for f in (bin_dir / "curl", fake_oc):
|
||||
f.chmod(0o755)
|
||||
if with_opencode:
|
||||
(bin_dir / "opencode").symlink_to(fake_oc)
|
||||
return home, bin_dir, fake_oc
|
||||
|
||||
|
||||
def run(home, bin_dir, fake_oc, *args, key=KEY):
|
||||
env = {"HOME": str(home), "PATH": f"{bin_dir}:/usr/bin:/bin", "FAKE_OPENCODE": str(fake_oc)}
|
||||
if key is not None:
|
||||
env["LLMHOST_API_KEY"] = key
|
||||
r = subprocess.run(["bash", str(SCRIPT), "--", *args], env=env, capture_output=True, text=True,
|
||||
stdin=subprocess.DEVNULL, start_new_session=True, timeout=60) # no terminal
|
||||
return r.returncode, r.stdout + r.stderr
|
||||
|
||||
|
||||
def conf(home):
|
||||
return json.loads((home / ".config/opencode/opencode.json").read_text())
|
||||
|
||||
|
||||
print("\n1. a new opencode user")
|
||||
home, b, oc = sandbox(with_opencode=False)
|
||||
code, out = run(home, b, oc, "--url", URL)
|
||||
check("succeeds", code == 0, out)
|
||||
check("installs opencode through the official installer", "fake opencode installed" in out
|
||||
and (home / ".opencode/bin/opencode").exists(), out)
|
||||
c = conf(home)
|
||||
p = c["provider"][PROV]
|
||||
check("provider added", p["options"]["baseURL"] == URL + "/v1", p)
|
||||
check("key referenced by file, not inlined", p["options"]["apiKey"] == "{file:" + str(home / f".config/opencode/{PROV}.key") + "}"
|
||||
and KEY not in json.dumps(c), p["options"])
|
||||
check("made the default model", c.get("model") == f"{PROV}/default", c.get("model"))
|
||||
check("schema set", c.get("$schema") == "https://opencode.ai/config.json")
|
||||
check("context from the server", p["models"]["default"]["limit"] == {"context": 131072, "output": 65536})
|
||||
check("thinking model: effort menu off", p["models"]["default"].get("variants", {}).get("high") == {"disabled": True})
|
||||
kf = home / f".config/opencode/{PROV}.key"
|
||||
check("key file saved 0600", kf.read_text().strip() == KEY and (kf.stat().st_mode & 0o777) == 0o600)
|
||||
check("key not echoed", KEY not in out)
|
||||
check("opencode sees it", f"opencode sees {PROV}/default" in out, out)
|
||||
check("no backup for a config that didn't exist", not (home / ".config/opencode/opencode.json.before-llmhost").exists())
|
||||
|
||||
print("\n2. an existing opencode user")
|
||||
home, b, oc = sandbox()
|
||||
cd = home / ".config/opencode"; cd.mkdir(parents=True)
|
||||
mine = {"$schema": "https://opencode.ai/config.json", "theme": "dark", "model": "anthropic/some-model",
|
||||
"provider": {"other": {"npm": "x", "models": {"m": {}}}}}
|
||||
(cd / "opencode.json").write_text(json.dumps(mine))
|
||||
auth = home / ".local/share/opencode/auth.json"; auth.parent.mkdir(parents=True)
|
||||
auth.write_text(json.dumps({PROV: {"type": "api", "key": "stale"}, "anthropic": {"type": "oauth"}}))
|
||||
STATE["reasoning"] = False
|
||||
code, out = run(home, b, oc, "--url", URL + "/v1/")
|
||||
c = conf(home)
|
||||
check("succeeds", code == 0, out)
|
||||
check("didn't reinstall opencode", "already installed" in out and not (home / ".opencode").exists(), out)
|
||||
check("other settings kept", c["theme"] == "dark" and "other" in c["provider"])
|
||||
check("their default model kept (no terminal to ask on)", c["model"] == "anthropic/some-model", c["model"])
|
||||
check("says how to pick it", "/models" in out, out)
|
||||
check("original backed up", json.loads((cd / "opencode.json.before-llmhost").read_text()) == mine)
|
||||
check("trailing /v1/ normalised", c["provider"][PROV]["options"]["baseURL"] == URL + "/v1")
|
||||
check("non-thinking model: no variants", "variants" not in c["provider"][PROV]["models"]["default"])
|
||||
a = json.loads(auth.read_text())
|
||||
check("stale cached key dropped, others kept", PROV not in a and "anthropic" in a, a)
|
||||
code, out = run(home, b, oc, "--url", URL, "--default")
|
||||
check("--default switches the model", conf(home)["model"] == f"{PROV}/default")
|
||||
check("backup not overwritten on a re-run", json.loads((cd / "opencode.json.before-llmhost").read_text()) == mine)
|
||||
code, out = run(home, b, oc, "--url", URL)
|
||||
check("a re-run keeps it the default", conf(home)["model"] == f"{PROV}/default")
|
||||
STATE["reasoning"] = True
|
||||
|
||||
print("\n3. --remove")
|
||||
code, out = run(home, b, oc, "--url", URL, "--remove", key=None)
|
||||
c = conf(home)
|
||||
check("succeeds without a key", code == 0, out)
|
||||
check("provider gone, others kept", PROV not in c["provider"] and "other" in c["provider"], c)
|
||||
check("model that pointed at it dropped", "model" not in c, c)
|
||||
check("key file gone", not (cd / f"{PROV}.key").exists())
|
||||
|
||||
print("\n4. refusals")
|
||||
home, b, oc = sandbox()
|
||||
code, out = run(home, b, oc, "--url", URL, key="sk-wrong")
|
||||
check("wrong key -> error", code != 0 and "rejected" in out, out)
|
||||
check("nothing written after a wrong key", not (home / ".config/opencode").exists())
|
||||
code, out = run(home, b, oc, "--url", URL, key=None)
|
||||
check("no key and no terminal -> error", code != 0 and "no API key" in out, out)
|
||||
code, out = run(home, b, oc, "--url", "ftp://x")
|
||||
check("bad URL -> error", code != 0 and "https://" in out, out)
|
||||
code, out = run(home, b, oc, "--url", "http://127.0.0.1:9")
|
||||
check("unreachable -> error", code != 0 and "couldn't reach" in out, out)
|
||||
cd = home / ".config/opencode"; cd.mkdir(parents=True)
|
||||
(cd / "opencode.json").write_text("{ not json")
|
||||
code, out = run(home, b, oc, "--url", URL)
|
||||
check("broken JSON left alone", code != 0 and (cd / "opencode.json").read_text() == "{ not json", out)
|
||||
(cd / "opencode.json").unlink()
|
||||
(cd / "opencode.jsonc").write_text('{ // mine\n "theme": "dark" }')
|
||||
code, out = run(home, b, oc, "--url", URL)
|
||||
check("a .jsonc is never rewritten; the block is printed", code == 0 and "by hand" in out
|
||||
and (cd / "opencode.jsonc").read_text().startswith("{ // mine") and not (cd / "opencode.json").exists(), out)
|
||||
|
||||
print("\n5. --help works when run as `bash -c`")
|
||||
r = subprocess.run(["bash", "-c", SCRIPT.read_text(), "--", "--help"], capture_output=True, text=True)
|
||||
check("prints usage", r.returncode == 0 and "--url" in r.stdout, r.stdout + r.stderr)
|
||||
|
||||
srv.shutdown()
|
||||
check.done(ROOT)
|
||||
145
tests/test_otp.py
Normal file
145
tests/test_otp.py
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
"""Authenticator codes: TOTP against RFC 6238, the verifier's replay and lockout rules, the
|
||||
QR encoder against reference matrices, and code sign-in on the dashboard."""
|
||||
import http.client
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
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 otp, paths, qr
|
||||
from llmhost.web import server as web
|
||||
|
||||
harness.guard(paths, ROOT)
|
||||
check = harness.Checks()
|
||||
|
||||
print("\n1. TOTP matches RFC 6238 (SHA-1 vectors)")
|
||||
RFC = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ" # base32 of "12345678901234567890"
|
||||
for t, want in ((59, "94287082"), (1111111109, "07081804"), (1111111111, "14050471"),
|
||||
(1234567890, "89005924"), (2000000000, "69279037"), (20000000000, "65353130")):
|
||||
check(f"t={t}", otp.code_at(RFC, t, digits=8) == want, otp.code_at(RFC, t, digits=8))
|
||||
check("6 digits is the last six", otp.code_at(RFC, 59) == "287082")
|
||||
check("new secrets are 160 bits of base32", len(otp.new_secret()) == 32 and otp.new_secret() != otp.new_secret())
|
||||
uri = otp.pairing_uri("ABCDEFGH", "mybox.local")
|
||||
check("pairing link", uri.startswith("otpauth://totp/llm-host:mybox.local?") and "secret=ABCDEFGH" in uri
|
||||
and "issuer=llm-host" in uri and "period=30" in uri, uri)
|
||||
check("grouped for typing", otp.grouped("ABCDEFGHIJ") == "ABCD EFGH IJ")
|
||||
|
||||
print("\n2. the verifier")
|
||||
S = "JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP"
|
||||
now = [1_700_000_000.0]
|
||||
v = otp.Verifier(S, clock=lambda: now[0])
|
||||
code = otp.code_at(S, now[0])
|
||||
check("current code accepted", v.check(code) == "ok")
|
||||
check("same code again refused (replay)", v.check(code) == "wrong")
|
||||
now[0] += 30
|
||||
check("previous step's code refused once a later one was used", v.check(otp.code_at(S, now[0] - 30)) == "wrong")
|
||||
check("drift: next step's code accepted", v.check(otp.code_at(S, now[0] + 30)) == "ok")
|
||||
check("spaces and dashes tolerated", otp.matching_step(S, " ".join(otp.code_at(S, now[0])), now[0]) is not None)
|
||||
check("wrong length refused", otp.matching_step(S, "12345", now[0]) is None)
|
||||
v2 = otp.Verifier(S, clock=lambda: now[0])
|
||||
for _ in range(otp.MAX_FAILURES):
|
||||
v2.check("000000")
|
||||
check(f"locked after {otp.MAX_FAILURES} wrong codes", v2.check(otp.code_at(S, now[0])) == "locked" and v2.locked_for() > 0)
|
||||
now[0] += otp.FAIL_WINDOW + 1
|
||||
check("unlocked after the window", v2.check(otp.code_at(S, now[0])) == "ok")
|
||||
|
||||
print("\n3. QR codes match reference matrices")
|
||||
golden = json.loads((harness.FIXTURES / "qr_golden.json").read_text())
|
||||
for text, g in golden.items():
|
||||
q = qr.QR(text, mask=g["mask"])
|
||||
rows = ["".join("1" if c else "0" for c in r) for r in q.m]
|
||||
check(f"v{g['version']} ({len(text)} bytes)", q.version == g["version"] and rows == g["rows"])
|
||||
q = qr.QR(otp.pairing_uri(otp.new_secret(), "a-rather-long-hostname.example.local"))
|
||||
check("a pairing link fits", 1 <= q.version <= qr.MAX_VERSION and 0 <= q.mask <= 7)
|
||||
check("terminal rendering: two modules per row, with a quiet zone", len(q.terminal()) == (q.size + 4 + 1) // 2)
|
||||
try:
|
||||
qr.QR("x" * 300)
|
||||
check("too long is refused", False)
|
||||
except ValueError:
|
||||
check("too long is refused", True)
|
||||
|
||||
print("\n4. code sign-in on the dashboard")
|
||||
KEY = "sk-test"
|
||||
|
||||
|
||||
class StubSampler:
|
||||
def snapshot(self):
|
||||
return {"ok": True}
|
||||
|
||||
def reset_stats(self):
|
||||
pass
|
||||
|
||||
|
||||
def serve(**kw):
|
||||
srv = ThreadingHTTPServer(("127.0.0.1", 0), web.make_handler(StubSampler(), KEY, **kw))
|
||||
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()
|
||||
cookies = [v for k, v in r.getheaders() if k.lower() == "set-cookie"]
|
||||
c.close()
|
||||
return r.status, data, cookies
|
||||
|
||||
|
||||
HOST = {"Host": "mybox.local:11340"}
|
||||
SAME = {**HOST, "Origin": "http://mybox.local:11340", "Content-Type": "application/json"}
|
||||
clock = [1_800_000_000.0]
|
||||
verifier = otp.Verifier(S, clock=lambda: clock[0])
|
||||
srv = serve(otp=verifier)
|
||||
cfg = json.loads(req(srv, "GET", "/auth/config", HOST)[1])
|
||||
check("config: key and codes", cfg == {"mode": "key", "key": True, "otp": True, "user": None, "name": None}, cfg)
|
||||
check("key still works", req(srv, "GET", "/api/status", {**HOST, "Authorization": f"Bearer {KEY}"})[0] == 200)
|
||||
body = json.dumps({"code": otp.code_at(S, clock[0])})
|
||||
check("code from another origin refused", req(srv, "POST", "/auth/otp", {**SAME, "Origin": "https://evil.test"}, body)[0] == 403)
|
||||
check("code without an Origin refused", req(srv, "POST", "/auth/otp", HOST, body)[0] == 403)
|
||||
st, data, cookies = req(srv, "POST", "/auth/otp", SAME, body)
|
||||
sess = cookies[0].split(";")[0] if cookies else ""
|
||||
check("right code -> session", st == 200 and sess.startswith("llmhost_session="), (st, data))
|
||||
check("session cookie HttpOnly, Lax; not Secure over plain http",
|
||||
"HttpOnly" in cookies[0] and "SameSite=Lax" in cookies[0] and "Secure" not in cookies[0], cookies)
|
||||
check("session opens the API", req(srv, "GET", "/api/status", {**HOST, "Cookie": sess})[0] == 200)
|
||||
check("session POST from this page works", req(srv, "POST", "/api/stats/reset", {**SAME, "Cookie": sess})[0] == 200)
|
||||
check("session POST from another origin refused",
|
||||
req(srv, "POST", "/api/stats/reset", {**SAME, "Cookie": sess, "Origin": "https://evil.test"})[0] == 403)
|
||||
cfg = json.loads(req(srv, "GET", "/auth/config", {**HOST, "Cookie": sess})[1])
|
||||
check("config names the session", cfg["user"] == "authenticator", cfg)
|
||||
check("same code can't be reused", req(srv, "POST", "/auth/otp", SAME, body)[0] == 401)
|
||||
clock[0] += 60
|
||||
st, _, cookies = req(srv, "POST", "/auth/otp", {**SAME, "X-Forwarded-Proto": "https"},
|
||||
json.dumps({"code": otp.code_at(S, clock[0])}))
|
||||
check("behind HTTPS the cookie is Secure", st == 200 and "Secure" in cookies[0], cookies)
|
||||
for _ in range(otp.MAX_FAILURES):
|
||||
req(srv, "POST", "/auth/otp", SAME, json.dumps({"code": "000000"}))
|
||||
st, data, _ = req(srv, "POST", "/auth/otp", SAME, json.dumps({"code": otp.code_at(S, clock[0] + 30)}))
|
||||
check("too many wrong codes -> 429", st == 429 and json.loads(data)["retry_after"] > 0, (st, data))
|
||||
st, _, cookies = req(srv, "POST", "/auth/logout", {**SAME, "Cookie": sess})
|
||||
check("sign out clears the cookie", st == 200 and "Max-Age=0" in cookies[0], cookies)
|
||||
check("old session no longer works", req(srv, "GET", "/api/status", {**HOST, "Cookie": sess})[0] == 401)
|
||||
srv.shutdown()
|
||||
|
||||
print("\n5. key sign-in switched off for the dashboard")
|
||||
v3 = otp.Verifier(S, clock=lambda: clock[0])
|
||||
srv = serve(otp=v3, key_login=False)
|
||||
check("config says so", json.loads(req(srv, "GET", "/auth/config", HOST)[1])["key"] is False)
|
||||
check("the key no longer opens the dashboard", req(srv, "GET", "/api/status", {**HOST, "Authorization": f"Bearer {KEY}"})[0] == 401)
|
||||
st, _, cookies = req(srv, "POST", "/auth/otp", SAME, json.dumps({"code": otp.code_at(S, clock[0] + 30)}))
|
||||
check("a code still does", st == 200 and req(srv, "GET", "/api/status", {**HOST, "Cookie": cookies[0].split(";")[0]})[0] == 200)
|
||||
srv.shutdown()
|
||||
|
||||
print("\n6. no codes without install-otp")
|
||||
srv = serve()
|
||||
check("config: no otp", json.loads(req(srv, "GET", "/auth/config", HOST)[1])["otp"] is False)
|
||||
check("/auth/otp is 404", req(srv, "POST", "/auth/otp", SAME, json.dumps({"code": "123456"}))[0] == 404)
|
||||
srv.shutdown()
|
||||
|
||||
check.done(ROOT)
|
||||
|
|
@ -140,6 +140,8 @@ req = urllib.request.Request(f"http://127.0.0.1:{OUTER}/v1/models",
|
|||
with urllib.request.urlopen(req, timeout=10) as r:
|
||||
d = json.loads(r.read())
|
||||
check("advertises the loaded model", [m["id"] for m in d["data"]] == [SERVED], d)
|
||||
check("reports context and whether it thinks", d["data"][0]["max_model_len"] == 262144
|
||||
and d["data"][0]["reasoning"] is False, d)
|
||||
|
||||
check.section("9. in front of vLLM: its model name and its own key are sent upstream")
|
||||
VOUTER = 18233
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue