unis-oa/backend/scripts/check_route_guards.py

129 lines
6.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""Fail when an API endpoint slipped past every role check.
菜单、按钮、数据都按角色控制这件事,靠人记住哪个接口漏了是记不住的;这里直接
把 FastAPI 的路由表过一遍,要求每个接口至少满足下面三条之一:
1. 挂权限点:``Depends(require_permission("…"))``(内置角色一律给 ``*``);
2. 只要登录:自助类接口(本人待办、日程、网盘、通知……),具体能不能碰某条
记录由 service 层的所有权判断兜住;
3. 写进下面的 ``ANONYMOUS`` 白名单——登录、健康检查、公开配置、封面图、SPA
壳子,仅此而已。
只依赖标准库和项目自身的 app 包,跑在 backend 目录下::
python3 scripts/check_route_guards.py
"""
from __future__ import annotations
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
from app.main import app # noqa: E402 (需要上面那行把 backend 目录放进 sys.path)
# 允许完全匿名访问的接口,加在这里要说明理由。
ANONYMOUS: dict[tuple[str, str], str] = {
("GET", "/api/v1/ping"): "健康检查",
("POST", "/api/v1/auth/login"): "登录入口",
("GET", "/api/v1/auth/captcha"): "登录页验证码,转发统一身份平台的验证码,不含用户数据",
("POST", "/api/v1/auth/refresh"): "用 refresh token 换 access token",
("POST", "/api/v1/auth/sso/state"): "发起统一门户免登:只发一条随机 state 给浏览器 Cookie,不含业务数据",
("POST", "/api/v1/auth/sso/login"): "免登落地换会话:由 Hub 签发的一次性票据鉴权,本身必须匿名可调",
("GET", "/api/v1/auth/sso/callback"): "统一门户免登回调:由 Hub 签发的一次性票据鉴权,票据不对就 302 回落地页报错,不放行任何数据",
("POST", "/api/v1/auth/sso/exchange"): "用回调发出的一次性短码换会话:短码 + 回调当场下发的 HttpOnly Cookie 双要件,用一次即废",
("GET", "/sso/hub"): "免登回调的别名路径,与 GET /api/v1/auth/sso/callback 同一入口",
("GET", "/api/v1/settings/public"): "登录页要读的公开配置",
("POST", "/api/v1/open/token"): "开放平台换访问令牌:用 app_key + app_secret 本身鉴权,必须匿名可调",
("POST", "/api/v1/embed/tickets/verify"): "嵌页面免登短码换身份:调用方是对方系统的服务端,"
"由约定的应用密钥(常数时间比对)加一次性短码鉴权,"
"短码用一次即废且只存哈希,本身必须匿名可调",
# 同一条源、同一把应用密钥、同一趟会话令牌:见 app/api/embeds.py:embed_callback
("POST", "/api/v1/embed/callback"): "嵌页面回写(表单值 / 已经发起了 / 审批结论):调用方是对方"
"系统的服务端,由约定的应用密钥(常数时间比对)加那一趟一次性"
"的会话令牌鉴权,令牌只存哈希、几小时就废,本身必须匿名可调",
# 外部核验送审时给出去的两条链接:对方系统(可能只是个抓文件的 worker)只能"跟着 URL 走",
# 拿不到访问令牌。两条都由 HMAC 签名 + 期限 + 绑单鉴权:改了附件 id、换了单号、过了过期时间,
# 签名都算不出来;每次调用仍照旧进 oa_open_call 留痕。判据见 service/external_check.py。
("GET", "/api/v1/open/checks/files"): "送审批次的附件清单入口:按 bizKey + 期限 HMAC 签名鉴权,"
"签名不对或过期一律 403,本身必须匿名可调",
("GET", "/api/v1/open/attachments/{attachment_id}/download"): "核验用附件的一次性下载地址:"
"按 附件 id + 单号 job + 期限 HMAC 签名鉴权,"
"并校验附件确实挂在这张单上,本身必须匿名可调",
("GET", "/api/v1/cms/documents/{document_id}/cover"): "资讯封面图,静态资源",
("GET", "/{full_path:path}"): "前端 SPA 壳子",
}
def dependency_calls(dependant):
"""Depth-first walk of a route's dependency tree."""
if getattr(dependant, "call", None):
yield dependant
for child in getattr(dependant, "dependencies", None) or []:
yield from dependency_calls(child)
def permission_codes(route) -> list[str]:
"""Permission codes attached to a route, ``ADMIN`` for the legacy admin guard."""
found: list[str] = []
for dep in dependency_calls(route.dependant):
name = getattr(dep.call, "__qualname__", "") or ""
if "require_permission" in name:
for cell in getattr(dep.call, "__closure__", None) or ():
try:
value = cell.cell_contents
except ValueError:
continue
if isinstance(value, str) and ":" in value:
found.append(value)
else:
found.append("?")
elif name.startswith("require_admin"):
found.append("ADMIN")
return sorted(set(found))
#: 除了本系统的登录会话之外,对外开放接口 ``/open/*`` 有自己的鉴权依赖:
#: 它校验应用令牌并限流,等价于"确认了调用方是谁",所以也算过这一关。
AUTH_DEPENDENCIES = ("current_user", "open_context")
def is_authenticated(route) -> bool:
names = [(getattr(dep.call, "__qualname__", "") or "") for dep in dependency_calls(route.dependant)]
return any(name.startswith(prefix) for name in names for prefix in AUTH_DEPENDENCIES)
def main() -> int:
from fastapi.routing import APIRoute
checked = gated = 0
problems: list[str] = []
for route in app.routes:
if not isinstance(route, APIRoute):
continue
for method in sorted(route.methods - {"HEAD", "OPTIONS"}):
checked += 1
codes = permission_codes(route)
if codes:
gated += 1
continue
if is_authenticated(route):
continue
reason = ANONYMOUS.get((method, route.path))
if reason:
continue
problems.append(f"{method} {route.path}")
for path in problems:
print(f"[FAIL] {path} 既没有权限点,也不要求登录,还不在匿名白名单里")
if problems:
print(f"共 {len(problems)} 个接口缺少角色相关校验")
return 1
print(f"通过:{checked} 个接口,{gated} 个挂权限点,其余要么要求登录要么在白名单内")
return 0
if __name__ == "__main__":
sys.exit(main())