The core speaks English only; every other language is a kind: "translation" plugin
(translation-<lang>; the French one is translation-fr in ai-agent-plugins, seeded once at start).
- plugins: kind translation (typed_manifest.parse_translation: lang, name, englishName, flag,
locale, promptLine, ui/backend JSON dictionaries — strict, operator-only, in the fingerprint);
a top-level "languages" field on any plugin (default ["en"]) shown on its page; seeding takes
translation-*; plugins/translations.py reads the enabled ones (first by id wins a code).
- core/i18n: tr / langs / localized / clean_pref / effective_lang read the installed
translations; a pick whose translation is gone reads English and is kept; browserLang records
any base code. core/i18n_fr.py and FRENCH_LINE are gone (language_line = the plugin's promptLine).
- The owner picks a language too (users.json ownerLang, PUT /api/me {lang}; English by default).
- Public GET /api/i18n/languages and /api/i18n/{lang} (ETag/304), guest host and sign-in included.
- Coverage: backend/core/i18n_keys/{ui,backend}.json (kept by the two i18n tests,
UPDATE_I18N_KEYS=1); a translation's page shows translated / missing / stale / placeholder
mismatches.
- Frontend: frontend/src/i18n/fr removed; the dictionary comes from the hub, cached in
localStorage and revalidated in the background (first boot in a language waits <= 4 s, any
failure is English); Lang is a string; number/currency style from the translation's locale;
LanguageSelect lists English + installed translations (hidden when none); Settings → Plugins
has a Translations kind (tab, catalog filter, group) and a Translation section with the
missing-strings count; mock is English only.
- Tests: test_i18n.py rewritten on a made-up translation; i18n_testkit.speaking() for the
tests that need a second language. authz golden, openapi.json + src/generated regenerated;
docs/plugins.md (Translations), CLAUDE.md, i18n README, docs/settings.md.
Changelog
- Added: languages are plugins — Settings → Plugins → Translations; the owner can pick a language.
- Changed: French moved to the translation-fr plugin (seeded at start: nothing changes for guests).
- Removed: the core's built-in French dictionaries.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
556 lines
26 KiB
Python
556 lines
26 KiB
Python
"""The trusted-caller gate: every /api request must come from Traefik, the
|
||
docker gateway, localhost or a caller holding INTERNAL_API_TOKEN — or carry a
|
||
guest's session cookie (users/). It also decides *who* the caller is
|
||
(``request.state.caller``, a :class:`users.caller.Caller`)."""
|
||
|
||
import dataclasses
|
||
import hmac
|
||
import os
|
||
import pathlib
|
||
import socket
|
||
import threading
|
||
import time
|
||
|
||
from fastapi import FastAPI, Request
|
||
from fastapi.responses import JSONResponse
|
||
from starlette.datastructures import MutableHeaders
|
||
|
||
from core.config import MAX_UPLOAD_BYTES
|
||
from core.i18n import primary_lang, tr
|
||
from authz import routes as authz_routes
|
||
from authz.routes import PUBLIC
|
||
from users.caller import (GUEST_HOSTS, OWNER, OWNER_NAME, SESSION_COOKIE, guest_from_record,
|
||
on_guest_surface, on_owner_surface, request_host)
|
||
from users.cli import (AS_SESSION_HEADER, GUEST_VIEW_URL, VIEW_URL_HEADER,
|
||
Refused, session_caller)
|
||
from mcpserver.caller import AS_USER_HEADER as MCP_AS_USER_HEADER, mcp_caller
|
||
from workers import bound as worker_bound
|
||
|
||
# ── trusted-caller gate ──────────────────────────────────────────────────────
|
||
# The backend has no auth of its own: the browser reaches it through Traefik
|
||
# (behind Authelia) and host tooling through the 127.0.0.1-published port. But
|
||
# the container also sits on the shared `main` docker network, where any other
|
||
# container could hit it directly — and a PUT into `.claude/` (hooks) or a
|
||
# /api/spawn is host-level code execution. So every /api request must come from
|
||
# a trusted peer: Traefik (the Authelia-guarded edge), the docker gateway (how
|
||
# host-originated connections to the published port appear), localhost, or a
|
||
# caller presenting the shared INTERNAL_API_TOKEN. Only /api/health stays open
|
||
# (deploy probes). Static assets are public-shell only, so they stay open too.
|
||
INTERNAL_API_TOKEN = os.environ.get("INTERNAL_API_TOKEN", "")
|
||
# A read-ONLY API key: a caller presenting it (X-API-Key) may hit **safe**
|
||
# (GET/HEAD/OPTIONS) /api/* routes only — every mutating method is refused. This
|
||
# is what the desk phone holds to fetch unread notifications: it must never be
|
||
# able to spawn a session or PUT into .claude/ (that's host-level code exec).
|
||
# Comma-separated to allow more than one key. Empty ⇒ feature off.
|
||
READONLY_API_KEYS = frozenset(
|
||
k.strip() for k in os.environ.get("READONLY_API_KEY", "").split(",")
|
||
if k.strip())
|
||
# Prometheus' scrape credential (telemetry/routes.py): ``Authorization:
|
||
# Bearer <METRICS_TOKEN>`` reads ``GET /api/metrics`` and nothing else, from
|
||
# any address — the logs stack scrapes over the docker network. Comma-separated;
|
||
# empty ⇒ only the owner's own callers reach the metrics.
|
||
METRICS_TOKENS = frozenset(
|
||
k.strip() for k in os.environ.get("METRICS_TOKEN", "").split(",") if k.strip())
|
||
# Methods a read-only key is allowed to use.
|
||
_SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
|
||
# The owner through a read-only credential (authz/scopes.py): the desk phone's
|
||
# key reads its unread notifications and nothing else; the READONLY_USERS bot
|
||
# reads what the Admin role reads, minus people, security and the machine.
|
||
OWNER_PHONE = dataclasses.replace(OWNER, readonly=True).narrowed("phone")
|
||
OWNER_BOT = dataclasses.replace(OWNER, readonly=True).narrowed("bot")
|
||
OWNER_METRICS = dataclasses.replace(OWNER, readonly=True).narrowed("metrics")
|
||
|
||
|
||
def _names(var: str) -> frozenset[str]:
|
||
return frozenset(n.strip().lower() for n in os.environ.get(var, "").split(",")
|
||
if n.strip())
|
||
|
||
|
||
# Through Traefik the owner is whoever Authelia vouched for (``Remote-User``).
|
||
# Authelia has more than one account, though: the password-only ``claude``
|
||
# bot the skills log in with is allowed on every ``*.lab`` host, which made it
|
||
# the owner here without a second factor. So the deployment names who is who:
|
||
# ``OWNER_USERS`` are the owner, ``READONLY_USERS`` may only read (safe
|
||
# methods, like a read-only API key), anyone else Authelia lets through is
|
||
# refused. Both empty ⇒ any Authelia user is the owner (standalone installs,
|
||
# and what this was before 2026-11-15).
|
||
OWNER_USERS = _names("OWNER_USERS")
|
||
READONLY_USERS = _names("READONLY_USERS")
|
||
# What an anonymous caller may send: a sign-in body is a few hundred bytes.
|
||
ANON_BODY_MAX = 64 * 1024
|
||
# …and a guest: JSON of a few MB at most (a prompt, a ui-state value), an
|
||
# upload on its one route. Declared, so nothing is read before it is refused —
|
||
# the handlers' own caps only bound what is *kept*.
|
||
GUEST_BODY_MAX = 4 * 1024 * 1024
|
||
GUEST_UPLOAD_MAX = 10 * MAX_UPLOAD_BYTES # a batch of attachments, 50 MB each
|
||
TRAEFIK_HOST = os.environ.get("TRAEFIK_HOST", "traefik")
|
||
_TRUSTED_TTL_S = 30.0
|
||
_trusted_lock = threading.Lock()
|
||
_trusted_cache: tuple[float, frozenset[str], frozenset[str]] = (
|
||
0.0, frozenset(), frozenset())
|
||
_trusted_refreshing = False
|
||
|
||
|
||
def _default_gateway_ips() -> set[str]:
|
||
"""The container's default-gateway IP(s) (/proc/net/route, IPv4)."""
|
||
ips: set[str] = set()
|
||
try:
|
||
for line in pathlib.Path("/proc/net/route").read_text().splitlines()[1:]:
|
||
f = line.split()
|
||
if len(f) >= 3 and f[1] == "00000000": # default route
|
||
ips.add(socket.inet_ntoa(bytes.fromhex(f[2])[::-1]))
|
||
except (OSError, ValueError):
|
||
pass
|
||
return ips
|
||
|
||
|
||
def _compute_resolved() -> tuple[frozenset[str], frozenset[str]]:
|
||
global _trusted_cache
|
||
edge_ips: set[str] = set()
|
||
try:
|
||
for info in socket.getaddrinfo(TRAEFIK_HOST, None):
|
||
edge_ips.add(info[4][0])
|
||
except OSError:
|
||
pass
|
||
out = frozenset({"127.0.0.1", "::1"} | _default_gateway_ips() | edge_ips)
|
||
edge = frozenset(edge_ips)
|
||
with _trusted_lock:
|
||
_trusted_cache = (time.monotonic(), out, edge)
|
||
return out, edge
|
||
|
||
|
||
def _bg_refresh_resolved() -> None:
|
||
global _trusted_refreshing
|
||
try:
|
||
_compute_resolved()
|
||
finally:
|
||
with _trusted_lock:
|
||
_trusted_refreshing = False
|
||
|
||
|
||
def _trusted_ips() -> frozenset[str]:
|
||
"""Gateway + Traefik IPs, re-resolved at most every _TRUSTED_TTL_S."""
|
||
return _resolved()[0]
|
||
|
||
|
||
def _resolved() -> tuple[frozenset[str], frozenset[str]]:
|
||
"""(every trusted IP, Traefik's alone), re-resolved at most every
|
||
_TRUSTED_TTL_S. After the initial warm load, TTL expiry refreshes in a
|
||
background daemon thread and returns the previous trusted set immediately
|
||
so the asyncio event loop never blocks on DNS or /proc/net/route."""
|
||
global _trusted_refreshing
|
||
now = time.monotonic()
|
||
with _trusted_lock:
|
||
ts, ips, edge = _trusted_cache
|
||
if ips:
|
||
if now - ts < _TRUSTED_TTL_S:
|
||
return ips, edge
|
||
if not _trusted_refreshing:
|
||
_trusted_refreshing = True
|
||
threading.Thread(target=_bg_refresh_resolved, daemon=True,
|
||
name="auth-dns-refresh").start()
|
||
return ips, edge
|
||
return _compute_resolved()
|
||
|
||
|
||
def via_edge(request: Request) -> bool:
|
||
"""Did this request come through Traefik — a browser, as opposed to a
|
||
host-side CLI (the docker gateway / localhost) or an internal-token peer?"""
|
||
client = request.client.host if request.client else ""
|
||
return client in _resolved()[1]
|
||
|
||
|
||
def _anon_lang(request: Request) -> str:
|
||
"""Nobody signed in yet: the browser's language."""
|
||
return primary_lang(request.headers.get("accept-language")) or "en"
|
||
|
||
|
||
def _guests_locked(lang: str = "en") -> JSONResponse:
|
||
"""Settings → Security → *Lock guests* is on."""
|
||
return JSONResponse({"detail": {"message": tr(lang, "guest access is paused for now"),
|
||
"kind": "guests_locked"}}, status_code=403)
|
||
|
||
|
||
def _authelia_user(request: Request) -> str:
|
||
"""Who Authelia's forward-auth signed in (``Remote-User``), else ''. Only
|
||
meaningful on a request from Traefik — see the gate."""
|
||
return (request.headers.get("remote-user") or "").strip()
|
||
|
||
|
||
def _same_origin(request: Request) -> bool:
|
||
"""A browser's mutating request must come from this very host. The
|
||
session cookie is SameSite=Lax already; this closes the rest (a sibling
|
||
subdomain, an old browser). No Origin ⇒ not a browser ⇒ nothing to check."""
|
||
origin = request.headers.get("origin")
|
||
if not origin:
|
||
return True
|
||
host = origin.split("://", 1)[-1].split("/", 1)[0].split(":")[0]
|
||
return host.rstrip(".").lower() == request_host(request)
|
||
|
||
|
||
def cross_site(request: Request) -> bool:
|
||
"""Is this a browser's request from another origin? Every caller's
|
||
state-changing request is refused when it is — the owner's too: Authelia's
|
||
cookie is ``Domain=lab.gabvdl.xyz; SameSite=Lax`` and every
|
||
``*.gabvdl.xyz`` page (a guest's site) is same-*site* with the admin host,
|
||
so the browser sends it on a cross-origin POST, and a body with no
|
||
Content-Type needs no preflight. Until 2026-11-15 such a page could
|
||
``POST /api/spawn`` as the owner. A browser always says where a POST comes
|
||
from (``Origin``; ``Sec-Fetch-Site`` on current ones); the CLI, hooks and
|
||
Home Assistant send neither and are not concerned."""
|
||
site = (request.headers.get("sec-fetch-site") or "").strip().lower()
|
||
if site and site not in ("same-origin", "none"):
|
||
return True
|
||
return not _same_origin(request)
|
||
|
||
|
||
def edge_role(request: Request) -> str | None:
|
||
"""What a request from Traefik is, by its Authelia user: ``"owner"``,
|
||
``"readonly"``, or None (no user, or one this deployment doesn't name)."""
|
||
user = _authelia_user(request).lower()
|
||
if not user:
|
||
return None
|
||
if user in READONLY_USERS:
|
||
return "readonly"
|
||
if OWNER_USERS and user not in OWNER_USERS:
|
||
return None
|
||
return "owner"
|
||
|
||
|
||
def _token_ok(tok: str) -> bool:
|
||
return bool(INTERNAL_API_TOKEN) and bool(tok) and hmac.compare_digest(
|
||
tok.encode(), INTERNAL_API_TOKEN.encode())
|
||
|
||
|
||
def _metrics_token(tok: str) -> bool:
|
||
return bool(tok) and any(hmac.compare_digest(tok.encode(), k.encode())
|
||
for k in METRICS_TOKENS)
|
||
|
||
|
||
def host_token(request: Request) -> bool:
|
||
"""Does the request carry the host token (``INTERNAL_API_TOKEN``), as
|
||
``X-Internal-Auth`` or ``Authorization: Bearer``?"""
|
||
if _token_ok(request.headers.get("x-internal-auth", "")):
|
||
return True
|
||
auth = request.headers.get("authorization", "")
|
||
return auth[:7].lower() == "bearer " and _token_ok(auth[7:].strip())
|
||
|
||
|
||
def _refuse(request: Request, caller, perm: str | None, template: str | None,
|
||
message, status: int = 403, log: bool = True) -> JSONResponse:
|
||
"""A permission refusal: the Security log's ``perm_denied`` line (once
|
||
per caller × route per quiet window), then the answer."""
|
||
if log:
|
||
from security.service import perm_denied
|
||
perm_denied(request.app.state.ai, request, caller, perm, template)
|
||
return JSONResponse({"detail": message}, status_code=status)
|
||
|
||
|
||
def _refuse_cross_site(request: Request) -> JSONResponse:
|
||
from security.service import cross_site_refused
|
||
cross_site_refused(request.app.state.ai, request)
|
||
return JSONResponse({"detail": "cross-site request refused"}, status_code=403)
|
||
|
||
|
||
def _body_len(request: Request) -> int | None:
|
||
"""The declared body size; None when it isn't declared."""
|
||
try:
|
||
return int(request.headers.get("content-length") or "")
|
||
except ValueError:
|
||
return None
|
||
|
||
|
||
def _oversized(request: Request, cap: int) -> bool:
|
||
"""A body past ``cap``, or one of undeclared size (chunked) — refused
|
||
before a byte is read. No Content-Length and no Transfer-Encoding is no
|
||
body at all (a DELETE, a bare POST)."""
|
||
if "transfer-encoding" in request.headers:
|
||
return True
|
||
return (_body_len(request) or 0) > cap
|
||
|
||
|
||
def _guest_session(request: Request):
|
||
"""The guest a valid session cookie belongs to, else None."""
|
||
token = request.cookies.get(SESSION_COOKIE)
|
||
if not token:
|
||
return None
|
||
deps = request.app.state.ai
|
||
rec = deps.auth.session(token)
|
||
if rec and GUEST_HOSTS and not rec.get("imp") and not on_guest_surface(request):
|
||
# Guests sign in on the guest host only; anywhere else the one guest
|
||
# session that belongs is the owner's impersonation. A guest's site on
|
||
# *.gabvdl.xyz can plant a Domain=.gabvdl.xyz cookie, which would
|
||
# otherwise turn the owner's admin browser into that guest.
|
||
return None
|
||
u = deps.users.active(rec["user"]) if rec and rec.get("user") else None
|
||
if not u:
|
||
return None
|
||
guest = guest_from_record(u, request.headers.get("accept-language"))
|
||
# The owner impersonating this guest: the guest in every respect, but
|
||
# /api/me says so (the PWA's "back to admin" bar).
|
||
return dataclasses.replace(guest, impersonator=rec["imp"]) if rec.get("imp") else guest
|
||
|
||
|
||
def remote_session(request: Request) -> dict | None:
|
||
"""The owner's live session on the internet address (``OWNER_HOSTS``,
|
||
remoteaccess/): the cookie's, unless *Internet access* is switched off."""
|
||
deps = request.app.state.ai
|
||
if deps.security_state.remote_locked():
|
||
return None
|
||
from remoteaccess.sessions import COOKIE
|
||
return deps.owner_sessions.check(request.cookies.get(COOKIE, ""))
|
||
|
||
|
||
def _remote_refused(request: Request) -> JSONResponse:
|
||
"""Nobody is signed in on the internet address: the login page (or, with
|
||
*Internet access* off, why it can't sign anyone in)."""
|
||
lang = _anon_lang(request)
|
||
if request.app.state.ai.security_state.remote_locked():
|
||
return JSONResponse({"detail": {"message": tr(lang, "internet access is switched off"),
|
||
"kind": "remote_locked"}}, status_code=403)
|
||
return JSONResponse({"detail": {"message": tr(lang, "login required"),
|
||
"kind": "login_required"}}, status_code=401)
|
||
|
||
|
||
def _evaluate_gate(request: Request, path: str) -> tuple[JSONResponse | None, str | None]:
|
||
"""Decide whether ``request`` passes the gate, setting ``request.state.caller``.
|
||
|
||
Two steps: *who* is calling (a guest's session, the edge's Authelia user,
|
||
a read-only key, a host caller and the narrower identity it asks for),
|
||
then *may they*: the permission ``authz/routes.py`` says the route needs,
|
||
against the caller's (``Caller.allows``) — one check for every kind.
|
||
|
||
Returns ``(error_response, view_url_header)``. When ``error_response`` is
|
||
not None the request is refused immediately; otherwise it continues to the
|
||
app (adding ``VIEW_URL_HEADER`` when ``view_url_header`` is set)."""
|
||
unsafe = request.method not in _SAFE_METHODS
|
||
if unsafe and cross_site(request):
|
||
return _refuse_cross_site(request), None
|
||
perm, template = authz_routes.matcher(request.app).lookup(request.method, path)
|
||
|
||
# The owner's internet address (OWNER_HOSTS): the owner's own session
|
||
# cookie is the one credential there — no Authelia in front, so neither
|
||
# Remote-User, nor the host token, nor where the request came from makes
|
||
# anyone the owner. Without one, only the sign-in answers.
|
||
owner_surface = on_owner_surface(request)
|
||
if owner_surface and remote_session(request) is None:
|
||
if perm == PUBLIC:
|
||
if unsafe and _oversized(request, ANON_BODY_MAX):
|
||
return JSONResponse({"detail": "request too large"}, status_code=413), None
|
||
request.state.caller = None
|
||
return None, None
|
||
return _remote_refused(request), None
|
||
|
||
# A guest's session (the built-in login, users/) decides the request
|
||
# outright, wherever it comes from: their permissions, and handlers then
|
||
# filter by conversation and project. (On the owner's internet address the
|
||
# only one left is the owner's impersonation — see _guest_session.)
|
||
guest = _guest_session(request)
|
||
if guest is not None:
|
||
if guest.impersonator is None and request.app.state.ai.security_state.guests_locked():
|
||
return _guests_locked(guest.lang), None
|
||
if not guest.allows(perm, request.method):
|
||
# what their role lacks, named — the PWA shows the message as is
|
||
from authz.catalog import BY_ID
|
||
p = BY_ID.get(perm or "")
|
||
if not p or p.tier != "person":
|
||
# the administration was never theirs: the app's own probes of
|
||
# it aren't news — a machine-level route, or none at all, is
|
||
return _refuse(request, guest, perm, template,
|
||
tr(guest.lang, "not available to guests"),
|
||
log=not p or p.tier == "host"), None
|
||
msg = tr(guest.lang, "your role doesn't include “{what}” — ask {owner}",
|
||
what=p.label, owner=OWNER_NAME)
|
||
return _refuse(request, guest, perm, template,
|
||
{"message": msg, "kind": "perm_denied", "perm": perm}), None
|
||
if unsafe and _oversized(
|
||
request, GUEST_UPLOAD_MAX if path == "/api/upload" else GUEST_BODY_MAX):
|
||
return JSONResponse({"detail": "request too large"}, status_code=413), None
|
||
request.state.caller = guest
|
||
return None, None
|
||
|
||
if owner_surface:
|
||
# A browser's JSON carries its Content-Type (as on the admin host below).
|
||
if unsafe and (_body_len(request) or 0) > 0 \
|
||
and not request.headers.get("content-type"):
|
||
return JSONResponse({"detail": "a request body needs a Content-Type"},
|
||
status_code=415), None
|
||
request.state.caller = OWNER
|
||
return None, None
|
||
|
||
# The guest surface (GUEST_HOSTS): nothing reached through it is ever the
|
||
# owner, even though it arrives from Traefik — without a session, the only
|
||
# thing to do there is log in. Through Traefik, the owner is also only
|
||
# whoever Authelia vouched for: the admin router's forward-auth sets
|
||
# Remote-User (over anything a client sent), every other router strips it.
|
||
# So a request from Traefik without one is anonymous whatever its Host
|
||
# says — `claude.lab.gabvdl.xyz.` (trailing dot) once matched the guest
|
||
# router but not GUEST_HOSTS and came out the owner, from the internet.
|
||
edge = via_edge(request)
|
||
role = edge_role(request) if edge else None
|
||
if on_guest_surface(request) or (edge and role is None):
|
||
if not on_guest_surface(request):
|
||
# What the owner was before 2026-11-01: a tripwire now.
|
||
from security.service import edge_anonymous
|
||
edge_anonymous(request.app.state.ai, request)
|
||
if perm == PUBLIC:
|
||
if unsafe and _oversized(request, ANON_BODY_MAX):
|
||
return JSONResponse({"detail": "request too large"}, status_code=413), None
|
||
if request.app.state.ai.security_state.guests_locked() \
|
||
and path != "/api/auth/logout" and not path.startswith("/api/i18n/"):
|
||
return _guests_locked(_anon_lang(request)), None
|
||
request.state.caller = None
|
||
return None, None
|
||
return JSONResponse({"detail": {"message": tr(_anon_lang(request), "login required"),
|
||
"kind": "login_required"}},
|
||
status_code=401), None
|
||
|
||
# A read-only API key downgrades the caller to the phone's scope, whatever
|
||
# the source IP — the phone reaches us over a "trusted" host loopback but
|
||
# may only read its unread notifications, never spawn/mutate. So this
|
||
# check comes before the IP one and, when the key matches, it decides the
|
||
# request outright (a read-only key on a POST is refused, not silently
|
||
# upgraded by a trusted IP).
|
||
if METRICS_TOKENS:
|
||
bearer = request.headers.get("authorization", "")
|
||
if bearer[:7].lower() == "bearer " and _metrics_token(bearer[7:].strip()):
|
||
if request.method not in _SAFE_METHODS or not OWNER_METRICS.allows(
|
||
perm, request.method):
|
||
return _refuse(request, OWNER_METRICS, perm, template,
|
||
"metrics token: not allowed here"), None
|
||
request.state.caller = OWNER_METRICS
|
||
return None, None
|
||
|
||
api_key = request.headers.get("x-api-key", "")
|
||
if api_key and api_key in READONLY_API_KEYS:
|
||
if request.method not in _SAFE_METHODS:
|
||
return JSONResponse(
|
||
{"detail": "read-only api key: method not allowed"},
|
||
status_code=403), None
|
||
if not OWNER_PHONE.allows(perm, request.method):
|
||
return _refuse(request, OWNER_PHONE, perm, template,
|
||
"read-only api key: not allowed here"), None
|
||
request.state.caller = OWNER_PHONE
|
||
return None, None
|
||
|
||
client = request.client.host if request.client else ""
|
||
tokened = host_token(request)
|
||
if client not in _trusted_ips():
|
||
if not tokened:
|
||
return JSONResponse({"detail": "forbidden"}, status_code=403), None
|
||
if edge:
|
||
# An Authelia account that may look but not touch (READONLY_USERS).
|
||
if role == "readonly":
|
||
if unsafe:
|
||
return JSONResponse({"detail": "read-only account: method not allowed"},
|
||
status_code=403), None
|
||
if not OWNER_BOT.allows(perm, request.method):
|
||
return _refuse(request, OWNER_BOT, perm, template,
|
||
"read-only account: not allowed here"), None
|
||
request.state.caller = OWNER_BOT
|
||
return None, None
|
||
# A browser's JSON carries its Content-Type. A body without one is
|
||
# what a cross-origin page can send without a preflight, and FastAPI
|
||
# would read it as JSON — refused here whatever its Origin says.
|
||
if unsafe and (_body_len(request) or 0) > 0 \
|
||
and not request.headers.get("content-type"):
|
||
return JSONResponse({"detail": "a request body needs a Content-Type"},
|
||
status_code=415), None
|
||
elif not tokened:
|
||
# Loopback / the docker gateway without the host token: still the
|
||
# owner this round, but written down (docs/permissions.md → "Loopback
|
||
# is not a credential"), so the callers left can be found before it
|
||
# is refused.
|
||
from security.service import loopback_tokenless
|
||
loopback_tokenless(request.app.state.ai, request, template)
|
||
# The `ai-agent` CLI the guard brokers for a guest's run (users/cli.py):
|
||
# the guest that run is for — a downgrade of a caller already trusted.
|
||
as_sid = request.headers.get(AS_SESSION_HEADER)
|
||
if as_sid is not None:
|
||
try:
|
||
caller = session_caller(request.app.state.ai, as_sid)
|
||
except Refused as e:
|
||
return JSONResponse({"detail": e.detail}, status_code=e.status), None
|
||
if not caller.is_owner:
|
||
caller = caller.narrowed("cli")
|
||
if not caller.allows(perm, request.method):
|
||
return _refuse(request, caller, perm, template,
|
||
tr(caller.lang, "not available to the ai-agent CLI")), None
|
||
request.state.caller = caller
|
||
view_url = GUEST_VIEW_URL if (not caller.is_owner and GUEST_VIEW_URL) else None
|
||
return None, view_url
|
||
# An MCP connection bound to one of the owner's workers
|
||
# (workers/bound.py): the owner narrowed to that worker's profile, its
|
||
# mode's scope, runs on that worker only — a downgrade too.
|
||
as_worker = request.headers.get(worker_bound.AS_WORKER_HEADER)
|
||
if as_worker is not None:
|
||
try:
|
||
caller = worker_bound.worker_caller(
|
||
request.app.state.ai, as_worker,
|
||
request.headers.get(worker_bound.AS_WORKER_MODE_HEADER))
|
||
except worker_bound.Refused as e:
|
||
return JSONResponse({"detail": e.detail}, status_code=e.status), None
|
||
if not caller.allows(perm, request.method):
|
||
return _refuse(request, caller, perm, template,
|
||
"not available to a connection bound to a worker"), None
|
||
request.state.caller = caller
|
||
return None, None
|
||
# A guest's MCP connection (mcpserver/caller.py): the tools call this
|
||
# API over loopback with the guest the connection is for — a downgrade
|
||
# too, to the CLI's scope.
|
||
as_user = request.headers.get(MCP_AS_USER_HEADER)
|
||
if as_user is not None:
|
||
try:
|
||
caller = mcp_caller(request.app.state.ai, as_user)
|
||
except Refused as e:
|
||
return JSONResponse({"detail": e.detail}, status_code=e.status), None
|
||
if not caller.is_owner:
|
||
caller = caller.narrowed("cli")
|
||
if not caller.allows(perm, request.method):
|
||
return _refuse(request, caller, perm, template,
|
||
tr(caller.lang, "not available to AI apps")), None
|
||
request.state.caller = caller
|
||
return None, None
|
||
request.state.caller = OWNER
|
||
return None, None
|
||
|
||
|
||
class TrustedCallerGate:
|
||
"""Pure ASGI middleware implementing the trusted-caller gate (no
|
||
BaseHTTPMiddleware task/stream wrapper per request or SSE connection)."""
|
||
|
||
def __init__(self, app):
|
||
self.app = app
|
||
|
||
async def __call__(self, scope, receive, send):
|
||
if scope["type"] != "http":
|
||
await self.app(scope, receive, send)
|
||
return
|
||
# The path the router will match — not ``request.url.path``, which
|
||
# Starlette rebuilds from the Host header: ``Host: x?`` made it empty, so a
|
||
# container on the docker network walked past this gate into any route
|
||
# that relies on it alone (found 2026-11-15).
|
||
path = scope.get("path") or ""
|
||
if not path.startswith("/api/") or path == "/api/health":
|
||
await self.app(scope, receive, send)
|
||
return
|
||
request = Request(scope, receive)
|
||
err, view_url = _evaluate_gate(request, path)
|
||
if err is not None:
|
||
await err(scope, receive, send)
|
||
return
|
||
if view_url:
|
||
async def send_with_view_url(message):
|
||
if message["type"] == "http.response.start":
|
||
headers = MutableHeaders(scope=message)
|
||
headers[VIEW_URL_HEADER] = view_url
|
||
await send(message)
|
||
await self.app(scope, receive, send_with_view_url)
|
||
return
|
||
await self.app(scope, receive, send)
|
||
|
||
|
||
def install(app: FastAPI) -> None:
|
||
"""Register the gate as the app's pure-ASGI HTTP middleware."""
|
||
app.add_middleware(TrustedCallerGate)
|