"""Only server-allowlisted accounts can browse sanitized request logs.""" import uuid from datetime import UTC, datetime, timedelta import pytest from sqlalchemy import select from app.core.config import get_settings from app.core.database import get_session_factory from app.modules.api_audit.models import ApiRequestLog from tests.factories import make_account BASE = '/v1/admin/api-logs' @pytest.fixture async def operator(monkeypatch): user = await make_account() monkeypatch.setattr(get_settings(), 'api_audit_reader_account_ids', [user['id']]) return user async def rows(): async with get_session_factory()() as db: return list(await db.scalars(select(ApiRequestLog).order_by(ApiRequestLog.created_at))) async def test_access_denied_by_default_and_for_coach(client, monkeypatch): monkeypatch.setattr(get_settings(), 'api_audit_reader_account_ids', []) assert (await client.get(BASE)).status_code == 401 for role in ('player', 'coach'): user = await make_account(role=role) assert (await client.get(BASE, headers=user['headers'])).status_code == 403 assert (await client.get(f'{BASE}/{uuid.uuid4()}', headers=user['headers'])).status_code == 403 async def test_list_and_detail_with_no_recursive_payloads(client, operator): response = await client.post('/v1/auth/login', json={'email': 'no@example.com', 'password': 'private-password'}) entry = (await rows())[-1] h = operator['headers'] listed = await client.get(BASE, headers=h, params={'request_id': response.headers['x-request-id']}) assert listed.status_code == 200 assert listed.headers['cache-control'] == 'no-store' item = listed.json()['items'][0] assert item['id'] == str(entry.id) and item['status_code'] == response.status_code assert 'request_payload' not in item and 'response_payload' not in item detail = await client.get(f'{BASE}/{entry.id}', headers=h) assert detail.status_code == 200 and detail.headers['cache-control'] == 'no-store' assert detail.json()['request_payload']['body']['password'] == '[REDACTED]' assert detail.json()['response_payload']['body'] == response.json() assert 'private-password' not in detail.text read_logs = [r for r in await rows() if r.path.startswith(BASE)] assert len(read_logs) == 2 assert all(r.account_id == operator['id'] and r.status_code == 200 for r in read_logs) assert all(r.response_payload['capture_status'] == 'omitted_audit_read' for r in read_logs) assert all(r.response_payload['body'] is None for r in read_logs) async def test_cursor_pagination_is_stable_with_timestamp_ties(client, operator): for _ in range(3): await client.get('/healthz', headers={'X-Request-Id': 'page-test'}) original = await rows() async with get_session_factory()() as db: await db.execute(ApiRequestLog.__table__.update().values(created_at=datetime.now(UTC))) await db.commit() params = {'request_id': 'page-test', 'limit': 2} first = (await client.get(BASE, headers=operator['headers'], params=params)).json() assert len(first['items']) == 2 and first['next_cursor'] second = (await client.get(BASE, headers=operator['headers'], params={**params, 'cursor': first['next_cursor']})).json() assert len(second['items']) == 1 and second['next_cursor'] is None ids = [r['id'] for page in (first, second) for r in page['items']] assert len(set(ids)) == 3 and set(ids) == {str(r.id) for r in original} async def test_filters(client, operator): from tests.integration.test_swing_reports import PAYLOAD, make_session, url sid = await make_session(operator['id']) response = await client.post(url(sid), json=PAYLOAD, headers=operator['headers']) assert response.status_code == 200 params = {'session_id': str(sid), 'analysis_id': PAYLOAD['analysis_id'], 'account_id': str(operator['id']), 'status_code': 200, 'method': 'POST', 'route': '/v1/sessions/{session_id}/swing-report', 'since': (datetime.now(UTC) - timedelta(hours=1)).isoformat(), 'until': (datetime.now(UTC) + timedelta(hours=1)).isoformat()} listed = await client.get(BASE, headers=operator['headers'], params=params) assert listed.status_code == 200 and len(listed.json()['items']) == 1 params['status_code'] = 422 assert (await client.get(BASE, headers=operator['headers'], params=params)).json()['items'] == [] @pytest.mark.parametrize('params', [ {'limit': 0}, {'limit': 201}, {'status_code': 600}, {'session_id': 'bad'}, {'cursor': 'bad'}, {'since': '2026-10-29T00:00:00'}, {'since': '2026-10-29T00:00:00Z', 'until': '2026-10-28T00:00:00Z'}, ]) async def test_invalid_filters(client, operator, params): assert (await client.get(BASE, headers=operator['headers'], params=params)).status_code == 400 async def test_missing_record(client, operator): assert (await client.get(f'{BASE}/{uuid.uuid4()}', headers=operator['headers'])).status_code == 404