-
Notifications
You must be signed in to change notification settings - Fork 857
Expand file tree
/
Copy pathtest_siem.py
More file actions
289 lines (209 loc) · 12.7 KB
/
Copy pathtest_siem.py
File metadata and controls
289 lines (209 loc) · 12.7 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
# -*- coding: utf-8 -*-
"""Location: ./tests/unit/mcpgateway/routers/test_siem.py
Copyright contributors to the MCP-CONTEXT-FORGE project
SPDX-License-Identifier: Apache-2.0
Tests for SIEM admin router.
"""
# Standard
from unittest.mock import AsyncMock, MagicMock
# Third-Party
import pytest
from fastapi import HTTPException
# First-Party
from mcpgateway.routers import siem
@pytest.mark.asyncio
async def test_get_siem_health(monkeypatch):
mock_service = MagicMock()
mock_service.get_health = AsyncMock(return_value={"status": "healthy"})
monkeypatch.setattr(siem, "get_siem_export_service", lambda: mock_service)
response = await siem.get_siem_health(_user={"email": "admin@example.com"})
assert response["status"] == "healthy"
@pytest.mark.asyncio
async def test_get_siem_destinations(monkeypatch):
mock_service = MagicMock()
mock_service.enabled = True
mock_service.list_destinations.return_value = [{"name": "dest-1"}]
monkeypatch.setattr(siem, "get_siem_export_service", lambda: mock_service)
response = await siem.get_siem_destinations(_user={"email": "admin@example.com"})
assert response["enabled"] is True
assert response["destinations"][0]["name"] == "dest-1"
@pytest.mark.asyncio
async def test_add_siem_destination_success(monkeypatch):
mock_service = MagicMock()
mock_service.add_destination = AsyncMock(return_value={"name": "dest-1", "type": "webhook"})
monkeypatch.setattr(siem, "get_siem_export_service", lambda: mock_service)
payload = siem.DestinationUpsertRequest(name="dest-1", type="webhook", url="https://example.com/hook")
response = await siem.add_siem_destination(payload=payload, _user={"email": "admin@example.com"})
assert response["status"] == "ok"
assert response["destination"]["name"] == "dest-1"
@pytest.mark.asyncio
async def test_add_siem_destination_validation_error(monkeypatch):
mock_service = MagicMock()
mock_service.add_destination = AsyncMock(side_effect=ValueError("invalid destination"))
monkeypatch.setattr(siem, "get_siem_export_service", lambda: mock_service)
payload = siem.DestinationUpsertRequest(name="dest-1", type="webhook", url="https://example.com/hook")
with pytest.raises(HTTPException) as exc_info:
await siem.add_siem_destination(payload=payload, _user={"email": "admin@example.com"})
assert exc_info.value.status_code == 400
@pytest.mark.asyncio
async def test_add_siem_destination_internal_error(monkeypatch):
mock_service = MagicMock()
mock_service.add_destination = AsyncMock(side_effect=RuntimeError("boom"))
monkeypatch.setattr(siem, "get_siem_export_service", lambda: mock_service)
payload = siem.DestinationUpsertRequest(name="dest-1", type="webhook", url="https://example.com/hook")
with pytest.raises(HTTPException) as exc_info:
await siem.add_siem_destination(payload=payload, _user={"email": "admin@example.com"})
assert exc_info.value.status_code == 500
@pytest.mark.asyncio
async def test_replace_siem_destinations_success(monkeypatch):
mock_service = MagicMock()
mock_service.replace_destinations = AsyncMock(return_value=[{"name": "dest-1", "type": "webhook"}])
monkeypatch.setattr(siem, "get_siem_export_service", lambda: mock_service)
payload = siem.DestinationBulkReplaceRequest(destinations=[siem.DestinationUpsertRequest(name="dest-1", type="webhook", url="https://example.com/hook")])
response = await siem.replace_siem_destinations(payload=payload, _user={"email": "admin@example.com"})
assert response["status"] == "ok"
assert response["destinations"][0]["name"] == "dest-1"
@pytest.mark.asyncio
async def test_replace_siem_destinations_validation_error(monkeypatch):
mock_service = MagicMock()
mock_service.replace_destinations = AsyncMock(side_effect=ValueError("invalid destination"))
monkeypatch.setattr(siem, "get_siem_export_service", lambda: mock_service)
payload = siem.DestinationBulkReplaceRequest(destinations=[siem.DestinationUpsertRequest(name="dest-1", type="webhook", url="https://example.com/hook")])
with pytest.raises(HTTPException) as exc_info:
await siem.replace_siem_destinations(payload=payload, _user={"email": "admin@example.com"})
assert exc_info.value.status_code == 400
@pytest.mark.asyncio
async def test_replace_siem_destinations_internal_error(monkeypatch):
mock_service = MagicMock()
mock_service.replace_destinations = AsyncMock(side_effect=RuntimeError("boom"))
monkeypatch.setattr(siem, "get_siem_export_service", lambda: mock_service)
payload = siem.DestinationBulkReplaceRequest(destinations=[siem.DestinationUpsertRequest(name="dest-1", type="webhook", url="https://example.com/hook")])
with pytest.raises(HTTPException) as exc_info:
await siem.replace_siem_destinations(payload=payload, _user={"email": "admin@example.com"})
assert exc_info.value.status_code == 500
@pytest.mark.asyncio
async def test_test_siem_destination_not_found(monkeypatch):
mock_service = MagicMock()
mock_service.test_destination = AsyncMock(side_effect=KeyError("Unknown destination"))
monkeypatch.setattr(siem, "get_siem_export_service", lambda: mock_service)
with pytest.raises(HTTPException) as exc_info:
await siem.test_siem_destination(destination_name="missing", _user={"email": "admin@example.com"})
assert exc_info.value.status_code == 404
@pytest.mark.asyncio
async def test_test_siem_destination_internal_error(monkeypatch):
mock_service = MagicMock()
mock_service.test_destination = AsyncMock(side_effect=RuntimeError("boom"))
monkeypatch.setattr(siem, "get_siem_export_service", lambda: mock_service)
with pytest.raises(HTTPException) as exc_info:
await siem.test_siem_destination(destination_name="dest-1", _user={"email": "admin@example.com"})
assert exc_info.value.status_code == 500
@pytest.mark.asyncio
async def test_add_siem_destination_escapes_validation_error_xss(monkeypatch):
"""Attacker-controlled input embedded in a ValueError must be HTML-escaped in the 400 detail (CWE-79)."""
payload_str = "<script>alert(1)</script>"
mock_service = MagicMock()
mock_service.add_destination = AsyncMock(side_effect=ValueError(f"invalid destination {payload_str}"))
monkeypatch.setattr(siem, "get_siem_export_service", lambda: mock_service)
payload = siem.DestinationUpsertRequest(name="dest-1", type="webhook", url="https://example.com/hook")
with pytest.raises(HTTPException) as exc_info:
await siem.add_siem_destination(payload=payload, _user={"email": "admin@example.com"})
assert exc_info.value.status_code == 400
assert payload_str not in str(exc_info.value.detail)
assert "<script>" in str(exc_info.value.detail)
@pytest.mark.asyncio
async def test_replace_siem_destinations_escapes_validation_error_xss(monkeypatch):
"""Attacker-controlled input embedded in a ValueError must be HTML-escaped in the 400 detail (CWE-79)."""
payload_str = "<script>alert(1)</script>"
mock_service = MagicMock()
mock_service.replace_destinations = AsyncMock(side_effect=ValueError(f"invalid destination {payload_str}"))
monkeypatch.setattr(siem, "get_siem_export_service", lambda: mock_service)
payload = siem.DestinationBulkReplaceRequest(destinations=[siem.DestinationUpsertRequest(name="dest-1", type="webhook", url="https://example.com/hook")])
with pytest.raises(HTTPException) as exc_info:
await siem.replace_siem_destinations(payload=payload, _user={"email": "admin@example.com"})
assert exc_info.value.status_code == 400
assert payload_str not in str(exc_info.value.detail)
assert "<script>" in str(exc_info.value.detail)
@pytest.mark.asyncio
async def test_test_siem_destination_escapes_name_xss(monkeypatch):
"""Attacker-controlled destination_name must be HTML-escaped before use (CWE-79)."""
payload_str = "<script>alert(1)</script>"
mock_service = MagicMock()
mock_service.test_destination = AsyncMock(side_effect=KeyError(f"Unknown destination: {payload_str}"))
monkeypatch.setattr(siem, "get_siem_export_service", lambda: mock_service)
with pytest.raises(HTTPException) as exc_info:
await siem.test_siem_destination(destination_name=payload_str, _user={"email": "admin@example.com"})
assert exc_info.value.status_code == 404
assert payload_str not in str(exc_info.value.detail)
assert "<script>" in str(exc_info.value.detail)
# The escaped name (not the raw payload) is what reaches the service layer.
mock_service.test_destination.assert_awaited_once_with("<script>alert(1)</script>")
# ---------------------------------------------------------------------------
# Deny-path regression tests (unauthenticated, insufficient permissions, feature disabled)
# ---------------------------------------------------------------------------
class TestSIEMRBACDenyPaths:
"""Verify SIEM endpoints reject requests without proper auth/permissions.
Per AGENTS.md: 'Security-sensitive changes must include deny-path regression
tests (unauthenticated, wrong team, insufficient permissions, feature disabled).'
"""
@pytest.mark.asyncio
async def test_health_endpoint_has_require_permission_decorator(self):
"""GET /admin/siem/health must be wrapped by @require_permission."""
assert hasattr(siem.get_siem_health, "__wrapped__"), "get_siem_health() is missing @require_permission decorator"
@pytest.mark.asyncio
async def test_destinations_endpoint_has_require_permission_decorator(self):
"""GET /admin/siem/destinations must be wrapped by @require_permission."""
assert hasattr(siem.get_siem_destinations, "__wrapped__"), "get_siem_destinations() is missing @require_permission decorator"
@pytest.mark.asyncio
async def test_add_destination_endpoint_has_require_permission_decorator(self):
"""POST /admin/siem/destinations must be wrapped by @require_permission."""
assert hasattr(siem.add_siem_destination, "__wrapped__"), "add_siem_destination() is missing @require_permission decorator"
@pytest.mark.asyncio
async def test_replace_destinations_endpoint_has_require_permission_decorator(self):
"""PUT /admin/siem/destinations must be wrapped by @require_permission."""
assert hasattr(siem.replace_siem_destinations, "__wrapped__"), "replace_siem_destinations() is missing @require_permission decorator"
@pytest.mark.asyncio
async def test_test_destination_endpoint_has_require_permission_decorator(self):
"""POST /admin/siem/test/{name} must be wrapped by @require_permission."""
assert hasattr(siem.test_siem_destination, "__wrapped__"), "test_siem_destination() is missing @require_permission decorator"
@pytest.mark.asyncio
async def test_health_denies_insufficient_permissions(self, monkeypatch):
"""GET /admin/siem/health must return 403 when permission check fails."""
class DenyPermissionService:
def __init__(self, _db):
pass
async def check_permission(self, **kwargs):
return False
monkeypatch.setattr("mcpgateway.middleware.rbac.PermissionService", DenyPermissionService)
with pytest.raises(HTTPException) as exc:
await siem.get_siem_health(
_user={"id": "viewer1", "email": "viewer@test.com", "db": MagicMock()},
)
assert exc.value.status_code == 403
@pytest.mark.asyncio
async def test_add_destination_denies_insufficient_permissions(self, monkeypatch):
"""POST /admin/siem/destinations must return 403 when permission check fails."""
class DenyPermissionService:
def __init__(self, _db):
pass
async def check_permission(self, **kwargs):
return False
monkeypatch.setattr("mcpgateway.middleware.rbac.PermissionService", DenyPermissionService)
payload = siem.DestinationUpsertRequest(name="dest-1", type="webhook", url="https://example.com/hook")
with pytest.raises(HTTPException) as exc:
await siem.add_siem_destination(
payload=payload,
_user={"id": "viewer1", "email": "viewer@test.com", "db": MagicMock()},
)
assert exc.value.status_code == 403
@pytest.mark.asyncio
async def test_health_denies_unauthenticated(self, monkeypatch):
"""GET /admin/siem/health must return 401 when no user is provided."""
class DenyPermissionService:
def __init__(self, _db):
pass
async def check_permission(self, **kwargs):
return False
monkeypatch.setattr("mcpgateway.middleware.rbac.PermissionService", DenyPermissionService)
with pytest.raises(HTTPException) as exc:
await siem.get_siem_health(_user=None)
assert exc.value.status_code == 401