test: adapt HTTP checks to persistent Bearer sessions

This commit is contained in:
2026-11-07 07:59:56 +03:00
parent 064421e6ee
commit 2f0a8672be
6 changed files with 155 additions and 16 deletions
+1 -1
View File
@@ -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)",)
+2 -5
View File
@@ -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
+4 -2
View File
@@ -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
+21 -5
View File
@@ -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):
+13 -3
View File
@@ -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,
+114
View File
@@ -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"'