jrrribeiro commited on
Commit
dc8a18a
·
1 Parent(s): f5f630b

test(acl): comprehensive ACL enforcement test suite with project isolation

Browse files

- Add 12 tests for project-level data isolation in detection and validation repos
- Test detection repository project isolation (4 tests):
* List returns only project-specific detections
* Count respects project boundaries
* Filters applied within project isolation
* Confidence filters respect project boundaries
- Test validation repository project isolation (4 tests):
* Save/load isolates validations by project
* List events respects project boundaries
* Optimistic locking is per-project scope
* Nonexistent project returns empty snapshot
- Test auth integration with repositories (4 tests):
* Users see only authorized projects
* Session contains only authorized projects
* User roles isolated per project

All tests use 16+ character detection_keys to pass Pydantic validation

Files changed (1) hide show
  1. tests/unit/test_acl_enforcement.py +359 -0
tests/unit/test_acl_enforcement.py ADDED
@@ -0,0 +1,359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for ACL (Access Control List) enforcement at repository level.
2
+
3
+ Validates that project isolation works correctly:
4
+ - Data from project A is not visible in project B
5
+ - Validation operations are isolated per project
6
+ - DetectionRepository filters by project_slug
7
+ """
8
+
9
+ import pytest
10
+ import tempfile
11
+ from pathlib import Path
12
+
13
+ from src.domain.models import Detection, Role, Validation
14
+ from src.repositories.in_memory_detection_repository import InMemoryDetectionRepository
15
+ from src.repositories.append_only_validation_repository import AppendOnlyValidationRepository
16
+ from src.auth.auth_service import AuthService
17
+
18
+
19
+ class TestDetectionRepositoryProjectIsolation:
20
+ """Test that DetectionRepository respects project boundaries."""
21
+
22
+ @pytest.fixture
23
+ def detection_repo(self):
24
+ """Create a new detection repository."""
25
+ return InMemoryDetectionRepository()
26
+
27
+ @pytest.fixture
28
+ def setup_multi_project_detections(self, detection_repo):
29
+ """Seed multiple projects with different detections."""
30
+ # Project 1: Kenya Survey
31
+ kenya_detections = [
32
+ Detection(
33
+ detection_key="00000000000KE001",
34
+ audio_id="audio_ke_001",
35
+ scientific_name="Cyanocorax cyanopogon",
36
+ confidence=0.95,
37
+ start_time=0.0,
38
+ end_time=1.5,
39
+ ),
40
+ Detection(
41
+ detection_key="00000000000KE002",
42
+ audio_id="audio_ke_002",
43
+ scientific_name="Ramphastos toco",
44
+ confidence=0.87,
45
+ start_time=0.0,
46
+ end_time=2.0,
47
+ ),
48
+ ]
49
+ detection_repo.seed("kenya-2024", kenya_detections)
50
+
51
+ # Project 2: Nairobi Survey
52
+ nairobi_detections = [
53
+ Detection(
54
+ detection_key="00000000000NB001",
55
+ audio_id="audio_nb_001",
56
+ scientific_name="Tockus erythrorhynchus",
57
+ confidence=0.92,
58
+ start_time=0.0,
59
+ end_time=1.2,
60
+ ),
61
+ ]
62
+ detection_repo.seed("nairobi-2023", nairobi_detections)
63
+
64
+ # Project 3: Demo
65
+ demo_detections = [
66
+ Detection(
67
+ detection_key="00000000000DE001",
68
+ audio_id="audio_demo_001",
69
+ scientific_name="Psarocolius decumanus",
70
+ confidence=0.78,
71
+ start_time=0.0,
72
+ end_time=1.8,
73
+ ),
74
+ Detection(
75
+ detection_key="00000000000DE002",
76
+ audio_id="audio_demo_002",
77
+ scientific_name="Cyanocorax cyanopogon",
78
+ confidence=0.85,
79
+ start_time=0.0,
80
+ end_time=1.1,
81
+ ),
82
+ Detection(
83
+ detection_key="00000000000DE003",
84
+ audio_id="audio_demo_003",
85
+ scientific_name="Tockus erythrorhynchus",
86
+ confidence=0.73,
87
+ start_time=0.0,
88
+ end_time=1.5,
89
+ ),
90
+ ]
91
+ detection_repo.seed("demo-project", demo_detections)
92
+
93
+ def test_list_detections_isolates_projects(self, detection_repo, setup_multi_project_detections):
94
+ """Test that listing detections from one project doesn't return data from others."""
95
+ kenya_items = detection_repo.list_detections(
96
+ project_slug="kenya-2024", page=1, page_size=10
97
+ )
98
+ nairobi_items = detection_repo.list_detections(
99
+ project_slug="nairobi-2023", page=1, page_size=10
100
+ )
101
+ demo_items = detection_repo.list_detections(
102
+ project_slug="demo-project", page=1, page_size=10
103
+ )
104
+
105
+ # Kenya project has exactly 2 items
106
+ assert len(kenya_items) == 2
107
+ assert all(item.detection_key.startswith("00000000000KE") for item in kenya_items)
108
+
109
+ # Nairobi project has exactly 1 item
110
+ assert len(nairobi_items) == 1
111
+ assert nairobi_items[0].detection_key.startswith("00000000000NB")
112
+
113
+ # Demo project has exactly 3 items
114
+ assert len(demo_items) == 3
115
+ assert all(item.detection_key.startswith("00000000000DE") for item in demo_items)
116
+
117
+ def test_count_detections_respects_boundaries(self, detection_repo, setup_multi_project_detections):
118
+ """Test that detection count is accurate per project."""
119
+ kenya_count = detection_repo.count_detections(project_slug="kenya-2024")
120
+ nairobi_count = detection_repo.count_detections(project_slug="nairobi-2023")
121
+ demo_count = detection_repo.count_detections(project_slug="demo-project")
122
+
123
+ assert kenya_count == 2
124
+ assert nairobi_count == 1
125
+ assert demo_count == 3
126
+
127
+ def test_filters_applied_within_project_isolation(self, detection_repo, setup_multi_project_detections):
128
+ """Test that filters work correctly within project boundaries."""
129
+ # Filter by species in Kenya
130
+ kenya_cyanocorax = detection_repo.list_detections(
131
+ project_slug="kenya-2024",
132
+ page=1,
133
+ page_size=10,
134
+ scientific_name="Cyanocorax cyanopogon",
135
+ )
136
+
137
+ assert len(kenya_cyanocorax) == 1
138
+ assert kenya_cyanocorax[0].detection_key == "00000000000KE001"
139
+
140
+ # Same species in demo project should be independent
141
+ demo_cyanocorax = detection_repo.list_detections(
142
+ project_slug="demo-project",
143
+ page=1,
144
+ page_size=10,
145
+ scientific_name="Cyanocorax cyanopogon",
146
+ )
147
+
148
+ assert len(demo_cyanocorax) == 1
149
+ assert demo_cyanocorax[0].detection_key == "00000000000DE002"
150
+
151
+ def test_confidence_filter_respects_project_boundaries(self, detection_repo, setup_multi_project_detections):
152
+ """Test that confidence filtering doesn't leak across projects."""
153
+ # Find high confidence items in each project
154
+ high_confidence = 0.90
155
+
156
+ kenya_high = detection_repo.list_detections(
157
+ project_slug="kenya-2024",
158
+ page=1,
159
+ page_size=10,
160
+ min_confidence=high_confidence,
161
+ )
162
+ nairobi_high = detection_repo.list_detections(
163
+ project_slug="nairobi-2023",
164
+ page=1,
165
+ page_size=10,
166
+ min_confidence=high_confidence,
167
+ )
168
+
169
+ assert len(kenya_high) == 1 # Only KE2024000001 (0.95)
170
+ assert len(nairobi_high) == 1 # Only NB2023000001 (0.92)
171
+
172
+ def test_nonexistent_project_returns_empty(self, detection_repo):
173
+ """Test that querying a non-existent project returns empty results."""
174
+ results = detection_repo.list_detections(
175
+ project_slug="nonexistent-project", page=1, page_size=10
176
+ )
177
+ assert len(results) == 0
178
+
179
+ count = detection_repo.count_detections(project_slug="nonexistent-project")
180
+ assert count == 0
181
+
182
+
183
+ class TestValidationRepositoryProjectIsolation:
184
+ """Test that ValidationRepository respects project boundaries."""
185
+
186
+ @pytest.fixture
187
+ def validation_repo(self):
188
+ """Create a temporary validation repository."""
189
+ with tempfile.TemporaryDirectory() as temp_dir:
190
+ yield AppendOnlyValidationRepository(base_dir=temp_dir)
191
+
192
+ def test_save_validation_isolates_by_project(self, validation_repo):
193
+ """Test that validations are isolated per project."""
194
+ # Save validation to project 1
195
+ validation1 = Validation(
196
+ detection_key="00000000PRJA0001",
197
+ status="positive",
198
+ validator="validator_demo",
199
+ notes="Clear detection",
200
+ )
201
+ version1 = validation_repo.save_validation("kenya-2024", validation1)
202
+
203
+ # Save validation with same key to project 2
204
+ validation2 = Validation(
205
+ detection_key="00000000PRJA0001", # Same key but different project
206
+ status="negative",
207
+ validator="validator_other",
208
+ notes="False alarm",
209
+ )
210
+ version2 = validation_repo.save_validation("nairobi-2023", validation2)
211
+
212
+ # Both should be version 1 in their respective projects
213
+ assert version1 == 1
214
+ assert version2 == 1
215
+
216
+ # Load snapshots - they should be different
217
+ snapshot1 = validation_repo.load_current_snapshot("kenya-2024")
218
+ snapshot2 = validation_repo.load_current_snapshot("nairobi-2023")
219
+
220
+ assert snapshot1["00000000PRJA0001"]["status"] == "positive"
221
+ assert snapshot2["00000000PRJA0001"]["status"] == "negative"
222
+
223
+ def test_list_events_respects_project_boundaries(self, validation_repo):
224
+ """Test that events are isolated per project."""
225
+ # Add events to project 1
226
+ val1 = Validation(
227
+ detection_key="0000000000KEY001",
228
+ status="positive",
229
+ validator="user1",
230
+ )
231
+ validation_repo.save_validation("project-a", val1)
232
+
233
+ val2 = Validation(
234
+ detection_key="0000000000KEY002",
235
+ status="negative",
236
+ validator="user2",
237
+ )
238
+ validation_repo.save_validation("project-a", val2)
239
+
240
+ # Add event to project 2
241
+ val3 = Validation(
242
+ detection_key="0000000000KEY001", # Same key, different project
243
+ status="uncertain",
244
+ validator="user3",
245
+ )
246
+ validation_repo.save_validation("project-b", val3)
247
+
248
+ # List events from each project
249
+ events_a = validation_repo.list_events("project-a")
250
+ events_b = validation_repo.list_events("project-b")
251
+
252
+ # Project A has 2 events
253
+ assert len(events_a) == 2
254
+ assert all(e["project_slug"] == "project-a" for e in events_a)
255
+
256
+ # Project B has 1 event
257
+ assert len(events_b) == 1
258
+ assert events_b[0]["project_slug"] == "project-b"
259
+
260
+ def test_optimistic_lock_respects_project_scope(self, validation_repo):
261
+ """Test that optimistic locking is per project."""
262
+ # Save initial validation to project 1
263
+ val = Validation(
264
+ detection_key="0000000000TEST001",
265
+ status="positive",
266
+ validator="user1",
267
+ )
268
+ v1 = validation_repo.save_validation("proj1", val)
269
+ assert v1 == 1
270
+
271
+ # Update in project 1 with correct version
272
+ val_update = Validation(
273
+ detection_key="0000000000TEST001",
274
+ status="negative",
275
+ validator="user1",
276
+ )
277
+ v2 = validation_repo.save_validation("proj1", val_update, expected_version=1)
278
+ assert v2 == 2
279
+
280
+ # In project 2, same key should be at version 0
281
+ val_other = Validation(
282
+ detection_key="0000000000TEST001",
283
+ status="uncertain",
284
+ validator="user2",
285
+ )
286
+ # Should succeed because version 0 is correct for project 2
287
+ v1_other = validation_repo.save_validation("proj2", val_other)
288
+ assert v1_other == 1
289
+
290
+ def test_nonexistent_project_returns_empty_snapshot(self, validation_repo):
291
+ """Test that querying non-existent project returns empty snapshot."""
292
+ snapshot = validation_repo.load_current_snapshot("nonexistent")
293
+ assert snapshot == {}
294
+
295
+ events = validation_repo.list_events("nonexistent")
296
+ assert events == []
297
+
298
+
299
+ class TestAuthServiceWithRepositoryIntegration:
300
+ """Test that AuthService correctly controls access to repositories."""
301
+
302
+ @pytest.fixture
303
+ def auth_service(self):
304
+ """Create an auth service with test users."""
305
+ service = AuthService()
306
+
307
+ # Setup users with different project access
308
+ service.register_user_project_access(
309
+ "admin_user",
310
+ {"project-a": Role.admin, "project-b": Role.admin},
311
+ )
312
+ service.register_user_project_access(
313
+ "validator_a",
314
+ {"project-a": Role.validator},
315
+ )
316
+ service.register_user_project_access(
317
+ "validator_b",
318
+ {"project-b": Role.validator},
319
+ )
320
+
321
+ return service
322
+
323
+ def test_user_can_only_see_authorized_projects(self, auth_service):
324
+ """Test that users can only access their authorized projects."""
325
+ # Validator A should see project-a
326
+ assert auth_service.is_user_authorized_for_project("validator_a", "project-a")
327
+ assert not auth_service.is_user_authorized_for_project("validator_a", "project-b")
328
+
329
+ # Validator B should see project-b
330
+ assert auth_service.is_user_authorized_for_project("validator_b", "project-b")
331
+ assert not auth_service.is_user_authorized_for_project("validator_b", "project-a")
332
+
333
+ # Admin should see both
334
+ assert auth_service.is_user_authorized_for_project("admin_user", "project-a")
335
+ assert auth_service.is_user_authorized_for_project("admin_user", "project-b")
336
+
337
+ def test_session_contains_only_authorized_projects(self, auth_service):
338
+ """Test that session lists only authorized projects."""
339
+ session_a = auth_service.login("validator_a")
340
+ assert session_a.authorized_projects == ["project-a"]
341
+
342
+ session_b = auth_service.login("validator_b")
343
+ assert session_b.authorized_projects == ["project-b"]
344
+
345
+ session_admin = auth_service.login("admin_user")
346
+ assert sorted(session_admin.authorized_projects) == ["project-a", "project-b"]
347
+
348
+ def test_user_role_isolation_per_project(self, auth_service):
349
+ """Test that user roles are correctly isolated per project."""
350
+ # Create a user with mixed roles
351
+ auth_service.register_user_project_access(
352
+ "mixed_user",
353
+ {"proj1": Role.admin, "proj2": Role.validator},
354
+ )
355
+
356
+ # Check roles per project
357
+ assert auth_service.get_user_role_for_project("mixed_user", "proj1") == Role.admin
358
+ assert auth_service.get_user_role_for_project("mixed_user", "proj2") == Role.validator
359
+ assert auth_service.get_user_role_for_project("mixed_user", "proj3") is None