From 2f0a8672be67af9e62d2693c3df9bd683fcdae57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=B0=D1=81=D0=BB=D0=BE=D0=B2?= Date: Sat, 7 Nov 2026 07:59:56 +0300 Subject: [PATCH] test: adapt HTTP checks to persistent Bearer sessions --- Makefile | 2 +- compose.yaml | 7 +- src/repository.py | 6 +- student-tests/conftest.py | 26 ++++++-- student-tests/test_api.py | 16 ++++- student-tests/test_sessions.py | 114 +++++++++++++++++++++++++++++++++ 6 files changed, 155 insertions(+), 16 deletions(-) create mode 100644 student-tests/test_sessions.py diff --git a/Makefile b/Makefile index 2a1e3f4..ac0a35c 100644 --- a/Makefile +++ b/Makefile @@ -1,5 +1,5 @@ PYTHON ?= python3 -BASE_URL ?= http://localhost:8080 +BASE_URL ?= http://127.0.0.1:8082 CA_FILE ?= ACTION_SCRIPT ?= TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) diff --git a/compose.yaml b/compose.yaml index 90ff7c2..cff40ee 100644 --- a/compose.yaml +++ b/compose.yaml @@ -35,10 +35,7 @@ services: memswap_limit: 128m migrate: image: ${API_IMAGE:-mtusi-messenger:lab2} - build: - context: . - args: - VCS_REF: ${VCS_REF:-unknown} + pull_policy: never command: [python, -m, src.migrate] environment: DATABASE_URL_FILE: /run/secrets/database_url @@ -72,7 +69,7 @@ services: memswap_limit: 512m pids_limit: 128 read_only: true - tmpfs: [/tmp:rw,noexec,nosuid,size=16m] + tmpfs: ["/tmp:rw,noexec,nosuid,size=16m"] cap_drop: [ALL] security_opt: [no-new-privileges:true] stop_grace_period: 10s diff --git a/src/repository.py b/src/repository.py index f08f17d..632353c 100644 --- a/src/repository.py +++ b/src/repository.py @@ -150,7 +150,8 @@ class PostgresRepository: try: with self.database.connection() as conn: conn.execute( - "INSERT INTO messages(id,chat_id,sender_id,text,created_at) " + "INSERT INTO messages(id,chat_id,sender_id," + "text,created_at) " "VALUES(%s,%s,%s,%s,%s)", ( message.id, @@ -174,7 +175,8 @@ class PostgresRepository: with self.database.connection() as conn: rows = conn.execute( "SELECT c.id,c.title,c.created_at,ARRAY(SELECT user_id " - "FROM members WHERE chat_id=c.id ORDER BY position) member_ids " + "FROM members WHERE chat_id=c.id " + "ORDER BY position) member_ids " "FROM chats c JOIN members own ON own.chat_id=c.id " "WHERE own.user_id=%s " + condition diff --git a/student-tests/conftest.py b/student-tests/conftest.py index 64d1b17..2b26ba1 100644 --- a/student-tests/conftest.py +++ b/student-tests/conftest.py @@ -10,7 +10,9 @@ from jsonschema import Draft202012Validator, FormatChecker CONTRACT = json.loads( (Path(__file__).parents[1] / "contracts/openapi.json").read_text() ) -BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080") +BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8082") +PASSWORD = "Synthetic-Password-๐ŸŒ-123" +TOKENS = {} def check(result: httpx.Response, status: int, schema: str) -> dict: @@ -38,9 +40,23 @@ def check(result: httpx.Response, status: int, schema: str) -> dict: def register(client: httpx.Client, **overrides) -> dict: - data = {"username": "u_" + uuid4().hex[:24], "display_name": "ะะปะธัะฐ ๐ŸŒ"} + data = { + "username": "u_" + uuid4().hex[:24], + "display_name": "ะะปะธัะฐ ๐ŸŒ", + "password": PASSWORD, + } data.update(overrides) - return check(client.post("/api/v1/users", json=data), 201, "User") + user = check(client.post("/api/v1/users", json=data), 201, "User") + session = check( + client.post( + "/api/v1/auth/sessions", + auth=httpx.BasicAuth(data["username"], data["password"]), + ), + 201, + "Session", + ) + TOKENS[user["id"]] = session["token"] + return user @pytest.fixture @@ -62,7 +78,7 @@ def chat(client, actors): return check( client.post( "/api/v1/chats", - headers={"X-User-Id": alice["id"]}, + headers=headers(alice), json={"title": "ะฃั‡ั‘ะฑะฐ ๐ŸŒ", "member_ids": [alice["id"], bob["id"]]}, ), 201, @@ -71,7 +87,7 @@ def chat(client, actors): def headers(actor: dict) -> dict: - return {"X-User-Id": actor["id"]} + return {"Authorization": "Bearer " + TOKENS[actor["id"]]} def history(client, actor, chat_id, limit=7): diff --git a/student-tests/test_api.py b/student-tests/test_api.py index 6551b29..964c142 100644 --- a/student-tests/test_api.py +++ b/student-tests/test_api.py @@ -6,7 +6,7 @@ from uuid import UUID, uuid4 import httpx import pytest -from conftest import BASE_URL, check, headers, history, register +from conftest import BASE_URL, PASSWORD, check, headers, history, register @pytest.mark.parametrize("path", ["/health/live", "/health/ready"]) @@ -54,6 +54,8 @@ def test_identity(client, actors): ], ) def test_invalid_user(client, data): + if isinstance(data, dict): + data = {"password": PASSWORD, **data} check(client.post("/api/v1/users", content=json.dumps(data)), 400, "Error") @@ -72,7 +74,11 @@ def test_duplicate_username(client, actors): check( client.post( "/api/v1/users", - json={"username": actors[0]["username"], "display_name": "B"}, + json={ + "username": actors[0]["username"], + "display_name": "B", + "password": PASSWORD, + }, ), 409, "Error", @@ -383,7 +389,11 @@ def test_registration_race(client): barrier.wait(timeout=15) result = conn.post( "/api/v1/users", - json={"username": username, "display_name": "Test"}, + json={ + "username": username, + "display_name": "Test", + "password": PASSWORD, + }, ) check( result, diff --git a/student-tests/test_sessions.py b/student-tests/test_sessions.py new file mode 100644 index 0000000..78a5ce4 --- /dev/null +++ b/student-tests/test_sessions.py @@ -0,0 +1,114 @@ +from uuid import uuid4 + +import httpx +import pytest +from conftest import PASSWORD, TOKENS, check, headers, register + + +@pytest.mark.parametrize( + "password", ["", "x" * 11, "x" * 129, " " * 12, 42, True, None] +) +def test_password_validation(client, password): + check( + client.post( + "/api/v1/users", + json={ + "username": "pwd_" + uuid4().hex[:20], + "display_name": "Test", + "password": password, + }, + ), + 400, + "Error", + ) + + +def test_full_utf8_password(client): + password = "๐ŸŒ" * 127 + ":" + user = register(client, password=password) + assert ( + check( + client.get("/api/v1/users/me", headers=headers(user)), 200, "User" + ) + == user + ) + + +@pytest.mark.parametrize( + "authorization", [None, "Basic broken", "Bearer unknown", "Basic /w=="] +) +def test_bad_basic(client, authorization): + result = client.post( + "/api/v1/auth/sessions", + headers={"Authorization": authorization} if authorization else {}, + ) + check(result, 401, "Error") + assert ( + result.headers["www-authenticate"] + == 'Basic realm="messenger", charset="UTF-8"' + ) + + +def test_wrong_password_and_unknown_user(client): + user = register(client) + for username in [user["username"], "missing_" + uuid4().hex[:20]]: + result = client.post( + "/api/v1/auth/sessions", + auth=httpx.BasicAuth(username, PASSWORD + "wrong"), + ) + data = check(result, 401, "Error") + assert data["error"]["message"] == "Authentication required" + + +def test_logout_is_not_revived_by_cache(client): + user = register(client) + auth = headers(user) + check(client.get("/api/v1/users/me", headers=auth), 200, "User") + result = client.delete("/api/v1/auth/sessions/current", headers=auth) + assert result.status_code == 204 and result.content == b"" + assert result.headers["x-request-id"] + check(client.get("/api/v1/users/me", headers=auth), 401, "Error") + check( + client.delete("/api/v1/auth/sessions/current", headers=auth), + 401, + "Error", + ) + + +def test_only_current_session_revoked(client): + user = register(client) + another = check( + client.post( + "/api/v1/auth/sessions", + auth=httpx.BasicAuth(user["username"], PASSWORD), + ), + 201, + "Session", + ) + assert another["token"] != TOKENS[user["id"]] + assert len(another["token"]) >= 32 + assert ( + client.delete( + "/api/v1/auth/sessions/current", headers=headers(user) + ).status_code + == 204 + ) + result = client.get( + "/api/v1/users/me", + headers={"Authorization": "Bearer " + another["token"]}, + ) + assert check(result, 200, "User") == user + + +def test_bearer_source_and_ignored_user_header(client, actors): + alice, bob, _ = actors + auth = {**headers(alice), "X-User-Id": bob["id"]} + assert ( + check(client.get("/api/v1/users/me", headers=auth), 200, "User")["id"] + == alice["id"] + ) + result = client.get( + "/api/v1/users/me", auth=httpx.BasicAuth(alice["username"], PASSWORD) + ) + check(result, 401, "Error") + assert result.headers["www-authenticate"] == 'Bearer realm="messenger"'