fix: support authenticated web deployments under a reverse proxy path

This commit is contained in:
AttilaNet
2026-11-10 20:01:44 +08:00
parent 0230a933b0
commit 99aff423d8
12 changed files with 529 additions and 31 deletions
+68 -23
View File
@@ -5,6 +5,7 @@ from __future__ import annotations
from collections import OrderedDict
from contextlib import asynccontextmanager
from dataclasses import replace
from html import escape
import hashlib
import inspect
import json
@@ -20,9 +21,10 @@ from urllib.parse import urlsplit
from fastapi import FastAPI, HTTPException, Path, Query, Request
from fastapi.exceptions import RequestValidationError
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr
from starlette._utils import get_route_path
from starlette.concurrency import run_in_threadpool
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.responses import FileResponse, JSONResponse, RedirectResponse, Response
from starlette.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse, Response
from starlette.staticfiles import StaticFiles
from . import GAME_VERSION, __version__
@@ -191,6 +193,17 @@ class _Boundary:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
base_path = self.settings.base_path
path = scope["path"]
# Keep a canonical external path for Starlette's root_path handling. Both
# the boundary and router must strip exactly the same, single prefix.
preserved = base_path and (path == base_path or path.startswith(base_path + "/"))
scope = {**scope, "root_path": base_path, "app_root_path": base_path}
if base_path and (not preserved or path == "/api/health"):
scope["path"] = base_path + path
if "raw_path" in scope:
scope["raw_path"] = base_path.encode("ascii") + scope["raw_path"]
path = get_route_path(scope)
request = Request(scope)
async def deny(status, code, message):
@@ -205,7 +218,7 @@ class _Boundary:
(b"x-frame-options", b"DENY"),
(b"content-security-policy", b"default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'"),
])
if scope["path"].startswith("/api/"):
if path.startswith("/api/"):
headers.append((b"cache-control", b"no-store"))
message = {**message, "headers": headers}
await send(message)
@@ -224,7 +237,14 @@ class _Boundary:
await deny(400, "invalid_host", "请求主机不受信任")
return
is_api = scope["path"] == "/api" or scope["path"].startswith("/api/")
if base_path and path == "":
target = base_path + "/"
if scope.get("query_string"):
target += "?" + scope["query_string"].decode("latin-1")
await RedirectResponse(target, status_code=307, headers={"Cache-Control": "no-store"})(scope, receive, secure_send)
return
is_api = path == "/api" or path.startswith("/api/")
if is_api and request.method in _WRITES:
origins = request.headers.getlist("origin")
fetch_site = request.headers.get("sec-fetch-site", "")
@@ -241,7 +261,7 @@ class _Boundary:
except ValueError:
await deny(403, "invalid_origin", "禁止跨站操作,请从当前工作台发起请求")
return
if is_api and scope["path"] not in _PUBLIC_PATHS and not self.sessions.authenticated(request):
if is_api and path not in _PUBLIC_PATHS and not self.sessions.authenticated(request):
status = 401 if self.settings.credential else 403
await deny(status, "authentication_required", "请先登录管理工作台" if status == 401 else "本机免密模式只允许本机访问")
return
@@ -252,7 +272,7 @@ class _Boundary:
await deny(414, "query_too_large", "查询条件过长")
return
body_limit = self.settings.max_body_bytes
if request.method == "POST" and _YIELDS_IMPORT_PATH.fullmatch(scope["path"]):
if request.method == "POST" and _YIELDS_IMPORT_PATH.fullmatch(path):
# An 8 MiB file expands to about 10.7 MiB in base64, plus JSON metadata.
body_limit = _YIELDS_IMPORT_BODY_BYTES
lengths = request.headers.getlist("content-length")
@@ -340,6 +360,33 @@ def _no_file_paths(value: Any, depth: int = 0) -> None:
_no_file_paths(item, depth + 1)
def _page_response(path: FilePath, settings: WebConfig) -> HTMLResponse:
if not path.is_file():
raise HTTPException(503, "前端资源尚未准备完成")
content = path.read_text(encoding="utf-8")
base_path = escape(settings.base_path, quote=True)
metadata = f'<meta name="ranch-web-base-path" content="{base_path}">'
content, replaced = re.subn(
r'''<meta\b(?=[^>]*\bname\s*=\s*["']ranch-web-base-path["'])[^>]*>''',
lambda match: metadata, content, flags=re.IGNORECASE,
)
if not replaced:
content, inserted = re.subn(r"<head\b[^>]*>", lambda match: match[0] + "\n " + metadata,
content, count=1, flags=re.IGNORECASE)
if not inserted:
content = metadata + "\n" + content
if base_path:
def prefix_attribute(match):
value = match[3]
if value != base_path and not value.startswith(base_path + "/"):
value = base_path + value
return match[1] + match[2] + value + match[2]
content = re.sub(r'''(\b(?:src|href|action)\s*=\s*)(["'])(/(?!/)[^"']*)\2''',
prefix_attribute, content, flags=re.IGNORECASE)
return HTMLResponse(content, headers={"Cache-Control": "no-store"})
class _Assets(StaticFiles):
def __init__(self, *, sessions: _Sessions, **kwargs):
super().__init__(**kwargs)
@@ -354,10 +401,12 @@ class _Assets(StaticFiles):
raise HTTPException(405)
authenticated = self.sessions.authenticated(Request(scope))
if path == "login.html" and authenticated:
return RedirectResponse("/", status_code=303, headers={"Cache-Control": "no-store"})
return RedirectResponse(self.sessions.settings.base_path + "/", status_code=303, headers={"Cache-Control": "no-store"})
if path not in _PUBLIC_ASSETS and not authenticated:
return RedirectResponse("/login", status_code=303, headers={"Cache-Control": "no-store"})
return RedirectResponse(self.sessions.settings.base_path + "/login", status_code=303, headers={"Cache-Control": "no-store"})
response = await super().get_response(path, scope)
if path in {"index.html", "login.html"} and isinstance(response, FileResponse):
response = await run_in_threadpool(_page_response, FilePath(response.path), self.sessions.settings)
if path not in _PUBLIC_ASSETS or path == "login.html":
response.headers["Cache-Control"] = "no-store"
return response
@@ -419,7 +468,7 @@ def create_app(data_dir=None, manager=None, config=None, updates=None) -> FastAP
raise RuntimeError("Web 服务关闭未完成,请查看已脱敏日志") from None
app = FastAPI(title="牧羊人之心 Web 工作台", version=__version__, lifespan=lifespan,
docs_url=None, redoc_url=None, openapi_url=None)
docs_url=None, redoc_url=None, openapi_url=None, root_path=settings.base_path)
app.state.manager, app.state.updates, app.state.config = manager, updates, settings
app.add_middleware(_Boundary, settings=settings, sessions=sessions)
@@ -560,17 +609,19 @@ def create_app(data_dir=None, manager=None, config=None, updates=None) -> FastAP
token = sessions.login(request, body.password)
response = JSONResponse({"required": True, "authenticated": True, "access_mode": "password"})
response.set_cookie(COOKIE_NAME, token, max_age=settings.session_ttl, httponly=True,
secure=settings.secure_cookie, samesite="strict", path="/")
# Remove the narrower cookie left by older versions before it can shadow the new session.
response.delete_cookie(COOKIE_NAME, path="/api", httponly=True, secure=settings.secure_cookie, samesite="strict")
secure=settings.secure_cookie, samesite="strict", path=settings.base_path or "/")
# Clear legacy paths without expiring the newly issued session cookie.
for path in dict.fromkeys(("/", "/api", settings.base_path + "/api")):
if path != (settings.base_path or "/"):
response.delete_cookie(COOKIE_NAME, path=path, httponly=True, secure=settings.secure_cookie, samesite="strict")
return response
@app.post("/api/auth/logout")
def admin_logout(request: Request):
sessions.logout(request)
response = JSONResponse({"authenticated": False})
response.delete_cookie(COOKIE_NAME, path="/", httponly=True, secure=settings.secure_cookie, samesite="strict")
response.delete_cookie(COOKIE_NAME, path="/api", httponly=True, secure=settings.secure_cookie, samesite="strict")
for path in dict.fromkeys((settings.base_path or "/", "/", "/api", settings.base_path + "/api")):
response.delete_cookie(COOKIE_NAME, path=path, httponly=True, secure=settings.secure_cookie, samesite="strict")
return response
@app.get("/api/schema")
@@ -680,20 +731,14 @@ def create_app(data_dir=None, manager=None, config=None, updates=None) -> FastAP
@app.get("/", include_in_schema=False)
def index(request: Request):
if not sessions.authenticated(request):
return RedirectResponse("/login", status_code=303, headers={"Cache-Control": "no-store"})
index_path = static_dir / "index.html"
if not index_path.is_file():
raise HTTPException(503, "前端资源尚未准备完成")
return FileResponse(index_path, media_type="text/html", headers={"Cache-Control": "no-store"})
return RedirectResponse(settings.base_path + "/login", status_code=303, headers={"Cache-Control": "no-store"})
return _page_response(static_dir / "index.html", settings)
@app.get("/login", include_in_schema=False)
def login_page(request: Request):
if sessions.authenticated(request):
return RedirectResponse("/", status_code=303, headers={"Cache-Control": "no-store"})
login_path = static_dir / "login.html"
if not login_path.is_file():
raise HTTPException(503, "前端资源尚未准备完成")
return FileResponse(login_path, media_type="text/html", headers={"Cache-Control": "no-store"})
return RedirectResponse(settings.base_path + "/", status_code=303, headers={"Cache-Control": "no-store"})
return _page_response(static_dir / "login.html", settings)
app.mount("/static", _Assets(directory=static_dir, sessions=sessions, check_dir=False, follow_symlink=False), name="static")
return app