claude-proxy / src /free_claude_code /api /admin_security.py
dheraingoud's picture
sync: upstream 9194f15 + custom addons (KeyRotator, RotatingChatTransport, sol/terra/luna, ScannerTrap, health, Py3.12 compat)
e99df76
Raw History Blame Contribute Delete
2.01 kB
from __future__ import annotations
"""Shared local-only security boundary for Admin product surfaces."""
import ipaddress
from urllib.parse import urlsplit
from fastapi import HTTPException, Request
def _is_loopback_host(host: str | None) -> bool:
if host is None:
return False
normalized = host.strip().strip("[]").lower()
if normalized == "localhost":
return True
try:
return ipaddress.ip_address(normalized).is_loopback
except ValueError:
return False
def _origin_is_local(origin: str | None) -> bool:
if not origin:
return True
try:
parsed = urlsplit(origin)
_ = parsed.port
except ValueError:
return False
return (
parsed.scheme in {"http", "https"}
and parsed.username is None
and parsed.password is None
and not parsed.path
and not parsed.query
and not parsed.fragment
and _is_loopback_host(parsed.hostname)
)
def _authority_is_local(authority: str | None) -> bool:
if not authority:
return False
try:
parsed = urlsplit(f"//{authority}")
_ = parsed.port
except ValueError:
return False
return (
parsed.username is None
and parsed.password is None
and not parsed.path
and not parsed.query
and not parsed.fragment
and _is_loopback_host(parsed.hostname)
)
def require_loopback_admin(request: Request) -> None:
"""Allow Admin access only from the local machine."""
client_host = request.client.host if request.client else None
if not _is_loopback_host(client_host):
raise HTTPException(status_code=403, detail="Admin UI is local-only")
if not _authority_is_local(request.headers.get("host")):
raise HTTPException(status_code=403, detail="Admin UI is local-only")
if not _origin_is_local(request.headers.get("origin")):
raise HTTPException(status_code=403, detail="Admin UI is local-only")