From 1f9e250c6049dd2579e28b757ec1ea23c7af749d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=B0=D0=BA=D1=81=D0=B8=D0=BC=20=D0=A8=D0=B5=D0=BF?= =?UTF-8?q?=D1=82=D1=83=D0=BD=D0=BE=D0=B2?= Date: Fri, 16 Oct 2026 11:44:19 +0300 Subject: [PATCH] lab3: cursor fix --- evidence/local_cursor_check.txt | 10 ++++++++++ src/main.py | 6 +++++- student-tests/checks.py | 30 ++++++++++++++++++++++++++++-- 3 files changed, 43 insertions(+), 3 deletions(-) create mode 100644 evidence/local_cursor_check.txt diff --git a/evidence/local_cursor_check.txt b/evidence/local_cursor_check.txt new file mode 100644 index 0000000..adb4fde --- /dev/null +++ b/evidence/local_cursor_check.txt @@ -0,0 +1,10 @@ +python3 student-tests/test_api.py --base-url "http://localhost:8080" +PASS: malformed JSON/media type, duplicate username, blank message, outsider access, pagination +PASS: 10 clients created exactly 100 unique messages +python3 student-tests/checks.py --base-url "http://localhost:8080" +PASS: registration race, invalid input, cursor scope/types on two API, read-after-write, logout +python3 student-tests/idempotency.py --base-url "http://localhost:8080" +PASS: shared idempotency, scope, conflict and auth on replay +docker exec "$(docker compose ps --status running -q api | head -n 1)" python student-tests/database.py +PASS: rollback of chat + members; migration reapplied twice +PASS: persisted key expiry, atomic message/result rollback diff --git a/src/main.py b/src/main.py index 7b6c172..f70818e 100644 --- a/src/main.py +++ b/src/main.py @@ -329,7 +329,11 @@ def decode_cursor(cursor: str, expected_scope: str) -> tuple[datetime, uuid.UUID raise ValueError padded = cursor + "=" * (-len(cursor) % 4) payload = json.loads(base64.b64decode(padded.encode(), altchars=b"-_", validate=True).decode()) - if set(payload) != {"scope", "created_at", "id"} or payload["scope"] != expected_scope: + if not isinstance(payload, dict) or set(payload) != {"scope", "created_at", "id"}: + raise ValueError + if payload["scope"] != expected_scope: + raise ValueError + if not isinstance(payload["created_at"], str) or not isinstance(payload["id"], str): raise ValueError created_at = datetime.fromisoformat(payload["created_at"].replace("Z", "+00:00")) item_id = uuid.UUID(payload["id"]) diff --git a/student-tests/checks.py b/student-tests/checks.py index 7bd8b0e..57c5347 100644 --- a/student-tests/checks.py +++ b/student-tests/checks.py @@ -1,15 +1,39 @@ """Дополнения к публичному smoke. Не печатает и не сохраняет tokens.""" +import base64 import concurrent.futures import json import sys import time from pathlib import Path from uuid import uuid4 +from urllib.parse import quote sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests')) from client import Client, arguments, check, run +def check_cursor_types(c, actor, path, cursor, schema): + check(bool(cursor), 'test requires a real pagination cursor') + payload = json.loads(base64.urlsafe_b64decode(cursor + '=' * (-len(cursor) % 4))) + c.call('GET', path + '?cursor=' + quote(cursor, safe=''), actor=actor, schema=schema) + invalid = [] + for field in ['created_at', 'id']: + for value in [1, 1.5, None, True, [], {}, '', 'invalid']: + invalid.append({**payload, field: value}) + invalid.extend([None, 1, True, [], 'cursor']) + for value in invalid: + encoded = base64.urlsafe_b64encode(json.dumps(value).encode()).decode().rstrip('=') + instances = set() + # Проверяем один и тот же cursor на обеих API за round-robin LB. + for _ in range(8): + response = c.call('GET', path + '?cursor=' + quote(encoded, safe=''), 400, actor=actor) + check(response['json']['error']['code'] == 'invalid_request', 'incorrect cursor error code') + instances.add(response['headers']['X-Instance-Id']) + if len(instances) >= 2: + break + check(len(instances) >= 2, 'invalid cursor was not checked on two API instances') + + def main(): def configure(p): p.add_argument('--expiry', action='store_true', help='API must run with TTL=2') @@ -50,14 +74,16 @@ def main(): page = c.call('GET', path + '/messages?limit=1', actor=alice, schema='MessagePage')['json'] other = c.call('POST', '/api/v1/chats', 201, actor=alice, body={'title': 'other', 'member_ids': [alice['id']]}, schema='Chat')['json'] - from urllib.parse import quote c.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' + quote(page['next_cursor'], safe=''), 400, actor=alice) + check_cursor_types(c, alice, path + '/messages', page['next_cursor'], 'MessagePage') + chats = c.call('GET', '/api/v1/chats?limit=1', actor=alice, schema='ChatPage')['json'] + check_cursor_types(c, alice, '/api/v1/chats', chats['next_cursor'], 'ChatPage') history = c.call('GET', path + '/messages', actor=bob, schema='MessagePage')['json']['items'] check(len(history) == 3 and history[-1]['text'] == 'read-after-write 2', 'read-after-write failed') c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice) c.call('GET', '/api/v1/users/me', 401, actor=alice) - print('PASS: registration race, invalid input, cursor scope, read-after-write, logout') + print('PASS: registration race, invalid input, cursor scope/types on two API, read-after-write, logout') if __name__ == '__main__':