forked from mtusi2026/mtusi2026lab7
90 lines
3.5 KiB
Python
Executable File
90 lines
3.5 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Проверяет rehash существующего пользователя и измеряет стоимость Argon2id."""
|
|
|
|
import argparse
|
|
import base64
|
|
import json
|
|
import subprocess
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / "tests"))
|
|
from client import Client, check, run
|
|
|
|
CHECK = """
|
|
import asyncio
|
|
import json
|
|
import statistics
|
|
import sys
|
|
import time
|
|
from argon2 import PasswordHasher
|
|
from argon2.profiles import RFC_9106_LOW_MEMORY
|
|
from infrastructure import database_pool_manager
|
|
from infrastructure.security.password_hasher import PasswordHasher as ApplicationHasher
|
|
|
|
async def main():
|
|
details = json.load(sys.stdin)
|
|
pool = database_pool_manager
|
|
await pool.create_pool(10)
|
|
try:
|
|
async with pool.acquire() as conn:
|
|
if details["action"] == "seed":
|
|
legacy = PasswordHasher.from_parameters(RFC_9106_LOW_MEMORY).hash(details["password"])
|
|
await conn.execute("UPDATE users SET password_hash=$1 WHERE username=$2", legacy, details["username"])
|
|
else:
|
|
value = await conn.fetchval("SELECT password_hash FROM users WHERE username=$1", details["username"])
|
|
assert value.startswith("$argon2id$v=19$m=19456,t=2,p=1$")
|
|
assert PasswordHasher().verify(value, details["password"])
|
|
finally:
|
|
await pool.close()
|
|
if details["action"] == "verify":
|
|
hasher = ApplicationHasher(2)
|
|
try:
|
|
async def duration():
|
|
start = time.perf_counter()
|
|
await hasher.verify_dummy("audit-argon2id")
|
|
return (time.perf_counter() - start) * 1000
|
|
observations = []
|
|
started = time.perf_counter()
|
|
for _ in range(16):
|
|
observations.extend(await asyncio.gather(duration(), duration()))
|
|
observations.sort()
|
|
print(f"Argon2id samples=32 workers=2 p50_ms={statistics.median(observations):.1f} "
|
|
f"p95_ms={observations[30]:.1f} verifications_per_second={len(observations)/(time.perf_counter()-started):.1f}")
|
|
finally:
|
|
hasher.close()
|
|
|
|
asyncio.run(main())
|
|
"""
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--base-url", required=True)
|
|
parser.add_argument("--ca-file", default=str(ROOT / "certs/ca.crt"))
|
|
args = parser.parse_args()
|
|
client = Client(args.base_url, args.ca_file)
|
|
actor = client.user("rehash")
|
|
credentials = actor["registration"]
|
|
|
|
def in_replica(action):
|
|
payload = json.dumps(dict(action=action, username=credentials["username"],
|
|
password=credentials["password"]))
|
|
subprocess.run(
|
|
["docker", "compose", "exec", "-T", "-e", "PYTHONPATH=/app/src", "api", "python", "-c", CHECK],
|
|
cwd=ROOT, input=payload, text=True, check=True,
|
|
)
|
|
|
|
in_replica("seed")
|
|
encoded = base64.b64encode(f'{credentials["username"]}:{credentials["password"]}'.encode())
|
|
result = client.call("POST", "/api/v1/auth/sessions", 201,
|
|
headers={"Authorization": "Basic " + encoded.decode()}, schema="Session")
|
|
check(result["json"]["user"]["id"] == actor["id"], "Логин после legacy hash")
|
|
in_replica("verify")
|
|
print("PASS Argon2id: успешный login обновил legacy hash, пароль и hash не выводятся")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
run(main)
|