23 lines
880 B
Python
23 lines
880 B
Python
"""认证校验:CLI / Agent 请求携带 GATEWAY_AUTH,后台管理请求携带 ADMIN_AUTH。"""
|
||
import secrets
|
||
|
||
from fastapi import HTTPException
|
||
|
||
from app.config import settings
|
||
|
||
|
||
def _constant_time_eq(a: str, b: str) -> bool:
|
||
"""常量时间字符串比较,避免时序侧信道。"""
|
||
return secrets.compare_digest((a or "").encode("utf-8"), (b or "").encode("utf-8"))
|
||
|
||
|
||
def require_auth(auth: str) -> None:
|
||
"""协议层鉴权:auth 必须与 GATEWAY_AUTH 一致,否则 401。"""
|
||
if not _constant_time_eq(auth, settings.gateway_auth):
|
||
raise HTTPException(status_code=401, detail="invalid auth")
|
||
|
||
|
||
def require_admin(auth: str) -> None:
|
||
"""后台管理鉴权:auth 必须与 ADMIN_AUTH 一致,否则 401。"""
|
||
if not _constant_time_eq(auth, settings.admin_auth):
|
||
raise HTTPException(status_code=401, detail="invalid admin auth") |