Sessions with no server storage: HMAC-signed cookies for Python web apps.

0 downloads

dbbasic-sessions/tests/test_security.py
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-sessions.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-sessions.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-sessions.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 Update README with PyPI and GitHub links 75676a8 1 year, 1 month ago History
test_security.py · 10.7 KB · 321 lines
1"""
2Security tests for dbbasic-sessions
3
4Tests cryptographic security, tampering detection, and attack resistance.
5"""
6
7import time
8import base64
9import json
10import hmac
11import hashlib
12import os
13import pytest
14from dbbasic_sessions import create_session, get_session
15
16
17class TestSignatureSecurity:
18 """Test HMAC signature security"""
19
20 def test_tampered_payload_rejected(self):
21 """Should reject token with modified payload"""
22 token = create_session('42')
23 payload, sig = token.split('.')
24
25 # Decode, modify, re-encode payload
26 data = json.loads(base64.urlsafe_b64decode(payload))
27 data['user_id'] = '999' # Try to become different user
28 new_payload = base64.urlsafe_b64encode(json.dumps(data).encode()).decode()
29
30 # Use old signature with new payload
31 tampered = f"{new_payload}.{sig}"
32 user_id = get_session(tampered)
33
34 assert user_id is None, "Tampered payload should be rejected"
35
36 def test_tampered_signature_rejected(self):
37 """Should reject token with modified signature"""
38 token = create_session('42')
39 payload, sig = token.split('.')
40
41 # Modify signature
42 tampered_sig = sig[:-4] + 'XXXX'
43 tampered = f"{payload}.{tampered_sig}"
44
45 user_id = get_session(tampered)
46 assert user_id is None, "Tampered signature should be rejected"
47
48 def test_signature_verification_is_constant_time(self):
49 """Should use constant-time comparison to prevent timing attacks"""
50 # This test verifies hmac.compare_digest is used
51 # We can't easily test timing directly, but we can verify
52 # that the function doesn't short-circuit on first difference
53
54 token = create_session('42')
55 payload, correct_sig = token.split('.')
56
57 # Create signatures that differ at different positions
58 wrong_sigs = [
59 'X' + correct_sig[1:], # Differ at start
60 correct_sig[:32] + 'X' + correct_sig[33:], # Differ in middle
61 correct_sig[:-1] + 'X', # Differ at end
62 ]
63
64 # All should be rejected
65 for wrong_sig in wrong_sigs:
66 tampered = f"{payload}.{wrong_sig}"
67 user_id = get_session(tampered)
68 assert user_id is None
69
70 def test_cannot_create_valid_signature_without_secret(self):
71 """Should not be able to forge signature without secret key"""
72 # Create a payload manually
73 data = {'user_id': '999', 'expires': int(time.time()) + 3600}
74 payload = base64.urlsafe_b64encode(json.dumps(data).encode()).decode()
75
76 # Try to sign with wrong secret
77 wrong_secret = 'wrong-secret'
78 wrong_sig = hmac.new(wrong_secret.encode(), payload.encode(), hashlib.sha256).hexdigest()
79 forged_token = f"{payload}.{wrong_sig}"
80
81 user_id = get_session(forged_token)
82 assert user_id is None, "Forged token should be rejected"
83
84
85class TestTokenExpiration:
86 """Test expiration security"""
87
88 def test_expired_token_rejected(self):
89 """Should reject expired token"""
90 token = create_session('42', ttl=1)
91 time.sleep(1.1)
92
93 user_id = get_session(token)
94 assert user_id is None, "Expired token should be rejected"
95
96 def test_cannot_extend_expiration_by_tampering(self):
97 """Should not allow extending expiration by modifying token"""
98 token = create_session('42', ttl=1)
99 payload, sig = token.split('.')
100
101 # Try to extend expiration
102 data = json.loads(base64.urlsafe_b64decode(payload))
103 data['expires'] = int(time.time()) + 9999999
104 new_payload = base64.urlsafe_b64encode(json.dumps(data).encode()).decode()
105
106 tampered = f"{new_payload}.{sig}"
107
108 user_id = get_session(tampered)
109 assert user_id is None, "Modified expiration should be rejected"
110
111 def test_replay_after_expiry_fails(self):
112 """Should not accept token replayed after expiry"""
113 token = create_session('42', ttl=1)
114
115 # Token valid initially
116 user_id = get_session(token)
117 assert user_id == '42'
118
119 # Wait for expiry
120 time.sleep(1.1)
121
122 # Token should now be invalid
123 user_id = get_session(token)
124 assert user_id is None, "Expired token should not be accepted"
125
126
127class TestSessionFixation:
128 """Test protection against session fixation attacks"""
129
130 def test_cannot_inject_token_via_url(self):
131 """Should only accept token from secure cookie, not URL"""
132 # This is a usage pattern test - the library itself doesn't
133 # enforce this, but the spec requires it
134
135 # Create a token
136 token = create_session('42')
137
138 # Token should work when passed correctly
139 user_id = get_session(token)
140 assert user_id == '42'
141
142 # Note: Application must not accept tokens from query params
143 # This test documents the expected usage pattern
144
145 def test_new_token_after_login(self):
146 """Should generate new token after each login"""
147 # Each login should get a fresh token
148 token1 = create_session('42')
149 time.sleep(1.01) # Wait 1+ second for timestamp to change
150 token2 = create_session('42')
151
152 # Tokens should be different (includes timestamp)
153 assert token1 != token2, "Each login should generate unique token"
154
155 # Both should be valid
156 assert get_session(token1) == '42'
157 assert get_session(token2) == '42'
158
159
160class TestPrivilegeEscalation:
161 """Test protection against privilege escalation"""
162
163 def test_cannot_change_user_id(self):
164 """Should not allow changing user_id in token"""
165 token = create_session('42')
166 payload, sig = token.split('.')
167
168 # Try to change user_id from 42 to 999
169 data = json.loads(base64.urlsafe_b64decode(payload))
170 data['user_id'] = '999'
171 new_payload = base64.urlsafe_b64encode(json.dumps(data).encode()).decode()
172
173 tampered = f"{new_payload}.{sig}"
174 user_id = get_session(tampered)
175
176 assert user_id is None, "Cannot escalate to different user"
177
178 def test_cannot_add_fields_to_token(self):
179 """Should not allow adding fields to token"""
180 token = create_session('42')
181 payload, sig = token.split('.')
182
183 # Try to add 'admin' field
184 data = json.loads(base64.urlsafe_b64decode(payload))
185 data['admin'] = True
186 new_payload = base64.urlsafe_b64encode(json.dumps(data).encode()).decode()
187
188 tampered = f"{new_payload}.{sig}"
189 user_id = get_session(tampered)
190
191 assert user_id is None, "Cannot add fields to token"
192
193
194class TestCryptographicStrength:
195 """Test cryptographic properties"""
196
197 def test_signature_length(self):
198 """Should use 256-bit (64 hex chars) signature"""
199 token = create_session('42')
200 payload, sig = token.split('.')
201
202 # HMAC-SHA256 produces 64 hex characters
203 assert len(sig) == 64, f"Signature should be 64 chars, got {len(sig)}"
204 assert all(c in '0123456789abcdef' for c in sig), "Signature should be hex"
205
206 def test_tokens_appear_random(self):
207 """Should generate tokens that appear random"""
208 tokens = []
209 for i in range(10):
210 # Use different user IDs to ensure uniqueness
211 # (tokens generated in same second will have same timestamp)
212 tokens.append(create_session(f'user_{i}'))
213
214 # All should be unique (different user IDs)
215 assert len(set(tokens)) == len(tokens), "Tokens should be unique"
216
217 def test_secret_key_requirement(self):
218 """Should use SECRET_KEY from environment"""
219 import dbbasic_sessions
220
221 # Check that default secret key is warning value
222 default_secret = dbbasic_sessions.SECRET
223
224 # Should have a value (even if default warning)
225 assert default_secret is not None
226 assert len(default_secret) > 0
227
228 def test_payload_is_visible_but_signed(self):
229 """Payload should be readable but tamper-proof"""
230 token = create_session('42')
231 payload, sig = token.split('.')
232
233 # Payload can be decoded (it's base64, not encrypted)
234 data = json.loads(base64.urlsafe_b64decode(payload))
235
236 assert data['user_id'] == '42'
237 assert 'expires' in data
238
239 # But cannot be modified without breaking signature
240 data['user_id'] = '999'
241 new_payload = base64.urlsafe_b64encode(json.dumps(data).encode()).decode()
242 tampered = f"{new_payload}.{sig}"
243
244 assert get_session(tampered) is None
245
246
247class TestErrorHandling:
248 """Test security of error handling"""
249
250 def test_errors_dont_leak_information(self):
251 """Should return None for all errors, not reveal details"""
252 invalid_tokens = [
253 'invalid',
254 'payload.badsig',
255 'bad-base64.sig',
256 '',
257 None,
258 'a.b.c.d', # Too many parts
259 ]
260
261 for token in invalid_tokens:
262 user_id = get_session(token)
263 assert user_id is None, f"Should return None for: {token}"
264
265 def test_no_exception_on_invalid_input(self):
266 """Should not raise exceptions for invalid input"""
267 invalid_inputs = [
268 'invalid',
269 '',
270 None,
271 'a' * 10000, # Very long
272 '\x00\x01\x02', # Binary
273 ]
274
275 for inp in invalid_inputs:
276 try:
277 user_id = get_session(inp)
278 assert user_id is None
279 except Exception as e:
280 pytest.fail(f"Should not raise exception for {inp}: {e}")
281
282
283class TestSecretKeyManagement:
284 """Test secret key security"""
285
286 def test_changing_secret_invalidates_tokens(self):
287 """Should invalidate all tokens when secret changes"""
288 import dbbasic_sessions
289
290 # Save original secret
291 original_secret = dbbasic_sessions.SECRET
292
293 try:
294 # Create token with original secret
295 dbbasic_sessions.SECRET = 'secret1'
296 token = create_session('42')
297
298 # Verify with same secret
299 user_id = get_session(token)
300 assert user_id == '42'
301
302 # Change secret
303 dbbasic_sessions.SECRET = 'secret2'
304
305 # Token should now be invalid
306 user_id = get_session(token)
307 assert user_id is None, "Token should be invalid after secret change"
308
309 finally:
310 # Restore original secret
311 dbbasic_sessions.SECRET = original_secret
312
313 def test_default_secret_warning(self):
314 """Should have clear warning in default secret"""
315 import dbbasic_sessions
316
317 # If using default secret, it should contain warning
318 if os.getenv('SECRET_KEY') is None:
319 default = dbbasic_sessions.SECRET
320 assert 'CHANGE' in default or 'PRODUCTION' in default, \
321 "Default secret should warn user to change it"