Files
mtusi2026lab7/tests/test_security_primitives.py
T
2026-11-04 19:22:35 +03:00

55 lines
2.2 KiB
Python

import base64
import hashlib
import unittest
from unittest.mock import patch
from src.security import (
PasswordHashCapacityError,
allowed_client_identity,
hash_password,
password_hash_needs_upgrade,
verify_password,
)
class PasswordHashTests(unittest.TestCase):
def test_argon2id_verifies_unicode_password(self):
encoded = hash_password("корректный-password-123")
self.assertTrue(encoded.startswith("$argon2id$"))
self.assertIn("m=19456,t=2,p=1", encoded)
self.assertTrue(verify_password("корректный-password-123", encoded))
self.assertFalse(verify_password("другой-password-123", encoded))
self.assertFalse(password_hash_needs_upgrade(encoded))
oversized = "$argon2id$v=19$m=999999,t=2,p=1$c2FsdA$ZGlnaWVzdA"
self.assertFalse(verify_password("attacker-password-123", oversized))
def test_legacy_scrypt_hash_is_verified_and_marked_for_upgrade(self):
password = "legacy-password-123"
salt = b"lab6-test-salt!!"
digest = hashlib.scrypt(
password.encode(), salt=salt, n=32768, r=8, p=1, dklen=32, maxmem=64 * 1024 * 1024
)
stored = "scrypt$32768$8$1${}${}".format(
base64.urlsafe_b64encode(salt).decode(),
base64.urlsafe_b64encode(digest).decode(),
)
self.assertTrue(verify_password(password, stored))
self.assertTrue(password_hash_needs_upgrade(stored))
def test_only_lb_service_identity_is_authorized(self):
trusted = {"subjectAltName": [("URI", "spiffe://mtusi2026lab7/load-balancer")]}
other = {"subjectAltName": [("URI", "spiffe://mtusi2026lab7/other-service")]}
self.assertTrue(allowed_client_identity(trusted))
self.assertFalse(allowed_client_identity(other))
self.assertFalse(allowed_client_identity({}))
def test_password_hash_capacity_fails_fast(self):
with patch("src.security._PASSWORD_HASH_SLOTS") as slots:
slots.acquire.return_value = False
with self.assertRaises(PasswordHashCapacityError):
verify_password("password", "$argon2id$malformed")
if __name__ == "__main__":
unittest.main()