Files
meida_backend/tests/unit/test_log_redaction.py
T
xsl 93b88db2f5 test: unit suite for the gateway invariants plus an integration slice
Covers routing, failover, the circuit breaker, structured-output retries, the
cache-prefix validator, cost computation including cached-token pricing, the
daily budget breaker, the quota protocol, the task state machine and log
redaction. HTTP is mocked -- no unit test spends money. The integration test
runs the real slice against PostgreSQL and Redis with a faked provider.
2026-08-14 00:26:39 +08:00

76 lines
2.7 KiB
Python
Executable File

"""Log redaction (NFR-SEC-03, 架构文档 §11.2).
日志中禁止出现手机号、UnionID、令牌、图片地址与诊断结论。
"""
from __future__ import annotations
from packages.shared.logging import REDACTED, make_redaction_processor
def redact(event: dict[str, object], extra: tuple[str, ...] = ()) -> dict[str, object]:
return dict(make_redaction_processor(extra)(None, "info", dict(event)))
def test_sensitive_top_level_keys_are_masked() -> None:
out = redact(
{
"event": "login",
"phone": "13800138000",
"union_id": "u-123",
"access_token": "abc.def.ghi",
"avatar_key": "user/1/avatar.png",
"user_id": 42,
}
)
assert out["phone"] == REDACTED
assert out["union_id"] == REDACTED
assert out["access_token"] == REDACTED
assert out["avatar_key"] == REDACTED
assert out["user_id"] == 42 # internal id is not sensitive on its own
def test_nested_structures_are_redacted() -> None:
out = redact({"event": "x", "payload": {"inner": {"phone": "13800138000", "ok": 1}}})
payload = out["payload"]
assert isinstance(payload, dict)
assert payload["inner"]["phone"] == REDACTED
assert payload["inner"]["ok"] == 1
def test_phone_numbers_inside_free_text_are_masked() -> None:
out = redact({"event": "sms", "detail": "验证码已发送至 13800138000"})
assert "13800138000" not in str(out["detail"])
assert "138****8000" in str(out["detail"])
def test_api_keys_in_free_text_are_masked() -> None:
# Never put a real key in a fixture, not even to prove it gets redacted:
# the test file itself would then carry the secret into git history.
fake_key = "sk-" + "0f1e2d3c4b5a69788796a5b4c3d2e1f0"
out = redact({"event": "cfg", "detail": f"using {fake_key}"})
assert fake_key not in str(out["detail"])
assert REDACTED in str(out["detail"])
def test_bearer_tokens_in_free_text_are_masked() -> None:
out = redact({"event": "req", "detail": "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.x.y"})
assert "eyJhbGciOiJIUzI1NiJ9" not in str(out["detail"])
def test_diagnosis_output_is_treated_as_sensitive() -> None:
out = redact({"event": "report", "dimensions": {"color_season": "浅暖柔和型"}})
assert out["dimensions"] == REDACTED
def test_extra_keys_can_be_configured() -> None:
out = redact({"event": "x", "custom_field": "secret"}, extra=("custom_field",))
assert out["custom_field"] == REDACTED
def test_lists_are_traversed() -> None:
out = redact({"event": "x", "items": [{"phone": "13800138000"}]})
items = out["items"]
assert isinstance(items, list)
assert items[0]["phone"] == REDACTED