Files
mtusi2026lab3-fork/student-tests/test_auth.py
T
2026-11-02 20:05:33 +03:00

194 lines
6.6 KiB
Python

"""Регистрация, вход по Basic, доступ по Bearer и выход."""
import base64
import uuid
import pytest
from conftest import assert_error, basic_header, register_and_login
BAD_BASIC = [
"Basic",
"Basic !!!not-base64!!!",
"Basic " + base64.b64encode(b"nocolon").decode(),
"Basic " + base64.b64encode("имя:password-123456".encode()).decode(),
"Basic " + base64.b64encode(b"user:\xff\xfe-bad-utf8").decode(),
"Bearer abc",
"",
]
def test_register_returns_user_without_secrets(client):
reply = client.post(
"/api/v1/users",
json={
"username": "reg_" + uuid.uuid4().hex[:8],
"display_name": "Имя",
"password": "long-enough-pass",
},
)
assert reply.status_code == 201
assert set(reply.json()) == {"id", "username", "display_name", "created_at"}
assert "password" not in reply.text and "hash" not in reply.text
@pytest.mark.parametrize(
"password", [None, "", "short", "a" * 11, "a" * 129, 123456789012, "пароль"]
)
def test_register_password_rules(client, password):
body = {"username": "pw_" + uuid.uuid4().hex[:8], "display_name": "x"}
if password is not None:
body["password"] = password
assert_error(client.post("/api/v1/users", json=body), 400, "invalid_request")
def test_register_password_border_lengths(client):
for password in ["a" * 12, "я" * 128, "p:a:s:s:w:o:r:d:1:2:3"]:
body = {
"username": "pb_" + uuid.uuid4().hex[:8],
"display_name": "x",
"password": password,
}
assert client.post("/api/v1/users", json=body).status_code == 201
def test_login_success_shape(client, alice):
reply = client.post(
"/api/v1/auth/sessions", headers=basic_header(alice.username, alice.password)
)
assert reply.status_code == 201
data = reply.json()
assert set(data) == {"token", "token_type", "expires_at", "user"}
assert data["token_type"] == "Bearer" and len(data["token"]) >= 32
assert data["user"] == alice.data
assert data["expires_at"].endswith("Z")
def test_each_login_gives_new_token(client, alice):
second = client.post(
"/api/v1/auth/sessions", headers=basic_header(alice.username, alice.password)
).json()["token"]
assert second != alice.token
def test_wrong_password_and_unknown_user_look_the_same(client, alice):
wrong = client.post(
"/api/v1/auth/sessions",
headers=basic_header(alice.username, "wrong-password-123"),
)
unknown = client.post(
"/api/v1/auth/sessions",
headers=basic_header("no_such_user_x", "wrong-password-123"),
)
assert_error(wrong, 401, "unauthorized")
assert_error(unknown, 401, "unauthorized")
assert wrong.headers["WWW-Authenticate"] == unknown.headers["WWW-Authenticate"]
assert wrong.headers["WWW-Authenticate"].startswith('Basic realm="messenger"')
assert wrong.json()["error"]["message"] == unknown.json()["error"]["message"]
@pytest.mark.parametrize("header", BAD_BASIC)
def test_malformed_basic_is_401(client, header):
reply = client.post("/api/v1/auth/sessions", headers={"Authorization": header})
assert_error(reply, 401, "unauthorized")
assert reply.headers["WWW-Authenticate"].startswith("Basic")
def test_login_without_header_is_401(client):
assert_error(client.post("/api/v1/auth/sessions"), 401, "unauthorized")
def test_password_with_colon_and_unicode_works(client):
for password in ["pass:with:colons:123", "пароль-с-юникодом-😀-123"]:
username = "uc_" + uuid.uuid4().hex[:8]
client.post(
"/api/v1/users",
json={"username": username, "display_name": "x", "password": password},
)
reply = client.post(
"/api/v1/auth/sessions", headers=basic_header(username, password)
)
assert reply.status_code == 201, password
def test_bearer_token_gives_access(client, alice):
reply = client.get("/api/v1/users/me", headers=alice.headers)
assert reply.status_code == 200 and reply.json() == alice.data
def test_business_endpoint_rejects_basic(client, alice):
reply = client.get(
"/api/v1/users/me", headers=basic_header(alice.username, alice.password)
)
assert_error(reply, 401, "unauthorized")
assert reply.headers["WWW-Authenticate"] == 'Bearer realm="messenger"'
@pytest.mark.parametrize(
"header",
["", "Bearer", "Bearer short", "Bearer " + "x" * 43, "Token abc", "bearer"],
)
def test_bad_or_unknown_bearer_is_401(client, header):
headers = {"Authorization": header} if header else {}
reply = client.get("/api/v1/users/me", headers=headers)
assert_error(reply, 401, "unauthorized")
assert reply.headers["WWW-Authenticate"] == 'Bearer realm="messenger"'
def test_x_user_id_alone_gives_no_access(client, alice):
assert_error(
client.get("/api/v1/users/me", headers={"X-User-Id": alice.id}),
401,
"unauthorized",
)
def test_x_user_id_does_not_change_owner_of_session(client, alice, bob):
reply = client.get(
"/api/v1/users/me", headers={**alice.headers, "X-User-Id": bob.id}
)
assert reply.json()["id"] == alice.id
def test_logout_revokes_token_and_repeat_is_401(client, alice):
first = client.delete("/api/v1/auth/sessions/current", headers=alice.headers)
assert first.status_code == 204 and first.content == b""
assert_error(
client.get("/api/v1/users/me", headers=alice.headers), 401, "unauthorized"
)
assert_error(
client.delete("/api/v1/auth/sessions/current", headers=alice.headers),
401,
"unauthorized",
)
def test_logout_without_token_is_401(client):
assert_error(client.delete("/api/v1/auth/sessions/current"), 401, "unauthorized")
def test_logout_revokes_only_current_session(client, alice):
second = client.post(
"/api/v1/auth/sessions", headers=basic_header(alice.username, alice.password)
).json()["token"]
client.delete("/api/v1/auth/sessions/current", headers=alice.headers)
assert (
client.get(
"/api/v1/users/me", headers={"Authorization": "Bearer " + second}
).status_code
== 200
)
def test_session_lives_longer_than_300_seconds(client, alice):
"""Сессия по умолчанию живёт не меньше 300 секунд."""
from datetime import datetime, timezone
data = client.post(
"/api/v1/auth/sessions", headers=basic_header(alice.username, alice.password)
).json()
left = datetime.fromisoformat(data["expires_at"][:-1] + "+00:00") - datetime.now(
timezone.utc
)
assert left.total_seconds() > 300