Implement PostgreSQL storage, sessions and persistence checks

This commit is contained in:
Daria0w0
2026-10-09 18:06:28 +03:00
parent 65003b6119
commit 83e3810d33
62 changed files with 4650 additions and 20 deletions
+21
View File
@@ -0,0 +1,21 @@
import subprocess
import uuid
from sessions import request, basic
suffix = uuid.uuid4().hex[:20]
username = "rollback_" + suffix
secret = "учебный:пароль:rollback"
user = request("POST", "/users", 201, {"username": username, "display_name": "Rollback", "password": secret})
session = request("POST", "/auth/sessions", 201, headers=basic(username, secret))
headers = {"Authorization": "Bearer " + session["token"]}
title = "rollback_" + suffix
request("POST", "/chats", 400, {"title": title, "member_ids": [user["id"], str(uuid.uuid4())]}, headers)
# title contains only a fixed prefix and locally generated hex characters.
sql = "SELECT count(*) FROM chats WHERE title='" + title + "';"
result = subprocess.run(
["docker", "compose", "exec", "-T", "postgres", "psql", "-X", "-U", "messenger", "-d", "messenger", "-At", "-c", sql],
check=True, capture_output=True, text=True,
)
assert result.stdout.strip() == "0", "failed chat creation left a row in PostgreSQL"
request("DELETE", "/auth/sessions/current", 204, headers=headers)
print("PASS: unknown second member -> 400; no chat row remains in PostgreSQL (rollback)")
+54
View File
@@ -0,0 +1,54 @@
import concurrent.futures
import json
import urllib.error
import urllib.request
import uuid
BASE = "http://localhost:8080"
def register(body):
request = urllib.request.Request(
BASE + "/api/v1/users",
data=json.dumps(body).encode("utf-8"),
headers={"Content-Type": "application/json"},
method="POST",
)
try:
response = urllib.request.urlopen(request, timeout=15)
except urllib.error.HTTPError as error:
response = error
with response:
data = json.load(response)
assert response.headers.get("X-Request-Id"), "missing request ID"
assert "password" not in data and "password_hash" not in data, "secret in response"
return response.status, data
def main():
username = "reg_" + uuid.uuid4().hex[:20]
body = {"username": username, "display_name": "Проверка регистрации", "password": "учебный:пароль"}
status, user = register(body)
assert status == 201, f"registration status={status}"
assert set(user) == {"id", "username", "display_name", "created_at"}
assert user["username"] == username and user["display_name"] == body["display_name"]
uuid.UUID(user["id"])
assert user["created_at"].endswith("Z"), "created_at must be UTC"
print("PASS: registration 201, public User fields only")
assert register(body)[0] == 409, "duplicate username must return 409"
print("PASS: duplicate username 409")
invalid = dict(body, username="bad_" + uuid.uuid4().hex[:20], password="short")
assert register(invalid)[0] == 400, "short password must return 400"
del invalid["password"]
assert register(invalid)[0] == 400, "missing password must return 400"
print("PASS: short and missing passwords 400")
concurrent_body = dict(body, username="race_" + uuid.uuid4().hex[:20])
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
results = list(executor.map(register, [concurrent_body, concurrent_body]))
assert sorted(status for status, _ in results) == [201, 409], "registration race failed"
print("PASS: concurrent same username -> 201 and 409")
print("Created username for SQL inspection:", username)
if __name__ == "__main__":
main()
+92
View File
@@ -0,0 +1,92 @@
import argparse
import base64
import datetime
import json
import time
import urllib.error
import urllib.request
import uuid
def request(method, path, expected, body=None, headers=None):
outgoing = dict(headers or {})
data = None
if body is not None:
outgoing["Content-Type"] = "application/json"
data = json.dumps(body).encode("utf-8")
req = urllib.request.Request("http://localhost:8080/api/v1" + path, data=data, headers=outgoing, method=method)
try:
response = urllib.request.urlopen(req, timeout=15)
except urllib.error.HTTPError as error:
response = error
with response:
raw = response.read()
assert response.status == expected, f"{method} {path}: expected {expected}, got {response.status}"
request_id = response.headers.get("X-Request-Id")
assert request_id, "missing request ID"
result = json.loads(raw) if raw else None
if expected == 401:
challenge = 'Basic realm="messenger", charset="UTF-8"' if path == "/auth/sessions" else 'Bearer realm="messenger"'
assert response.headers.get("WWW-Authenticate") == challenge, "wrong auth challenge"
assert result["error"]["request_id"] == request_id
if expected == 204:
assert raw == b"", "logout must have empty body"
return result
def basic(username, password):
encoded = base64.b64encode((username + ":" + password).encode("utf-8")).decode("ascii")
return {"Authorization": "Basic " + encoded}
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--expiry", action="store_true", help="Requires API SESSION_TTL_SECONDS=2")
args = parser.parse_args()
username = "session_" + uuid.uuid4().hex[:20]
password = "учебный:пароль:сессии"
user = request("POST", "/users", 201, {"username": username, "display_name": "Сессии", "password": password})
credentials = basic(username, password)
request("POST", "/auth/sessions", 401, headers=basic(username, "неправильный:пароль"))
request("POST", "/auth/sessions", 401, headers=basic("missing_" + uuid.uuid4().hex[:20], password))
request("POST", "/auth/sessions", 401)
request("POST", "/auth/sessions", 400, body={}, headers=credentials)
print("PASS: wrong/missing credentials 401; login JSON body 400")
session = request("POST", "/auth/sessions", 201, headers=credentials)
assert set(session) == {"token", "token_type", "expires_at", "user"}
assert session["token_type"] == "Bearer" and session["user"] == user
assert len(base64.urlsafe_b64decode(session["token"] + "=")) == 32
assert session["expires_at"].endswith("Z")
bearer = {"Authorization": "Bearer " + session["token"]}
if args.expiry:
expires = datetime.datetime.fromisoformat(session["expires_at"].replace("Z", "+00:00"))
remaining = (expires - datetime.datetime.now(datetime.timezone.utc)).total_seconds()
assert 0 < remaining <= 3, "Run API with SESSION_TTL_SECONDS=2"
request("GET", "/users/me", 200, headers=bearer)
time.sleep(remaining + 0.3)
request("GET", "/users/me", 401, headers=bearer)
request("DELETE", "/auth/sessions/current", 401, headers=bearer)
print("PASS: short TTL session works before expiry and returns 401 after expiry")
return
assert request("GET", "/users/me", 200, headers=bearer) == user
spoofed = dict(bearer, **{"X-User-Id": str(uuid.uuid4())})
assert request("GET", "/users/me", 200, headers=spoofed) == user
request("GET", "/users/me", 401, headers={"X-User-Id": user["id"]})
request("GET", "/users/me", 401, headers=credentials)
request("GET", "/users/me", 401, headers={"Authorization": "Bearer " + "A" * 43})
print("PASS: Bearer identifies user; X-User-Id and Basic give no access")
other = request("POST", "/auth/sessions", 201, headers=credentials)
assert other["token"] != session["token"]
request("DELETE", "/auth/sessions/current", 204, headers=bearer)
request("GET", "/users/me", 401, headers=bearer)
request("DELETE", "/auth/sessions/current", 401, headers=bearer)
other_bearer = {"Authorization": "Bearer " + other["token"]}
request("GET", "/users/me", 200, headers=other_bearer)
request("DELETE", "/auth/sessions/current", 204, headers=other_bearer)
print("PASS: logout 204; revoked token 401; other session remains valid")
if __name__ == "__main__":
main()