feat: add durable bearer authentication

This commit is contained in:
Самохвалов Андрей Ремович
2026-10-01 22:24:06 +03:00
parent 07a06f186c
commit ea984c0af3
6 changed files with 284 additions and 6 deletions
+7
View File
@@ -0,0 +1,7 @@
CREATE TABLE sessions (
token_hash bytea PRIMARY KEY,
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
expires_at timestamptz NOT NULL
);
CREATE INDEX sessions_user_idx ON sessions (user_id);
+20 -5
View File
@@ -1,9 +1,10 @@
"""Lab 1 HTTP routes."""
"""Messenger HTTP routes."""
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, Query
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response
from .auth import basic_credentials, bearer_token
from .models import CreateChat, CreateMessage, CreateUser
from .store import store
@@ -25,9 +26,23 @@ def register_user(body: CreateUser):
return store.register(body.username, body.display_name, body.password)
def current_user() -> dict:
# U2 replaces this placeholder with PostgreSQL-backed Bearer sessions.
raise HTTPException(401, headers={"WWW-Authenticate": 'Bearer realm="messenger"'})
@router.post("/api/v1/auth/sessions", status_code=201)
async def create_session(request: Request, response: Response):
if await request.body():
raise HTTPException(400)
username, password = basic_credentials(request.headers.get("authorization"))
response.headers["Cache-Control"] = "no-store"
return store.create_session(username, password)
def current_user(request: Request) -> dict:
return store.authenticated(bearer_token(request.headers.get("authorization")))
@router.delete("/api/v1/auth/sessions/current", status_code=204)
def revoke_session(request: Request):
store.revoke_session(bearer_token(request.headers.get("authorization")))
return Response(status_code=204)
@router.get("/api/v1/users/me")
+43
View File
@@ -0,0 +1,43 @@
"""Parse HTTP credentials without exposing them in errors or logs."""
import base64
import binascii
import hashlib
import re
from fastapi import HTTPException
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
BEARER_CHALLENGE = 'Bearer realm="messenger"'
USERNAME = re.compile(r"[a-z0-9_]{3,32}\Z")
def unauthorized(challenge: str) -> HTTPException:
return HTTPException(401, headers={"WWW-Authenticate": challenge})
def basic_credentials(header: str | None) -> tuple[str, str]:
if not header or not header.startswith("Basic "):
raise unauthorized(BASIC_CHALLENGE)
try:
raw = base64.b64decode(header[6:], validate=True).decode("utf-8")
username, password = raw.split(":", 1)
except (binascii.Error, UnicodeError, ValueError):
raise unauthorized(BASIC_CHALLENGE) from None
if not USERNAME.fullmatch(username) or not 12 <= len(password) <= 128:
raise unauthorized(BASIC_CHALLENGE)
return username, password
def bearer_token(header: str | None) -> str:
if not header or not header.startswith("Bearer "):
raise unauthorized(BEARER_CHALLENGE)
token = header[7:]
if not 32 <= len(token) <= 256 or not token.isascii() or not re.fullmatch(r"[A-Za-z0-9_-]+", token):
raise unauthorized(BEARER_CHALLENGE)
return token
def token_hash(token: str) -> bytes:
return hashlib.sha256(token.encode("ascii")).digest()
+46
View File
@@ -3,17 +3,21 @@
import base64
import binascii
import json
import os
import secrets
from contextlib import contextmanager
from datetime import datetime, timezone
from uuid import UUID, uuid4
import psycopg
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerificationError
from fastapi import HTTPException
from psycopg.errors import UniqueViolation
from psycopg_pool import PoolTimeout
from . import db
from .auth import BASIC_CHALLENGE, BEARER_CHALLENGE, token_hash, unauthorized
password_hasher = PasswordHasher()
@@ -116,6 +120,48 @@ class Store:
raise HTTPException(401)
return user_view(row)
def create_session(self, username: str, password: str) -> dict:
with connection() as conn:
row = conn.execute(
"SELECT id,username,display_name,created_at,password_hash FROM users WHERE username=%s",
(username,),
).fetchone()
try:
valid = row is not None and password_hasher.verify(row["password_hash"], password)
except (VerificationError, InvalidHashError):
valid = False
if not valid:
raise unauthorized(BASIC_CHALLENGE)
token = secrets.token_urlsafe(32)
ttl = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
expiry = conn.execute(
"INSERT INTO sessions (token_hash,user_id,expires_at) "
"VALUES (%s,%s,clock_timestamp()+make_interval(secs => %s)) RETURNING expires_at",
(token_hash(token), row["id"], ttl),
).fetchone()["expires_at"]
return {"token": token, "token_type": "Bearer", "expires_at": timestamp(expiry), "user": user_view(row)}
def authenticated(self, token: str) -> dict:
with connection() as conn:
row = conn.execute(
"SELECT u.id,u.username,u.display_name,u.created_at FROM sessions s "
"JOIN users u ON u.id=s.user_id "
"WHERE s.token_hash=%s AND s.expires_at>clock_timestamp()",
(token_hash(token),),
).fetchone()
if row is None:
raise unauthorized(BEARER_CHALLENGE)
return user_view(row)
def revoke_session(self, token: str) -> None:
with connection() as conn:
row = conn.execute(
"DELETE FROM sessions WHERE token_hash=%s AND expires_at>clock_timestamp() RETURNING token_hash",
(token_hash(token),),
).fetchone()
if row is None:
raise unauthorized(BEARER_CHALLENGE)
def create_chat(self, actor_id: str, title: str, member_ids: list[str]) -> dict:
if actor_id not in member_ids:
raise HTTPException(400)
+167
View File
@@ -0,0 +1,167 @@
"""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()
+1 -1
View File
@@ -30,7 +30,7 @@ class DatabaseTests(unittest.TestCase):
def test_migration_and_unique_username_race(self):
with psycopg.connect(URL) as conn:
versions = conn.execute("SELECT version FROM schema_migrations").fetchall()
self.assertEqual(versions, [(1,)])
self.assertEqual(versions, [(1,), (2,)])
name = "u_" + uuid4().hex[:16]
def register(_):