import base64 import json import secrets import urllib.error import urllib.request BASE_URL = "http://" + "127.0.0.1:8080" username = "test_" + secrets.token_hex(5) password = "StrongPassword123!" def request(method, path, body=None, authorization=None): headers = {} if body is not None: headers["Content-Type"] = "application/json" body = json.dumps(body).encode("utf-8") if authorization: headers["Authorization"] = authorization req = urllib.request.Request( BASE_URL + path, data=body, headers=headers, method=method, ) try: with urllib.request.urlopen(req, timeout=10) as response: data = response.read() return response.status, dict(response.headers), ( json.loads(data) if data else None ) except urllib.error.HTTPError as error: data = error.read() return error.code, dict(error.headers), ( json.loads(data) if data else None ) def check(name, actual, expected): result = "PASS" if actual == expected else "FAIL" print(f"{result}: {name}: {actual} (expected {expected})") if actual != expected: raise SystemExit(1) print("1. Registration") status, headers, user = request( "POST", "/api/v1/users", { "username": username, "display_name": "Test User", "password": password, }, ) print("Registration status:", status) print("Registration headers:", headers) print("Registration body:", user) check("registration", status, 201) assert "password" not in user assert "password_hash" not in user assert "X-Request-Id" in headers print("User ID:", user["id"]) print("\n2. Basic login") credentials = base64.b64encode( f"{username}:{password}".encode() ).decode() status, headers, session = request( "POST", "/api/v1/auth/sessions", authorization="Basic " + credentials, ) check("login", status, 201) token = session["token"] assert session["token_type"] == "Bearer" assert len(token) >= 40 print("\n3. Access with Bearer token") status, headers, me = request( "GET", "/api/v1/users/me", authorization="Bearer " + token, ) check("authorized request", status, 200) assert me["id"] == user["id"] print("\n4. Access without token") status, headers, body = request( "GET", "/api/v1/users/me", ) check("missing token", status, 401) assert any( key.lower() == "www-authenticate" and value == 'Bearer realm="messenger"' for key, value in headers.items() ), f"Неверный WWW-Authenticate: {headers}" print("\n5. X-User-Id cannot authorize") req = urllib.request.Request( BASE_URL + "/api/v1/users/me", headers={"X-User-Id": user["id"]}, ) try: urllib.request.urlopen(req, timeout=10) raise AssertionError("X-User-Id unexpectedly authorized") except urllib.error.HTTPError as error: check("X-User-Id rejected", error.code, 401) print("\n6. Logout") status, headers, body = request( "DELETE", "/api/v1/auth/sessions/current", authorization="Bearer " + token, ) check("logout", status, 204) print("\n7. Reuse revoked token") status, headers, body = request( "GET", "/api/v1/users/me", authorization="Bearer " + token, ) check("revoked token rejected", status, 401) print("\nALL AUTH CHECKS PASSED")