"""Regression tests for password compatibility and HTTP framing/drain.""" import hashlib import http.client import logging from pathlib import Path import sys import threading import unittest from unittest.mock import patch sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src')) from messenger import security from messenger.config import Config from messenger.server import ApiServer from messenger.validation import require_idempotency_key from messenger.errors import InvalidRequest class IdempotencyValidationTests(unittest.TestCase): def test_key_format(self): for value in ('abc', 'A-Z_0.1:key', 'x' * 128): self.assertEqual(require_idempotency_key(value), value) for value in (None, '', 'x' * 129, 'a b', 'ключ', 'a\n'): with self.assertRaises(InvalidRequest): require_idempotency_key(value) class PasswordTests(unittest.TestCase): @unittest.skipUnless(hasattr(hashlib, 'scrypt'), 'host Python lacks scrypt; run in API image') def test_native_scrypt_is_used_and_can_be_verified(self): encoded = security.hash_password('test-password-123') self.assertTrue(encoded.startswith('scrypt:'), encoded.split(':')[0]) self.assertTrue(security.verify_password('test-password-123', encoded)) def test_password_roundtrip(self): for password in ('test-password-123', 'Я' * 100): hashed = security.hash_password(password) self.assertTrue(security.verify_password(password, hashed)) self.assertFalse(security.verify_password(password + 'x', hashed)) def test_bcrypt_hash_remains_readable_when_scrypt_available(self): import bcrypt encoded = 'bcrypt:' + bcrypt.hashpw(hashlib.sha256(b'test-password-123').digest(), bcrypt.gensalt(4)).decode() with patch.object(security, '_HAS_SCRYPT', True): self.assertTrue(security.verify_password('test-password-123', encoded)) class HTTPTests(unittest.TestCase): def test_persistent_response_has_length_and_instance_id(self): class API: def dispatch(self, request): return 200, {'status': 'ok'} config = Config.from_env({'CURSOR_SECRET': 'shared'}) server = ApiServer(('127.0.0.1', 0), API(), config, logging.getLogger('test'), None) thread = threading.Thread(target=server.serve_forever, daemon=True) thread.start() try: conn = http.client.HTTPConnection(*server.server_address, timeout=1) conn.request('GET', '/health/live') response = conn.getresponse() self.assertIsNotNone(response.getheader('Content-Length')) instance = response.getheader('X-Instance-Id') self.assertTrue(instance) self.assertEqual(response.read(), b'{"status":"ok"}') conn.request('GET', '/health/live') response = conn.getresponse() self.assertEqual(response.getheader('X-Instance-Id'), instance) response.read() conn.close() finally: server.shutdown() server.server_close() thread.join() if __name__ == '__main__': unittest.main()