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
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)
|
||||
Loading…
Add table
Add a link
Reference in a new issue