forked from mtusi2026/mtusi2026lab2
ЛР 2: PostgreSQL, сессии в Valkey, трек 2
This commit is contained in:
@@ -0,0 +1,114 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Level 4: session semantics — wrong password, challenges, logout, token quality."""
|
||||
import json
|
||||
import uuid
|
||||
|
||||
from common import arguments, basic, call, credentials, expect, login, member, register, run
|
||||
|
||||
|
||||
def wrong_password_gives_same_401(base):
|
||||
actor = register(base, "pw")
|
||||
name = actor["registration"]["username"]
|
||||
wrong = call(base, "POST", "/api/v1/auth/sessions", headers={"Authorization": basic(name, "wrong-password-123")})
|
||||
unknown = call(base, "POST", "/api/v1/auth/sessions", headers={"Authorization": basic("u_absent_" + uuid.uuid4().hex[:8], "wrong-password-123")})
|
||||
expect(wrong["status"] == unknown["status"] == 401, "ожидался 401 в обоих случаях")
|
||||
expect(wrong["json"]["error"]["code"] == unknown["json"]["error"]["code"] == "unauthorized", "код ошибки отличается")
|
||||
expect(wrong["headers"].get("WWW-Authenticate", "").startswith("Basic"), "нет Basic challenge")
|
||||
expect(wrong["json"]["error"]["request_id"] == wrong["headers"].get("X-Request-Id"), "request_id не совпадает с заголовком")
|
||||
|
||||
|
||||
def basic_is_rejected_on_business_endpoints(base):
|
||||
actor = register(base, "basic")
|
||||
name = actor["registration"]["username"]
|
||||
password = actor["registration"]["password"]
|
||||
result = call(base, "GET", "/api/v1/users/me", headers={"Authorization": basic(name, password)})
|
||||
expect(result["status"] == 401, "Basic на /users/me вернул %s" % result["status"])
|
||||
expect(result["headers"].get("WWW-Authenticate", "").startswith("Bearer"), "нет Bearer challenge")
|
||||
|
||||
|
||||
def x_user_id_does_not_authenticate(base):
|
||||
alice = member(base, "alice")
|
||||
bob = register(base, "bob")
|
||||
anonymous = call(base, "GET", "/api/v1/users/me", headers={"X-User-Id": alice["id"]})
|
||||
expect(anonymous["status"] == 401, "X-User-Id без Bearer дал %s" % anonymous["status"])
|
||||
overridden = call(base, "GET", "/api/v1/users/me", token=alice["token"], headers={"X-User-Id": bob["id"]})
|
||||
expect(overridden["status"] == 200 and overridden["json"]["id"] == alice["id"], "X-User-Id подменил владельца сессии")
|
||||
|
||||
|
||||
def logout_revokes_only_its_own_token(base):
|
||||
actor = member(base, "logout")
|
||||
second = login(base, dict(actor))
|
||||
first_token = actor["token"]
|
||||
revoked = call(base, "DELETE", "/api/v1/auth/sessions/current", token=first_token)
|
||||
expect(revoked["status"] == 204, "logout вернул %s" % revoked["status"])
|
||||
expect(call(base, "GET", "/api/v1/users/me", token=first_token)["status"] == 401, "отозванный токен всё ещё работает")
|
||||
expect(call(base, "DELETE", "/api/v1/auth/sessions/current", token=first_token)["status"] == 401, "повторный logout не 401")
|
||||
expect(call(base, "GET", "/api/v1/users/me", token=second["token"])["status"] == 200, "logout убил вторую сессию")
|
||||
|
||||
|
||||
def token_is_opaque_and_unique(base):
|
||||
actor = member(base, "token")
|
||||
name = actor["registration"]["username"]
|
||||
expect(len(actor["token"]) >= 32, "токен короче 32 символов")
|
||||
expect(name not in actor["token"] and actor["id"] not in actor["token"], "токен раскрывает имя или id пользователя")
|
||||
again = login(base, dict(actor))
|
||||
expect(again["token"] != actor["token"], "повторный вход выдал тот же токен")
|
||||
expect(actor["session"]["token_type"] == "Bearer", "token_type не Bearer")
|
||||
|
||||
|
||||
def short_password_is_rejected(base):
|
||||
body = credentials("short")
|
||||
body["password"] = "short"
|
||||
expect(call(base, "POST", "/api/v1/users", body=body)["status"] == 400, "короткий пароль принят")
|
||||
body = credentials("long")
|
||||
body["password"] = "x" * 129
|
||||
expect(call(base, "POST", "/api/v1/users", body=body)["status"] == 400, "пароль длиннее 128 принят")
|
||||
|
||||
|
||||
def password_is_never_returned(base):
|
||||
actor = member(base, "leak")
|
||||
expect("password" not in actor["user"] and "password_hash" not in actor["user"], "User содержит пароль")
|
||||
me = call(base, "GET", "/api/v1/users/me", token=actor["token"])["json"]
|
||||
expect(set(me) == {"id", "username", "display_name", "created_at"}, "в /users/me лишние поля: %s" % sorted(me))
|
||||
expect("password" not in str(actor["session"]["user"]), "сессия раскрывает пароль")
|
||||
|
||||
|
||||
def login_rejects_a_request_body(base):
|
||||
actor = register(base, "body")
|
||||
header = basic(actor["registration"]["username"], actor["registration"]["password"])
|
||||
with_body = call(base, "POST", "/api/v1/auth/sessions", body={"username": actor["registration"]["username"]}, headers={"Authorization": header})
|
||||
expect(with_body["status"] == 400, "вход с JSON-телом дал %s" % with_body["status"])
|
||||
raw_body = call(base, "POST", "/api/v1/auth/sessions", raw=b"anything", headers={"Authorization": header}, content_type="text/plain")
|
||||
expect(raw_body["status"] == 400, "вход с произвольным телом дал %s" % raw_body["status"])
|
||||
clean = call(base, "POST", "/api/v1/auth/sessions", headers={"Authorization": header})
|
||||
expect(clean["status"] == 201, "вход без тела дал %s" % clean["status"])
|
||||
|
||||
|
||||
def broken_utf8_credentials_are_rejected(base):
|
||||
actor = register(base, "utf8")
|
||||
name = actor["registration"]["username"]
|
||||
import base64 as b64
|
||||
|
||||
header = "Basic " + b64.b64encode(name.encode() + b":" + actor["registration"]["password"].encode() + b"\xff").decode()
|
||||
result = call(base, "POST", "/api/v1/auth/sessions", headers={"Authorization": header})
|
||||
expect(result["status"] == 401, "повреждённый UTF-8 в пароле дал %s" % result["status"])
|
||||
body = credentials("utf8reg")
|
||||
bad_body = json.dumps(body, ensure_ascii=False).encode("utf-8").replace(b'"password"', b'"passw\xffrd"')
|
||||
broken = call(base, "POST", "/api/v1/users", raw=bad_body, content_type="application/json")
|
||||
expect(broken["status"] == 400, "повреждённый UTF-8 в теле дал %s" % broken["status"])
|
||||
|
||||
|
||||
TESTS = [
|
||||
wrong_password_gives_same_401,
|
||||
basic_is_rejected_on_business_endpoints,
|
||||
x_user_id_does_not_authenticate,
|
||||
logout_revokes_only_its_own_token,
|
||||
token_is_opaque_and_unique,
|
||||
short_password_is_rejected,
|
||||
password_is_never_returned,
|
||||
login_rejects_a_request_body,
|
||||
broken_utf8_credentials_are_rejected,
|
||||
]
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(TESTS, arguments(__doc__).base_url)
|
||||
Reference in New Issue
Block a user