test_audit_interception.py
9.8 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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
"""审计切面:确认**每一次**工具调用都被记录,且状态分类正确。
这是整个审计能力的核心断言。切点选在 FastMCP.call_tool 而不是网关,
就是为了覆盖 AI Agent 直连 MCP 服务(绕过网关)的那条路径。
"""
from __future__ import annotations
import json
import httpx
import pytest
import respx
from mcp.server.fastmcp.exceptions import ToolError
from mcp_hive.core.audit import recorder as recorder_module
from mcp_hive.core.audit.entry import AuditStatus
from mcp_hive.core.context import CallContext, set_context
from mcp_hive.core.mcp.host import build_instance
from mcp_hive.core.registry import get_manifest
from mcp_hive.services.used_car import api_client
BASE = "http://upstream.test/facade"
class CapturingRecorder:
"""把审计记录收在内存里,不碰数据库。"""
def __init__(self) -> None:
self.entries = []
def submit(self, entry) -> None:
self.entries.append(entry)
@pytest.fixture
def captured(monkeypatch):
rec = CapturingRecorder()
monkeypatch.setattr(recorder_module, "_recorder", rec)
return rec
@pytest.fixture
async def service(app_settings, fake_credentials):
instance = build_instance(get_manifest("used_car"), app_settings)
assert instance.ok, instance.error
async with api_client.lifespan():
yield instance
async def test_successful_call_is_recorded_with_row_count(service, captured):
set_context(CallContext(client_ip="10.0.0.1", caller_channel="agent", caller_label="分析 Skill"))
with respx.mock(base_url=BASE) as mock:
mock.post("/mcp/monthly/list").mock(
return_value=httpx.Response(
200,
json={"data": [{"a": 1}, {"a": 2}], "schema": [{"key": "a", "name_cn": "甲"}]},
)
)
await service.mcp.call_tool("query_monthly_data", {"month": "2026-08"})
assert len(captured.entries) == 1
entry = captured.entries[0]
assert entry.status == AuditStatus.SUCCESS
assert entry.tool_name == "query_monthly_data"
assert entry.service == "used_car"
assert entry.row_count == 2
assert entry.result_bytes > 0
assert entry.arguments == {"month": "2026-08"}
assert entry.caller_label == "分析 Skill"
assert entry.caller_channel == "agent"
assert entry.client_ip == "10.0.0.1"
# 无鉴权,身份永远是「未验证」
assert entry.identity_verified is False
async def test_returned_data_is_recorded_not_just_its_size(service, captured):
"""审计要能看到这次调用到底返回了什么,不能只留个行数。"""
payload = {"data": [{"store_name": "岚图", "eval_quantity": 31}], "schema": [{"key": "a"}]}
with respx.mock(base_url=BASE) as mock:
mock.post("/mcp/monthly/list").mock(return_value=httpx.Response(200, json=payload))
await service.mcp.call_tool("query_monthly_data", {"month": "2026-08"})
entry = captured.entries[-1]
assert entry.result == payload
assert entry.to_row()["result_json"] == json.dumps(payload, ensure_ascii=False)
async def test_failed_call_records_no_result(service, captured):
"""调用失败时没有返回值可记,这一列必须是 NULL 而不是空对象。"""
with respx.mock(base_url=BASE) as mock:
mock.post("/mcp/shelf/list").mock(side_effect=httpx.ConnectError("refused"))
with pytest.raises(ToolError):
await service.mcp.call_tool("query_shelf_data", {})
entry = captured.entries[-1]
assert entry.result is None
assert entry.to_row()["result_json"] is None
async def test_oversized_result_is_capped_but_stays_valid_json(service, captured):
"""返回结果按字符数封顶。截断后存的仍必须是合法 JSON,否则这一列读不回来。"""
rows = [{"i": i, "pad": "x" * 200} for i in range(400)]
with respx.mock(base_url=BASE) as mock:
mock.post("/mcp/monthly/list").mock(
return_value=httpx.Response(200, json={"data": rows, "schema": []})
)
await service.mcp.call_tool("query_monthly_data", {"month": "2026-08"})
row = captured.entries[-1].to_row(max_result_chars=2000)
parsed = json.loads(row["result_json"]) # 截断后依然解析得开
assert parsed["_truncated"] is True
assert len(row["result_json"]) < 2500
async def test_backend_error_is_recorded_with_upstream_code(service, captured):
with respx.mock(base_url=BASE) as mock:
mock.post("/mcp/shelf/list").mock(
return_value=httpx.Response(
200, json={"error_code": "STORE_NOT_FOUND", "message": "门店未上架"}
)
)
with pytest.raises(ToolError):
await service.mcp.call_tool("query_shelf_data", {"store_name": "不存在"})
entry = captured.entries[-1]
assert entry.status == AuditStatus.BACKEND_ERROR
# FastMCP 会把工具异常包一层 ToolError,剥不开的话这里会退化成 INTERNAL_ERROR
assert entry.error_code == "STORE_NOT_FOUND"
assert entry.upstream_status == 200
async def test_validation_error_is_recorded_without_touching_upstream(service, captured):
"""非法参数应该在本地就被拦下,不该白跑一次上游请求。"""
# assert_all_called=False:这个用例的重点就是那条路由「不该被调用」
with respx.mock(base_url=BASE, assert_all_called=False) as mock:
route = mock.post("/mcp/daily/list")
with pytest.raises(ToolError):
await service.mcp.call_tool(
"query_daily_report",
{"store_name": "X", "start_date": "2026-99-99", "end_date": "2026-08-31"},
)
assert route.call_count == 0
entry = captured.entries[-1]
assert entry.status == AuditStatus.VALIDATION_ERROR
assert entry.error_code == "INVALID_PARAM"
async def test_timeout_is_recorded_as_timeout_not_generic_error(service, captured):
with respx.mock(base_url=BASE) as mock:
mock.post("/mcp/daily/list").mock(side_effect=httpx.ConnectTimeout("slow"))
with pytest.raises(ToolError):
await service.mcp.call_tool(
"query_daily_report",
{"store_name": "X", "start_date": "2026-08-01", "end_date": "2026-08-31"},
)
entry = captured.entries[-1]
assert entry.status == AuditStatus.TIMEOUT
assert entry.error_code == "UPSTREAM_TIMEOUT"
async def test_truncated_result_is_flagged_in_audit(service, captured):
"""审计里要能看出「这次调用返回的数据被截断了」。"""
rows = [{"i": i} for i in range(600)] # 默认上限 500
with respx.mock(base_url=BASE) as mock:
mock.post("/mcp/monthly/list").mock(
return_value=httpx.Response(200, json={"data": rows, "schema": []})
)
await service.mcp.call_tool("query_monthly_data", {"month": "2026-08"})
entry = captured.entries[-1]
assert entry.truncated is True
assert entry.row_count == 500
async def test_every_call_gets_a_distinct_call_id(service, captured):
"""同一个上下文(同一个 request_id)下的多次调用必须各自成行。"""
set_context(CallContext(request_id="same-request"))
with respx.mock(base_url=BASE) as mock:
mock.post("/mcp/monthly/list").mock(
return_value=httpx.Response(200, json={"data": [], "schema": []})
)
await service.mcp.call_tool("query_monthly_data", {"month": "2026-08"})
await service.mcp.call_tool("query_monthly_data", {"month": "2026-07"})
assert len(captured.entries) == 2
assert captured.entries[0].request_id == captured.entries[1].request_id == "same-request"
assert captured.entries[0].call_id != captured.entries[1].call_id
async def test_missing_required_month_is_rejected_locally(service, captured):
"""接口规范里 month 是必填。少传必填项要在本地就被 schema 拦下,不该白跑一次上游。"""
with respx.mock(base_url=BASE, assert_all_called=False) as mock:
route = mock.post("/mcp/monthly/list")
with pytest.raises(ToolError):
await service.mcp.call_tool("query_monthly_data", {})
assert route.call_count == 0
assert captured.entries[-1].status != AuditStatus.SUCCESS
async def test_blank_store_name_is_rejected_locally(service, captured):
"""空串是合法的 str,但对上游等同于没传,会换回一个语焉不详的 400。"""
with respx.mock(base_url=BASE, assert_all_called=False) as mock:
route = mock.post("/mcp/daily/list")
with pytest.raises(ToolError):
await service.mcp.call_tool(
"query_daily_report",
{"store_name": " ", "start_date": "2026-08-01", "end_date": "2026-08-02"},
)
assert route.call_count == 0
assert captured.entries[-1].status == AuditStatus.VALIDATION_ERROR
async def test_audit_failure_never_breaks_the_tool_call(service, monkeypatch):
"""审计出问题绝不能影响业务返回 —— 这是审计作为旁路能力的底线。"""
class ExplodingRecorder:
def submit(self, entry):
raise RuntimeError("审计炸了")
monkeypatch.setattr(recorder_module, "_recorder", ExplodingRecorder())
with respx.mock(base_url=BASE) as mock:
mock.post("/mcp/monthly/list").mock(
return_value=httpx.Response(200, json={"data": [{"a": 1}], "schema": []})
)
result = await service.mcp.call_tool("query_monthly_data", {"month": "2026-08"})
structured = result[1] if isinstance(result, tuple) else result
assert structured["data"] == [{"a": 1}]
async def test_secrets_in_arguments_are_masked_before_recording(service, captured):
"""当前三个工具的入参都不敏感,这是给未来的服务兜底。"""
from mcp_hive.core.audit.masking import mask_arguments
assert mask_arguments({"token": "abc", "month": "2026-08"}) == {
"token": "***",
"month": "2026-08",
}