test_gateway_api.py
12.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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
"""网关 HTTP 接口:登录保护 + 错误语义。
错误语义的要求:不同的失败原因必须映射到不同的状态码和错误码,
不能一律压成 503「服务不可达」——那样「工具名写错」和「服务宕机」
在界面上长得一模一样。
"""
from __future__ import annotations
import httpx
import pytest
from mcp_hive.core.errors import ServiceUnreachable, ToolCallTimeout, ToolNotFound
@pytest.fixture
async def anon_client():
"""未登录的客户端,用来验证鉴权本身。"""
from mcp_hive.gateway import app as gateway_app
# 每个用例都从干净的状态缓存开始,否则会串味
gateway_app._status_cache["data"] = None
gateway_app._status_cache["at"] = 0.0
# raise_app_exceptions=False:FastAPI 的兜底 handler 会先返回 500 响应,
# 再把原异常重新抛出交给 uvicorn 记录。默认配置下测试端会收到那个异常而看不到响应体,
# 关掉之后行为才和浏览器看到的一致。
transport = httpx.ASGITransport(app=gateway_app.app, raise_app_exceptions=False)
async with (
gateway_app.app.router.lifespan_context(gateway_app.app),
httpx.AsyncClient(transport=transport, base_url="http://test") as c,
):
yield c
@pytest.fixture
async def client(anon_client):
"""已登录的客户端。httpx 的 cookie jar 会自动带上会话 cookie。"""
response = await anon_client.post(
"/api/login", json={"username": "admin", "password": "123456"}
)
assert response.status_code == 200, response.text
return anon_client
# ------------------------------------------------------------------ 登录
async def test_api_requires_login(anon_client):
response = await anon_client.get("/api/services")
assert response.status_code == 401
assert response.json()["error_code"] == "UNAUTHORIZED"
async def test_healthz_is_public(anon_client):
"""探活不能要登录,否则容器编排判不了健康。"""
response = await anon_client.get("/healthz")
assert response.status_code == 200
assert response.json()["status"] == "ok"
async def test_login_page_and_assets_are_public(anon_client):
"""登录页自己和它引用的 CSS/JS 必须放行,否则页面渲染不出来。"""
for path in ["/login.html", "/css/tokens.css", "/js/main.js"]:
assert (await anon_client.get(path)).status_code == 200, path
async def test_page_request_redirects_to_login(anon_client):
response = await anon_client.get("/", follow_redirects=False)
assert response.status_code == 302
assert response.headers["location"] == "/login.html"
@pytest.mark.parametrize(
("username", "password"),
[("admin", "wrong"), ("root", "123456"), ("", "")],
)
async def test_bad_credentials_are_rejected(anon_client, username, password):
response = await anon_client.post(
"/api/login", json={"username": username, "password": password}
)
assert response.status_code == 401
# 不区分「用户名不对」和「密码不对」,别把存在哪些账号透出去
assert response.json()["message"] == "用户名或密码错误"
async def test_logout_clears_the_session(client):
assert (await client.post("/api/logout")).status_code == 200
assert (await client.get("/api/services")).status_code == 401
@pytest.fixture
def stub_mcp(monkeypatch):
"""替换掉真实的 MCP 客户端,单测不依赖任何在跑的服务。"""
from mcp_hive.gateway import mcp_client
class Stub:
def __init__(self) -> None:
self.tools = [
{
"name": "query_monthly_data",
"description": "月度",
"input_schema": {"type": "object"},
}
]
self.list_error: Exception | None = None
self.call_error: Exception | None = None
self.call_result = {
"is_error": False,
"content": [],
"structured_content": {"data": []},
}
stub = Stub()
async def fake_list_tools(url):
if stub.list_error:
raise stub.list_error
return stub.tools
async def fake_call_tool(url, tool, args):
if stub.call_error:
raise stub.call_error
return dict(stub.call_result)
async def fake_ping(url):
if stub.list_error:
return False, 0, str(stub.list_error)
return True, len(stub.tools), None
monkeypatch.setattr(mcp_client, "list_tools", fake_list_tools)
monkeypatch.setattr(mcp_client, "call_tool", fake_call_tool)
monkeypatch.setattr(mcp_client, "ping", fake_ping)
return stub
# ---------------------------------------------------------------- 基础接口
async def test_meta_reports_the_logged_in_user(client):
body = (await client.get("/api/meta")).json()
assert body["user"] == "admin"
assert body["service_count"] >= 1
async def test_every_response_carries_a_request_id(client):
response = await client.get("/api/meta")
assert response.headers.get("X-Request-Id")
async def test_services_list(client, stub_mcp):
body = (await client.get("/api/services")).json()
assert body[0]["key"] == "used_car"
assert body[0]["online"] is True
assert body[0]["tool_count"] == 1
assert "latency_ms" in body[0]
async def test_offline_service_reports_error_without_failing_the_request(client, stub_mcp):
"""一个服务掉线不能让整页 500 —— 状态里带上错误原因就行。"""
stub_mcp.list_error = ServiceUnreachable("连不上")
response = await client.get("/api/services")
assert response.status_code == 200
assert response.json()[0]["online"] is False
assert "连不上" in response.json()[0]["error"]
# ---------------------------------------------------------------- 错误语义
async def test_unknown_service_is_404(client):
response = await client.get("/api/services/nope/tools")
assert response.status_code == 404
assert response.json()["error_code"] == "SERVICE_NOT_FOUND"
async def test_unknown_tool_is_404_not_503(client, stub_mcp):
"""关键回归:旧实现把这个也报成 503「服务不可达」,用户完全被误导。"""
stub_mcp.call_error = ToolNotFound("服务里没有名为 'nope' 的工具")
response = await client.post(
"/api/services/used_car/call", json={"tool": "nope", "arguments": {}}
)
assert response.status_code == 404
assert response.json()["error_code"] == "TOOL_NOT_FOUND"
async def test_unreachable_service_is_503(client, stub_mcp):
stub_mcp.call_error = ServiceUnreachable("连接失败")
response = await client.post(
"/api/services/used_car/call", json={"tool": "query_monthly_data", "arguments": {}}
)
assert response.status_code == 503
assert response.json()["error_code"] == "SERVICE_UNREACHABLE"
async def test_tool_timeout_is_504(client, stub_mcp):
stub_mcp.call_error = ToolCallTimeout("超时")
response = await client.post(
"/api/services/used_car/call", json={"tool": "query_monthly_data", "arguments": {}}
)
assert response.status_code == 504
async def test_all_errors_share_one_response_shape(client, stub_mcp):
"""前端只处理一种错误结构:{error_code, message, request_id}。"""
stub_mcp.call_error = ServiceUnreachable("x")
responses = [
await client.get("/api/services/nope/tools"),
await client.post("/api/services/used_car/call", json={"tool": "t"}),
await client.get("/api/audit/logs?status=乱写"),
]
for response in responses:
body = response.json()
assert {"error_code", "message", "request_id"} <= set(body), body
async def test_invalid_payload_is_400_with_readable_message(client):
response = await client.post("/api/services/used_car/call", json={"tool": ""})
assert response.status_code == 400
assert response.json()["error_code"] == "INVALID_PARAM"
assert "tool" in response.json()["message"]
async def test_unhandled_exception_does_not_leak_internals(client, stub_mcp):
"""旧实现直接把 str(exc) 吐给浏览器,可能带出内部地址和堆栈细节。"""
stub_mcp.call_error = RuntimeError("内部数据库密码是 hunter2")
response = await client.post(
"/api/services/used_car/call", json={"tool": "query_monthly_data", "arguments": {}}
)
assert response.status_code == 500
body = response.json()
assert "hunter2" not in response.text
assert body["request_id"]
# ------------------------------------------------------------------ 调用
async def test_successful_call_includes_structured_content_and_timing(client, stub_mcp):
body = (
await client.post(
"/api/services/used_car/call",
json={"tool": "query_monthly_data", "arguments": {"month": "2026-08"}},
)
).json()
assert body["is_error"] is False
# 旧实现丢掉了 structured_content,前端因此没法渲染中文表头的表格
assert body["structured_content"] == {"data": []}
assert isinstance(body["elapsed_ms"], int)
async def test_caller_label_header_is_percent_decoded(client, stub_mcp):
"""HTTP 头只能放 ISO-8859-1,中文调用方标识按约定走百分号编码。"""
from mcp_hive.core.context import current_context
seen = {}
async def capture(url, tool, args):
seen["caller"] = current_context().caller_label
return {"is_error": False, "content": [], "structured_content": None}
from mcp_hive.gateway import mcp_client
mcp_client.call_tool = capture
await client.post(
"/api/services/used_car/call",
json={"tool": "query_monthly_data", "arguments": {}},
headers={"X-MCP-Caller": "%E6%9D%A8%E6%8C%AF%E4%BA%AE"},
)
assert seen["caller"] == "杨振亮"
# ------------------------------------------------------------------ 审计接口
async def test_audit_endpoints_report_unavailable_when_db_is_off(client):
"""conftest 里数据库配置为空,审计接口应给出可操作的提示而不是 500。"""
for path in ["/api/audit/logs", "/api/audit/logs/some-call-id", "/api/audit/facets"]:
response = await client.get(path)
assert response.status_code == 503, path
assert response.json()["error_code"] == "DB_UNAVAILABLE"
async def test_invalid_status_filter_is_rejected(client):
response = await client.get("/api/audit/logs?status=乱写")
assert response.status_code == 400
assert "success" in response.json()["message"]
async def test_invalid_date_filter_is_rejected(client):
response = await client.get("/api/audit/logs?from=不是日期")
assert response.status_code == 400
assert response.json()["error_code"] == "INVALID_PARAM"
# ------------------------------------------------------------------ 服务配置
async def test_service_config_requires_login(anon_client):
"""凭证接口尤其不能裸奔。"""
assert (await anon_client.get("/api/config/services")).status_code == 401
async def test_config_endpoints_report_unavailable_when_db_is_off(client):
"""数据库没配是「去改配置」而不是「程序坏了」,必须是 503 不是 500。"""
response = await client.get("/api/config/services")
assert response.status_code == 503
assert response.json()["error_code"] == "DB_UNAVAILABLE"
async def test_service_config_never_returns_either_plaintext_secret(client, monkeypatch):
"""两层签名两把密钥,页面上都只能回显后 4 位。"""
from mcp_hive.core.config import credentials as creds_module
async def fake_list():
return {
"used_car": {
"service_key": "used_car",
"base_url": "http://upstream.test/facade",
"app_key": "k",
"secret": "super-secret-value",
"gw_app_id": "gw-app",
"gw_secret": "super-gateway-secret",
"enabled": 1,
"updated_at": "2026-09-01 10:00:00",
"updated_by": "admin",
}
}
monkeypatch.setattr(creds_module, "list_credentials", fake_list)
# 假装数据库配好了,否则 _require_db 会先 503
monkeypatch.setattr("mcp_hive.gateway.app.is_configured", lambda _db: True)
response = await client.get("/api/config/services")
assert response.status_code == 200
assert "super-secret-value" not in response.text
assert "super-gateway-secret" not in response.text
row = next(r for r in response.json() if r["key"] == "used_car")
assert row["secret_masked"] == "***alue"
assert row["gw_secret_masked"] == "***cret"
assert row["gw_app_id"] == "gw-app"
assert row["configured"] is True
async def test_saving_an_unknown_service_is_404(client):
response = await client.put(
"/api/config/services/nope",
json={"base_url": "http://x", "app_key": "k", "secret": "s", "enabled": True},
)
assert response.status_code == 404