feat: add replicated API with transactional message idempotency
This commit is contained in:
@@ -0,0 +1,115 @@
|
||||
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:8083")
|
||||
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",
|
||||
500: "internal_error",
|
||||
}[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
|
||||
@@ -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")
|
||||
@@ -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")
|
||||
@@ -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",
|
||||
)
|
||||
@@ -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"'
|
||||
Reference in New Issue
Block a user