feat(observability): add bounded OTLP signals, causal jobs and SLO rules

This commit is contained in:
2026-11-20 15:41:53 +03:00
parent 470d9d6f1e
commit 8f3ff33b2d
76 changed files with 9995 additions and 33 deletions
+119
View File
@@ -0,0 +1,119 @@
import json
import os
from pathlib import Path
from uuid import uuid4
import httpx
import pytest
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:8086")
PASSWORD = "Synthetic-Password-🌍-123"
TOKENS = {}
def check(result: httpx.Response, status: int, schema: str) -> dict:
assert result.status_code == status, result.text
assert result.headers["x-request-id"]
assert result.headers["x-instance-id"]
assert result.headers["content-type"].startswith("application/json")
payload = result.json()
spec = {"$ref": f"#/components/schemas/{schema}", **CONTRACT}
Draft202012Validator(spec, format_checker=FormatChecker()).validate(
payload
)
if schema == "Error":
assert payload["error"]["request_id"] == result.headers["x-request-id"]
assert (
payload["error"]["code"]
== {
400: "invalid_request",
401: "unauthorized",
404: "not_found",
409: "conflict",
413: "payload_too_large",
415: "unsupported_media_type",
429: "rate_limited",
500: "internal_error",
503: "unavailable",
}[status]
)
return payload
def register(client: httpx.Client, **overrides) -> dict:
data = {
"username": "u_" + uuid4().hex[:24],
"display_name": "Алиса 🌍",
"password": PASSWORD,
}
data.update(overrides)
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
def client():
with httpx.Client(
base_url=BASE_URL, timeout=15, trust_env=False
) as client:
yield client
@pytest.fixture
def actors(client):
return register(client), register(client), register(client)
@pytest.fixture
def chat(client, actors):
alice, bob, _ = actors
return check(
client.post(
"/api/v1/chats",
headers=headers(alice),
json={"title": "Учёба 🌍", "member_ids": [alice["id"], bob["id"]]},
),
201,
"Chat",
)
def headers(actor: dict) -> dict:
return {
"Authorization": "Bearer " + TOKENS[actor["id"]],
"Idempotency-Key": uuid4().hex,
}
def history(client, actor, chat_id, limit=7):
found, cursor = [], None
while True:
params = {"limit": limit}
if cursor:
params["cursor"] = cursor
page = check(
client.get(
f"/api/v1/chats/{chat_id}/messages",
headers=headers(actor),
params=params,
),
200,
"MessagePage",
)
found.extend(page["items"])
cursor = page["next_cursor"]
if cursor is None:
return found
+412
View File
@@ -0,0 +1,412 @@
import base64
import json
import threading
from concurrent.futures import ThreadPoolExecutor
from uuid import UUID, uuid4
import httpx
import pytest
from conftest import BASE_URL, PASSWORD, check, headers, history, register
@pytest.mark.parametrize("path", ["/health/live", "/health/ready"])
def test_health(client, path):
assert check(client.get(path), 200, "Health") == {"status": "ok"}
@pytest.mark.parametrize(
"value", [None, "not-a-uuid", str(uuid4()), uuid4().hex]
)
def test_identification(client, value):
check(
client.get(
"/api/v1/users/me", headers={"X-User-Id": value} if value else {}
),
401,
"Error",
)
def test_identity(client, actors):
assert (
check(
client.get("/api/v1/users/me", headers=headers(actors[0])),
200,
"User",
)
== actors[0]
)
@pytest.mark.parametrize(
"data",
[
{},
[],
None,
{"username": "ABC", "display_name": "A"},
{"username": "abc\n", "display_name": "A"},
{"username": 123, "display_name": "A"},
{"username": "abc", "display_name": " "},
{"username": "abc", "display_name": "x" * 101},
{"username": "abc", "display_name": "A", "extra": True},
{"username": "abc", "display_name": "\ud800"},
],
)
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")
@pytest.mark.parametrize(
"raw", [b"{", b"NaN", b'{"username":"abc", "display_name":NaN}', b"\xff"]
)
def test_malformed_json(client, raw):
check(client.post("/api/v1/users", content=raw), 400, "Error")
def test_auth_before_json(client):
check(client.post("/api/v1/chats", content=b"{"), 401, "Error")
def test_duplicate_username(client, actors):
check(
client.post(
"/api/v1/users",
json={
"username": actors[0]["username"],
"display_name": "B",
"password": PASSWORD,
},
),
409,
"Error",
)
def test_unicode_codepoints(client, actors, chat):
user = register(client, display_name="🌍" * 100)
assert user["display_name"] == "🌍" * 100
text = "🌍" * 4000
result = check(
client.post(
f"/api/v1/chats/{chat['id']}/messages",
headers=headers(actors[0]),
json={"text": text},
),
201,
"Message",
)
assert result["text"] == text
assert result["sender_id"] == actors[0]["id"]
@pytest.mark.parametrize(
"method,suffix,body",
[
("GET", "", None),
("GET", "/messages", None),
("POST", "/messages", {"text": "hello"}),
],
)
def test_acl(client, actors, chat, method, suffix, body):
outsider = headers(actors[2])
actual = check(
client.request(
method,
f"/api/v1/chats/{chat['id']}{suffix}",
headers=outsider,
json=body,
),
404,
"Error",
)
missing = check(
client.request(
method,
f"/api/v1/chats/{uuid4()}{suffix}",
headers=outsider,
json=body,
),
404,
"Error",
)
assert actual["error"]["message"] == missing["error"]["message"]
@pytest.mark.parametrize("value", ["", " \t\n", 42, True, None, "a" * 4001])
def test_bad_message(client, actors, chat, value):
check(
client.post(
f"/api/v1/chats/{chat['id']}/messages",
headers=headers(actors[0]),
json={"text": value},
),
400,
"Error",
)
def test_sender_not_client_controlled(client, actors, chat):
check(
client.post(
f"/api/v1/chats/{chat['id']}/messages",
headers=headers(actors[0]),
json={"text": "Hi", "sender_id": actors[1]["id"]},
),
400,
"Error",
)
@pytest.mark.parametrize(
"case",
[
"duplicate",
"unknown",
"no_caller",
"empty",
"wrong_type",
"bad_uuid",
"too_many",
"blank_title",
],
)
def test_invalid_chat(client, actors, case):
a, b, _ = actors
members = {
"duplicate": [a["id"], a["id"]],
"unknown": [a["id"], str(uuid4())],
"no_caller": [b["id"]],
"empty": [],
"wrong_type": a["id"],
"bad_uuid": ["broken"],
"too_many": [str(uuid4()) for _ in range(101)],
"blank_title": [a["id"]],
}[case]
check(
client.post(
"/api/v1/chats",
headers=headers(a),
json={
"title": " " if case == "blank_title" else "Title",
"member_ids": members,
},
),
400,
"Error",
)
@pytest.mark.parametrize(
"limit", ["0", "101", "-1", "1.5", "true", "1e1", "", "12"]
)
def test_bad_limit(client, actors, chat, limit):
check(
client.get(
f"/api/v1/chats/{chat['id']}/messages",
headers=headers(actors[0]),
params={"limit": limit},
),
400,
"Error",
)
@pytest.mark.parametrize(
"cursor", ["", "broken", "W10", "e30", "*", "x" * 2049]
)
def test_bad_cursor(client, actors, chat, cursor):
check(
client.get(
f"/api/v1/chats/{chat['id']}/messages",
headers=headers(actors[0]),
params={"cursor": cursor},
),
400,
"Error",
)
def test_pagination(client, actors, chat):
a, b, outsider = actors
sent = []
path = f"/api/v1/chats/{chat['id']}/messages"
for i in range(23):
sent.append(
check(
client.post(
path,
headers=headers(a if i % 2 else b),
json={"text": f"Msg {i}"},
),
201,
"Message",
)
)
got = history(client, a, chat["id"])
assert got == sorted(
sent, key=lambda m: (m["created_at"], UUID(m["id"]).int)
)
first = check(
client.get(path, headers=headers(a), params={"limit": 1}),
200,
"MessagePage",
)
second = check(
client.get(
path,
headers=headers(b),
params={"limit": 22, "cursor": first["next_cursor"]},
),
200,
"MessagePage",
)
assert second["items"] == got[1:]
assert second["next_cursor"] is None
chats = check(
client.get("/api/v1/chats", headers=headers(outsider)), 200, "ChatPage"
)
assert chats["items"] == []
other = check(
client.post(
"/api/v1/chats",
headers=headers(a),
json={"title": "Other", "member_ids": [a["id"]]},
),
201,
"Chat",
)
check(
client.get(
f"/api/v1/chats/{other['id']}/messages",
headers=headers(a),
params={"cursor": first["next_cursor"]},
),
400,
"Error",
)
# Валидный base64/JSON с неверным типом ключа тоже даёт 400.
data = json.loads(
base64.urlsafe_b64decode(
first["next_cursor"] + "=" * (-len(first["next_cursor"]) % 4)
)
)
data["at"] = 17
forged = (
base64.urlsafe_b64encode(json.dumps(data).encode())
.decode()
.rstrip("=")
)
check(
client.get(path, headers=headers(a), params={"cursor": forged}),
400,
"Error",
)
def test_chat_pagination_scope(client, actors):
a, b, _ = actors
created = []
for i in range(4):
created.append(
check(
client.post(
"/api/v1/chats",
headers=headers(a),
json={"title": str(i), "member_ids": [a["id"], b["id"]]},
),
201,
"Chat",
)
)
page = check(
client.get("/api/v1/chats", headers=headers(a), params={"limit": 2}),
200,
"ChatPage",
)
assert page["items"] == created[:2]
last = check(
client.get(
"/api/v1/chats",
headers=headers(a),
params={"limit": 2, "cursor": page["next_cursor"]},
),
200,
"ChatPage",
)
assert last["items"] == created[2:]
assert last["next_cursor"] is None
check(
client.get(
"/api/v1/chats",
headers=headers(b),
params={"cursor": page["next_cursor"]},
),
400,
"Error",
)
def test_concurrent_messages(client, actors, chat):
barrier = threading.Barrier(10)
a = actors[0]
path = f"/api/v1/chats/{chat['id']}/messages"
def worker(i):
with httpx.Client(
base_url=BASE_URL, timeout=15, trust_env=False
) as conn:
barrier.wait(timeout=15)
return [
check(
conn.post(
path, headers=headers(a), json={"text": f"{i}:{j}"}
),
201,
"Message",
)["id"]
for j in range(10)
]
with ThreadPoolExecutor(max_workers=10) as pool:
ids = [item for batch in pool.map(worker, range(10)) for item in batch]
rows = history(client, a, chat["id"])
assert len(rows) == len(ids) == len(set(ids)) == 100
assert set(ids) == {row["id"] for row in rows}
assert len({row["text"] for row in rows}) == 100
def test_registration_race(client):
username = "race_" + uuid4().hex[:20]
barrier = threading.Barrier(10)
def worker(_):
with httpx.Client(
base_url=BASE_URL, timeout=15, trust_env=False
) as conn:
barrier.wait(timeout=15)
result = conn.post(
"/api/v1/users",
json={
"username": username,
"display_name": "Test",
"password": PASSWORD,
},
)
check(
result,
result.status_code,
"User" if result.status_code == 201 else "Error",
)
return result.status_code
with ThreadPoolExecutor(max_workers=10) as pool:
statuses = list(pool.map(worker, range(10)))
assert statuses.count(201) == 1
assert statuses.count(409) == 9
def test_unknown_path(client):
check(client.get("/does-not-exist"), 404, "Error")
+277
View File
@@ -0,0 +1,277 @@
import hashlib
import io
import time
from pathlib import Path
from uuid import uuid4
import pytest
from conftest import check, headers
from PIL import Image
PNG = (Path(__file__).parents[1] / "tests/fixtures/sample.png").read_bytes()
def upload(
client, actor, chat, *, data=PNG, filename="Фото 🌍.png", mime="image/png"
):
return client.post(
f"/api/v1/chats/{chat['id']}/attachments",
headers={**headers(actor), "Content-Type": mime},
params={"filename": filename},
content=data,
)
def wait_ready(client, actor, attachment):
end = time.monotonic() + 60
while time.monotonic() < end:
row = check(
client.get(
f"/api/v1/attachments/{attachment['id']}",
headers=headers(actor),
),
200,
"Attachment",
)
if row["status"] == "ready":
return row
assert row["status"] != "failed", row
time.sleep(0.2)
raise TimeoutError("Pipeline readiness")
def test_attachment_roundtrip_acl_and_message(client, actors, chat):
attachment = check(upload(client, actors[0], chat), 202, "Attachment")
assert attachment["status"] == "queued" and attachment["variants"] == []
attachment = wait_ready(client, actors[0], attachment)
assert attachment["sha256"] == hashlib.sha256(PNG).hexdigest()
assert attachment["size_bytes"] == len(PNG)
path = f"/api/v1/attachments/{attachment['id']}"
assert (
check(client.get(path, headers=headers(actors[1])), 200, "Attachment")
== attachment
)
downloaded = client.get(path + "/content", headers=headers(actors[1]))
assert downloaded.status_code == 200 and downloaded.content == PNG
assert downloaded.headers["Content-Type"] == "image/png"
assert not downloaded.history
for suffix in ["", "/content"]:
check(
client.get(path + suffix, headers=headers(actors[2])), 404, "Error"
)
check(client.get(path + suffix), 401, "Error")
thumb = client.get(
path + "/content",
headers=headers(actors[1]),
params={"variant": "thumbnail"},
)
assert thumb.status_code == 200
with Image.open(io.BytesIO(thumb.content)) as image:
assert image.format == "JPEG" and image.size == (256, 160)
sent = check(
client.post(
f"/api/v1/chats/{chat['id']}/messages",
headers=headers(actors[1]),
json={"text": "", "attachment_ids": [attachment["id"]]},
),
201,
"Message",
)
assert sent["attachment_ids"] == [attachment["id"]]
assert sent["sender_id"] == actors[1]["id"]
@pytest.mark.parametrize(
"name",
[
"../x.png",
"x/y.png",
"x\\y.png",
"x\x00.png",
"x\x7f.png",
"x\n.png",
"a" * 256,
"",
],
)
def test_filename_guard(client, actors, chat, name):
check(upload(client, actors[0], chat, filename=name), 400, "Error")
@pytest.mark.parametrize(
"data,mime,status",
[
(b"not an image", "image/png", 415),
(PNG, "image/jpeg", 415),
(PNG, "application/octet-stream", 415),
(PNG[:25], "image/png", 415),
(b"", "image/png", 415),
(b"x" * (10 * 1024 * 1024 + 1), "image/png", 413),
],
)
def test_image_guards(client, actors, chat, data, mime, status):
r = upload(client, actors[0], chat, data=data, mime=mime)
check(r, status, "Error")
def test_jpeg_original_unchanged(client, actors, chat):
stream = io.BytesIO()
Image.new("RGB", (320, 200), (30, 60, 90)).save(stream, format="JPEG")
jpeg = stream.getvalue()
attachment = check(
upload(
client,
actors[0],
chat,
data=jpeg,
filename="camera.jpg",
mime="image/jpeg",
),
202,
"Attachment",
)
attachment = wait_ready(client, actors[0], attachment)
r = client.get(
f"/api/v1/attachments/{attachment['id']}/content",
headers=headers(actors[1]),
)
assert r.content == jpeg
def test_cross_chat_link_and_unknown(client, actors, chat):
a = check(upload(client, actors[0], chat), 202, "Attachment")
other = check(
client.post(
"/api/v1/chats",
headers=headers(actors[0]),
json={"title": "Other", "member_ids": [actors[0]["id"]]},
),
201,
"Chat",
)
for identity in [a["id"], str(uuid4())]:
check(
client.post(
f"/api/v1/chats/{other['id']}/messages",
headers=headers(actors[0]),
json={"text": "", "attachment_ids": [identity]},
),
404,
"Error",
)
check(
client.post(
f"/api/v1/chats/{chat['id']}/messages",
headers=headers(actors[0]),
json={"text": "", "attachment_ids": [a["id"], a["id"]]},
),
400,
"Error",
)
def test_default_attachments_are_semantically_equal(client, actors, chat):
h = headers(actors[0])
path = f"/api/v1/chats/{chat['id']}/messages"
first = check(
client.post(path, headers=h, json={"text": "Semantic default"}),
201,
"Message",
)
second = check(
client.post(
path,
headers=h,
json={"attachment_ids": [], "text": "Semantic default"},
),
201,
"Message",
)
assert first == second and first["attachment_ids"] == []
def test_pixel_limit_before_decode(client, actors, chat):
# Compressible synthetic image stays below10MiB but exceeds40M pixels.
stream = io.BytesIO()
Image.new("1", (8000, 5001)).save(stream, format="PNG")
assert len(stream.getvalue()) < 10 * 1024 * 1024
r = upload(client, actors[0], chat, data=stream.getvalue())
assert r.status_code == 413
def test_chunked_body_limit_without_content_length(client, actors, chat):
r = client.post(
f"/api/v1/chats/{chat['id']}/attachments",
headers={**headers(actors[0]), "Content-Type": "image/png"},
params={"filename": "chunked.png"},
content=iter([b"x" * (10 * 1024 * 1024 + 1)]),
)
assert r.request.headers.get("content-length") is None
assert r.status_code == 413
assert r.json()["error"]["code"] == "payload_too_large"
assert r.json()["error"]["request_id"] == r.headers["x-request-id"]
@pytest.mark.parametrize("size", [(1, 17), (320, 200), (1600, 900)])
def test_variant_geometry_and_alpha(client, actors, chat, size):
stream = io.BytesIO()
Image.new("RGBA", size, (0, 0, 0, 0)).save(stream, format="PNG")
a = check(
upload(client, actors[0], chat, data=stream.getvalue()),
202,
"Attachment",
)
a = wait_ready(client, actors[0], a)
for v in a["variants"]:
r = client.get(
f"/api/v1/attachments/{a['id']}/content",
headers=headers(actors[1]),
params={"variant": v["name"]},
)
assert len(r.content) == v["size_bytes"]
assert hashlib.sha256(r.content).hexdigest() == v["sha256"]
with Image.open(io.BytesIO(r.content)) as image:
assert image.size == (v["width"], v["height"])
assert not image.getexif()
assert min(image.convert("RGB").getpixel((0, 0))) >= 250
if v["name"] == "crop":
assert image.size == (128, 128)
else:
bound = 256 if v["name"] == "thumbnail" else 1280
assert max(image.size) <= bound
assert image.width <= size[0] and image.height <= size[1]
def test_exif_orientation_applied_but_original_preserved(client, actors, chat):
stream = io.BytesIO()
exif = Image.Exif()
exif[274] = 6
exif[270] = "Synthetic metadata must be removed"
Image.new("RGB", (320, 200), "red").save(stream, format="JPEG", exif=exif)
raw = stream.getvalue()
a = check(
upload(
client,
actors[0],
chat,
data=raw,
mime="image/jpeg",
filename="exif.jpg",
),
202,
"Attachment",
)
a = wait_ready(client, actors[0], a)
r = client.get(
f"/api/v1/attachments/{a['id']}/content", headers=headers(actors[1])
)
assert r.content == raw
v = next(v for v in a["variants"] if v["name"] == "thumbnail")
assert (v["width"], v["height"]) == (160, 256)
r = client.get(
f"/api/v1/attachments/{a['id']}/content",
headers=headers(actors[1]),
params={"variant": "thumbnail"},
)
with Image.open(io.BytesIO(r.content)) as image:
assert image.size == (160, 256) and not image.getexif()
+26
View File
@@ -0,0 +1,26 @@
import json
from uuid import uuid4
import pytest
from conftest import check, headers
@pytest.mark.parametrize("encoding", ["utf-16", "utf-32"])
def test_only_utf8_json(client, encoding):
payload = {"username": "u_" + uuid4().hex[:20], "display_name": "UTF"}
payload["password"] = "Synthetic-encoding-test-123"
result = client.post(
"/api/v1/users",
content=json.dumps(payload).encode(encoding),
headers={"Content-Type": "application/json"},
)
check(result, 400, "Error")
def test_leading_zero_limit(client, actors, chat):
result = client.get(
"/api/v1/chats/" + chat["id"] + "/messages",
headers=headers(actors[0]),
params={"limit": "0001"},
)
check(result, 200, "MessagePage")
+23
View File
@@ -0,0 +1,23 @@
from conftest import check, headers
def test_history_acl_precedes_query_validation(client, actors, chat):
path = f"/api/v1/chats/{chat['id']}/messages"
check(
client.get(
path,
headers=headers(actors[2]),
params={"limit": 0, "cursor": "broken"},
),
404,
"Error",
)
check(
client.get(
path,
headers=headers(actors[0]),
params={"limit": 0, "cursor": "broken"},
),
400,
"Error",
)
+75
View File
@@ -0,0 +1,75 @@
from concurrent.futures import ThreadPoolExecutor
from uuid import uuid4
import httpx
import pytest
from conftest import BASE_URL, check, headers, history
@pytest.mark.parametrize("key", [None, "", "a b", "x" * 129, "a/b"])
def test_key_required_and_valid(client, actors, chat, key):
h = headers(actors[0])
h.pop("Idempotency-Key")
if key is not None:
h["Idempotency-Key"] = key
check(
client.post(
f"/api/v1/chats/{chat['id']}/messages",
headers=h,
json={"text": "Key"},
),
400,
"Error",
)
def test_parallel_replay_across_instances(client, actors, chat):
h = headers(actors[0])
path = f"/api/v1/chats/{chat['id']}/messages"
def send(_):
with httpx.Client(base_url=BASE_URL, trust_env=False, timeout=15) as c:
r = c.post(path, headers=h, json={"text": "Один результат 🌍"})
return check(r, 201, "Message"), r.headers["x-instance-id"]
with ThreadPoolExecutor(max_workers=10) as pool:
results = list(pool.map(send, range(30)))
assert len({r[0]["id"] for r in results}) == 1
assert len({r[1] for r in results}) >= 2
assert history(client, actors[0], chat["id"]) == [results[0][0]]
check(
client.post(path, headers=h, json={"text": "Другой текст"}),
409,
"Error",
)
# Другой пользователь может независимо использовать тот же ключ.
other = headers(actors[1])
other["Idempotency-Key"] = h["Idempotency-Key"]
second = check(
client.post(path, headers=other, json={"text": "Боб"}), 201, "Message"
)
assert second["id"] != results[0][0]["id"]
def test_replay_rechecks_acl(client, actors, chat):
h = headers(actors[0])
path = f"/api/v1/chats/{chat['id']}/messages"
check(
client.post(path, headers=h, json={"text": "Existing"}), 201, "Message"
)
outsider = headers(actors[2])
outsider["Idempotency-Key"] = h["Idempotency-Key"]
check(
client.post(path, headers=outsider, json={"text": "Existing"}),
404,
"Error",
)
check(
client.post(
path,
headers={"Idempotency-Key": uuid4().hex},
json={"text": "Existing"},
),
401,
"Error",
)
+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"'