The Orus devbox (a dial-out worker, off the personal tailnet) can't reach ai-agent.lab: its MCP server through the hub failed with a TLS error. GET hub/machines now gives a link worker the guest host's tools URL and public: true; relay tokens carry public (mint / PUT), and the guest host lets only those through (anything else there, a wrong token included, is a 404). The owner's internet address still never serves the relay. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
634 lines
26 KiB
Python
634 lines
26 KiB
Python
"""``relay.serve`` — authenticated streaming relays a plugin keeps to upstreams
|
|
whose credentials it manages (the hub gateway of the ``mcp-servers`` plugin,
|
|
2026-11-26; homelab spec ``data/log/2026-11-26-ai-agent-mcp-plugin-spec.md``
|
|
§4.3). Owner only, operator approval.
|
|
|
|
The plugin's handlers keep **routes** (``name`` → an upstream URL and the
|
|
headers to send it — values are secrets: stored, never returned) and
|
|
**tokens** (``aiar1.<id>.<secret>``, shown once, stored as a SHA-256, each
|
|
listing the routes it opens). A machine then talks to
|
|
``/proxy/tools/relay/<plugin>/<name>[/<path>]`` with ``Authorization: Bearer
|
|
aiar1…`` as if it were the upstream: MCP Streamable HTTP (a POST answered
|
|
with JSON or with ``text/event-stream``, a long-lived GET event stream, a
|
|
DELETE) passes through unbuffered.
|
|
|
|
Storage: ``PLUGINS_DIR/relay/<pluginId>.json`` (0600)::
|
|
|
|
{"routes": {name: {upstream, headers: {k: v}, createdAt, updatedAt,
|
|
lastUsedAt, lastStatus}},
|
|
"tokens": {id: {label, routes: [name], sha256, createdAt, lastUsedAt}}}
|
|
|
|
What the relay forwards: only ``Content-Type``, ``Accept``,
|
|
``Mcp-Session-Id``, ``MCP-Protocol-Version`` and ``Last-Event-ID`` from the
|
|
caller, plus the route's headers (``Accept-Encoding: identity`` — no
|
|
compression); back: the status, ``Content-Type``, ``Mcp-Session-Id``,
|
|
``MCP-Protocol-Version`` and ``Cache-Control`` (+ ``X-Accel-Buffering: no``
|
|
on an event stream). An upstream 401/403 becomes the relay's own **403**
|
|
``relay_unauthorized`` **without** ``WWW-Authenticate``, and a bad token or an
|
|
unlisted route is a 403 too: a harness must not start an OAuth flow of its own
|
|
against the hub (a 401 sends an MCP client looking for the hub's own
|
|
``/.well-known/oauth-protected-resource``). Connect timeout 15 s; no read
|
|
timeout on an event stream (a JSON answer may idle :data:`IDLE_S` between
|
|
chunks). No egress filter: the owner's plugin, like the owner's proxies.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import hashlib
|
|
import hmac
|
|
import json
|
|
import logging
|
|
import os
|
|
import pathlib
|
|
import re
|
|
import secrets
|
|
import threading
|
|
import time
|
|
import urllib.parse
|
|
from typing import Any
|
|
|
|
import anyio
|
|
import httpx
|
|
from fastapi import APIRouter, Request
|
|
from fastapi.responses import JSONResponse, StreamingResponse
|
|
from starlette.concurrency import run_in_threadpool
|
|
|
|
from plugins.proxyroutes import _active_plugin, _bearer, _error, _who
|
|
from plugins.store import OWNER_UID
|
|
from users.caller import on_guest_surface, on_public_surface
|
|
from workers import guests
|
|
|
|
log = logging.getLogger(__name__)
|
|
router = APIRouter(include_in_schema=False)
|
|
|
|
CAP = "relay.serve"
|
|
TOKEN_PREFIX = "aiar1"
|
|
NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
|
|
_ID_RE = re.compile(r"^[a-f0-9]{16}$")
|
|
# RFC 9110 token characters.
|
|
_HEADER_RE = re.compile(r"^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,64}$")
|
|
# Never set by a route: the hop's own, or what the relay decides itself.
|
|
_NOT_ROUTE_HEADERS = frozenset({
|
|
"host", "content-length", "transfer-encoding", "connection", "keep-alive",
|
|
"upgrade", "te", "trailer", "proxy-connection", "accept-encoding",
|
|
})
|
|
FORWARD_REQUEST = ("content-type", "accept", "mcp-session-id", "mcp-protocol-version",
|
|
"last-event-id")
|
|
FORWARD_RESPONSE = ("content-type", "mcp-session-id", "mcp-protocol-version", "cache-control")
|
|
MAX_ROUTES = 64
|
|
MAX_TOKENS = 64
|
|
MAX_HEADERS = 32
|
|
MAX_HEADER_VALUE = 8192
|
|
MAX_LABEL = 120
|
|
MAX_BODY = 16 * 1024 * 1024
|
|
CONNECT_S = 15.0
|
|
# How long the upstream may take to answer a request's headers (a JSON-mode
|
|
# server holds a tool call's POST until it is done), and how long a non-stream
|
|
# answer may idle between chunks.
|
|
HEADERS_WAIT_S = float(os.environ.get("RELAY_RESPONSE_TIMEOUT_S", "600"))
|
|
IDLE_S = float(os.environ.get("RELAY_IDLE_TIMEOUT_S", "300"))
|
|
USE_WRITE_EVERY_S = 60.0
|
|
UNAUTHORIZED = {"error": "relay_unauthorized",
|
|
"message": "signed out on the hub — sign in again in MCP servers"}
|
|
|
|
|
|
def _now() -> int:
|
|
return int(time.time())
|
|
|
|
|
|
def _sha(token: str) -> str:
|
|
return hashlib.sha256(token.encode()).hexdigest()
|
|
|
|
|
|
def public_upstream(url: str) -> str:
|
|
"""An upstream as it may be shown: no userinfo, no query, no fragment."""
|
|
p = urllib.parse.urlsplit(url)
|
|
host = p.hostname or ""
|
|
if ":" in host:
|
|
host = f"[{host}]"
|
|
netloc = host + (f":{p.port}" if p.port else "")
|
|
return urllib.parse.urlunsplit((p.scheme, netloc, p.path, "", ""))
|
|
|
|
|
|
def clean_upstream(raw: Any) -> str:
|
|
if not isinstance(raw, str):
|
|
raise ValueError("upstream must be an http(s) URL")
|
|
url = raw.strip()
|
|
if len(url) > 2048 or re.search(r"\s", url):
|
|
raise ValueError("upstream must be an http(s) URL")
|
|
p = urllib.parse.urlsplit(url)
|
|
if p.scheme not in ("http", "https") or not p.hostname or p.fragment:
|
|
raise ValueError("upstream must be an http(s) URL (no fragment)")
|
|
try:
|
|
p.port
|
|
except ValueError:
|
|
raise ValueError("upstream has a bad port") from None
|
|
return url
|
|
|
|
|
|
def clean_headers(raw: Any) -> dict[str, str]:
|
|
if raw is None:
|
|
return {}
|
|
if not isinstance(raw, dict) or len(raw) > MAX_HEADERS:
|
|
raise ValueError(f"headers must be an object of at most {MAX_HEADERS} entries")
|
|
out: dict[str, str] = {}
|
|
for k, v in raw.items():
|
|
if not isinstance(k, str) or not _HEADER_RE.match(k) or k.lower() in _NOT_ROUTE_HEADERS:
|
|
raise ValueError(f"header name not allowed: {str(k)[:64]!r}")
|
|
if not isinstance(v, str) or len(v) > MAX_HEADER_VALUE or any(c in v for c in "\r\n\0"):
|
|
raise ValueError(f"{k}: invalid value")
|
|
out[k] = v
|
|
return out
|
|
|
|
|
|
# ── the store ────────────────────────────────────────────────────────────────
|
|
class RelayStore:
|
|
"""``<root>/<pluginId>.json`` per plugin — re-read when its mtime moves
|
|
(the deploy cutover's twin shares the file), written atomically, 0600."""
|
|
|
|
def __init__(self, root: str | os.PathLike):
|
|
self.root = pathlib.Path(root)
|
|
self._lock = threading.Lock()
|
|
self._cache: dict[str, tuple[int, dict]] = {}
|
|
# (pid, "r"|"t", name|id) → (monotonic of the last write, status)
|
|
self._wrote: dict[tuple[str, str, str], tuple[float, Any]] = {}
|
|
# usage newer than the file (writes are throttled): merged into reads
|
|
self._fresh: dict[tuple[str, str, str], dict] = {}
|
|
|
|
def path(self, pid: str) -> pathlib.Path:
|
|
return self.root / f"{pid}.json"
|
|
|
|
def _read(self, pid: str) -> dict:
|
|
p = self.path(pid)
|
|
try:
|
|
mt = p.stat().st_mtime_ns
|
|
except OSError:
|
|
self._cache.pop(pid, None)
|
|
return {"routes": {}, "tokens": {}}
|
|
hit = self._cache.get(pid)
|
|
if hit and hit[0] == mt:
|
|
return hit[1]
|
|
try:
|
|
data = json.loads(p.read_text(encoding="utf-8"))
|
|
except (OSError, ValueError):
|
|
data = {}
|
|
if not isinstance(data, dict):
|
|
data = {}
|
|
data = {"routes": dict(data.get("routes") or {}), "tokens": dict(data.get("tokens") or {})}
|
|
self._cache[pid] = (mt, data)
|
|
return data
|
|
|
|
def _write(self, pid: str, data: dict) -> None:
|
|
self.root.mkdir(parents=True, exist_ok=True)
|
|
try:
|
|
os.chmod(self.root, 0o700)
|
|
except OSError:
|
|
pass
|
|
p = self.path(pid)
|
|
tmp = p.with_name(f".{p.name}.{os.getpid()}.tmp")
|
|
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
json.dump(data, f, indent=1, sort_keys=True)
|
|
os.chmod(tmp, 0o600)
|
|
os.replace(tmp, p)
|
|
self._cache[pid] = (p.stat().st_mtime_ns, data)
|
|
|
|
def _copy(self, pid: str) -> dict:
|
|
return json.loads(json.dumps(self._read(pid)))
|
|
|
|
# routes
|
|
def put_route(self, pid: str, name: str, upstream: Any, headers: Any) -> dict:
|
|
if not NAME_RE.match(name or ""):
|
|
raise ValueError("a route name is letters, digits, . _ - (64 max)")
|
|
url, hdrs = clean_upstream(upstream), clean_headers(headers)
|
|
with self._lock:
|
|
data = self._copy(pid)
|
|
if name not in data["routes"] and len(data["routes"]) >= MAX_ROUTES:
|
|
raise ValueError(f"at most {MAX_ROUTES} routes")
|
|
old = data["routes"].get(name) or {}
|
|
now = _now()
|
|
data["routes"][name] = {**{k: old[k] for k in ("lastUsedAt", "lastStatus") if k in old},
|
|
"upstream": url, "headers": hdrs,
|
|
"createdAt": old.get("createdAt") or now, "updatedAt": now}
|
|
self._write(pid, data)
|
|
return self._public_route(pid, name, data["routes"][name])
|
|
|
|
def delete_route(self, pid: str, name: str) -> bool:
|
|
with self._lock:
|
|
data = self._copy(pid)
|
|
if data["routes"].pop(name, None) is None:
|
|
return False
|
|
self._write(pid, data)
|
|
self._fresh.pop((pid, "r", name), None)
|
|
return True
|
|
|
|
def route(self, pid: str, name: str) -> dict | None:
|
|
with self._lock:
|
|
r = self._read(pid)["routes"].get(name)
|
|
return json.loads(json.dumps(r)) if isinstance(r, dict) else None
|
|
|
|
def _public_route(self, pid: str, name: str, r: dict) -> dict:
|
|
fresh = self._fresh.get((pid, "r", name)) or {}
|
|
return {"name": name, "upstream": public_upstream(str(r.get("upstream") or "")),
|
|
"headerNames": sorted((r.get("headers") or {}).keys()),
|
|
"updatedAt": r.get("updatedAt"),
|
|
"lastUsedAt": fresh.get("lastUsedAt", r.get("lastUsedAt")),
|
|
"lastStatus": fresh.get("lastStatus", r.get("lastStatus"))}
|
|
|
|
def routes(self, pid: str) -> list[dict]:
|
|
with self._lock:
|
|
data = self._read(pid)
|
|
return [self._public_route(pid, n, r) for n, r in sorted(data["routes"].items())]
|
|
|
|
# tokens
|
|
@staticmethod
|
|
def _clean_routes(raw: Any) -> list[str]:
|
|
if not isinstance(raw, list) or len(raw) > MAX_ROUTES:
|
|
raise ValueError(f"routes must be a list of at most {MAX_ROUTES} names")
|
|
out = sorted({str(n) for n in raw})
|
|
if any(not NAME_RE.match(n) for n in out):
|
|
raise ValueError("a route name is letters, digits, . _ - (64 max)")
|
|
return out
|
|
|
|
@staticmethod
|
|
def _clean_label(raw: Any) -> str:
|
|
return re.sub(r"[\r\n\t]", " ", str(raw or "")).strip()[:MAX_LABEL]
|
|
|
|
def mint(self, pid: str, label: Any, routes: Any, public: bool = False) -> dict:
|
|
"""``public``: the token of a machine off the tailnet (a dial-out
|
|
worker) — the only kind the guest host lets through."""
|
|
names = self._clean_routes(routes if routes is not None else [])
|
|
with self._lock:
|
|
data = self._copy(pid)
|
|
if len(data["tokens"]) >= MAX_TOKENS:
|
|
raise ValueError(f"at most {MAX_TOKENS} tokens")
|
|
tid = secrets.token_hex(8)
|
|
while tid in data["tokens"]:
|
|
tid = secrets.token_hex(8)
|
|
token = f"{TOKEN_PREFIX}.{tid}.{secrets.token_urlsafe(32)}"
|
|
data["tokens"][tid] = {"label": self._clean_label(label), "routes": names,
|
|
"sha256": _sha(token), "createdAt": _now(), "lastUsedAt": None,
|
|
"public": public is True}
|
|
self._write(pid, data)
|
|
return {"id": tid, "token": token}
|
|
|
|
def update_token(self, pid: str, tid: str, *, routes: Any = None, label: Any = None,
|
|
public: Any = None) -> dict | None:
|
|
names = self._clean_routes(routes) if routes is not None else None
|
|
with self._lock:
|
|
data = self._copy(pid)
|
|
t = data["tokens"].get(tid)
|
|
if not isinstance(t, dict):
|
|
return None
|
|
if names is not None:
|
|
t["routes"] = names
|
|
if label is not None:
|
|
t["label"] = self._clean_label(label)
|
|
if isinstance(public, bool):
|
|
t["public"] = public
|
|
self._write(pid, data)
|
|
return self._public_token(pid, tid, t)
|
|
|
|
def delete_token(self, pid: str, tid: str) -> bool:
|
|
with self._lock:
|
|
data = self._copy(pid)
|
|
if data["tokens"].pop(tid, None) is None:
|
|
return False
|
|
self._write(pid, data)
|
|
self._fresh.pop((pid, "t", tid), None)
|
|
return True
|
|
|
|
def _public_token(self, pid: str, tid: str, t: dict) -> dict:
|
|
fresh = self._fresh.get((pid, "t", tid)) or {}
|
|
return {"id": tid, "label": t.get("label") or "", "routes": list(t.get("routes") or []),
|
|
"public": t.get("public") is True, "createdAt": t.get("createdAt"),
|
|
"lastUsedAt": fresh.get("lastUsedAt", t.get("lastUsedAt"))}
|
|
|
|
def tokens(self, pid: str) -> list[dict]:
|
|
with self._lock:
|
|
data = self._read(pid)
|
|
return [self._public_token(pid, i, t) for i, t in sorted(data["tokens"].items())]
|
|
|
|
def check(self, pid: str, token: str) -> tuple[str, list[str]] | None:
|
|
"""``(token id, its routes)`` when ``token`` is one of the plugin's."""
|
|
hit = self.check_full(pid, token)
|
|
return (hit[0], hit[1]) if hit else None
|
|
|
|
def check_full(self, pid: str, token: str) -> tuple[str, list[str], bool] | None:
|
|
"""``(token id, its routes, public)`` when ``token`` is one of the plugin's."""
|
|
parts = (token or "").split(".")
|
|
if len(parts) != 3 or parts[0] != TOKEN_PREFIX or not _ID_RE.match(parts[1]):
|
|
return None
|
|
with self._lock:
|
|
t = self._read(pid)["tokens"].get(parts[1])
|
|
if not isinstance(t, dict) or not hmac.compare_digest(str(t.get("sha256") or ""), _sha(token)):
|
|
return None
|
|
return parts[1], list(t.get("routes") or []), t.get("public") is True
|
|
|
|
def used(self, pid: str, name: str, tid: str, status: int) -> None:
|
|
"""Record a call: kept in memory at once, written to the file at most
|
|
once per route per :data:`USE_WRITE_EVERY_S` — or when its status
|
|
changes (a route that starts answering 401 shows at once)."""
|
|
now, mono = _now(), time.monotonic()
|
|
with self._lock:
|
|
self._fresh[(pid, "r", name)] = {"lastUsedAt": now, "lastStatus": status}
|
|
self._fresh[(pid, "t", tid)] = {"lastUsedAt": now}
|
|
last = self._wrote.get((pid, "r", name))
|
|
if last and mono - last[0] < USE_WRITE_EVERY_S and last[1] == status:
|
|
return
|
|
self._wrote[(pid, "r", name)] = (mono, status)
|
|
data = self._copy(pid)
|
|
r, t = data["routes"].get(name), data["tokens"].get(tid)
|
|
if isinstance(r, dict):
|
|
r.update(lastUsedAt=now, lastStatus=status)
|
|
if isinstance(t, dict):
|
|
t["lastUsedAt"] = now
|
|
try:
|
|
self._write(pid, data)
|
|
except OSError as e:
|
|
log.warning("relay %s: usage not saved: %s", pid, e)
|
|
|
|
def purge(self, pid: str) -> None:
|
|
with self._lock:
|
|
try:
|
|
self.path(pid).unlink()
|
|
except FileNotFoundError:
|
|
pass
|
|
self._cache.pop(pid, None)
|
|
for k in [k for k in self._fresh if k[0] == pid]:
|
|
self._fresh.pop(k, None)
|
|
for k in [k for k in self._wrote if k[0] == pid]:
|
|
self._wrote.pop(k, None)
|
|
|
|
|
|
_stores: dict[str, RelayStore] = {}
|
|
_stores_lock = threading.Lock()
|
|
|
|
|
|
def store_for(deps) -> RelayStore:
|
|
root = str(pathlib.Path(deps.plugin_store.root) / "relay")
|
|
with _stores_lock:
|
|
s = _stores.get(root)
|
|
if s is None:
|
|
s = _stores[root] = RelayStore(root)
|
|
return s
|
|
|
|
|
|
def purge(deps, pid: str) -> None:
|
|
"""A purged uninstall: the routes' secrets go with the plugin's."""
|
|
try:
|
|
store_for(deps).purge(pid)
|
|
except Exception as e: # noqa: BLE001
|
|
log.warning("relay purge %s: %s", pid, e)
|
|
|
|
|
|
# ── the plugin's bridges (handler token only) ────────────────────────────────
|
|
def _bridge(request: Request, pid: str):
|
|
who, err = _who(request, pid)
|
|
if err:
|
|
return None, err
|
|
if who.handler != pid:
|
|
return None, _error(403, f"{CAP} is only available to the plugin's own handlers", "handler_only")
|
|
if not who.is_owner:
|
|
return None, _error(403, f"{CAP} is owner-only", "capability")
|
|
deps = request.app.state.ai
|
|
_, rec, _, _, err = _active_plugin(deps, who, pid)
|
|
if err:
|
|
return None, err
|
|
if CAP not in (rec["manifest"].get("capabilities") or []):
|
|
return None, _error(403, f"plugin lacks {CAP} capability", "capability")
|
|
return store_for(deps), None
|
|
|
|
|
|
async def _body(request: Request) -> dict:
|
|
try:
|
|
b = await request.json()
|
|
except Exception:
|
|
return {}
|
|
return b if isinstance(b, dict) else {}
|
|
|
|
|
|
@router.get("/proxy/tools/plugins/{pid}/hub/relay/routes")
|
|
async def relay_routes(pid: str, request: Request):
|
|
st, err = _bridge(request, pid)
|
|
if err:
|
|
return err
|
|
return await run_in_threadpool(st.routes, pid)
|
|
|
|
|
|
@router.put("/proxy/tools/plugins/{pid}/hub/relay/routes/{name}")
|
|
async def relay_put_route(pid: str, name: str, request: Request):
|
|
st, err = _bridge(request, pid)
|
|
if err:
|
|
return err
|
|
body = await _body(request)
|
|
try:
|
|
route = await run_in_threadpool(st.put_route, pid, name, body.get("upstream"),
|
|
body.get("headers"))
|
|
except ValueError as e:
|
|
return _error(400, str(e), "bad_request")
|
|
return {"ok": True, "route": route}
|
|
|
|
|
|
@router.delete("/proxy/tools/plugins/{pid}/hub/relay/routes/{name}")
|
|
async def relay_delete_route(pid: str, name: str, request: Request):
|
|
st, err = _bridge(request, pid)
|
|
if err:
|
|
return err
|
|
return {"ok": await run_in_threadpool(st.delete_route, pid, name)}
|
|
|
|
|
|
@router.get("/proxy/tools/plugins/{pid}/hub/relay/tokens")
|
|
async def relay_tokens(pid: str, request: Request):
|
|
st, err = _bridge(request, pid)
|
|
if err:
|
|
return err
|
|
return await run_in_threadpool(st.tokens, pid)
|
|
|
|
|
|
@router.post("/proxy/tools/plugins/{pid}/hub/relay/tokens")
|
|
async def relay_mint(pid: str, request: Request):
|
|
st, err = _bridge(request, pid)
|
|
if err:
|
|
return err
|
|
body = await _body(request)
|
|
try:
|
|
return await run_in_threadpool(st.mint, pid, body.get("label"), body.get("routes"),
|
|
body.get("public") is True)
|
|
except ValueError as e:
|
|
return _error(400, str(e), "bad_request")
|
|
|
|
|
|
@router.put("/proxy/tools/plugins/{pid}/hub/relay/tokens/{tid}")
|
|
async def relay_update_token(pid: str, tid: str, request: Request):
|
|
st, err = _bridge(request, pid)
|
|
if err:
|
|
return err
|
|
body = await _body(request)
|
|
try:
|
|
tok = await run_in_threadpool(lambda: st.update_token(
|
|
pid, tid, routes=body.get("routes"), label=body.get("label"),
|
|
public=body.get("public")))
|
|
except ValueError as e:
|
|
return _error(400, str(e), "bad_request")
|
|
if tok is None:
|
|
return _error(404, "no such token", "not_found")
|
|
return {"ok": True, "token": tok}
|
|
|
|
|
|
@router.delete("/proxy/tools/plugins/{pid}/hub/relay/tokens/{tid}")
|
|
async def relay_delete_token(pid: str, tid: str, request: Request):
|
|
st, err = _bridge(request, pid)
|
|
if err:
|
|
return err
|
|
return {"ok": await run_in_threadpool(st.delete_token, pid, tid)}
|
|
|
|
|
|
# ── the public relay (where machines connect) ────────────────────────────────
|
|
# One client per event loop (the app has one; a test's servers have theirs):
|
|
# a client's pool is bound to the loop it was first used on.
|
|
_client: tuple[Any, httpx.AsyncClient] | None = None
|
|
|
|
|
|
def _http() -> httpx.AsyncClient:
|
|
global _client
|
|
loop = asyncio.get_running_loop()
|
|
if _client is None or _client[0] is not loop:
|
|
_client = (loop, httpx.AsyncClient(
|
|
timeout=httpx.Timeout(connect=CONNECT_S, read=None, write=60.0, pool=CONNECT_S),
|
|
limits=httpx.Limits(max_connections=64, max_keepalive_connections=16),
|
|
follow_redirects=False))
|
|
return _client[1]
|
|
|
|
|
|
def _refused(status: int, error: str, message: str) -> JSONResponse:
|
|
return JSONResponse({"error": error, "message": message}, status_code=status)
|
|
|
|
|
|
def upstream_url(upstream: str, path: str, query: str) -> str:
|
|
p = urllib.parse.urlsplit(upstream)
|
|
base = p.path
|
|
if path:
|
|
base = base.rstrip("/") + "/" + path
|
|
q = "&".join(x for x in (p.query, query) if x)
|
|
return urllib.parse.urlunsplit((p.scheme, p.netloc, base or "/", q, ""))
|
|
|
|
|
|
async def _iter(resp: httpx.Response, stream: bool):
|
|
"""The upstream's body as it comes — closed when the caller goes or the
|
|
upstream ends. A non-stream answer may idle :data:`IDLE_S` per chunk."""
|
|
it = resp.aiter_bytes()
|
|
try:
|
|
while True:
|
|
try:
|
|
chunk = await (it.__anext__() if stream else asyncio.wait_for(it.__anext__(), IDLE_S))
|
|
except StopAsyncIteration:
|
|
return
|
|
except (asyncio.TimeoutError, httpx.HTTPError) as e:
|
|
log.info("relay stream ended: %s", type(e).__name__)
|
|
return
|
|
if chunk:
|
|
yield chunk
|
|
finally:
|
|
# also when the caller went away mid-stream (a cancelled task)
|
|
with anyio.CancelScope(shield=True):
|
|
await resp.aclose()
|
|
|
|
|
|
class _TooLarge(Exception):
|
|
pass
|
|
|
|
|
|
async def _relay(request: Request, pid: str, name: str, path: str):
|
|
# Machines reach the relay over the tailnet. The owner's internet address
|
|
# never serves it; the guest host only for a *public* token — a dial-out
|
|
# worker's, a machine off the tailnet that comes in there like its link.
|
|
public_host = on_public_surface(request)
|
|
if public_host and not on_guest_surface(request):
|
|
return _refused(404, "not_found", "not found")
|
|
if guests.ip_locked(request):
|
|
return _refused(429, "locked", "too many bad tokens from this address")
|
|
deps = request.app.state.ai
|
|
st = store_for(deps)
|
|
hit = await run_in_threadpool(st.check_full, pid, _bearer(request))
|
|
if hit is None:
|
|
guests.bad_token(deps, request, "/proxy/tools/relay")
|
|
if public_host:
|
|
return _refused(404, "not_found", "not found")
|
|
return _refused(403, "relay_auth", "unknown relay token")
|
|
tid, allowed, public = hit
|
|
if public_host and not public:
|
|
return _refused(404, "not_found", "not found")
|
|
rec, _grant, _managed = deps.plugin_store.resolve_active_for_caller(OWNER_UID, pid)
|
|
if not rec or CAP not in ((rec.get("manifest") or {}).get("capabilities") or []):
|
|
return _refused(404, "not_found", f"no relay for {pid!r}")
|
|
if name not in allowed:
|
|
return _refused(403, "relay_auth", "this token doesn't open that route")
|
|
route = await run_in_threadpool(st.route, pid, name)
|
|
if not route:
|
|
return _refused(404, "not_found", f"no relay route {name!r}")
|
|
if path and ".." in path.split("/"):
|
|
return _refused(400, "bad_request", "bad path")
|
|
|
|
mine = route.get("headers") or {}
|
|
ours = {k.lower() for k in mine}
|
|
headers = {k: v for k, v in request.headers.items()
|
|
if k.lower() in FORWARD_REQUEST and k.lower() not in ours}
|
|
headers.update(mine)
|
|
headers["Accept-Encoding"] = "identity"
|
|
content: Any = None
|
|
if request.method == "POST":
|
|
try:
|
|
declared = int(request.headers.get("content-length") or -1)
|
|
except ValueError:
|
|
declared = -1
|
|
if declared > MAX_BODY:
|
|
return _refused(413, "too_large", "request body too large")
|
|
if declared >= 0:
|
|
content = await request.body()
|
|
else:
|
|
async def _limited(it):
|
|
total = 0
|
|
async for chunk in it:
|
|
total += len(chunk)
|
|
if total > MAX_BODY:
|
|
raise _TooLarge()
|
|
yield chunk
|
|
content = _limited(request.stream())
|
|
url = upstream_url(str(route["upstream"]), path, request.url.query)
|
|
client = _http()
|
|
try:
|
|
req = client.build_request(request.method, url, headers=headers, content=content)
|
|
resp = await asyncio.wait_for(client.send(req, stream=True), HEADERS_WAIT_S)
|
|
except _TooLarge:
|
|
return _refused(413, "too_large", "request body too large")
|
|
except (httpx.TimeoutException, asyncio.TimeoutError):
|
|
await run_in_threadpool(st.used, pid, name, tid, 504)
|
|
return _refused(504, "relay_upstream", "the upstream didn't answer in time")
|
|
except httpx.HTTPError as e:
|
|
await run_in_threadpool(st.used, pid, name, tid, 502)
|
|
return _refused(502, "relay_upstream", f"the upstream is unreachable ({type(e).__name__})")
|
|
await run_in_threadpool(st.used, pid, name, tid, resp.status_code)
|
|
if resp.status_code in (401, 403):
|
|
await resp.aclose()
|
|
return JSONResponse(dict(UNAUTHORIZED), status_code=403)
|
|
out_headers = {k: v for k, v in resp.headers.items() if k.lower() in FORWARD_RESPONSE}
|
|
ctype = (resp.headers.get("content-type") or "").lower()
|
|
stream = ctype.startswith("text/event-stream")
|
|
if stream:
|
|
out_headers["X-Accel-Buffering"] = "no"
|
|
if "cache-control" not in {k.lower() for k in out_headers}:
|
|
out_headers["Cache-Control"] = "no-cache"
|
|
return StreamingResponse(_iter(resp, stream), status_code=resp.status_code, headers=out_headers)
|
|
|
|
|
|
@router.api_route("/proxy/tools/relay/{pid}/{name}", methods=["GET", "POST", "DELETE"])
|
|
async def relay_root(pid: str, name: str, request: Request):
|
|
return await _relay(request, pid, name, "")
|
|
|
|
|
|
@router.api_route("/proxy/tools/relay/{pid}/{name}/{path:path}", methods=["GET", "POST", "DELETE"])
|
|
async def relay_path(pid: str, name: str, path: str, request: Request):
|
|
return await _relay(request, pid, name, path)
|