-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_app.py
More file actions
509 lines (423 loc) · 17.1 KB
/
test_app.py
File metadata and controls
509 lines (423 loc) · 17.1 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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
"""
Comprehensive Test Suite for Policy-as-Code Platform
=====================================================
Tests all endpoints, edge cases, and policy evaluation scenarios.
Usage:
python -m pytest test_app.py -v
or
python test_app.py
"""
import pytest
import json
from app import create_app, db
from app.models import User, Policy, AuditLog
from datetime import datetime
class TestAuthEndpoints:
"""Test authentication endpoints."""
@pytest.fixture
def client(self):
"""Create test client."""
app = create_app('testing')
with app.test_client() as client:
with app.app_context():
db.create_all()
yield client
db.drop_all()
def test_register_success(self, client):
"""Test successful user registration."""
response = client.post('/auth/register',
json={
'username': 'testuser',
'email': '[email protected]',
'password': 'password123',
'role': 'employee',
'department': 'engineering'
})
assert response.status_code == 201
data = json.loads(response.data)
assert data['status'] == 'success'
assert 'user' in data['data']
def test_register_duplicate_username(self, client):
"""Test registration with duplicate username."""
# Create first user
client.post('/auth/register',
json={
'username': 'testuser',
'email': '[email protected]',
'password': 'password123',
'role': 'employee',
'department': 'engineering'
})
# Try to create duplicate
response = client.post('/auth/register',
json={
'username': 'testuser',
'email': '[email protected]',
'password': 'password123',
'role': 'employee',
'department': 'engineering'
})
assert response.status_code == 409
data = json.loads(response.data)
assert 'already exists' in data['message'].lower()
def test_register_invalid_role(self, client):
"""Test registration with invalid role."""
response = client.post('/auth/register',
json={
'username': 'testuser',
'email': '[email protected]',
'password': 'password123',
'role': 'superadmin',
'department': 'engineering'
})
assert response.status_code == 400
data = json.loads(response.data)
assert 'invalid role' in data['message'].lower()
def test_register_short_password(self, client):
"""Test registration with short password."""
response = client.post('/auth/register',
json={
'username': 'testuser',
'email': '[email protected]',
'password': '123',
'role': 'employee',
'department': 'engineering'
})
assert response.status_code == 400
data = json.loads(response.data)
assert 'at least 6 characters' in data['message'].lower()
def test_register_missing_fields(self, client):
"""Test registration with missing required fields."""
response = client.post('/auth/register',
json={
'username': 'testuser'
})
assert response.status_code == 400
def test_login_success(self, client):
"""Test successful login."""
# Register user first
client.post('/auth/register',
json={
'username': 'testuser',
'email': '[email protected]',
'password': 'password123',
'role': 'employee',
'department': 'engineering'
})
# Login
response = client.post('/auth/login',
json={
'username': 'testuser',
'password': 'password123'
})
assert response.status_code == 200
data = json.loads(response.data)
assert data['status'] == 'success'
assert 'access_token' in data['data']
def test_login_invalid_credentials(self, client):
"""Test login with invalid credentials."""
response = client.post('/auth/login',
json={
'username': 'nonexistent',
'password': 'wrongpassword'
})
assert response.status_code == 401
data = json.loads(response.data)
assert 'invalid' in data['message'].lower()
def test_login_missing_fields(self, client):
"""Test login with missing fields."""
response = client.post('/auth/login',
json={
'username': 'testuser'
})
assert response.status_code == 400
def test_get_profile_authenticated(self, client):
"""Test getting profile with valid token."""
# Register and login
client.post('/auth/register',
json={
'username': 'testuser',
'email': '[email protected]',
'password': 'password123',
'role': 'employee',
'department': 'engineering'
})
login_response = client.post('/auth/login',
json={
'username': 'testuser',
'password': 'password123'
})
token = json.loads(login_response.data)['data']['access_token']
# Get profile
response = client.get('/auth/profile',
headers={'Authorization': f'Bearer {token}'})
assert response.status_code == 200
data = json.loads(response.data)
assert data['data']['user']['username'] == 'testuser'
def test_get_profile_no_token(self, client):
"""Test getting profile without token."""
response = client.get('/auth/profile')
assert response.status_code == 401
class TestPolicyEvaluation:
"""Test OPA policy evaluation."""
@pytest.fixture
def client(self):
"""Create test client with sample users."""
app = create_app('testing')
with app.test_client() as client:
with app.app_context():
db.create_all()
# Create test users
admin = User(username='admin', email='[email protected]',
role='admin', department='management')
admin.set_password('admin123')
manager = User(username='manager', email='[email protected]',
role='manager', department='engineering')
manager.set_password('manager123')
employee = User(username='employee', email='[email protected]',
role='employee', department='engineering')
employee.set_password('employee123')
db.session.add_all([admin, manager, employee])
db.session.commit()
yield client
db.drop_all()
def get_token(self, client, username, password):
"""Helper to get auth token."""
response = client.post('/auth/login',
json={'username': username, 'password': password})
return json.loads(response.data)['data']['access_token']
def test_admin_full_access(self, client):
"""Test admin has full access to all resources."""
token = self.get_token(client, 'admin', 'admin123')
response = client.post('/policy/evaluate',
headers={'Authorization': f'Bearer {token}'},
json={
'action': 'delete',
'resource': {
'type': 'document',
'department': 'hr'
}
})
assert response.status_code == 200
data = json.loads(response.data)
assert data['data']['allow'] == True
def test_manager_office_hours(self, client):
"""Test manager access during office hours."""
token = self.get_token(client, 'manager', 'manager123')
# Simulate office hours (10 AM)
response = client.post('/policy/evaluate',
headers={'Authorization': f'Bearer {token}'},
json={
'action': 'read',
'resource': {
'type': 'document',
'department': 'engineering'
},
'environment': {
'hour': 10
}
})
assert response.status_code == 200
data = json.loads(response.data)
assert data['data']['allow'] == True
def test_manager_outside_hours(self, client):
"""Test manager access denied outside office hours."""
token = self.get_token(client, 'manager', 'manager123')
# Simulate outside office hours (8 PM)
response = client.post('/policy/evaluate',
headers={'Authorization': f'Bearer {token}'},
json={
'action': 'read',
'resource': {
'type': 'document',
'department': 'engineering'
},
'environment': {
'hour': 20
}
})
assert response.status_code == 200
data = json.loads(response.data)
assert data['data']['allow'] == False
def test_employee_read_own_department(self, client):
"""Test employee can read own department resources."""
token = self.get_token(client, 'employee', 'employee123')
response = client.post('/policy/evaluate',
headers={'Authorization': f'Bearer {token}'},
json={
'action': 'read',
'resource': {
'type': 'document',
'department': 'engineering'
}
})
assert response.status_code == 200
data = json.loads(response.data)
assert data['data']['allow'] == True
def test_employee_cannot_write(self, client):
"""Test employee cannot write resources."""
token = self.get_token(client, 'employee', 'employee123')
response = client.post('/policy/evaluate',
headers={'Authorization': f'Bearer {token}'},
json={
'action': 'write',
'resource': {
'type': 'document',
'department': 'engineering'
}
})
assert response.status_code == 200
data = json.loads(response.data)
assert data['data']['allow'] == False
def test_employee_cross_department_denied(self, client):
"""Test employee cannot access other department resources."""
token = self.get_token(client, 'employee', 'employee123')
response = client.post('/policy/evaluate',
headers={'Authorization': f'Bearer {token}'},
json={
'action': 'read',
'resource': {
'type': 'document',
'department': 'hr'
}
})
assert response.status_code == 200
data = json.loads(response.data)
assert data['data']['allow'] == False
class TestAuditLogging:
"""Test audit logging functionality."""
@pytest.fixture
def client(self):
"""Create test client."""
app = create_app('testing')
with app.test_client() as client:
with app.app_context():
db.create_all()
# Create test user
user = User(username='testuser', email='[email protected]',
role='employee', department='engineering')
user.set_password('password123')
db.session.add(user)
db.session.commit()
yield client
db.drop_all()
def test_audit_log_created_on_evaluation(self, client):
"""Test that audit logs are created for policy evaluations."""
# Login
response = client.post('/auth/login',
json={'username': 'testuser', 'password': 'password123'})
token = json.loads(response.data)['data']['access_token']
# Make policy evaluation
client.post('/policy/evaluate',
headers={'Authorization': f'Bearer {token}'},
json={
'action': 'read',
'resource': {'type': 'document', 'department': 'engineering'}
})
# Check audit log was created
from app import create_app
app = create_app('testing')
with app.app_context():
log_count = AuditLog.query.count()
assert log_count > 0
class TestEdgeCases:
"""Test edge cases and error handling."""
@pytest.fixture
def client(self):
"""Create test client."""
app = create_app('testing')
with app.test_client() as client:
with app.app_context():
db.create_all()
yield client
db.drop_all()
def test_empty_request_body(self, client):
"""Test endpoints with empty request body."""
response = client.post('/auth/register', json={})
assert response.status_code == 400
def test_malformed_json(self, client):
"""Test endpoints with malformed JSON."""
response = client.post('/auth/register',
data='not valid json',
content_type='application/json')
assert response.status_code in [400, 415]
def test_sql_injection_attempt(self, client):
"""Test SQL injection prevention."""
response = client.post('/auth/register',
json={
'username': "admin' OR '1'='1",
'email': '[email protected]',
'password': 'password123',
'role': 'employee',
'department': 'engineering'
})
# Should either succeed (creating user with that username) or fail validation
# But should NOT cause SQL injection
assert response.status_code in [201, 400, 409]
def test_xss_prevention(self, client):
"""Test XSS prevention in user inputs."""
response = client.post('/auth/register',
json={
'username': '<script>alert("xss")</script>',
'email': '[email protected]',
'password': 'password123',
'role': 'employee',
'department': 'engineering'
})
# Should handle script tags safely
assert response.status_code in [201, 400]
def test_very_long_input(self, client):
"""Test handling of very long inputs."""
long_string = 'a' * 10000
response = client.post('/auth/register',
json={
'username': long_string,
'email': '[email protected]',
'password': 'password123',
'role': 'employee',
'department': 'engineering'
})
# Should handle gracefully
assert response.status_code in [400, 500]
def test_unicode_characters(self, client):
"""Test handling of unicode characters."""
response = client.post('/auth/register',
json={
'username': 'user_测试_🎉',
'email': '[email protected]',
'password': 'password123',
'role': 'employee',
'department': 'engineering'
})
# Should handle unicode gracefully
assert response.status_code in [201, 400]
def test_concurrent_registrations(self, client):
"""Test handling of concurrent user registrations."""
import threading
results = []
def register_user(username):
response = client.post('/auth/register',
json={
'username': username,
'email': f'{username}@example.com',
'password': 'password123',
'role': 'employee',
'department': 'engineering'
})
results.append(response.status_code)
threads = [threading.Thread(target=register_user, args=(f'user{i}',))
for i in range(5)]
for t in threads:
t.start()
for t in threads:
t.join()
# All should succeed
assert all(code == 201 for code in results)
def run_tests():
"""Run all tests."""
print("\n" + "="*70)
print(" Running Comprehensive Test Suite")
print("="*70 + "\n")
pytest.main([__file__, '-v', '--tb=short'])
if __name__ == '__main__':
run_tests()