test_audit.py
7.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
"""审计:脱敏、记录构造、写入器的降级行为。
不依赖 MySQL —— 仓库用假实现替换掉。
"""
from __future__ import annotations
import asyncio
import json
from datetime import datetime
import pytest
from mcp_hive.core.audit import recorder as recorder_module
from mcp_hive.core.audit.entry import AuditEntry, AuditStatus, CallerChannel
from mcp_hive.core.audit.masking import mask_arguments
from mcp_hive.core.audit.recorder import AuditRecorder
from mcp_hive.core.config.settings import AppSettings, DatabaseSettings
def make_entry(**overrides) -> AuditEntry:
base = {
"request_id": "req-1",
"ts": datetime(2026, 8, 1, 10, 0, 0),
"service": "used_car",
"tool_name": "query_monthly_data",
"status": AuditStatus.SUCCESS,
"duration_ms": 42,
}
base.update(overrides)
return AuditEntry(**base)
# -------------------------------------------------------------------- 脱敏
@pytest.mark.parametrize(
"key",
["secret", "password", "token", "api_key", "apiKey", "appKey", "sign", "Authorization"],
)
def test_sensitive_keys_are_masked(key):
assert mask_arguments({key: "s3cr3t"})[key] == "***"
def test_normal_values_pass_through():
args = {"store_name": "比亚迪深圳南山店", "month": "2026-08", "store_id": 42}
assert mask_arguments(args) == args
def test_masking_is_recursive():
result = mask_arguments({"outer": {"password": "x", "keep": 1}})
assert result["outer"]["password"] == "***"
assert result["outer"]["keep"] == 1
def test_long_strings_are_truncated():
result = mask_arguments({"note": "x" * 900})
assert len(result["note"]) < 900
assert result["note"].endswith("…")
def test_masking_survives_deep_nesting():
deep = current = {}
for _ in range(20):
current["next"] = {}
current = current["next"]
assert mask_arguments(deep) # 不能爆栈
# --------------------------------------------------------------- 记录构造
def test_identity_is_never_marked_verified():
"""本系统不做鉴权,这一列必须恒为 0,避免被误当成可追责的凭据。"""
assert make_entry().to_row()["identity_verified"] == 0
def test_each_entry_gets_its_own_call_id():
"""一次 HTTP 请求可以携带多次工具调用,审计行的唯一标识不能用 request_id。"""
a, b = make_entry(), make_entry()
assert a.call_id != b.call_id
assert a.request_id == b.request_id
def test_arguments_are_serialized_as_json():
row = make_entry(arguments={"month": "2026-08"}).to_row()
assert json.loads(row["arguments_json"]) == {"month": "2026-08"}
def test_oversized_arguments_are_truncated_with_a_marker():
row = make_entry(arguments={"blob": "x" * 10000}).to_row(max_argument_chars=200)
payload = json.loads(row["arguments_json"])
assert payload["_truncated"] is True
assert len(row["arguments_json"]) < 400
def test_error_message_is_capped_to_column_width():
row = make_entry(error_message="e" * 2000).to_row()
assert len(row["error_message"]) <= 512
def test_empty_error_message_becomes_null():
assert make_entry(error_message="").to_row()["error_message"] is None
def test_jsonl_round_trips():
payload = json.loads(make_entry(arguments={"a": 1}).to_jsonl())
assert payload["tool_name"] == "query_monthly_data"
assert payload["ts"].startswith("2026-08-01")
# ----------------------------------------------------------------- 写入器
class FakeRepo:
def __init__(self, fail: bool = False) -> None:
self.rows: list[AuditEntry] = []
self.fail = fail
self.calls = 0
async def insert_many(self, entries):
self.calls += 1
if self.fail:
raise RuntimeError("数据库挂了")
self.rows.extend(entries)
return len(entries)
def make_settings() -> AppSettings:
"""数据库故意留空:这些用例全部注入假仓库,不碰真实的库。"""
return AppSettings(
log_level="INFO",
mcp_host="127.0.0.1",
mcp_port=53101,
gateway_host="127.0.0.1",
gateway_port=8100,
console_password="123456",
session_secret="s",
database=DatabaseSettings(host="", port=3306, name="", user="", password=""),
)
@pytest.fixture
def recorder_env(tmp_path, monkeypatch):
"""把 recorder 的模块常量换成单测友好的取值(落盘到 tmp、刷新间隔调短)。
这些参数从环境变量改成了模块常量,所以单测靠 monkeypatch 改常量,
而不是构造一份配置对象传进去。
"""
fallback = tmp_path / "audit.jsonl"
monkeypatch.setattr(recorder_module, "FALLBACK_PATH", str(fallback))
monkeypatch.setattr(recorder_module, "FLUSH_INTERVAL", 0.05)
monkeypatch.setattr(recorder_module, "BATCH_SIZE", 10)
monkeypatch.setattr(recorder_module, "QUEUE_SIZE", 100)
return fallback
async def test_recorder_writes_entries_to_repo(recorder_env):
recorder = AuditRecorder(make_settings())
repo = FakeRepo()
recorder._repo = repo # 注入假仓库,跳过真实数据库
await recorder.start()
recorder.submit(make_entry(tool_name="a"))
recorder.submit(make_entry(tool_name="b"))
await recorder.stop()
assert {e.tool_name for e in repo.rows} == {"a", "b"}
assert recorder.written == 2
async def test_recorder_falls_back_to_file_when_db_fails(recorder_env):
"""数据库挂了绝不能影响业务查询,审计降级写本地文件。"""
recorder = AuditRecorder(make_settings())
recorder._repo = FakeRepo(fail=True)
await recorder.start()
recorder.submit(make_entry(tool_name="degraded"))
await recorder.stop()
fallback = recorder_env
assert fallback.exists()
assert "degraded" in fallback.read_text(encoding="utf-8")
assert recorder.fallback_written == 1
async def test_submit_never_raises_even_without_start(recorder_env):
"""审计的任何问题都不能把业务调用带崩。"""
recorder = AuditRecorder(make_settings())
recorder.submit(make_entry()) # 没 start,也不能抛
async def test_full_queue_drops_instead_of_blocking(recorder_env, monkeypatch):
"""宁可丢审计,也不能阻塞工具调用。"""
monkeypatch.setattr(recorder_module, "QUEUE_SIZE", 2)
recorder = AuditRecorder(make_settings())
for _ in range(10):
recorder.submit(make_entry())
assert recorder.dropped == 8 # 队列只吃下 2 条
async def test_health_reports_counters(recorder_env):
recorder = AuditRecorder(make_settings())
health = recorder.health()
assert set(health) >= {"db_ready", "queued", "written", "dropped"}
async def test_writer_survives_a_failing_batch_and_keeps_running(recorder_env):
"""后台任务不能因为一次异常就退出,否则后面所有审计都丢了。"""
recorder = AuditRecorder(make_settings())
repo = FakeRepo(fail=True)
recorder._repo = repo
await recorder.start()
recorder.submit(make_entry(tool_name="first"))
await asyncio.sleep(0.2)
repo.fail = False
recorder.submit(make_entry(tool_name="second"))
await recorder.stop()
assert [e.tool_name for e in repo.rows] == ["second"]
assert recorder.fallback_written == 1
def test_caller_channel_values():
assert CallerChannel.AGENT in CallerChannel.ALL
assert CallerChannel.CONSOLE in CallerChannel.ALL