import unittest from unittest.mock import MagicMock, patch from app.belki.image_host import MAX_MIRRORED_IMAGE_BYTES, ImageHostClient, ImageHostError, ImageStoreClient, detect_raster_image_type as detect_mirrored_image_type from app.main import (ADMIN_SESSION_TTL_SECONDS, MAX_ADMIN_AUTH_ATTEMPTS, MAX_ADMIN_SESSIONS, MAX_CONCURRENT_ADMIN_UPDATES, MAX_CONCURRENT_REQUESTS, MAX_ISSUED_WEB_UPLOAD_URLS, MAX_JSON_BODY_BYTES, REQUEST_READ_TIMEOUT_SECONDS, ADMIN_AUTH_WINDOW_SECONDS, BelkiHTTPServer, Handler, _ADMIN_AUTH_ATTEMPTS, _ADMIN_SESSIONS, _ISSUED_WEB_UPLOAD_URLS, admin_auth_rate_limit_key, admin_session_authorized, allow_admin_auth_attempt, acquire_admin_update_slot, clear_admin_auth_attempts, detect_raster_image_type, forget_admin_session, remember_admin_session, remember_issued_web_upload, release_admin_update_slot, safe_upload_name, validate_web_attachments, validate_web_report_attachments, WEB_UPLOAD_URL_TTL_SECONDS) from app.belki.api import ApiError class ImageHostClientTests(unittest.TestCase): def test_web_report_screenshots_are_required_only_for_inspections(self) -> None: with self.assertRaisesRegex(ApiError, "осмотра"): validate_web_report_attachments({"mode": "inspection", "attachments": []}) self.assertEqual(validate_web_report_attachments({"mode": "coaching", "attachments": []}), []) def test_upload_input_helpers_accept_only_supported_raster_signatures(self) -> None: self.assertEqual(detect_raster_image_type(b"\x89PNG\r\n\x1a\ncontent"), "image/png") self.assertEqual(detect_raster_image_type(b"\xff\xd8\xffcontent"), "image/jpeg") self.assertEqual(detect_raster_image_type(b"RIFF\x00\x00\x00\x00WEBPcontent"), "image/webp") self.assertIsNone(detect_raster_image_type(b"")) self.assertEqual(safe_upload_name("../../report.png", "image/png"), "report.png") self.assertEqual(safe_upload_name("", "image/webp"), "screenshot.webp") self.assertEqual(MAX_JSON_BODY_BYTES, 20 * 1024 * 1024) def test_web_attachments_must_come_from_image_host_upload(self) -> None: _ISSUED_WEB_UPLOAD_URLS.clear() remember_issued_web_upload("https://img.nyan404.ru/photo/known.jpg", now=100) self.assertEqual( validate_web_attachments([{"type": "photo", "url": "https://img.nyan404.ru/photo/known.jpg"}], now=100), [{"type": "photo", "url": "https://img.nyan404.ru/photo/known.jpg"}], ) with self.assertRaisesRegex(ApiError, "через форму Белок"): validate_web_attachments([{"type": "photo", "url": "http://127.0.0.1:8080/private"}], now=100) def test_web_upload_url_authorization_expires(self) -> None: _ISSUED_WEB_UPLOAD_URLS.clear() url = "https://img.nyan404.ru/photo/temporary.jpg" remember_issued_web_upload(url, now=100) with self.assertRaisesRegex(ApiError, "через форму Белок"): validate_web_attachments([{"type": "photo", "url": url}], now=100 + WEB_UPLOAD_URL_TTL_SECONDS) self.assertNotIn(url, _ISSUED_WEB_UPLOAD_URLS) def test_web_upload_url_authorization_has_a_fixed_capacity(self) -> None: _ISSUED_WEB_UPLOAD_URLS.clear() for index in range(MAX_ISSUED_WEB_UPLOAD_URLS + 1): remember_issued_web_upload(f"https://img.nyan404.ru/photo/{index}.jpg", now=index) self.assertEqual(len(_ISSUED_WEB_UPLOAD_URLS), MAX_ISSUED_WEB_UPLOAD_URLS) self.assertNotIn("https://img.nyan404.ru/photo/0.jpg", _ISSUED_WEB_UPLOAD_URLS) def test_http_server_limits_read_time_and_concurrent_requests(self) -> None: server = BelkiHTTPServer(("127.0.0.1", 0), Handler) try: self.assertEqual(REQUEST_READ_TIMEOUT_SECONDS, 15) self.assertEqual(MAX_CONCURRENT_REQUESTS, 32) finally: server.server_close() def test_admin_login_attempts_are_limited_per_source(self) -> None: _ADMIN_AUTH_ATTEMPTS.clear() for _ in range(MAX_ADMIN_AUTH_ATTEMPTS): self.assertTrue(allow_admin_auth_attempt("192.0.2.1", now=100)) self.assertFalse(allow_admin_auth_attempt("192.0.2.1", now=100)) self.assertTrue(allow_admin_auth_attempt("192.0.2.1", now=100 + ADMIN_AUTH_WINDOW_SECONDS)) clear_admin_auth_attempts("192.0.2.1") self.assertNotIn("192.0.2.1", _ADMIN_AUTH_ATTEMPTS) def test_admin_auth_rate_limit_skips_only_configured_proxy_peers(self) -> None: from ipaddress import ip_network trusted = (ip_network("10.42.3.0/24"),) self.assertEqual( admin_auth_rate_limit_key("10.42.3.58", exempt_proxy_networks=trusted), None, ) self.assertEqual( admin_auth_rate_limit_key("10.42.4.58", exempt_proxy_networks=trusted), "10.42.4.58", ) self.assertEqual( admin_auth_rate_limit_key("192.0.2.44", exempt_proxy_networks=trusted), "192.0.2.44", ) def test_admin_sessions_expire_and_have_a_fixed_capacity(self) -> None: _ADMIN_SESSIONS.clear() remember_admin_session("active", now=100) self.assertTrue(admin_session_authorized("active", now=100)) self.assertFalse(admin_session_authorized("active", now=100 + ADMIN_SESSION_TTL_SECONDS)) for index in range(MAX_ADMIN_SESSIONS + 1): remember_admin_session(f"token-{index}", now=index) self.assertEqual(len(_ADMIN_SESSIONS), MAX_ADMIN_SESSIONS) self.assertNotIn("token-0", _ADMIN_SESSIONS) forget_admin_session("token-1") self.assertNotIn("token-1", _ADMIN_SESSIONS) def test_admin_update_connections_have_a_separate_bounded_pool(self) -> None: acquired = [acquire_admin_update_slot() for _ in range(MAX_CONCURRENT_ADMIN_UPDATES)] try: self.assertTrue(all(acquired)) self.assertFalse(acquire_admin_update_slot()) finally: for slot in acquired: if slot: release_admin_update_slot() def test_default_client_requires_private_storage_settings(self) -> None: with patch.dict("os.environ", {}, clear=True): with self.assertRaisesRegex(ImageHostError, "not configured"): next(ImageStoreClient()._clients()) def test_upload_uses_private_storage_and_returns_belki_url(self) -> None: client = ImageStoreClient(endpoints="minio-a:9000", access_key="access", secret_key="secret", bucket="belki-images", public_url="https://cat.example.test") minio = MagicMock() with patch.object(client, "_clients", return_value=iter([minio])): url = client.upload_bytes(b"\x89PNG\r\n\x1a\nimage", "screenshot.png", "image/png") self.assertRegex(str(url), r"^https://cat\.example\.test/api/images/[a-f0-9]{32}\.png$") minio.put_object.assert_called_once() self.assertEqual(minio.put_object.call_args.args[:2], ("belki-images", str(url).rsplit("/", 1)[1])) def test_upload_fails_over_to_another_minio_node(self) -> None: client = ImageStoreClient(endpoints="minio-a:9000,minio-b:9000", access_key="access", secret_key="secret", public_url="https://cat.example.test") unavailable, healthy = MagicMock(), MagicMock() unavailable.put_object.side_effect = OSError("network unavailable") with patch.object(client, "_clients", return_value=iter([unavailable, healthy])): url = client.upload_bytes(b"\xff\xd8\xffimage", "screenshot.jpg") self.assertTrue(str(url).endswith(".jpg")) unavailable.put_object.assert_called_once() healthy.put_object.assert_called_once() def test_mirror_stops_before_reading_an_oversized_vk_image(self) -> None: client = ImageHostClient(endpoints="minio:9000", access_key="access", secret_key="secret", public_url="https://cat.example.test") response = MagicMock() response.__enter__.return_value = response response.headers.get.side_effect = lambda name: str(MAX_MIRRORED_IMAGE_BYTES + 1) if name == "Content-Length" else None with patch("app.belki.image_host.urlopen", return_value=response): with self.assertRaisesRegex(ImageHostError, "too large"): client.mirror({"url": "https://vk.example.test/photo.jpg"}) response.read.assert_not_called() def test_mirror_reads_at_most_the_configured_limit_plus_sentinel(self) -> None: client = ImageHostClient(endpoints="minio:9000", access_key="access", secret_key="secret", public_url="https://cat.example.test") response = MagicMock() response.__enter__.return_value = response response.headers.get.return_value = None response.read.return_value = b"\x89PNG\r\n\x1a\nimage" with patch("app.belki.image_host.urlopen", return_value=response), patch.object(client, "upload_bytes", return_value="https://cat.example.test/api/images/a.jpg"): client.mirror({"url": "https://vk.example.test/photo.jpg", "owner_id": 1, "id": 2}) response.read.assert_called_once_with(MAX_MIRRORED_IMAGE_BYTES + 1) def test_mirror_rejects_non_image_bytes_even_with_an_image_content_type(self) -> None: client = ImageHostClient(endpoints="minio:9000", access_key="access", secret_key="secret", public_url="https://cat.example.test") response = MagicMock() response.__enter__.return_value = response response.headers.get.return_value = None response.headers.get_content_type.return_value = "image/jpeg" response.read.return_value = b"not an image" with patch("app.belki.image_host.urlopen", return_value=response): with self.assertRaisesRegex(ImageHostError, "not a supported"): client.mirror({"url": "https://vk.example.test/photo.jpg"}) self.assertEqual(detect_mirrored_image_type(b"RIFF\x00\x00\x00\x00WEBPimage"), "image/webp") if __name__ == "__main__": unittest.main() """Image-host and HTTP security regression tests."""