"""Изолированные проверки ASGI-лимитов и реального пула Argon2 в образе API.""" import asyncio import errno import json import os from pathlib import Path from tempfile import TemporaryDirectory import threading import time from unittest.mock import patch from src.core import security from src.core.request_limits import RequestLimitsMiddleware from src.core.settings import settings def scope(path='/api/v1/users', headers=()): return {'type': 'http', 'asgi': {'version': '3.0'}, 'http_version': '1.1', 'method': 'POST', 'scheme': 'http', 'path': path, 'raw_path': path.encode(), 'query_string': b'', 'headers': [(b'content-type', b'application/json'), *headers], 'state': {'request_id': 'limit-test'}, 'server': ('localhost', 80), 'client': ('localhost', 1)} async def invoke(app, messages=(), path='/api/v1/users', headers=(), delay=0): sent = [] pending = iter(messages or [{'type': 'http.request', 'body': b'{}', 'more_body': False}]) async def receive(): if delay: await asyncio.sleep(delay) return next(pending) async def send(message): sent.append(message) await app(scope(path, headers), receive, send) if not sent: return None status = next(m['status'] for m in sent if m['type'] == 'http.response.start') data = json.loads(b''.join(m.get('body', b'') for m in sent if m['type'] == 'http.response.body')) if status >= 400: assert data['error']['request_id'] == 'limit-test' return status, data async def main(): assert os.geteuid() != 0, 'API работает от root' status = Path('/proc/self/status').read_text() assert 'NoNewPrivs:\t1' in status assert 'CapEff:\t0000000000000000' in status probe = Path('/app/.production-write-probe') try: probe.write_text('probe') except OSError as error: assert error.errno == errno.EROFS, error.errno else: probe.unlink() raise AssertionError('Корневая файловая система API доступна для записи') with TemporaryDirectory() as directory: Path(directory, 'probe').write_text('temporary') print('PASS: non-root, read-only rootfs, пустые capabilities, no-new-privileges; /tmp доступен') called = 0 async def endpoint(scope, receive, send): nonlocal called called += 1 message = await receive() await send({'type': 'http.response.start', 'status': 200, 'headers': []}) await send({'type': 'http.response.body', 'body': json.dumps({'bytes': len(message['body'])}).encode()}) app = RequestLimitsMiddleware(endpoint) maximum = settings.http_max_body_bytes assert (await invoke(app, headers=[(b'content-length', str(maximum+1).encode())]))[0] == 413 assert called == 0 chunks = [{'type': 'http.request', 'body': b' ' * 40000, 'more_body': True}, {'type': 'http.request', 'body': b' ' * 40000, 'more_body': False}] assert (await invoke(app, messages=chunks))[0] == 413 assert (await invoke(app, messages=chunks, headers=[(b'content-length', b'1')]))[0] == 413 assert (await invoke(app, headers=[(b'content-length', b'-1')]))[0] == 400 with patch.object(settings, 'http_body_timeout_seconds', 0.02): assert (await invoke(app, delay=0.1))[0] == 408 assert await invoke(app, messages=[{'type': 'http.disconnect'}]) is None assert called == 0 assert (await invoke(app))[0] == 200 assert app.limiter.borrowed_tokens == 0 print('PASS: Content-Length/chunked/ложный размер, timeout, disconnect; слот всегда освобождается') gate = asyncio.Event() entered = asyncio.Event() active = 0 async def blocked(scope, receive, send): nonlocal active if scope['path'].startswith('/api/'): active += 1 if active == 2: entered.set() await gate.wait() await endpoint(scope, receive, send) with patch.object(settings, 'http_concurrency_limit', 2): limited = RequestLimitsMiddleware(blocked) tasks = [asyncio.create_task(invoke(limited)) for _ in range(2)] try: await asyncio.wait_for(entered.wait(), 1) assert (await invoke(limited))[0] == 503 assert (await invoke(limited, path='/health/live'))[0] == 200 tasks[0].cancel() await asyncio.gather(tasks[0], return_exceptions=True) assert limited.limiter.borrowed_tokens == 1 gate.set() assert (await tasks[1])[0] == 200 assert (await invoke(limited))[0] == 200 finally: gate.set() for task in tasks: task.cancel() await asyncio.gather(*tasks, return_exceptions=True) assert limited.limiter.borrowed_tokens == 0 print('PASS: перегрузка=503 в общем JSON, health доступен, отмена запроса не теряет слот') lock = threading.Lock() active = peak = 0 def slow_hash(password): nonlocal active, peak with lock: active += 1 peak = max(peak, active) try: time.sleep(0.03) return 'hashed-' + password finally: with lock: active -= 1 count = settings.password_hash_concurrency * 4 with patch.object(security, 'hash_password', slow_hash): result = await asyncio.gather(*(security.hash_password_async(str(i)) for i in range(count))) assert result == ['hashed-' + str(i) for i in range(count)] assert peak == settings.password_hash_concurrency, peak assert security.password_limiter.borrowed_tokens == 0 print('PASS: очередь Argon2 соблюдает лимит параллелизма; результаты не смешиваются') asyncio.run(main())