Spaces:
Running
Running
File size: 2,007 Bytes
9f6a4bd e99df76 691dc7c 8e438ab | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | 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")
|