Files
AgentLab/backend/app/auth/middleware.py
T
ThearchyHelios d8034ca71a 对外访问地址只留一个:core/public_url.py 的 public_base_url(),通知、Webhook 链接、OIDC 回调、来源核对都改用它
以前有两个「对外地址」:环境变量 AGENTLAB_PUBLIC_URL 只管 OIDC 回调和 Origin 核对,设置里 notify.public_base_url 只管
通知里的链接。只配了环境变量的部署,通知里不带链接;只在设置里填了的,回调又按请求的 Host 拼——违背「一种说法」。

- 新增 core/public_url.py:环境变量优先,其次设置(沿用 notify.public_base_url 这个键),都没有是 None。设置的值缓存在
  进程里(中间件按请求核对来源,不能每次查库):启动时 refresh 一次,PUT /api/settings 写完库就 remember,不用重启;
  通知、定时任务 Webhook 手里本来就有会话,用 refresh 取,顺手按库里的值对齐缓存
- 地址的形状检查和规范化只有一份(url_problem / normalize),设置接口的中文报错和环境变量的启动校验都用它;环境变量
  写错了(没有 http:// 或 https://、带 ? 或 #)启动时就报错,不再拼出坏的回调地址
- GET /api/settings 另给只读的 public_url 一组 {value, env_locked},设置页据此显示「由环境变量指定」;环境变量设了时
  PUT 把这一项改成别的值回 409(public_url_env_locked,field 指到这一项),原样写回不算改;public_url 一组写不进库
- notify/service 取地址的那一处、scheduler/webhook 链接里的地址、api/auth 的 OIDC 回调、auth/middleware 的 Origin 核对
  都改走 public_base_url;deploy/agentlab.env 把这个变量的说法改成全站唯一的对外访问地址

测试 tests/test_public_url.py:先后顺序(环境变量 > 设置 > 无)、规范化、启动校验、PUT 刷新缓存、环境变量锁定(409、
不挡原样写回)、只配环境变量时通知带链接、OIDC 回调和 Origin 核对认设置里的地址。去掉修复回跑,只配环境变量的通知
链接、按设置核对 Origin 两条都会失败。设置页把它挪到「通用」在后面的前端提交里。
2026-10-16 10:18:12 +08:00

142 lines
6.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""按请求认出是谁,写进 api/deps 的 contextvar(A7 第 2、4 条)。
纯 ASGI 中间件:HTTP 和 WebSocket 都经过它(Starlette 的 BaseHTTPMiddleware 不管 WebSocket),SSE 流式响应在它的
调用里发完,contextvar 一直有效。
关登录:不拦任何请求,写进 contextvar 的是等同管理员、未认证、署名取自 X-Actor 的身份;actor_of 照旧自己解码请求头,
和加这一层之前一模一样。
开登录:
- 会话 cookie → Principal(认证过的用户名、角色、组);没有会话是匿名(username=None),X-Actor 一律不看;
- /api 下除了登录本身、健康检查、入站钩子,匿名一律 401。各路由的角色要求另由 main.py 的路由级依赖管,这里兜底:
哪个路由忘了挂依赖,也不会对没登录的人敞开;
- 非 GET 的请求必须带 X-AgentLab-Request 头,带了 Origin 的必须是本站或登记的前端地址(CSRF)。自定义请求头跨站发不出来
(要过 CORS 预检,只放行配置里的前端地址),SameSite=Lax 的 cookie 也不随跨站的表单提交带过去;
- WebSocket:没登录的握手前就关掉;登录了的交给路由,按运行判(api/deps.py 的 run_scope:user 角色只能连自己能读、
查询结果在工具边界遮过的运行,也就是自己的问数据运行;应用实例页照旧轮询)。
"""
from __future__ import annotations
import json
from http.cookies import SimpleCookie
from typing import Any
from app.core.config import settings
#: 开登录时匿名也能访问的接口
_PUBLIC = frozenset({"/api/health", "/api/auth/me", "/api/auth/login", "/api/auth/logout", "/api/auth/oidc/start",
"/api/auth/oidc/callback", "/api/auth/jwks", "/api/auth/bootstrap"})
#: 只认签名、不走会话的入站钩子(也不查 CSRF:调用方是外部系统,没有浏览器的 Origin)
_HOOKS = "/api/hooks/"
_SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
CSRF_HEADER = "x-agentlab-request"
def _headers(scope: dict[str, Any]) -> dict[str, str]:
return {k.decode("latin-1").lower(): v.decode("latin-1") for k, v in scope.get("headers") or []}
def _cookie(headers: dict[str, str], name: str) -> str | None:
raw = headers.get("cookie")
if not raw:
return None
jar = SimpleCookie()
try:
jar.load(raw)
except Exception: # noqa: BLE001 - 坏掉的 cookie 头当没有
return None
morsel = jar.get(name)
return morsel.value if morsel else None
def _origin_ok(origin: str, headers: dict[str, str], scope: dict[str, Any]) -> bool:
from app.core.public_url import origin_of, public_base_url
allowed = {o.rstrip("/") for o in settings.cors_origins}
# 对外访问地址(环境变量或设置里的那一项,core/public_url.py):反向代理后面请求的 Host 不一定是它
if address := public_base_url():
allowed.add(origin_of(address))
host = headers.get("x-forwarded-host") or headers.get("host")
if host:
scheme = headers.get("x-forwarded-proto") or scope.get("scheme") or "http"
allowed.add(f"{scheme}://{host}")
return origin.rstrip("/") in allowed
async def _reply(send: Any, status: int, detail: str, code: str) -> None:
body = json.dumps({"detail": detail, "code": code}, ensure_ascii=False).encode()
await send({"type": "http.response.start", "status": status,
"headers": [(b"content-type", b"application/json"), (b"content-length", str(len(body)).encode())]})
await send({"type": "http.response.body", "body": body})
async def resolve(headers: dict[str, str], mode: str) -> Any:
"""cookie → Principal。没有有效会话是匿名(username=None、role 为空)。"""
from app.api.deps import Principal
from app.auth.sessions import COOKIE, principal_of, user_of
from app.db.base import SessionLocal
token = _cookie(headers, COOKIE)
if token:
async with SessionLocal() as session:
user = await user_of(session, token)
if user is not None:
return await principal_of(session, user, mode)
return Principal(username=None, role="", verified=False, mode=mode)
class AuthMiddleware:
def __init__(self, app: Any) -> None:
self.app = app
async def __call__(self, scope: dict[str, Any], receive: Any, send: Any) -> None:
if scope["type"] not in ("http", "websocket"):
await self.app(scope, receive, send)
return
from app.api.deps import reset_principal, set_principal
from app.auth import current_mode
# 登录设置在启动时读进缓存(main.py 的 _platform_startup),改设置的接口改完就刷新;这里不查库
mode = current_mode()
headers = _headers(scope)
if mode == "off":
# 关登录:所有人等同管理员,署名是自报的 X-Actor。actor_of 照旧自己解码请求头,这里写进来只为让审计、
# current_principal() 也拿得到这个署名
from app.api.deps import Principal, decode_actor
actor = decode_actor(headers.get("x-actor"))
token = set_principal(Principal(username=actor, display_name=actor, role="admin", mode="off"))
try:
await self.app(scope, receive, send)
finally:
reset_principal(token)
return
path = scope.get("path") or ""
is_api = path.startswith("/api/")
if scope["type"] == "http" and is_api and not path.startswith(_HOOKS) \
and scope.get("method", "GET").upper() not in _SAFE_METHODS:
if CSRF_HEADER not in headers:
await _reply(send, 403, "请求缺少来源标记,已拒绝。请从 AgentLab 页面操作", "csrf_header")
return
origin = headers.get("origin")
if origin and not _origin_ok(origin, headers, scope):
await _reply(send, 403, "请求来自其他站点,已拒绝", "csrf_origin")
return
principal = await resolve(headers, mode)
if scope["type"] == "websocket" and not principal.username:
# 握手前关闭:服务端回 403,不建立连接。登录了的不在这里一刀切:能不能连哪次运行要看运行(run_scope)
await receive()
await send({"type": "websocket.close", "code": 1008})
return
if (scope["type"] == "http" and is_api and not principal.username and path not in _PUBLIC
and not path.startswith(_HOOKS)):
await _reply(send, 401, "请先登录", "auth_required")
return
token = set_principal(principal)
try:
await self.app(scope, receive, send)
finally:
reset_principal(token)