OWNER_HOSTS (homelab: hub.gabvdl.xyz) answers as the owner without Authelia, for the one device that can't be on the personal tailnet (the Orus Mac). On it the gate takes only the owner's __Host-aia_owner session (7 days, host-only, Strict) — no Remote-User, host token or guest cookie is anyone; without one only the sign-in answers. - remoteaccess/webauthn.py: WebAuthn checked by the hub on `cryptography` (challenge, exact origin, RP ID, user present + verified, signature, counter); a small CBOR reader for new passkeys; fuzzed (80k inputs). - passkeys added only through a one-time link made on the admin host (15 min, one use, hashed, fragment-borne); no mail fallback — Pocket ID was rejected because a mailed code there can enrol a passkey. - Settings → Security: Internet access off (drops every session, back on from the admin host only); pushes on every sign-in and passkey added. - machine paths (worker proxy tokens, tool proxy) refused there. - tests: test_remote_access.py (31), test_webauthn.py (7). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
358 lines
16 KiB
Python
358 lines
16 KiB
Python
"""``/proxy/claude/<account>/v1/…`` — the Anthropic API, on the lab's logins,
|
|
for the workers (see service.py) — and ``/proxy/opencode/<account>/responses``,
|
|
its twin on the Codex backend for opencode's ChatGPT logins (opencode.py).
|
|
|
|
Outside ``/api``: the trusted-caller gate never sees it, and neither does
|
|
Authelia (Traefik routes this prefix on its own router). The worker's proxy
|
|
token is the whole auth, so everything is refused until it names a worker,
|
|
the account is one that worker may bill, and the path is the API's.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import datetime
|
|
import re
|
|
import time
|
|
|
|
import httpx
|
|
from fastapi import APIRouter, HTTPException, Request
|
|
from fastapi.responses import JSONResponse, StreamingResponse
|
|
from starlette.background import BackgroundTask
|
|
from starlette.concurrency import run_in_threadpool
|
|
|
|
import accounts as accounts_mod
|
|
from users.caller import on_guest_surface, on_public_surface
|
|
from workers import guests, terminal
|
|
from . import limits, opencode, service
|
|
|
|
router = APIRouter()
|
|
|
|
_PATH_RE = re.compile(r"^v1/[A-Za-z0-9/_.-]{1,200}$")
|
|
# What opencode's ChatGPT provider calls on the Codex backend.
|
|
_CODEX_PATH_RE = re.compile(r"^responses(/compact)?$")
|
|
# Never forwarded either way: hop-by-hop, what httpx sets itself, the
|
|
# worker's credential, and anything an edge or a browser added.
|
|
_DROP_REQ = {"host", "connection", "keep-alive", "proxy-authorization", "te",
|
|
"trailer", "transfer-encoding", "upgrade", "content-length",
|
|
"authorization", "x-api-key", "cookie", "forwarded", "x-real-ip",
|
|
"remote-user", "remote-groups", "remote-email", "remote-name"}
|
|
_DROP_RESP = {"connection", "keep-alive", "transfer-encoding", "content-length",
|
|
"set-cookie", "trailer", "upgrade"}
|
|
_OAUTH_BETA = "oauth-2025-04-20"
|
|
|
|
_client: httpx.AsyncClient | None = None
|
|
|
|
|
|
def _http() -> httpx.AsyncClient:
|
|
global _client
|
|
if _client is None:
|
|
# read=None: a long thinking turn streams nothing for minutes.
|
|
_client = httpx.AsyncClient(timeout=httpx.Timeout(30.0, read=None),
|
|
limits=httpx.Limits(max_connections=64))
|
|
return _client
|
|
|
|
|
|
def _error(status: int, kind: str, message: str) -> JSONResponse:
|
|
"""An error in the API's own shape, so the CLI shows the message."""
|
|
return JSONResponse({"type": "error", "error": {"type": kind, "message": message}},
|
|
status_code=status)
|
|
|
|
|
|
def _bearer(request: Request) -> str:
|
|
auth = request.headers.get("authorization") or ""
|
|
if auth.lower().startswith("bearer "):
|
|
return auth[7:].strip()
|
|
return (request.headers.get("x-api-key") or "").strip()
|
|
|
|
|
|
def _now_iso() -> str:
|
|
return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
|
|
|
|
def _passthrough(request: Request, drop: set[str] = frozenset()) -> dict[str, str]:
|
|
return {k: v for k, v in request.headers.items()
|
|
if k.lower() not in _DROP_REQ | drop and not k.lower().startswith("x-forwarded-")}
|
|
|
|
|
|
def _claude_headers(request: Request, token: str, _extra: dict) -> dict[str, str]:
|
|
out = _passthrough(request, {"accept-encoding"})
|
|
out["authorization"] = f"Bearer {token}"
|
|
# Plain text back, so the meter (limits.UsageTap) can read the usage.
|
|
out["accept-encoding"] = "identity"
|
|
beta = [b.strip() for b in (out.get("anthropic-beta") or "").split(",") if b.strip()]
|
|
if _OAUTH_BETA not in beta:
|
|
out["anthropic-beta"] = ",".join([_OAUTH_BETA, *beta])
|
|
return out
|
|
|
|
|
|
def _opencode_headers(request: Request, token: str, extra: dict) -> dict[str, str]:
|
|
out = _passthrough(request, {"chatgpt-account-id"})
|
|
out["authorization"] = f"Bearer {token}"
|
|
if extra.get("accountId"):
|
|
out["chatgpt-account-id"] = extra["accountId"]
|
|
return out
|
|
|
|
|
|
async def _token(deps, tokens, account: str, what: str,
|
|
refused: str | None = None) -> str | JSONResponse:
|
|
try:
|
|
return await run_in_threadpool(tokens.get, account, refused=refused)
|
|
except HTTPException as e:
|
|
d = e.detail if isinstance(e.detail, dict) else {"message": str(e.detail)}
|
|
label = (accounts_mod.get(account) or {}).get("label") or account
|
|
if d.get("kind") == "auth":
|
|
_report(deps, account, d.get("message") or "signed out")
|
|
return _error(401, "authentication_error",
|
|
f"the Homelab's {label} {what} login is signed out — "
|
|
"sign it in again from the ai-agent's Settings → Accounts")
|
|
return _error(503, "api_error", f"the Homelab can't read its {label} login: "
|
|
f"{d.get('message') or 'sidecar unreachable'}")
|
|
|
|
|
|
def _report(deps, account: str, message: str) -> None:
|
|
try:
|
|
deps.account_health.report(account, message, "auth")
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
_last_refusal: dict[tuple[str, str], float] = {}
|
|
|
|
|
|
_pushed_refusal: dict[tuple[str, str], str] = {}
|
|
|
|
|
|
def _refused(deps, w: dict, no: tuple) -> None:
|
|
"""A guest computer's refused call goes to the Security log — once per
|
|
computer and kind per ten minutes — and, refused for its budget or the
|
|
owner's plan, to the owner's phone once a day per guest."""
|
|
kind = no[3] if len(no) > 3 else "other"
|
|
key = (w["id"], kind)
|
|
now = time.time()
|
|
if now - _last_refusal.get(key, 0) < 600:
|
|
return
|
|
_last_refusal[key] = now
|
|
from security.service import record
|
|
owner = guests.owner_of(w)
|
|
record(deps, "guest_proxy_refused", who=owner,
|
|
detail=f"{w.get('name')}: {no[2]}", data={"worker": w["id"], "kind": kind})
|
|
day = time.strftime("%Y-%m-%d", time.gmtime(now))
|
|
if kind in ("budget", "plan") and _pushed_refusal.get((owner, kind)) != day:
|
|
_pushed_refusal[(owner, kind)] = day
|
|
try:
|
|
from notifications.service import _create_notify
|
|
u = deps.users.get(owner) or {}
|
|
_create_notify(deps, {
|
|
"title": f"⏸️ {u.get('name') or owner}'s computer is waiting",
|
|
"message": f"{w.get('name')}: {no[2]}",
|
|
"type": "warn", "url": f"/settings/users/{owner}?tab=budget"})
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
_pushed_leak: dict[str, str] = {}
|
|
|
|
|
|
def _own_login_leak(deps, w: dict, sid: str, account: str) -> bool:
|
|
"""A call through the proxy from a run the hub launched on the guest's
|
|
*own* Claude (``meta.account`` = ``guest-<uid>``): something on their
|
|
computer sent it here anyway — a settings file holding the proxy's pair,
|
|
which the sidecar now unsets (``sidecar/proxy_pair.py``), or one it
|
|
can't (managed settings, an older sidecar). The host's plan pays for it,
|
|
so the conversation says so: ``account`` becomes the host's (spend,
|
|
budget and cards follow), ``ownLoginLeak`` marks why, the Security log
|
|
keeps it, and the owner gets one push a day per guest. Not refused: a
|
|
guest may resume that conversation in their terminal on ai-agent Claude,
|
|
which is this same call, legitimately. True when it restamped. Asked on
|
|
every call (``peek`` is a dict lookup): a later turn of the same
|
|
conversation is stamped their own again."""
|
|
owner = guests.owner_of(w)
|
|
meta = deps.meta_store.peek(sid)
|
|
if meta.get("worker") != w["id"] or meta.get("account") != accounts_mod.guest_account(owner):
|
|
return False
|
|
deps.meta_store.update(sid, {"account": account, "ownLoginLeak": True})
|
|
deps.hub.publish({"type": "meta", "id": sid})
|
|
st = deps.worker_store.status(w["id"]) or {}
|
|
where = ", ".join(h.get("path") or "its environment"
|
|
for h in ((st.get("ownLogin") or {}).get("override") or ())) \
|
|
or "a setting on that computer"
|
|
from security.service import record
|
|
record(deps, "guest_own_login_leak", who=owner, sid=sid,
|
|
detail=f"{w.get('name')}: a run on their own Claude went through the proxy "
|
|
f"on {account} ({where})", data={"worker": w["id"]})
|
|
day = time.strftime("%Y-%m-%d", time.gmtime())
|
|
if _pushed_leak.get(owner) != day:
|
|
_pushed_leak[owner] = day
|
|
try:
|
|
from notifications.service import _create_notify
|
|
u = deps.users.get(owner) or {}
|
|
_create_notify(deps, {
|
|
"title": f"💸 {u.get('name') or owner}'s own-Claude run billed you",
|
|
"message": f"{w.get('name')} sent a run meant for their own Claude "
|
|
f"through your {account} account — {where}. Counted on "
|
|
"your account and their budget.",
|
|
"type": "warn", "url": f"/settings/users/{owner}?tab=budget"})
|
|
except Exception:
|
|
pass
|
|
return True
|
|
|
|
|
|
def _worker(request: Request, *, public_ok: bool = False):
|
|
"""The worker a proxy token names. On the public guest host only a
|
|
guest's machine is served (``public_ok``): the owner's workers reach the
|
|
proxy over the tailnet, and their tokens are refused out there — the same
|
|
answer as no token, so the public host says nothing about them."""
|
|
if guests.ip_locked(request):
|
|
return None, _error(429, "rate_limit_error", "too many bad tokens from this "
|
|
"address — try again in an hour")
|
|
w = service.worker_for_token(request.app.state.ai.worker_store, _bearer(request))
|
|
if w and on_public_surface(request) and not (
|
|
public_ok and on_guest_surface(request) and guests.is_guest(w)):
|
|
w = None
|
|
if not w:
|
|
guests.bad_token(request.app.state.ai, request, "/proxy")
|
|
return None, _error(401, "authentication_error", "unknown worker token — "
|
|
"re-pair this worker with the ai-agent")
|
|
return w, None
|
|
|
|
|
|
async def _forward(request: Request, w: dict, account: str, url: str, *, tokens, what: str,
|
|
headers, last_key: str, body: bytes | None = None, meter: bool = False):
|
|
"""Send the request upstream on the account's token, retrying once on a
|
|
401 with a fresh (refreshed) one, and stream the reply back — through the
|
|
meter (``limits.UsageTap`` → the ledger) when ``meter``."""
|
|
deps = request.app.state.ai
|
|
if body is None:
|
|
body = await request.body()
|
|
refused = None
|
|
for _attempt in range(2):
|
|
token = await _token(deps, tokens, account, what, refused)
|
|
if isinstance(token, JSONResponse):
|
|
return token, None
|
|
req = _http().build_request(request.method, url, params=request.query_params,
|
|
headers=headers(request, token, tokens.extra(account)),
|
|
content=body)
|
|
try:
|
|
resp = await _http().send(req, stream=True)
|
|
except httpx.HTTPError as e:
|
|
return _error(502, "api_error", f"the Homelab couldn't reach the API: {e}"), None
|
|
if resp.status_code == 401 and refused is None:
|
|
# The lab may have refreshed (or lost) the login since we cached
|
|
# it: fetch again — refreshing — and retry once.
|
|
await resp.aclose()
|
|
refused = token
|
|
continue
|
|
break
|
|
if resp.status_code == 401:
|
|
_report(deps, account, "the API refused the Homelab's token")
|
|
deps.worker_store.set_status(w["id"], **{last_key: _now_iso()}, proxyLastAccount=account)
|
|
headers_out = {k: v for k, v in resp.headers.items() if k.lower() not in _DROP_RESP}
|
|
stream = _metered(resp, w, account, _session(request)) \
|
|
if meter and resp.status_code < 400 else resp.aiter_raw()
|
|
return StreamingResponse(stream, status_code=resp.status_code,
|
|
headers=headers_out, background=BackgroundTask(resp.aclose)), resp
|
|
|
|
|
|
def _session(request: Request) -> str | None:
|
|
"""The Claude Code session making the call (the CLI sends its id on each
|
|
one), when it looks like one."""
|
|
sid = (request.headers.get("x-claude-code-session-id") or "").strip().lower()
|
|
return sid if terminal.SID_RE.match(sid) else None
|
|
|
|
|
|
async def _metered(resp, w: dict, account: str, sid: str | None = None):
|
|
"""The reply's bytes, unchanged, read by a usage tap on the way; the
|
|
call lands in the ledger when the stream ends (or the worker hangs up)."""
|
|
tap = limits.UsageTap(resp.headers.get("content-type"))
|
|
try:
|
|
async for chunk in resp.aiter_raw():
|
|
try:
|
|
tap.feed(chunk)
|
|
except Exception:
|
|
pass
|
|
yield chunk
|
|
finally:
|
|
tap.finish()
|
|
if tap.usage:
|
|
limits.LEDGER.record({"t": time.time(), "worker": w["id"],
|
|
"guest": guests.owner_of(w), "account": account,
|
|
"model": tap.model, "usage": tap.usage,
|
|
"usd": round(tap.cost(), 6),
|
|
**({"session": sid} if sid else {})})
|
|
|
|
|
|
@router.api_route("/proxy/claude/{account}/{path:path}", methods=["GET", "POST"],
|
|
include_in_schema=False)
|
|
async def claude_proxy(request: Request, account: str, path: str):
|
|
w, err = _worker(request, public_ok=True)
|
|
if err:
|
|
return err
|
|
account = (account or "").strip().lower()
|
|
if account not in service.proxied_accounts(w):
|
|
return _error(403, "permission_error",
|
|
f"{w.get('name') or 'this worker'} may not use the {account!r} "
|
|
"account — tick it on the worker's page (Settings → Profiles)")
|
|
if not _PATH_RE.match(path) or ".." in path:
|
|
return _error(404, "not_found_error", "not an API path")
|
|
body = await request.body()
|
|
deps = request.app.state.ai
|
|
no = await run_in_threadpool(limits.refusal, deps, w, account, body, path,
|
|
request.headers.get("anthropic-beta"))
|
|
if no:
|
|
_refused(deps, w, no)
|
|
return _error(*no[:3])
|
|
guest = guests.is_guest(w)
|
|
if guest:
|
|
# A session typed in the computer's own terminal on ai-agent Claude:
|
|
# this call makes it one the hub mirrors (workers/terminal.py).
|
|
sid = _session(request)
|
|
if sid:
|
|
await run_in_threadpool(terminal.claim, deps, w, sid, "proxy")
|
|
await run_in_threadpool(_own_login_leak, deps, w, sid, account)
|
|
limits.enter(w["id"])
|
|
try:
|
|
out, resp = await _forward(request, w, account, f"{service.UPSTREAM}/{path}",
|
|
tokens=service.TOKENS, what="Claude",
|
|
headers=_claude_headers, last_key="proxyLastAt",
|
|
body=body, meter=True)
|
|
except BaseException:
|
|
if guest:
|
|
limits.leave(w["id"])
|
|
raise
|
|
if guest:
|
|
if isinstance(out, StreamingResponse):
|
|
# Leaves when the reply has been streamed out (or the worker hung up).
|
|
prev = out.background
|
|
async def _done():
|
|
limits.leave(w["id"])
|
|
if prev is not None:
|
|
await prev()
|
|
out.background = BackgroundTask(_done)
|
|
else:
|
|
limits.leave(w["id"])
|
|
snap = service.usage_from_headers(resp.headers) if resp is not None else None
|
|
if snap:
|
|
try:
|
|
request.app.state.ai.usage_poller.observe(account, snap)
|
|
except Exception:
|
|
pass
|
|
return out
|
|
|
|
|
|
@router.post("/proxy/opencode/{account}/{path:path}", include_in_schema=False)
|
|
async def opencode_proxy(request: Request, account: str, path: str):
|
|
w, err = _worker(request)
|
|
if err:
|
|
return err
|
|
account = (account or "").strip().lower()
|
|
if account not in opencode.proxied_accounts(w):
|
|
return _error(403, "permission_error",
|
|
f"{w.get('name') or 'this worker'} may not use the {account!r} "
|
|
"account — tick it on the worker's page (Settings → Profiles)")
|
|
if not _CODEX_PATH_RE.match(path):
|
|
return _error(404, "not_found_error", "not a Codex API path")
|
|
out, _resp = await _forward(request, w, account, f"{opencode.UPSTREAM}/{path}",
|
|
tokens=opencode.TOKENS, what="ChatGPT",
|
|
headers=_opencode_headers, last_key="opencodeProxyLastAt")
|
|
return out
|