forked from mtusi2026/mtusi2026lab4
113 lines
4.4 KiB
Python
113 lines
4.4 KiB
Python
"""Own tests for the security helpers and keyset cursors (stdlib unittest)."""
|
|
import base64
|
|
import datetime as dt
|
|
import json
|
|
import sys
|
|
import unittest
|
|
import uuid
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT))
|
|
|
|
from app import main as api
|
|
from app.security import (bearer_token, hash_password, parse_basic,
|
|
token_hash, verify_password)
|
|
|
|
|
|
class PasswordTests(unittest.TestCase):
|
|
def test_kdf_round_trip_and_uniqueness(self):
|
|
first = hash_password("T3st-passphrase-123")
|
|
second = hash_password("T3st-passphrase-123")
|
|
self.assertNotEqual(first, second, "salt must be unique")
|
|
self.assertTrue(first.startswith("scrypt$"))
|
|
self.assertTrue(verify_password("T3st-passphrase-123", first))
|
|
self.assertFalse(verify_password("wrong-password", first))
|
|
|
|
def test_unicode_and_colon_password(self):
|
|
secret = "пароль:с:двоеточием-123"
|
|
stored = hash_password(secret)
|
|
self.assertTrue(verify_password(secret, stored))
|
|
self.assertFalse(verify_password("пароль", stored))
|
|
|
|
|
|
class CredentialTests(unittest.TestCase):
|
|
def test_basic_colon_inside_password(self):
|
|
raw = "u_alice_123:T3st-with:colon-12345"
|
|
header = "Basic " + base64.b64encode(raw.encode()).decode()
|
|
self.assertEqual(parse_basic(header), ("u_alice_123", "T3st-with:colon-12345"))
|
|
|
|
def test_basic_rejects_short_password_and_bad_scheme(self):
|
|
raw = "u_alice_123:short"
|
|
self.assertIsNone(parse_basic("Basic " + base64.b64encode(raw.encode()).decode()))
|
|
self.assertIsNone(parse_basic("Bearer abcdef"))
|
|
|
|
def test_bearer_only(self):
|
|
self.assertEqual(bearer_token("Bearer abc"), "abc")
|
|
self.assertIsNone(bearer_token("Basic abc"))
|
|
self.assertIsNone(bearer_token(None))
|
|
|
|
def test_token_hash_is_stable_and_not_the_token(self):
|
|
token = "s" * 43
|
|
self.assertEqual(token_hash(token), token_hash(token))
|
|
self.assertNotEqual(token_hash(token), token)
|
|
|
|
|
|
class IdempotencyTests(unittest.TestCase):
|
|
def test_key_pattern(self):
|
|
self.assertIsNotNone(api.IDEMPOTENCY_KEY_RE.fullmatch('abc-123.XYZ:9_'))
|
|
self.assertIsNone(api.IDEMPOTENCY_KEY_RE.fullmatch('bad key'))
|
|
self.assertIsNone(api.IDEMPOTENCY_KEY_RE.fullmatch(''))
|
|
|
|
def test_canonical_body_hash_ignores_key_order(self):
|
|
import hashlib
|
|
a = json.dumps({'text': 'Привет'}, sort_keys=True, separators=(',', ':'))
|
|
b = json.dumps({'text': 'Привет'}, separators=(',', ':'))
|
|
self.assertEqual(hashlib.sha256(a.encode()).hexdigest(),
|
|
hashlib.sha256(b.encode()).hexdigest())
|
|
|
|
|
|
class AttachmentTests(unittest.TestCase):
|
|
def test_filename_rejects_path_traversal(self):
|
|
for bad in ('../x.png', 'a/b.png', 'a\\b.png', 'a\x00b', 'a\nb'):
|
|
with self.assertRaises(api.ApiError):
|
|
api.validate_filename(bad)
|
|
self.assertEqual(api.validate_filename('photo.png'), 'photo.png')
|
|
|
|
def test_probe_real_fixture(self):
|
|
from app.images import probe
|
|
data = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
|
content_type, width, height = probe(data)
|
|
self.assertEqual(content_type, 'image/png')
|
|
self.assertGreater(width, 0)
|
|
self.assertGreater(height, 0)
|
|
|
|
def test_probe_rejects_garbage(self):
|
|
from app.images import InvalidImage, probe
|
|
with self.assertRaises(InvalidImage):
|
|
probe(b'not an image at all')
|
|
|
|
|
|
class CursorTests(unittest.TestCase):
|
|
def test_round_trip(self):
|
|
created = dt.datetime(2026, 11, 16, 12, 0, 0, 123456, tzinfo=dt.timezone.utc)
|
|
item_id = uuid.uuid4()
|
|
encoded = api.encode_cursor("messages", "scope-1", created, item_id)
|
|
back_created, back_id = api.decode_cursor(encoded, "messages", "scope-1")
|
|
self.assertEqual(back_created, created)
|
|
self.assertEqual(back_id, item_id)
|
|
|
|
def test_wrong_scope_rejected(self):
|
|
created = dt.datetime.now(dt.timezone.utc)
|
|
encoded = api.encode_cursor("messages", "chat-A", created, uuid.uuid4())
|
|
with self.assertRaises(api.ApiError):
|
|
api.decode_cursor(encoded, "messages", "chat-B")
|
|
|
|
def test_garbage_rejected(self):
|
|
with self.assertRaises(api.ApiError):
|
|
api.decode_cursor("not-a-cursor", "messages", "chat-A")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main(verbosity=2)
|