"""HTTP and database checks for durable Basic/Bearer sessions.""" import base64 import hashlib import json import os import socket import subprocess import sys import time import unittest import urllib.error import urllib.request from uuid import uuid4 import psycopg URL = os.environ.get("DATABASE_URL") @unittest.skipUnless(URL, "set DATABASE_URL to a disposable PostgreSQL database") class AuthTests(unittest.TestCase): @classmethod def setUpClass(cls): subprocess.run([sys.executable, "scripts/migrate.py"], check=True) with socket.socket() as sock: sock.bind(("127.0.0.1", 0)) cls.port = sock.getsockname()[1] cls.start_server() @classmethod def start_server(cls, ttl="3600"): env = {**os.environ, "SESSION_TTL_SECONDS": ttl} cls.server = subprocess.Popen( [sys.executable, "-m", "uvicorn", "src.main:app", "--host", "127.0.0.1", "--port", str(cls.port)], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) for _ in range(100): if cls.server.poll() is not None: raise AssertionError("API server exited during startup") try: cls.call("GET", "/health/ready", expected=200) return except (AssertionError, urllib.error.URLError): time.sleep(0.05) raise AssertionError("API server did not become ready") @classmethod def stop_server(cls): cls.server.terminate() try: cls.server.wait(timeout=5) except subprocess.TimeoutExpired: cls.server.kill() cls.server.wait(timeout=5) @classmethod def tearDownClass(cls): cls.stop_server() @classmethod def call(cls, method, path, *, body=None, authorization=None, user_id=None, expected=200): headers = {"Accept": "application/json"} data = None if body is not None: data = json.dumps(body, ensure_ascii=False).encode() headers["Content-Type"] = "application/json" if authorization is not None: headers["Authorization"] = authorization if user_id is not None: headers["X-User-Id"] = user_id request = urllib.request.Request( f"http://127.0.0.1:{cls.port}{path}", data=data, headers=headers, method=method, ) try: response = urllib.request.urlopen(request, timeout=5) except urllib.error.HTTPError as error: response = error with response: status = response.status response_headers = response.headers data = response.read() assert status == expected, (method, path, expected, status) request_id = response_headers.get("X-Request-Id") assert request_id payload = json.loads(data) if data else None if status >= 400: assert payload["error"]["request_id"] == request_id assert "password" not in data.decode().lower() assert "token" not in data.decode().lower() return payload, response_headers def user(self, password="Пароль:очень-длинный-123"): username = "u_" + uuid4().hex[:16] body = {"username": username, "display_name": "Алиса", "password": password} user, _ = self.call("POST", "/api/v1/users", body=body, expected=201) self.assertNotIn("password", user) return user, password def login(self, username, password, expected=201): encoded = base64.b64encode(f"{username}:{password}".encode()).decode() return self.call("POST", "/api/v1/auth/sessions", authorization="Basic " + encoded, expected=expected) def test_basic_bearer_logout_and_storage(self): alice, password = self.user() bob, _ = self.user() session, headers = self.login(alice["username"], password) self.assertEqual(session["token_type"], "Bearer") self.assertEqual(session["user"], alice) self.assertGreaterEqual(len(base64.urlsafe_b64decode(session["token"] + "=" * (-len(session["token"]) % 4))), 32) self.assertEqual(headers.get("Cache-Control"), "no-store") bearer = "Bearer " + session["token"] me, _ = self.call("GET", "/api/v1/users/me", authorization=bearer, user_id=bob["id"]) self.assertEqual(me, alice) with psycopg.connect(URL) as conn: row = conn.execute("SELECT token_hash,expires_at FROM sessions WHERE user_id=%s", (alice["id"],)).fetchone() password_hash = conn.execute("SELECT password_hash FROM users WHERE id=%s", (alice["id"],)).fetchone()[0] self.assertEqual(row[0], hashlib.sha256(session["token"].encode()).digest()) self.assertNotEqual(password_hash, password) self.assertTrue(password_hash.startswith("$argon2id$")) self.call("DELETE", "/api/v1/auth/sessions/current", authorization=bearer, expected=204) for method, path in (("GET", "/api/v1/users/me"), ("DELETE", "/api/v1/auth/sessions/current")): _, headers = self.call(method, path, authorization=bearer, expected=401) self.assertEqual(headers.get("WWW-Authenticate"), 'Bearer realm="messenger"') def test_challenges_and_uniform_credentials(self): user, password = self.user() failures = [] for username, candidate in ((user["username"], "wrong-password-123"), ("missing_user_123", password)): payload, headers = self.login(username, candidate, expected=401) failures.append((payload["error"]["code"], payload["error"]["message"])) self.assertEqual(headers.get("WWW-Authenticate"), 'Basic realm="messenger", charset="UTF-8"') self.assertEqual(failures[0], failures[1]) encoded = base64.b64encode(f"{user['username']}:{password}".encode()).decode() for authorization in (None, "Basic " + encoded, "Bearer garbage"): _, headers = self.call("GET", "/api/v1/users/me", authorization=authorization, user_id=user["id"], expected=401) self.assertEqual(headers.get("WWW-Authenticate"), 'Bearer realm="messenger"') _, headers = self.call("POST", "/api/v1/auth/sessions", authorization="Bearer garbage", expected=401) self.assertEqual(headers.get("WWW-Authenticate"), 'Basic realm="messenger", charset="UTF-8"') self.call("POST", "/api/v1/auth/sessions", authorization="Basic " + encoded, body={"unexpected": True}, expected=400) def test_z_short_ttl_survives_server_restart_without_extension(self): self.stop_server() self.start_server(ttl="2") try: user, password = self.user() session, _ = self.login(user["username"], password) bearer = "Bearer " + session["token"] self.call("GET", "/api/v1/users/me", authorization=bearer) with psycopg.connect(URL) as conn: before = conn.execute("SELECT expires_at FROM sessions WHERE user_id=%s", (user["id"],)).fetchone()[0] self.stop_server() self.start_server(ttl="3600") with psycopg.connect(URL) as conn: after = conn.execute("SELECT expires_at FROM sessions WHERE user_id=%s", (user["id"],)).fetchone()[0] self.assertEqual(before, after) time.sleep(2.1) _, headers = self.call("GET", "/api/v1/users/me", authorization=bearer, expected=401) self.assertEqual(headers.get("WWW-Authenticate"), 'Bearer realm="messenger"') finally: self.stop_server() self.start_server() if __name__ == "__main__": unittest.main()