Files
gabrielvidalandClaude Opus 5.5 cb0ae01121 feat(plugins): proxy.wake wakes a Dynamic service before an internal call
An internal plugin proxy can name a services-manager service to wake:
"proxy": {"internal": true, "wake": {"service": "music-dl", "holdMinutes": 15}}.
A stopped container has no Docker DNS entry, so a call on its name fails
with httpx.ConnectError before it reaches anything.

- manifest: proxy.wake = {service (^[a-z0-9][a-z0-9_.-]{0,62}$),
  holdMinutes (int 1..240, default 15)}, refused without internal: true;
  out["proxy"]["wake"] is None when absent. In the approval fingerprint only
  when declared (all 42 hub plugins keep theirs); the capability line says
  which service it wakes.
- proxy: forward() / open_stream() (and so run_inspect) first POST
  $SERVICES_MANAGER_URL/api/services/<svc>/wake?hold=<min>&wait=60&trigger=cli
  (default http://services-manager:8080, 70 s timeout); one wake per service
  per 60 s, a 2xx answer cached, concurrent calls share one wake (an
  asyncio.Lock per service and loop). A ConnectError forces a wake past the
  cache and retries once (a streamed upload only if none of its body was
  read). services-manager down or refusing is logged, never fails the call.
- tests: backend/test_plugin_proxy_wake.py (12 cases).
- docs/plugins.md: the proxy.wake section + the tool proxy line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 18:23:13 +01:00

620 lines
23 KiB
Python

"""Generic allowlisted outbound HTTP proxy for live plugins (v1).
* Enforces ``proxy.allow`` (method + regex path) and ``proxy.denyParams``.
* Enforces ``plugins.egress.check_public_url`` (including redirect hops) unless
``proxy.internal`` is true AND the operator approved the plugin.
* Injects the declared user/hub secret (header, query or HTTP Basic) and
interpolates ``{{user.id}}``, ``{{user.domains}}`` and ``{{config.<k>}}`` in
static headers.
* Scrubs every secret stored for ``(uid, plugin_id)`` out of responses and
error messages before returning.
* Supports declarative ``proxy.inspect`` (including ``requireOnlyScopes`` for
read-only token enforcement, e.g. Meta Business).
* ``proxy.wake`` (internal only): asks the homelab's services-manager to wake
a Dynamic service before calling it (:func:`ensure_awake`), and once more —
then retries — when the call can't connect (a stopped container has no
Docker DNS entry).
"""
from __future__ import annotations
import asyncio
import base64
import json
import logging
import os
import re
import threading
import time
import weakref
from typing import Any
from urllib.parse import urljoin
import httpx
from plugins.egress import check_public_url
from plugins.store import OWNER_UID, PluginStore
_TMPL_RE = re.compile(r"\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}")
_DROP_REQ_HEADERS = frozenset({
"host", "authorization", "cookie", "connection", "content-length",
"transfer-encoding", "x-forwarded-for", "x-forwarded-host",
"x-forwarded-proto", "x-internal-auth", "x-api-key", "remote-user",
})
_DROP_RES_HEADERS = frozenset({
"transfer-encoding", "connection", "content-encoding", "content-length",
"set-cookie",
})
# A candidate secret checked before it is saved (Settings → a hub key's
# Replace): the plugin's test action runs with a handler token registered
# here, and that run's proxy calls use the candidate instead of the stored
# secret. In memory only, for the length of the run — never written down.
_candidates: dict[str, str] = {}
_candidates_lock = threading.Lock()
def register_candidate(token: str, value: str) -> None:
with _candidates_lock:
_candidates[token] = value
def drop_candidate(token: str) -> None:
with _candidates_lock:
_candidates.pop(token, None)
def candidate_for(token: str) -> str | None:
if not token:
return None
with _candidates_lock:
return _candidates.get(token)
log = logging.getLogger(__name__)
# ── proxy.wake: a Dynamic service of the homelab's services-manager ─────────
# A call on a stopped container's name fails before it reaches anything, so
# the proxy asks services-manager to wake it first. One wake per service per
# _WAKE_TTL seconds (it also extends the hold on an awake service, so the hold
# keeps sliding while the plugin is in use); concurrent calls share one wake.
_WAKE_TTL = 60.0
_WAKE_WAIT_S = 60
_WAKE_TIMEOUT_S = 70.0
_wake_ok_at: dict[str, float] = {}
# Locks are per event loop (an asyncio.Lock belongs to the loop it waited on).
_wake_locks: "weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, dict[str, asyncio.Lock]]" = (
weakref.WeakKeyDictionary())
def _services_manager_url() -> str:
return (os.environ.get("SERVICES_MANAGER_URL") or "http://services-manager:8080").rstrip("/")
def _wake_lock(name: str) -> asyncio.Lock:
locks = _wake_locks.setdefault(asyncio.get_running_loop(), {})
lock = locks.get(name)
if lock is None:
lock = locks[name] = asyncio.Lock()
return lock
async def ensure_awake(client: httpx.AsyncClient, wake: dict[str, Any] | None, *,
force: bool = False) -> bool:
"""Wake ``wake.service`` through services-manager (``hold`` = its
``holdMinutes``, waiting up to a minute for it to be ready). Skipped when a
wake answered 2xx in the last minute, unless ``force`` (the call couldn't
connect) — then only a wake that finished after this call asked counts.
Never raises: a services-manager that is down or refuses only gets logged,
and the proxied call goes ahead. True when a wake answered (or a recent
one stands)."""
if not wake or not wake.get("service"):
return False
name = str(wake["service"])
asked = time.monotonic()
def fresh() -> bool:
at = _wake_ok_at.get(name)
if at is None:
return False
return at >= asked if force else time.monotonic() - at < _WAKE_TTL
if fresh():
return True
async with _wake_lock(name):
if fresh():
return True
hold = int(wake.get("holdMinutes") or 15)
url = f"{_services_manager_url()}/api/services/{name}/wake"
try:
resp = await client.post(
url, params={"hold": str(hold), "wait": str(_WAKE_WAIT_S), "trigger": "cli"},
timeout=_WAKE_TIMEOUT_S,
)
except Exception as e: # noqa: BLE001 — never fail the proxied call
log.warning("proxy.wake: waking %s failed: %s", name, e)
return False
if not 200 <= resp.status_code < 300:
log.warning("proxy.wake: services-manager answered %s for %s: %s",
resp.status_code, name, resp.text[:200])
return False
_wake_ok_at[name] = time.monotonic()
try:
ready = bool(resp.json().get("ready"))
except Exception: # noqa: BLE001
ready = False
if not ready:
log.warning("proxy.wake: %s not ready after %ss", name, _WAKE_WAIT_S)
return True
class ProxyError(Exception):
def __init__(self, status: int, message: str, kind: str = "plugin_proxy"):
super().__init__(message)
self.status = status
self.message = message
self.kind = kind
def _user_domains(deps, uid: str) -> str:
if uid == OWNER_UID:
return ""
try:
from users import domains as user_domains
u = deps.users.get(uid) or {"id": uid}
bucket, domain = user_domains.address_of(u, user_domains.default_domain(deps))
return user_domains.base_of(bucket, domain)
except Exception:
return ""
def _render_template(s: str, *, uid: str, domains: str, config: dict[str, Any]) -> str:
def repl(m: re.Match) -> str:
key = m.group(1)
if key == "user.id":
return uid
if key == "user.domains":
return domains
if key == "user.tag":
return user_tag(uid)
if key.startswith("config."):
return str(config.get(key[len("config."):]) or "")
return ""
return _TMPL_RE.sub(repl, s)
def _query_ok(rule: dict[str, Any], params: dict[str, str]) -> bool:
for name, pat in (rule.get("query") or {}).items():
val = params.get(name)
if val is None:
return False
try:
if not re.fullmatch(pat, val):
return False
except re.error:
return False
return True
def match_rule(proxy_cfg: dict[str, Any], method: str, rel_path: str,
params: dict[str, str] | None = None) -> dict[str, Any] | None:
"""The first ``proxy.allow`` rule matching method + path (+ its ``query``),
or None. ``params`` = the call's query string merged with a form body."""
m = method.upper()
clean = rel_path.lstrip("/")
for rule in proxy_cfg.get("allow") or []:
if rule.get("method", "").upper() != m:
continue
try:
if not re.fullmatch(rule["path"], clean):
continue
except re.error:
continue
if rule.get("query") and not _query_ok(rule, params or {}):
continue
return rule
return None
def _path_allowed(proxy_cfg: dict[str, Any], method: str, rel_path: str) -> bool:
return match_rule(proxy_cfg, method, rel_path) is not None
def rule_handler_only(proxy_cfg: dict[str, Any], rule: dict[str, Any]) -> bool:
v = rule.get("handlerOnly")
return bool(proxy_cfg.get("handlerOnly")) if v is None else bool(v)
def user_tag(uid: str) -> str:
return "owner" if uid == OWNER_UID else f"guest-{uid}"
def _secret_for(store: PluginStore, manifest: dict[str, Any], uid: str,
key: str, *, override_secret: str | None = None) -> tuple[str | None, bool]:
return store.get_secret_for_caller(uid, manifest["id"], key, manifest,
override_secret=override_secret)
def strip_json_keys(obj: Any, keys: set[str]) -> Any:
"""Recursively drop any dict key in ``keys`` (e.g. ``access_token``)."""
if not keys:
return obj
if isinstance(obj, dict):
return {k: strip_json_keys(v, keys) for k, v in obj.items() if k not in keys}
if isinstance(obj, list):
return [strip_json_keys(v, keys) for v in obj]
return obj
def _prepare_request(
deps,
store: PluginStore,
uid: str,
rec: dict[str, Any],
*,
method: str,
rel_path: str,
query_params: list[tuple[str, str]] | None = None,
req_headers: dict[str, str] | None = None,
override_secret: str | None = None,
rule: dict[str, Any] | None = None,
trusted: bool = True,
) -> tuple[dict[str, Any], str, list[tuple[str, str]], dict[str, str], list[str], bool]:
"""``rule`` = the matched allow rule (looked up when None); ``trusted`` =
the call is the plugin's own handler or the owner — ``forcedParams`` then
don't apply."""
mf = rec.get("manifest") or {}
pr = mf.get("proxy")
if not pr:
raise ProxyError(404, "this plugin has no outbound proxy")
clean_path = (rel_path or "").lstrip("/")
if ".." in clean_path.split("/") or "\\" in clean_path:
raise ProxyError(400, "invalid proxy path")
if rule is None:
rule = match_rule(pr, method, clean_path, dict(query_params or []))
if rule is None:
raise ProxyError(403, f"plugin proxy refuses {method.upper()} /{clean_path}")
url = f"{pr['baseUrl'].rstrip('/')}/{clean_path}" if clean_path else pr["baseUrl"]
internal = bool(pr.get("internal"))
if not internal:
ok, why = check_public_url(url)
if not ok:
raise ProxyError(403, f"blocked outbound URL: {why}")
deny = set(pr.get("denyParams") or [])
params: list[tuple[str, str]] = []
for k, v in (query_params or []):
if k.lower() in deny:
raise ProxyError(403, f"query parameter '{k}' is forbidden by plugin policy")
params.append((k, v))
domains = _user_domains(deps, uid)
cfg = rec.get("config") or {}
forced = rule.get("forcedParams") or {}
if forced and not trusted:
names = {n.lower() for n in forced}
params = [(k, v) for k, v in params if k.lower() not in names]
for n, tmpl in forced.items():
params.append((n, _render_template(tmpl, uid=uid, domains=domains, config=cfg)))
headers: dict[str, str] = {}
for k, v in (req_headers or {}).items():
if k.lower() not in _DROP_REQ_HEADERS:
headers[k] = v
for k, v in (pr.get("headers") or {}).items():
headers[k] = _render_template(v, uid=uid, domains=domains, config=cfg)
secrets_to_scrub = store.all_secret_values(uid, mf["id"])
if override_secret:
secrets_to_scrub.append(override_secret)
using_own_secret = False
auth = None if rule.get("noAuth") else pr.get("auth")
if auth and auth.get("secret"):
sec_val, using_own_secret = _secret_for(store, mf, uid, auth["secret"],
override_secret=override_secret)
if not sec_val:
raise ProxyError(412, f"plugin '{mf['id']}' secret '{auth['secret']}' is not configured yet", "missing_secret")
ain = auth.get("in") or "header"
if ain == "header":
headers[auth.get("name") or "Authorization"] = f"{auth.get('prefix') or ''}{sec_val}"
elif ain == "query":
params.append((auth.get("name") or "key", sec_val))
elif ain == "basic":
raw = f"{auth.get('username') or ''}:{sec_val}".encode("utf-8")
headers["Authorization"] = "Basic " + base64.b64encode(raw).decode("ascii")
return pr, url, params, headers, secrets_to_scrub, using_own_secret
def scrub_bytes(data: bytes, secrets_list: list[str]) -> bytes:
if not data or not secrets_list:
return data
out = data
for s in secrets_list:
b = s.encode("utf-8", "ignore")
if len(b) >= 6 and b in out:
out = out.replace(b, b"***")
return out
def scrub_text(text: str, secrets_list: list[str]) -> str:
if not text or not secrets_list:
return text
out = text
for s in secrets_list:
if len(s) >= 6 and s in out:
out = out.replace(s, "***")
return out
async def forward(
client: httpx.AsyncClient,
deps,
store: PluginStore,
uid: str,
rec: dict[str, Any],
*,
method: str,
rel_path: str,
query_params: list[tuple[str, str]] | None = None,
req_headers: dict[str, str] | None = None,
body: bytes | None = None,
override_secret: str | None = None,
rule: dict[str, Any] | None = None,
trusted: bool = True,
) -> tuple[int, dict[str, str], bytes]:
"""Execute one allowlisted outbound request for ``rec`` on behalf of ``uid``."""
pr, url, params, headers, secrets_to_scrub, _ = _prepare_request(
deps, store, uid, rec,
method=method, rel_path=rel_path,
query_params=query_params, req_headers=req_headers,
override_secret=override_secret, rule=rule, trusted=trusted,
)
internal = bool(pr.get("internal"))
max_bytes = int(pr.get("maxBytes") or 20 * 1024 * 1024)
if body and len(body) > max_bytes:
raise ProxyError(413, f"request body exceeds plugin limit ({max_bytes} bytes)")
wake = pr.get("wake") if internal else None
if wake:
await ensure_awake(client, wake)
# Follow up to 3 redirects manually so every hop is egress-checked!
cur_url = url
cur_params: list[tuple[str, str]] | None = params
resp = None
retried = False
hop = 0
while hop < 4:
try:
resp = await client.request(
method.upper(), cur_url, params=cur_params,
headers=headers, content=body, follow_redirects=False,
)
except httpx.TimeoutException:
raise ProxyError(504, "upstream API timed out") from None
except httpx.ConnectError as e:
if wake and not retried:
# Stopped since the last wake (or the wake was throttled):
# wake it for real and try this hop once more.
retried = True
await ensure_awake(client, wake, force=True)
continue
msg = scrub_text(str(e), secrets_to_scrub)
raise ProxyError(502, f"upstream request failed: {msg[:200]}") from None
except httpx.HTTPError as e:
msg = scrub_text(str(e), secrets_to_scrub)
raise ProxyError(502, f"upstream request failed: {msg[:200]}") from None
if resp.status_code in (301, 302, 303, 307, 308) and resp.headers.get("location"):
nxt = urljoin(cur_url, resp.headers["location"])
if not internal:
ok, why = check_public_url(nxt)
if not ok:
raise ProxyError(403, f"redirect blocked: {why}")
cur_url = nxt
cur_params = None
hop += 1
continue
break
assert resp is not None
raw_bytes = resp.content
if len(raw_bytes) > max_bytes:
raise ProxyError(502, "upstream response exceeded plugin limit")
# Optional server-side JSON field stripping (e.g. Meta Page access_token)
strip_keys = set(pr.get("stripResponseKeys") or [])
if strip_keys and raw_bytes:
ct = (resp.headers.get("content-type") or "").lower()
stripped_head = raw_bytes.lstrip()[:1]
if "json" in ct or stripped_head in (b"{", b"["):
try:
parsed = json.loads(raw_bytes.decode("utf-8"))
cleaned = strip_json_keys(parsed, strip_keys)
raw_bytes = json.dumps(cleaned, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
except (UnicodeDecodeError, ValueError):
pass
if pr.get("scrubSecrets", True):
raw_bytes = scrub_bytes(raw_bytes, secrets_to_scrub)
out_headers = {
k: scrub_text(v, secrets_to_scrub) if pr.get("scrubSecrets", True) else v
for k, v in resp.headers.items()
if k.lower() not in _DROP_RES_HEADERS
}
return resp.status_code, out_headers, raw_bytes
class UploadTooLarge(Exception):
pass
async def limited(it: Any, max_bytes: int, *, upload: bool = False):
"""Pass an async byte iterator through, stopping past ``max_bytes``: an
upload raises :class:`UploadTooLarge` (→ 413), a download just ends (the
client sees the connection drop rather than a silently larger file)."""
total = 0
async for chunk in it:
total += len(chunk)
if total > max_bytes:
if upload:
raise UploadTooLarge()
return
yield chunk
async def open_stream(
client: httpx.AsyncClient,
deps,
store: PluginStore,
uid: str,
rec: dict[str, Any],
*,
method: str,
rel_path: str,
query_params: list[tuple[str, str]] | None = None,
req_headers: dict[str, str] | None = None,
body_iter: Any = None,
timeout: float = 900.0,
rule: dict[str, Any] | None = None,
trusted: bool = True,
) -> tuple[httpx.Response, dict[str, str], list[str], bool]:
"""Open a streaming upstream request (for large uploads/downloads like
video-extract or 3d-render). Caller must close the returned response and
iterate it through :func:`limited` (``proxy.maxBytes``)."""
pr, url, params, headers, secrets_to_scrub, _ = _prepare_request(
deps, store, uid, rec,
method=method, rel_path=rel_path,
query_params=query_params, req_headers=req_headers,
rule=rule, trusted=trusted,
)
max_bytes = int(pr.get("maxBytes") or 20 * 1024 * 1024)
try:
declared = int((req_headers or {}).get("content-length") or 0)
except ValueError:
declared = 0
if declared > max_bytes:
raise ProxyError(413, f"request body exceeds plugin limit ({max_bytes} bytes)")
if body_iter is not None:
body_iter = limited(body_iter, max_bytes, upload=True)
wake = pr.get("wake") if pr.get("internal") else None
if wake:
await ensure_awake(client, wake)
# A streamed body can be sent only once: retry after a ConnectError only
# while nothing of it has been read.
body_started = False
async def _tracked(it: Any):
nonlocal body_started
body_started = True
async for chunk in it:
yield chunk
def _build() -> httpx.Request:
return client.build_request(
method.upper(), url, params=params, headers=headers,
content=_tracked(body_iter) if (wake and body_iter is not None) else body_iter,
timeout=httpx.Timeout(30.0, read=timeout, write=timeout),
)
try:
try:
resp = await client.send(_build(), stream=True)
except httpx.ConnectError:
if not wake or body_started:
raise
await ensure_awake(client, wake, force=True)
resp = await client.send(_build(), stream=True)
except UploadTooLarge:
raise ProxyError(413, f"request body exceeds plugin limit ({max_bytes} bytes)") from None
except httpx.TimeoutException:
raise ProxyError(504, "upstream API timed out") from None
except httpx.HTTPError as e:
if isinstance(e.__cause__, UploadTooLarge) or isinstance(e.__context__, UploadTooLarge):
raise ProxyError(413, f"request body exceeds plugin limit ({max_bytes} bytes)") from None
msg = scrub_text(str(e), secrets_to_scrub)
raise ProxyError(502, f"upstream request failed: {msg[:200]}") from None
try:
out_len = int(resp.headers.get("content-length") or 0)
except ValueError:
out_len = 0
if out_len > max_bytes:
await resp.aclose()
raise ProxyError(502, "upstream response exceeded plugin limit")
scrub = bool(pr.get("scrubSecrets", True))
out_headers = {
k: scrub_text(v, secrets_to_scrub) if scrub else v
for k, v in resp.headers.items()
if k.lower() not in _DROP_RES_HEADERS
}
return resp, out_headers, secrets_to_scrub, scrub
async def run_inspect(
client: httpx.AsyncClient,
deps,
store: PluginStore,
uid: str,
rec: dict[str, Any],
*,
override_secret: str | None = None,
) -> dict[str, Any]:
"""Run ``proxy.inspect`` against upstream, verifying status 2xx and
``requireOnlyScopes`` (when declared — e.g. Meta read-only verification)."""
mf = rec.get("manifest") or {}
pr = mf.get("proxy") or {}
ins = pr.get("inspect")
if not ins:
return {"ok": True, "message": "no inspect check declared"}
q = [(str(k), str(v)) for k, v in (ins.get("params") or {}).items()]
status, _, raw = await forward(
client, deps, store, uid, rec,
method=ins.get("method") or "GET",
rel_path=ins["path"],
query_params=q,
override_secret=override_secret,
)
if not 200 <= status < 300:
snippet = raw.decode("utf-8", "replace")[:240]
raise ProxyError(400 if status in (400, 401, 403) else 502,
f"upstream rejected credentials (HTTP {status}): {snippet}", "inspect_failed")
data = None
try:
data = json.loads(raw)
except ValueError:
pass
allowed_scopes = set(ins.get("requireOnlyScopes") or [])
if allowed_scopes and isinstance(data, dict):
# Support Meta Graph's {"data":[{"permission":"...","status":"granted"}]}
# as well as flat {"scopes": [...]} or {"permissions": [...]}.
granted: set[str] = set()
if isinstance(data.get("data"), list):
for row in data["data"]:
if isinstance(row, dict) and row.get("permission") and row.get("status", "granted") == "granted":
granted.add(str(row["permission"]))
for k in ("scopes", "permissions"):
if isinstance(data.get(k), list):
granted.update(str(x) for x in data[k])
forbidden = sorted(granted - allowed_scopes)
if forbidden:
raise ProxyError(
400,
f"token carries disallowed write/extra scopes: {', '.join(forbidden)}",
"forbidden_scopes",
)
return {"ok": True, "scopes": sorted(granted)}
return {"ok": True, "status": status, "data": data}