forked from mtusi2026/mtusi2026lab3
132 lines
4.9 KiB
Python
132 lines
4.9 KiB
Python
"""Вход по Basic, opaque Bearer-сессия, неверный пароль и logout"""
|
||
|
||
import base64
|
||
from datetime import UTC, datetime
|
||
|
||
import httpx
|
||
import pytest
|
||
from helpers import (
|
||
assert_unauthorized,
|
||
auth,
|
||
basic,
|
||
psql,
|
||
public_user,
|
||
unique_username,
|
||
)
|
||
|
||
SESSIONS_PATH = "/api/v1/auth/sessions"
|
||
CURRENT_SESSION_PATH = "/api/v1/auth/sessions/current"
|
||
|
||
|
||
def test_login_returns_opaque_bearer_session(api: httpx.Client, make_user) -> None:
|
||
alice = make_user("alice")
|
||
response = api.post(
|
||
SESSIONS_PATH, headers=basic(alice["username"], alice["password"])
|
||
)
|
||
assert response.status_code == 201, response.text
|
||
session = response.json()
|
||
assert set(session) == {"token", "token_type", "expires_at", "user"}
|
||
assert session["token_type"] == "Bearer"
|
||
assert session["user"] == public_user(alice)
|
||
assert len(session["token"]) >= 43 # 32 байта в base64url
|
||
assert alice["id"] not in session["token"]
|
||
assert alice["username"] not in session["token"]
|
||
assert session["token"] != alice["token"]
|
||
expires_at = datetime.fromisoformat(session["expires_at"].replace("Z", "+00:00"))
|
||
assert expires_at > datetime.now(UTC)
|
||
|
||
|
||
def test_wrong_password_and_unknown_user_are_indistinguishable(
|
||
api: httpx.Client, make_user
|
||
) -> None:
|
||
alice = make_user("alice")
|
||
wrong = api.post(SESSIONS_PATH, headers=basic(alice["username"], "Wrong-pass-123"))
|
||
unknown = api.post(
|
||
SESSIONS_PATH, headers=basic(unique_username("ghost"), "Wrong-pass-123")
|
||
)
|
||
for response in (wrong, unknown):
|
||
assert_unauthorized(response, scheme="Basic")
|
||
assert 'realm="messenger"' in response.headers["WWW-Authenticate"]
|
||
assert wrong.json()["error"]["message"] == unknown.json()["error"]["message"]
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
"authorization",
|
||
[
|
||
None,
|
||
"",
|
||
"Basic",
|
||
"Basic !!!not-base64!!!",
|
||
"Basic " + base64.b64encode(b"no-colon-here").decode(),
|
||
"Basic " + base64.b64encode(b"\xff\xfe:password").decode(),
|
||
"Bearer some-token",
|
||
],
|
||
)
|
||
def test_malformed_basic_is_unauthorized(
|
||
api: httpx.Client, authorization: str | None
|
||
) -> None:
|
||
headers = {} if authorization is None else {"Authorization": authorization}
|
||
assert_unauthorized(api.post(SESSIONS_PATH, headers=headers), scheme="Basic")
|
||
|
||
|
||
def test_utf8_password_with_colon(api: httpx.Client) -> None:
|
||
username = unique_username("utf")
|
||
password = "пароль:с:двоеточием 🔐"
|
||
body = {"username": username, "display_name": "x", "password": password}
|
||
assert api.post("/api/v1/users", json=body).status_code == 201
|
||
assert api.post(SESSIONS_PATH, headers=basic(username, password)).status_code == 201
|
||
assert_unauthorized(
|
||
api.post(SESSIONS_PATH, headers=basic(username, "пароль:с:двоеточием")),
|
||
scheme="Basic",
|
||
)
|
||
|
||
|
||
def test_basic_is_rejected_on_business_endpoints(api: httpx.Client, make_user) -> None:
|
||
alice = make_user("alice")
|
||
headers = basic(alice["username"], alice["password"])
|
||
assert_unauthorized(api.get("/api/v1/users/me", headers=headers))
|
||
assert_unauthorized(api.get("/api/v1/chats", headers=headers))
|
||
|
||
|
||
def test_logout_revokes_only_current_session(api: httpx.Client, make_user) -> None:
|
||
alice = make_user("alice")
|
||
second = api.post(
|
||
SESSIONS_PATH, headers=basic(alice["username"], alice["password"])
|
||
)
|
||
other_session = {**alice, "token": second.json()["token"]}
|
||
|
||
assert api.get("/api/v1/users/me", headers=auth(alice)).status_code == 200
|
||
response = api.delete(CURRENT_SESSION_PATH, headers=auth(alice))
|
||
assert response.status_code == 204
|
||
assert response.content == b""
|
||
|
||
assert_unauthorized(api.get("/api/v1/users/me", headers=auth(alice)))
|
||
assert_unauthorized(api.delete(CURRENT_SESSION_PATH, headers=auth(alice)))
|
||
assert api.get("/api/v1/users/me", headers=auth(other_session)).status_code == 200
|
||
|
||
|
||
def test_logout_without_token(api: httpx.Client) -> None:
|
||
assert_unauthorized(api.delete(CURRENT_SESSION_PATH))
|
||
assert_unauthorized(
|
||
api.delete(CURRENT_SESSION_PATH, headers={"Authorization": "Bearer unknown"})
|
||
)
|
||
|
||
|
||
def test_relogin_after_logout(api: httpx.Client, make_user) -> None:
|
||
alice = make_user("alice")
|
||
api.delete(CURRENT_SESSION_PATH, headers=auth(alice))
|
||
again = api.post(SESSIONS_PATH, headers=basic(alice["username"], alice["password"]))
|
||
assert again.status_code == 201
|
||
renewed = {**alice, "token": again.json()["token"]}
|
||
assert api.get("/api/v1/users/me", headers=auth(renewed)).status_code == 200
|
||
|
||
|
||
def test_password_is_not_stored_in_plaintext(make_user) -> None:
|
||
"""Проверка в БД стенда: в users лежит PHC-строка Argon2id, а не пароль"""
|
||
alice = make_user("alice")
|
||
stored = psql(
|
||
f"SELECT password_hash FROM users WHERE username = '{alice['username']}';"
|
||
)
|
||
assert stored.startswith("$argon2id$")
|
||
assert alice["password"] not in stored
|