118 lines
4.9 KiB
Python
118 lines
4.9 KiB
Python
"""Проверки rehash, общего окна входа, logout и фактического истечения сессии."""
|
||
import base64
|
||
import os
|
||
import statistics
|
||
import subprocess
|
||
import sys
|
||
import time
|
||
import uuid
|
||
from pathlib import Path
|
||
|
||
from argon2.low_level import Type, hash_secret
|
||
|
||
root = Path(__file__).resolve().parents[1]
|
||
sys.path.insert(0, str(root / "tests"))
|
||
from client import Client, check, timestamp
|
||
|
||
client = Client(ca_file=str(root / "certs/private/ingress/ca.crt"))
|
||
sessions = "/api/v1/auth/sessions"
|
||
policy = "$argon2id$v=19$m=65536,t=3,p=4$"
|
||
|
||
|
||
def account():
|
||
username = "auth_" + uuid.uuid4().hex[:16]
|
||
password = uuid.uuid4().hex
|
||
user = client.call("POST", "/api/v1/users", 201, body={
|
||
"username": username, "password": password, "display_name": "Проверка входа"
|
||
}, schema="User")["json"]
|
||
return str(uuid.UUID(user["id"])), username, password
|
||
|
||
|
||
def login(username, password, expected):
|
||
basic = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||
return client.call("POST", sessions, expected, headers={"Authorization": "Basic " + basic},
|
||
schema="Session" if expected == 201 else None)
|
||
|
||
|
||
def sql(query):
|
||
cmd = ["docker", "compose", "-f", str(root / "compose.yaml"), "exec", "-T",
|
||
"postgres", "psql", "-XAtq", "-v", "ON_ERROR_STOP=1", "-U", "messenger", "-d", "messenger"]
|
||
p = subprocess.run(cmd, input=query, text=True, capture_output=True, cwd="/tmp")
|
||
check(p.returncode == 0, "Ошибка SQL при подготовке или проверке тестового пользователя")
|
||
return p.stdout.strip()
|
||
|
||
|
||
def check_rehash():
|
||
uid, username, password = account()
|
||
legacy = hash_secret(password.encode(), os.urandom(16), time_cost=2,
|
||
memory_cost=19456, parallelism=1, hash_len=32, type=Type.ID).decode()
|
||
sql(f"UPDATE users SET password_hash='{legacy}' WHERE id='{uid}';")
|
||
query = f"SELECT password_hash FROM users WHERE id='{uid}';"
|
||
login(username, "incorrect", 401)
|
||
check(sql(query) == legacy, "Неверный пароль изменил хеш")
|
||
login(username, password, 201)
|
||
current = sql(query)
|
||
check(current.startswith(policy) and current != legacy, "Не подтверждён rehash")
|
||
login(username, password, 201)
|
||
check(sql(query) == current, "Актуальный хеш был изменён повторно")
|
||
print("PASS rehash: обновление только после успешного входа", flush=True)
|
||
|
||
|
||
def check_limit():
|
||
_, username, password = account()
|
||
replicas = set()
|
||
for _ in range(6):
|
||
result = login(username, "incorrect", 401)
|
||
replicas.add(result["headers"]["X-Instance-Id"])
|
||
check(len(replicas) == 2, "Попытки должны пройти через обе реплики")
|
||
blocked = login(username, password, 429)
|
||
check(blocked["json"]["error"]["code"] == "rate_limited", "Неверный код ошибки")
|
||
delay = int(blocked["headers"]["Retry-After"])
|
||
check(1 <= delay <= 30, "Неверный Retry-After")
|
||
time.sleep(delay + 1)
|
||
login(username, password, 201)
|
||
print(f"PASS rate-limit: 6 попыток через 2 реплики, HTTP 429, Retry-After={delay}, затем 201", flush=True)
|
||
|
||
|
||
def on_both(token, status):
|
||
replicas = set()
|
||
for _ in range(40):
|
||
reply = client.call("GET", "/api/v1/users/me", status, actor={"token": token},
|
||
schema="User" if status == 200 else None)
|
||
replicas.add(reply["headers"]["X-Instance-Id"])
|
||
if len(replicas) == 2:
|
||
return
|
||
raise RuntimeError("Ответила только одна реплика")
|
||
|
||
|
||
def check_sessions():
|
||
_, username, password = account()
|
||
active = login(username, password, 201)["json"]
|
||
on_both(active["token"], 200)
|
||
client.call("DELETE", sessions + "/current", 204, actor={"token": active["token"]})
|
||
on_both(active["token"], 401)
|
||
fresh = login(username, password, 201)["json"]
|
||
on_both(fresh["token"], 200)
|
||
remaining = max(0, timestamp(fresh["expires_at"]).timestamp() - time.time())
|
||
print(f"Ожидание реального срока сессии: {remaining:.1f} с", flush=True)
|
||
time.sleep(remaining + 1)
|
||
on_both(fresh["token"], 401)
|
||
print("PASS sessions: logout и expiry подтверждены на обеих репликах", flush=True)
|
||
|
||
|
||
def measure():
|
||
timings = []
|
||
for _ in range(3):
|
||
_, username, password = account()
|
||
for _ in range(5):
|
||
timings.append(login(username, password, 201)["elapsed"] * 1000)
|
||
print(f"Вход по HTTPS: n={len(timings)}, медиана={statistics.median(timings):.1f} мс, "
|
||
f"максимум={max(timings):.1f} мс (включая БД, сеть и создание сессии)", flush=True)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
check_rehash()
|
||
check_limit()
|
||
measure()
|
||
check_sessions()
|