Files
mtusi2026lab7/student-tests/adapters/test_login_protection.py
T

56 lines
2.3 KiB
Python

import asyncio
from argon2 import PasswordHasher
from sqlalchemy import text
from conftest import PASSWORD, basic, new_user, running_app, sql_connection
async def test_login_budget_shared_between_independent_apps(database: str) -> None:
async with sql_connection() as connection:
await connection.execute(text("DELETE FROM login_budget"))
async with (
running_app(login_attempts=3, login_window_seconds=60) as first,
running_app(login_attempts=3, login_window_seconds=60) as second,
):
async with sql_connection() as connection:
await connection.execute(
text("INSERT INTO login_budget VALUES (1, floor(extract(epoch FROM now())/60), 1)")
)
responses = await asyncio.gather(
*[
http.post("/api/v1/auth/sessions", headers=basic("absent_user", PASSWORD))
for http in [first, second] * 4
]
)
assert sum(response.status_code == 401 for response in responses) == 2
rejected = [response for response in responses if response.status_code == 429]
assert len(rejected) == 6
assert all(response.headers["retry-after"] == "60" for response in rejected)
async def test_successful_login_upgrades_old_hash_without_changing_password(database: str) -> None:
old = PasswordHasher(time_cost=1, memory_cost=8192, parallelism=1)
async with running_app() as http:
user = new_user("rehash")
registered = await http.post("/api/v1/users", json=user)
assert registered.status_code == 201
async with sql_connection() as connection:
await connection.execute(
text("UPDATE users SET password_hash=:hash WHERE username=:username"),
{"hash": old.hash(PASSWORD), "username": user["username"]},
)
response = await http.post(
"/api/v1/auth/sessions", headers=basic(user["username"], PASSWORD)
)
assert response.status_code == 201
async with sql_connection() as connection:
current = (
await connection.execute(
text("SELECT password_hash FROM users WHERE username=:username"),
{"username": user["username"]},
)
).scalar_one()
assert "m=19456,t=2,p=1" in current
assert old.verify(current, PASSWORD)