test(auth): lab7 verify rehash, shared limits and session expiry and measure login cost
This commit is contained in:
@@ -0,0 +1,20 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func BenchmarkLoginArgon2id(b *testing.B) {
|
||||||
|
hasher := NewArgon2idHasher()
|
||||||
|
const password = "test-only-benchmark"
|
||||||
|
encoded, err := hasher.Hash(password)
|
||||||
|
if err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
b.ReportAllocs()
|
||||||
|
b.ResetTimer()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
ok, err := hasher.Verify(password, encoded)
|
||||||
|
if err != nil || !ok {
|
||||||
|
b.Fatal("проверка пароля не прошла", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Executable
+22
@@ -0,0 +1,22 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
project=$PWD
|
||||||
|
export COMPOSE_FILE="$project/compose.yaml"
|
||||||
|
cd /tmp
|
||||||
|
ids=$(docker compose ps -q api)
|
||||||
|
id=${ids%%$'\n'*}
|
||||||
|
test -n "$id"
|
||||||
|
read -r nano memory < <(docker inspect -f '{{.HostConfig.NanoCpus}} {{.HostConfig.Memory}}' "$id")
|
||||||
|
cpus=$(awk -v n="$nano" 'BEGIN {printf "%.6f", n/1000000000}')
|
||||||
|
((nano > 0 && memory > 0))
|
||||||
|
docker build --target builder -t mtusi-lab7-argon-builder "$project"
|
||||||
|
image=$(docker build -q - <<'DOCKER'
|
||||||
|
FROM mtusi-lab7-argon-builder
|
||||||
|
RUN go test -c -o /tmp/password-bench ./internal/service
|
||||||
|
ENTRYPOINT ["/tmp/password-bench"]
|
||||||
|
DOCKER
|
||||||
|
)
|
||||||
|
echo "Argon2id: память=64 МиБ, t=3, p=4; лимиты контейнера: CPU=$cpus, память=$memory байт"
|
||||||
|
docker run --rm --cpus "$cpus" --memory "$memory" --network none "$image" \
|
||||||
|
-test.run '^$' -test.bench '^BenchmarkLoginArgon2id$' -test.benchtime=5x -test.benchmem -test.count=3
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
"""Проверки 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()
|
||||||
Executable
+37
@@ -0,0 +1,37 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
project=$PWD
|
||||||
|
export COMPOSE_FILE="$project/compose.yaml"
|
||||||
|
python=${PYTHON:-python3}
|
||||||
|
if [[ -z ${PYTHON:-} && -x "$project/.venv/bin/python" ]]; then
|
||||||
|
python="$project/.venv/bin/python"
|
||||||
|
elif [[ $python == */* && $python != /* ]]; then
|
||||||
|
python="$project/$python"
|
||||||
|
fi
|
||||||
|
cd /tmp
|
||||||
|
if ! command -v "$python" >/dev/null; then
|
||||||
|
echo "Интерпретатор не найден: $python. Укажите PYTHON для WSL." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
"$python" -c 'from argon2.low_level import hash_secret' || {
|
||||||
|
echo "Установите argon2-cffi в выбранный Python: $python" >&2
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
# Короткий TTL только для новых сессий на время отдельного теста.
|
||||||
|
restore() { docker compose up -d --no-deps --no-build --wait --wait-timeout 120 api; }
|
||||||
|
trap restore EXIT
|
||||||
|
SESSION_TTL_SECONDS=20 docker compose up -d --no-deps --no-build --wait --wait-timeout 120 api
|
||||||
|
# Даём балансировщику обновить адреса после пересоздания реплик.
|
||||||
|
stable=0
|
||||||
|
for ((i=0;i<60;i++)); do
|
||||||
|
if curl -fsS --max-time 3 --cacert "$project/certs/private/ingress/ca.crt" https://localhost:8443/health/ready >/dev/null; then
|
||||||
|
stable=$((stable+1))
|
||||||
|
if ((stable >= 12)); then break; fi
|
||||||
|
else
|
||||||
|
stable=0
|
||||||
|
fi
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
((stable >= 12))
|
||||||
|
"$python" "$project/student-tests/auth-test.py"
|
||||||
Reference in New Issue
Block a user