fourcal-pms/backend/app/service/audit.py

432 lines
18 KiB
Python
Raw Permalink 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.

"""写操作审计:所有改数据的请求都留一条 ``operation_log``。
老系统的审计是"谁想起来谁写一行",结果就是出了事查不到人:接口上百条,只有零星几条
接口记得记日志,格式还各写各的。这里把审计挪到 ASGI 中间件,**按方法判定而不是按接口
判定**——POST/PUT/PATCH/DELETE 一律留痕,新加接口不需要记得挂什么东西,漏不掉。
三条口径:
1. **一次操作一条**。接口想补充业务语义(项目名、删除原因、影响面)用 :func:`enrich`
挂到 ``request.state`` 上,由中间件并到同一行里,不另开一条。
2. **口令这类东西绝不入库**。请求体里命中敏感字样的键统一替换成 ``***``,整段还带
长度上限;上传类请求(multipart)只记元信息,不碰内容。
3. **审计失败不影响业务**。日志写在响应出去之后,异常只打警告,绝不把一次已经成功的
保存变成 500。
登录/免登/改口令不在这条链路里:前两者有自己的 ``login_log`` 与 ``sso_handoff``,改口令
在接口里写了一条动作更明确的 ``operation_log``;三条路径的请求体都是要防着的东西,
混进来除了多存一份敏感数据没别的好处。
审计页上的**对象名**由这里按 ``object_type`` 反查一次(见 ``NAME_LOOKUPS``),不要求每个
接口自己记得报名字——接口会一个个新增,靠人记的规矩一定会漏。
"""
from __future__ import annotations
import json
import logging
import time
from typing import Any
from starlette.concurrency import run_in_threadpool
from starlette.types import ASGIApp, Message, Receive, Scope, Send
from ..db import SessionFactory
from ..models import OperationLog
logger = logging.getLogger("pms.audit")
MUTATING_METHODS = frozenset({"POST", "PUT", "PATCH", "DELETE"})
#: 不审计的路径。登录/免登/改口令有自己的日志,且请求体是要防着的东西。
SKIP_PREFIXES = ("/api/health", "/api/docs", "/api/openapi.json")
SKIP_PATHS = ("/api/v1/auth/login", "/api/v1/auth/password")
SKIP_SUBTREES = ("/api/v1/auth/sso",)
#: 请求体只截这么多字节进日志;再长的(整表批量保存)留个长度就够定位了。
BODY_LIMIT = 4096
#: 命中这些字样的键一律抹掉,别把口令、令牌、验证码存进审计表。刻意不收 "code"/"key"
#: 这种宽泛字样——部门编码、岗位编码、字典编码都是审计要看的,被糊掉等于白记。
SENSITIVE_HINTS = ("password", "passwd", "token", "secret", "captcha", "credential",
"authorization", "ticket")
#: 路径尾巴上是这些词时,动作按词记,不按 HTTP 方法猜。
VERB_TAILS = {
"submit": "submit", "withdraw": "withdraw", "approve": "approve", "reject": "reject",
"rollback": "rollback", "transfer": "transfer", "add-sign": "add_sign", "act": "act",
"remind": "remind", "publish": "publish", "offline": "offline", "restore": "restore",
"purge": "purge", "reset": "reset", "toggle": "toggle", "sync": "sync",
"calculate": "calculate", "new-version": "new_version", "logout": "logout",
"exchange": "sso_exchange", "run": "run", "stage": "stage",
}
METHOD_ACTIONS = {"POST": "create", "PUT": "update", "PATCH": "update", "DELETE": "delete"}
#: 路径段 → (对象类型, 记 id 用的路径参数名)。深的那段优先,外层那段进 detail。
SEGMENT_OBJECT: dict[str, tuple[str, str]] = {
"projects": ("project", "project_id"),
"members": ("project_member", "account_id"),
"visible-roles": ("project_visible_role", "role_id"),
"attachments": ("attachment", "attachment_id"),
"units": ("org_unit", "unit_id"),
"positions": ("position", "position_id"),
"accounts": ("account", "id"),
"roles": ("perm_role", "role_id"),
"permissions": ("perm_node", "node_id"),
"nodes": ("perm_node", "node_id"),
"data-policies": ("perm_data_policy", "policy_id"),
"field-scopes": ("field_scope", "scope_id"),
"configs": ("system_config", "code"),
"calc-rules": ("calc_rule", ""),
"dicts": ("dict_type", "dict_id"),
"items": ("dict_item", "item_id"),
"flows": ("approval_flow", "flow_id"),
"delegates": ("approval_delegate", ""),
"instances": ("approval_instance", "instance_id"),
"tasks": ("approval_task", "task_id"),
"versions": ("biz_revision", "revision_id"),
"snapshots": ("calc_snapshot", "snapshot_id"),
"lines": ("biz_line", "line_id"),
"stage": ("project_stage", ""),
"finance": ("biz_revision", "project_id"),
"approvals": ("approval", ""),
}
#: 审计页要显示"改的是哪个东西",按对象类型回查一次显示名列。查不到就留空,
#: 对象 id 与请求体都还在,不影响定位。
NAME_LOOKUPS: dict[str, tuple[str, str]] = {
"project": ("Project", "name"),
"project_member": ("Account", "display_name"),
"org_unit": ("OrgUnit", "name"),
"position": ("Position", "name"),
"account": ("Account", "display_name"),
"perm_role": ("PermRole", "name"),
"perm_node": ("PermNode", "name"),
"perm_data_policy": ("PermDataPolicy", "name"),
"system_config": ("SystemConfig", "name"),
"dict_type": ("DictType", "name"),
"approval_flow": ("ApprovalFlow", "name"),
"approval_instance": ("ApprovalInstance", "project_name"),
}
ACTION_LABELS = {
"create": "新增", "update": "修改", "delete": "删除", "purge": "彻底删除",
"restore": "恢复", "submit": "提交送审", "withdraw": "撤回送审", "approve": "审批通过",
"reject": "审批不通过", "rollback": "退回修改", "transfer": "转办", "add_sign": "加签",
"act": "办理审批", "remind": "催办", "publish": "发布流程", "offline": "下线流程",
"reset": "恢复默认", "toggle": "启停", "sync": "同步", "calculate": "试算",
"new_version": "新建版本", "logout": "登出", "sso_exchange": "免登换会话", "run": "执行",
"stage": "推进阶段", "delete_check": "删除前检查",
"change_password": "修改口令", "unknown": "操作",
}
def action_label(action: str) -> str:
return ACTION_LABELS.get(action, action or "操作")
# ---------------------------------------------------------------------------
# 接口侧的业务补充
# ---------------------------------------------------------------------------
def enrich(request: Any, *, action: str = "", object_type: str = "", object_id: Any = None,
object_name: str = "", **detail: Any) -> None:
"""给这次请求的审计行补业务语义;由中间件在响应之后合并成一行。
``request`` 传 FastAPI 的 ``Request``,没有的话传 ``request.state`` 所在的那个对象——
只认 ``state``,因此 ASGI 中间件重建出来的 ``Request`` 也能读到这里写的东西。
"""
state = getattr(request, "state", request)
bag: dict[str, Any] = getattr(state, "audit", None) or {}
if action:
bag["action"] = action
if object_type:
bag["object_type"] = object_type
if object_id is not None:
bag["object_id"] = str(object_id)
if object_name:
bag["object_name"] = object_name[:255]
if detail:
bag.setdefault("detail", {}).update(detail)
try:
state.audit = bag
except Exception: # pragma: no cover - 极少数 state 实现不允许挂属性
pass
# ---------------------------------------------------------------------------
# 路径 → 对象
# ---------------------------------------------------------------------------
def _is_param(segment: str) -> bool:
return segment.startswith("{") and segment.endswith("}")
def resolve_object(route_path: str, path_params: dict[str, Any]) -> tuple[str, str, str, str]:
"""从路由模板里折出 (对象类型, 对象 id, 父类型, 父 id)。
取**最深**一段能对上 id 的作为主体:删成员记的是那个成员,不是项目;项目 id 仍然
进 detail,查的时候按项目也能捞出来。
"""
segments = [s for s in route_path.split("/") if s][2:] # 去掉 api/v1
found: list[tuple[str, str]] = []
for segment in segments:
if _is_param(segment):
continue
mapped = SEGMENT_OBJECT.get(segment)
if not mapped:
continue
object_type, param = mapped
value = path_params.get(param) if param else None
found.append((object_type, "" if value is None else str(value)))
if not found:
return "", "", "", ""
deepest = next((item for item in reversed(found) if item[1]), found[-1])
outer = found[0]
if outer[0] == deepest[0]:
return deepest[0], deepest[1], "", ""
return deepest[0], deepest[1], outer[0], outer[1]
def resolve_action(method: str, route_path: str) -> str:
tail = [s for s in route_path.split("/") if s][-1]
if not _is_param(tail):
verb = VERB_TAILS.get(tail)
if verb:
return verb
return METHOD_ACTIONS.get(method, "unknown")
# ---------------------------------------------------------------------------
# 请求体脱敏
# ---------------------------------------------------------------------------
def _sensitive(key: str) -> bool:
lowered = key.lower().replace("_", "")
return any(hint in lowered for hint in SENSITIVE_HINTS)
def redact(value: Any, *, depth: int = 0) -> Any:
"""递归脱敏。列表/字典原样折,命中敏感字样的键换成 ``***``。"""
if depth > 6:
return "…"
if isinstance(value, dict):
return {(k if isinstance(k, str) else str(k)):
("***" if isinstance(k, str) and _sensitive(k) else redact(v, depth=depth + 1))
for k, v in list(value.items())[:120]}
if isinstance(value, list):
folded = [redact(item, depth=depth + 1) for item in value[:60]]
if len(value) > 60:
folded.append(f"…共 {len(value)} 条")
return folded
if isinstance(value, (str, int, float, bool)) or value is None:
if isinstance(value, str) and len(value) > 500:
return value[:500] + f"…共 {len(value)} 字"
return value
return str(value)[:500]
def _body_for_log(content_type: str, raw: bytes) -> Any:
if not raw:
return None
length = len(raw)
text = raw[:BODY_LIMIT].decode("utf-8", "replace")
if content_type.startswith("multipart/"):
return {"_upload": True, "bytes": length}
try:
return redact(json.loads(text))
except ValueError:
return {"_raw": text[:BODY_LIMIT] + (f"…共 {length} 字节" if length > BODY_LIMIT else "")}
# ---------------------------------------------------------------------------
# 中间件
# ---------------------------------------------------------------------------
class AuditMiddleware:
"""原生 ASGI 中间件:只观察,不改请求也不改响应。
没用 ``BaseHTTPMiddleware`` 是因为要在不吃掉请求体的前提下看到同一段 body——
在这里套一层 ``receive``,消息照样原样往下传,接口读到的字节一个不少。
"""
def __init__(self, app: ASGIApp) -> None:
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
path = scope.get("path", "")
method = scope.get("method", "")
if (scope.get("type") != "http" or method not in MUTATING_METHODS
or path.startswith(SKIP_PREFIXES) or path in SKIP_PATHS
or path.startswith(SKIP_SUBTREES)):
await self.app(scope, receive, send)
return
chunks: list[bytes] = []
seen = 0
async def watching_receive() -> Message:
nonlocal seen
message = await receive()
if message.get("type") == "http.request":
piece = message.get("body", b"") or b""
if seen < BODY_LIMIT * 2:
chunks.append(piece)
seen += len(piece)
return message
outcome: dict[str, Any] = {"status": 0, "body": b""}
async def watching_send(message: Message) -> None:
kind = message.get("type")
if kind == "http.response.start":
outcome["status"] = message.get("status", 0)
elif kind == "http.response.body" and len(outcome["body"]) < 2048:
# 响应体只在内存里截一小段,不整段留下:失败的要写出"为什么没改成",
# 新增成功的要拿 data.id ——本系统所有创建接口都回 ok({"id": N}),
# 认这一条约定,新建出来的对象 id 就不用每个接口自己报一遍。
outcome["body"] += message.get("body", b"") or b""
await send(message)
started = time.perf_counter()
try:
await self.app(scope, watching_receive, watching_send)
finally:
raw = b"".join(chunks)
elapsed = round((time.perf_counter() - started) * 1000, 1)
try:
await run_in_threadpool(self._record, scope, raw, outcome, elapsed)
except Exception as exc: # pragma: no cover - 审计绝不能带崩业务
logger.warning("写审计日志失败 %s %s:%s", method, path, exc)
# -- 落库 ---------------------------------------------------------------
def _record(self, scope: Scope, raw: bytes, outcome: dict[str, Any], elapsed: float) -> None:
status = int(outcome.get("status") or 0)
from starlette.requests import Request
request = Request(scope)
route = scope.get("route")
route_path = getattr(route, "path_format", None) or getattr(route, "path", "") or scope.get("path", "")
path_params = dict(scope.get("path_params") or {})
payload = _parse_json(outcome.get("body") or b"")
state = getattr(request, "state", None)
bag: dict[str, Any] = getattr(state, "audit", None) or {}
account = getattr(state, "account", None)
object_type, object_id, parent_type, parent_id = resolve_object(route_path, path_params)
action = bag.get("action") or resolve_action(scope.get("method", ""), route_path)
if bag.get("object_type"):
object_type = bag["object_type"]
object_id = bag.get("object_id", object_id)
query = dict(request.query_params)
detail: dict[str, Any] = {
"method": scope.get("method", ""),
"path": scope.get("path", ""),
"route": route_path,
"status": status,
"ok": status < 400,
"durationMs": elapsed,
}
if query:
detail["query"] = redact(query)
if path_params:
detail["params"] = redact(path_params)
body = _body_for_log(request.headers.get("content-type", ""), raw)
if body is not None:
detail["body"] = body
error = bag.get("error") or _error_from_response(payload)
if error:
detail["error"] = error
if not object_id and action == "create":
object_id = _created_id(payload)
if parent_type:
detail["parentType"], detail["parentId"] = parent_type, parent_id
detail.update(bag.get("detail") or {})
if not bag.get("object_name"):
object_name_hint = _lookup_name(object_type, object_id)
else:
object_name_hint = bag["object_name"]
with SessionFactory()() as session:
session.add(OperationLog(
account_id=getattr(account, "id", None),
account_name=(getattr(account, "display_name", "") or getattr(account, "account", "")
or bag.get("account_name", ""))[:100],
action=action[:64],
object_type=(object_type or (route_path.split("/")[2] if route_path.count("/") > 2 else ""))[:64],
object_id=(object_id or bag.get("object_id") or "")[:64],
object_name=str(object_name_hint or "")[:255],
detail_json=json.dumps(detail, ensure_ascii=False, default=str),
ip=(request.headers.get("X-Forwarded-For", "").split(",")[0].strip()
or (request.client.host if request.client else ""))[:64],
))
session.commit()
def _lookup_name(object_type: str, object_id: str) -> str:
"""按对象类型把显示名捞出来。捞不到不算错,审计页留空也比编一个强。"""
from .. import models
spec = NAME_LOOKUPS.get(object_type)
if not spec or not (object_id or "").isdigit():
return ""
model = getattr(models, spec[0], None)
if model is None:
return ""
try:
with SessionFactory()() as session:
row = session.get(model, int(object_id))
except Exception: # pragma: no cover - 对象已被同一次操作删掉
return ""
if row is None:
return ""
value = getattr(row, spec[1], "")
if spec[1] == "display_name":
value = value or getattr(row, "account", "")
return str(value or "")
def install(app: Any) -> None:
"""把审计中间件挂到应用最外层(后加的在外层,能看到路由已经跑完的结果)。"""
app.add_middleware(AuditMiddleware)
def _parse_json(raw: bytes) -> dict[str, Any]:
if not raw:
return {}
try:
payload = json.loads(raw.decode("utf-8", "replace"))
except ValueError:
return {}
return payload if isinstance(payload, dict) else {}
def _created_id(payload: dict[str, Any]) -> str:
"""新增接口回的那条 ``{"ok": true, "data": {"id": N}}``。"""
data = payload.get("data")
if isinstance(data, dict) and data.get("id") is not None:
return str(data["id"])[:64]
return ""
def _error_from_response(payload: dict[str, Any]) -> dict[str, Any]:
"""从统一响应包里挑出要进审计的那几个字段,别的大段 detail 不存。"""
error = payload.get("error")
if not isinstance(error, dict):
return {}
folded = {"code": str(error.get("code", ""))[:64], "message": str(error.get("message", ""))[:500]}
if error.get("traceId"):
folded["traceId"] = str(error["traceId"])[:64]
detail = error.get("detail")
if detail:
folded["detail"] = redact(detail)
return folded