Add sessions, login, logout and CSRF (REVIEW SEC-007)
The three endpoints web/src/auth/AuthProvider.tsx was written against. It
already distinguishes 404 ("this server has no auth at all", show a banner)
from 401 ("not signed in"), so these landing is what makes the banner go away.
Cookies with server-side state, not JWTs, and the reason is revocation. Signing
someone out, or ending every session when a password changes, has to take
effect on the next request. A self-contained token cannot be withdrawn before
it expires without a deny-list, which is the database lookup it was meant to
avoid. So logout DELETEs the row and the old cookie is dead immediately.
The cookie is not the primary key. sessions.id stays internal and the browser
carries a separate 64-hex token of which only the SHA-256 is stored, exactly as
device tokens work. Using the id would have been simpler and would mean a
database dump handed over every live session.
CSRF is a per-session token, checked in middleware rather than per route so a
new endpoint cannot forget it. Two decisions worth keeping:
- It triggers only on unsafe methods for requests that CARRY THE SESSION
COOKIE. Device endpoints authenticate with a bearer token and send no
cookies, so /ingest is untouched - a camera has no way to obtain a CSRF
token and blocking it would take the whole system down. Login is exempt by
the same rule, with no special case: there is no session cookie yet.
- The header is compared against the token on the session row, not against
the CSRF cookie. Plain double-submit accepts any self-consistent pair, so
anyone able to write a cookie on the domain can satisfy it while the
victim's session cookie rides along. Binding it to the session means they
would also need a value they cannot read.
Login answers every failure identically - same status, same body - because
"no such user" confirms which accounts exist and "wrong code" confirms the
password was right. It also hashes the submitted password when the username
does not exist, so a missing user is not measurably faster than a wrong
password; that timing difference is a username oracle.
Failed logins are audited, not just successful ones. A log of only the
successes cannot answer the question worth asking afterwards.
Rate limited by address rather than by username. Keying on the username would
let someone lock a known account out by failing at it deliberately, turning the
protection into a denial of service against the person it protects.
session_cookie_secure is a setting rather than a constant for one reason worth
writing down: a Secure cookie is silently discarded over http, so with it
hardcoded true every local login would return 200 and never sign anyone in,
with nothing in any log. The tests hit the same trap through http://testserver.
--- and the migration baseline had to be frozen to do any of this ---
0001 called Base.metadata.create_all(). That could not drift from the models,
which was its purpose, but it also meant a fresh database got the *current*
models from 0001 and then had every later migration applied on top of what it
had just created. The first migration added after it therefore failed with
"column token_hash of relation sessions already exists" - not on this machine,
where the columns were added incrementally, but on any clean one.
tests/test_schema_matches_models.py caught it immediately, which is the only
reason it did not reach a deployment. It is also the reason this is fixed now
rather than at the next schema change: the problem gets worse with every
revision added on top of it.
So 0001 is now explicit DDL for the schema as it stood at the end of Phase 1,
generated against an empty database with the new columns temporarily removed
from the model, and it says at the top not to edit it for a model change.
Verified on a fresh database: upgrade to head, downgrade to base, upgrade
again, alembic check clean at each end.
Also: the suite was leaking audit rows. audit_log.user_id is ON DELETE SET NULL
on purpose, and a failed login for a username that never existed writes NULL
from the start, so no user-scoped cleanup could ever match it - seven runs had
quietly left eight rows behind. Swept by id high-water mark now. Two
consecutive suite runs leave zero users, zero sessions, zero audit rows and
zero jobs.
Verified against a real uvicorn as well as the test client: 401 before login,
200 with both cookies and the right HttpOnly flags, 403 on logout without the
CSRF header with the session still alive afterwards, 204 with it, 401 after.
Mutation-tested the three properties this commit claims: comparing CSRF against
the cookie instead of the session, dropping the expiry check, and dropping the
TOTP requirement each failed exactly the tests written for them.
Tests: 221 -> 257.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
9c44ab6b2a
commit
0c3fb2d837
16 files changed
+1796
-21
No files matched your search
@@ -13,6 +13,12 @@ os.environ.setdefault("POORBIRD_STATE_DIR", "/tmp/poorbird-test/state")
|
||||
# camera would, and would otherwise spend its own budget and start asserting
|
||||
# against 429s. tests/test_ratelimit.py turns it back on deliberately.
|
||||
os.environ.setdefault("POORBIRD_RATE_LIMIT_ENABLED", "false")
|
||||
# The test client speaks http://testserver, and a Secure cookie is not stored
|
||||
# for an http origin -- so with this left at its production default every
|
||||
# session test would fail with "not signed in" and nothing to show why. The
|
||||
# same trap catches local development against the Vite dev server, which is
|
||||
# why this is a setting at all. See config.session_cookie_secure.
|
||||
os.environ.setdefault("POORBIRD_SESSION_COOKIE_SECURE", "false")
|
||||
|
||||
|
||||
def database_is_reachable() -> bool:
|
||||
|
||||
@@ -0,0 +1,524 @@
|
||||
"""Sessions, login, logout and CSRF (SPEC 3.1, REVIEW SEC-007).
|
||||
|
||||
Needs a real PostgreSQL: sessions are rows, and the point of server-side
|
||||
sessions is that deleting the row takes effect immediately. Mocking that away
|
||||
would test the mock.
|
||||
|
||||
The ``client`` fixture is session-scoped and its cookie jar therefore outlives
|
||||
a single test, so every fixture here clears it. A signed-in cookie leaking into
|
||||
the next test would make that test pass for the wrong reason, which is worse
|
||||
than failing.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
import uuid
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
import pyotp
|
||||
import pytest
|
||||
from conftest import needs_db
|
||||
from sqlalchemy import delete, func, select, text
|
||||
|
||||
from poorbird.api.sessions import CSRF_COOKIE, CSRF_HEADER, SESSION_COOKIE
|
||||
from poorbird.models import AuditLog, User
|
||||
from poorbird.models import Session as UserSession
|
||||
from poorbird.passwords import hash_password
|
||||
from poorbird.totp import new_secret
|
||||
|
||||
pytestmark = [pytest.mark.db, needs_db]
|
||||
|
||||
PASSWORD = "a-perfectly-usable-passphrase"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db():
|
||||
from poorbird.db import SessionLocal
|
||||
|
||||
with SessionLocal() as session:
|
||||
yield session
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clean_cookies(client):
|
||||
"""No test starts signed in, and none leaves a cookie behind."""
|
||||
client.cookies.clear()
|
||||
yield
|
||||
client.cookies.clear()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def no_audit_leaks(db):
|
||||
"""Sweep audit rows by id, not by user.
|
||||
|
||||
audit_log.user_id is ON DELETE SET NULL on purpose -- a trail that vanished
|
||||
with the account would be useless -- so deleting a test's user does not
|
||||
delete its audit rows. Worse, a failed login for a username that never
|
||||
existed writes user_id NULL from the start, which no user-scoped cleanup
|
||||
can ever match. Seven suite runs had quietly left eight such rows behind
|
||||
before this fixture existed.
|
||||
|
||||
A high-water mark catches every row any test in this file creates,
|
||||
whichever user it is attributed to, including none.
|
||||
"""
|
||||
high_water = db.scalar(select(func.coalesce(func.max(AuditLog.id), 0)))
|
||||
yield
|
||||
db.execute(delete(AuditLog).where(AuditLog.id > high_water))
|
||||
db.commit()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_user(db):
|
||||
"""Users that are removed even when the test fails.
|
||||
|
||||
Teardown belongs in a fixture: a failing assertion skips the rest of the
|
||||
test body, so cleanup written at the end of it silently never runs. This
|
||||
has bitten this suite three times already.
|
||||
|
||||
Sessions cascade from the user, but audit_log rows are ON DELETE SET NULL
|
||||
by design -- an audit trail that vanished when the account did would be
|
||||
useless -- so they are removed explicitly here.
|
||||
"""
|
||||
created: list[int] = []
|
||||
|
||||
def make(
|
||||
*,
|
||||
role: str = "viewer",
|
||||
password: str | None = PASSWORD,
|
||||
totp: bool = False,
|
||||
is_active: bool = True,
|
||||
) -> User:
|
||||
user = User(
|
||||
username=f"t_{secrets.token_hex(6)}",
|
||||
password_hash=hash_password(password) if password is not None else None,
|
||||
role=role,
|
||||
totp_secret=new_secret() if totp else None,
|
||||
is_active=is_active,
|
||||
)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
created.append(user.id)
|
||||
return user
|
||||
|
||||
yield make
|
||||
|
||||
for user_id in created:
|
||||
db.execute(text("DELETE FROM audit_log WHERE user_id = :i"), {"i": user_id})
|
||||
db.execute(text("DELETE FROM sessions WHERE user_id = :i"), {"i": user_id})
|
||||
db.execute(text("DELETE FROM users WHERE id = :i"), {"i": user_id})
|
||||
db.commit()
|
||||
|
||||
|
||||
def login(client, user: User, *, password: str = PASSWORD, totp: str | None = None):
|
||||
body: dict[str, object] = {"username": user.username, "password": password}
|
||||
if totp is not None:
|
||||
body["totp"] = totp
|
||||
return client.post("/api/v1/auth/login", json=body)
|
||||
|
||||
|
||||
def csrf_headers(client) -> dict[str, str]:
|
||||
"""What the browser does: read the readable cookie, echo it in the header."""
|
||||
return {CSRF_HEADER: client.cookies.get(CSRF_COOKIE, "")}
|
||||
|
||||
|
||||
# --- signing in -------------------------------------------------------------
|
||||
|
||||
|
||||
def test_a_correct_password_signs_you_in(client, make_user):
|
||||
user = make_user(role="editor")
|
||||
response = login(client, user)
|
||||
|
||||
assert response.status_code == 200
|
||||
body = response.json()
|
||||
assert body == {
|
||||
"id": user.id,
|
||||
"username": user.username,
|
||||
"role": "editor",
|
||||
"locale": "de",
|
||||
"theme": "light",
|
||||
}
|
||||
|
||||
|
||||
def test_the_response_carries_no_password_or_secret_material(client, make_user):
|
||||
"""A response shape is where things accumulate, and this one goes to a
|
||||
browser. Assert the absence, not just the presence."""
|
||||
user = make_user(totp=True)
|
||||
body = login(client, user, totp=pyotp.TOTP(user.totp_secret).now()).json()
|
||||
|
||||
assert set(body) == {"id", "username", "role", "locale", "theme"}
|
||||
serialised = str(body)
|
||||
assert PASSWORD not in serialised
|
||||
assert user.totp_secret not in serialised
|
||||
|
||||
|
||||
def test_both_cookies_are_set_with_the_right_visibility(client, make_user):
|
||||
response = login(client, make_user())
|
||||
|
||||
cookies = response.headers.get_list("set-cookie")
|
||||
session_cookie = next(c for c in cookies if c.startswith(SESSION_COOKIE))
|
||||
csrf_cookie = next(c for c in cookies if c.startswith(CSRF_COOKIE))
|
||||
|
||||
# The session cookie must be unreadable by script; the CSRF cookie must be
|
||||
# readable, because the whole mechanism is the app's own JS echoing it.
|
||||
assert "HttpOnly" in session_cookie
|
||||
assert "HttpOnly" not in csrf_cookie
|
||||
# Lax, not Strict: Strict would also drop the cookie when someone follows an
|
||||
# ordinary link into the app and they would arrive apparently signed out.
|
||||
assert "SameSite=lax" in session_cookie.lower() or "samesite=lax" in session_cookie.lower()
|
||||
|
||||
|
||||
def test_a_wrong_password_is_refused(client, make_user):
|
||||
assert login(client, make_user(), password="not the password").status_code == 401
|
||||
|
||||
|
||||
def test_an_unknown_username_is_refused_identically(client, make_user):
|
||||
"""Same status and same message as a wrong password.
|
||||
|
||||
A distinguishable answer is a username oracle: it tells an attacker which
|
||||
accounts exist, which is the first half of the work.
|
||||
"""
|
||||
user = make_user()
|
||||
wrong_password = login(client, user, password="not the password")
|
||||
no_such_user = client.post(
|
||||
"/api/v1/auth/login", json={"username": "nobody-here", "password": PASSWORD}
|
||||
)
|
||||
|
||||
assert wrong_password.status_code == no_such_user.status_code == 401
|
||||
assert wrong_password.json() == no_such_user.json()
|
||||
|
||||
|
||||
def test_a_user_with_no_password_set_cannot_sign_in(client, make_user):
|
||||
"""Every row seeded before Phase 3 has password_hash IS NULL. None of them
|
||||
may be loggable-in, and the route must not 500 trying."""
|
||||
assert login(client, make_user(password=None)).status_code == 401
|
||||
|
||||
|
||||
def test_an_inactive_account_is_refused(client, make_user):
|
||||
assert login(client, make_user(is_active=False)).status_code == 401
|
||||
|
||||
|
||||
def test_a_deactivated_user_loses_an_existing_session(client, make_user, db):
|
||||
"""Deactivating an account has to take effect now, not at expiry."""
|
||||
user = make_user()
|
||||
assert login(client, user).status_code == 200
|
||||
assert client.get("/api/v1/auth/session").status_code == 200
|
||||
|
||||
user.is_active = False
|
||||
db.commit()
|
||||
|
||||
assert client.get("/api/v1/auth/session").status_code == 401
|
||||
|
||||
|
||||
# --- second factor ----------------------------------------------------------
|
||||
|
||||
|
||||
def test_totp_is_required_when_the_account_has_a_secret(client, make_user):
|
||||
user = make_user(totp=True)
|
||||
assert login(client, user).status_code == 401
|
||||
|
||||
|
||||
def test_a_wrong_totp_code_is_refused(client, make_user):
|
||||
user = make_user(totp=True)
|
||||
assert login(client, user, totp="000000").status_code == 401
|
||||
|
||||
|
||||
def test_a_correct_totp_code_signs_you_in(client, make_user):
|
||||
user = make_user(totp=True)
|
||||
assert login(client, user, totp=pyotp.TOTP(user.totp_secret).now()).status_code == 200
|
||||
|
||||
|
||||
def test_a_totp_code_alone_is_not_enough(client, make_user):
|
||||
"""The second factor is second, not alternative."""
|
||||
user = make_user(totp=True)
|
||||
response = login(client, user, password="wrong", totp=pyotp.TOTP(user.totp_secret).now())
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
def test_an_account_without_totp_ignores_a_supplied_code(client, make_user):
|
||||
"""Sending a code to an account that has no secret must not fail closed in
|
||||
the other direction -- it is simply irrelevant."""
|
||||
assert login(client, make_user(), totp="123456").status_code == 200
|
||||
|
||||
|
||||
# --- the session itself -----------------------------------------------------
|
||||
|
||||
|
||||
def test_session_returns_401_when_not_signed_in(client):
|
||||
"""401, not 404. The UI reads 404 as "this server has no auth at all" and
|
||||
shows a banner; now that the endpoint exists, that must stop."""
|
||||
assert client.get("/api/v1/auth/session").status_code == 401
|
||||
|
||||
|
||||
def test_session_returns_the_user_when_signed_in(client, make_user):
|
||||
user = make_user(role="admin", totp=True)
|
||||
login(client, user, totp=pyotp.TOTP(user.totp_secret).now())
|
||||
|
||||
response = client.get("/api/v1/auth/session")
|
||||
assert response.status_code == 200
|
||||
assert response.json()["username"] == user.username
|
||||
assert response.json()["role"] == "admin"
|
||||
|
||||
|
||||
def test_only_the_hash_of_the_session_token_is_stored(client, make_user, db):
|
||||
"""The cookie value must not be findable in the database.
|
||||
|
||||
This is the whole reason sessions.id is internal and the cookie is a
|
||||
separate token: a database dump should not hand over every live session.
|
||||
"""
|
||||
user = make_user()
|
||||
login(client, user)
|
||||
cookie = client.cookies.get(SESSION_COOKIE)
|
||||
|
||||
rows = db.scalars(select(UserSession).where(UserSession.user_id == user.id)).all()
|
||||
assert len(rows) == 1
|
||||
assert rows[0].token_hash != cookie
|
||||
assert cookie not in rows[0].token_hash
|
||||
# And the token must actually resolve, or the hash is of the wrong thing.
|
||||
assert client.get("/api/v1/auth/session").status_code == 200
|
||||
|
||||
|
||||
def test_an_unknown_session_cookie_is_refused(client, make_user):
|
||||
make_user()
|
||||
client.cookies.set(SESSION_COOKIE, secrets.token_hex(32))
|
||||
assert client.get("/api/v1/auth/session").status_code == 401
|
||||
|
||||
|
||||
def test_an_expired_session_is_refused_and_cleaned_up(client, make_user, db):
|
||||
user = make_user()
|
||||
login(client, user)
|
||||
|
||||
db.execute(
|
||||
text("UPDATE sessions SET expires_at = :t WHERE user_id = :i"),
|
||||
{"t": datetime.now(UTC) - timedelta(minutes=1), "i": user.id},
|
||||
)
|
||||
db.commit()
|
||||
|
||||
assert client.get("/api/v1/auth/session").status_code == 401
|
||||
# Enforced on read, and swept on the way past.
|
||||
assert db.scalars(select(UserSession).where(UserSession.user_id == user.id)).all() == []
|
||||
|
||||
|
||||
def test_each_login_opens_a_separate_session(client, make_user, db):
|
||||
"""Two browsers, two rows. Signing out of one must not sign out the other,
|
||||
which is only possible if they are distinct."""
|
||||
user = make_user()
|
||||
login(client, user)
|
||||
first = client.cookies.get(SESSION_COOKIE)
|
||||
client.cookies.clear()
|
||||
login(client, user)
|
||||
second = client.cookies.get(SESSION_COOKIE)
|
||||
|
||||
assert first != second
|
||||
assert len(db.scalars(select(UserSession).where(UserSession.user_id == user.id)).all()) == 2
|
||||
|
||||
|
||||
# --- signing out ------------------------------------------------------------
|
||||
|
||||
|
||||
def test_logout_ends_the_session(client, make_user, db):
|
||||
user = make_user()
|
||||
login(client, user)
|
||||
|
||||
assert client.post("/api/v1/auth/logout", headers=csrf_headers(client)).status_code == 204
|
||||
assert db.scalars(select(UserSession).where(UserSession.user_id == user.id)).all() == []
|
||||
|
||||
|
||||
def test_the_old_cookie_stops_working_after_logout(client, make_user):
|
||||
"""The row is deleted, not flagged, so this is immediate. It is the reason
|
||||
sessions are server-side rather than a self-contained token."""
|
||||
user = make_user()
|
||||
login(client, user)
|
||||
cookie = client.cookies.get(SESSION_COOKIE)
|
||||
csrf = csrf_headers(client)
|
||||
|
||||
client.post("/api/v1/auth/logout", headers=csrf)
|
||||
client.cookies.set(SESSION_COOKIE, cookie)
|
||||
|
||||
assert client.get("/api/v1/auth/session").status_code == 401
|
||||
|
||||
|
||||
def test_logout_without_a_session_is_not_an_error(client):
|
||||
"""A client must always be able to sign out. A 401 here would leave a
|
||||
browser holding a cookie it cannot get rid of."""
|
||||
assert client.post("/api/v1/auth/logout").status_code == 204
|
||||
|
||||
|
||||
def test_logging_out_one_session_leaves_the_other_alone(client, make_user, db):
|
||||
user = make_user()
|
||||
login(client, user)
|
||||
first_cookie = client.cookies.get(SESSION_COOKIE)
|
||||
|
||||
client.cookies.clear()
|
||||
login(client, user)
|
||||
client.post("/api/v1/auth/logout", headers=csrf_headers(client))
|
||||
|
||||
client.cookies.clear()
|
||||
client.cookies.set(SESSION_COOKIE, first_cookie)
|
||||
assert client.get("/api/v1/auth/session").status_code == 200
|
||||
|
||||
|
||||
def test_changing_a_password_ends_every_session(client, make_user, db):
|
||||
"""Otherwise the old password keeps working through any browser already
|
||||
signed in, which is usually why it was changed."""
|
||||
from poorbird.api.sessions import revoke_all_for_user
|
||||
|
||||
user = make_user()
|
||||
login(client, user)
|
||||
assert client.get("/api/v1/auth/session").status_code == 200
|
||||
|
||||
assert revoke_all_for_user(db, user.id) == 1
|
||||
db.commit()
|
||||
|
||||
assert client.get("/api/v1/auth/session").status_code == 401
|
||||
|
||||
|
||||
# --- CSRF -------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_a_mutating_request_without_a_csrf_header_is_refused(client, make_user):
|
||||
user = make_user()
|
||||
login(client, user)
|
||||
|
||||
response = client.post("/api/v1/auth/logout")
|
||||
assert response.status_code == 403
|
||||
assert "csrf" in response.json()["detail"].lower()
|
||||
|
||||
|
||||
def test_a_mutating_request_with_a_wrong_csrf_token_is_refused(client, make_user):
|
||||
user = make_user()
|
||||
login(client, user)
|
||||
|
||||
response = client.post("/api/v1/auth/logout", headers={CSRF_HEADER: secrets.token_hex(32)})
|
||||
assert response.status_code == 403
|
||||
|
||||
|
||||
def test_a_csrf_token_from_a_different_session_is_refused(client, make_user):
|
||||
"""The check is against the token on *this* session's row, not merely
|
||||
against the cookie. Plain double-submit would accept any self-consistent
|
||||
pair, so someone able to write a cookie on the domain could satisfy it.
|
||||
"""
|
||||
user = make_user()
|
||||
login(client, user)
|
||||
victim_session_cookie = client.cookies.get(SESSION_COOKIE)
|
||||
|
||||
client.cookies.clear()
|
||||
login(client, user)
|
||||
other_csrf = client.cookies.get(CSRF_COOKIE)
|
||||
|
||||
# The victim's session, with an attacker-chosen (but real) CSRF value in
|
||||
# both the cookie and the header -- which is exactly what a cookie-writing
|
||||
# attacker could arrange.
|
||||
client.cookies.clear()
|
||||
client.cookies.set(SESSION_COOKIE, victim_session_cookie)
|
||||
client.cookies.set(CSRF_COOKIE, other_csrf)
|
||||
|
||||
response = client.post("/api/v1/auth/logout", headers={CSRF_HEADER: other_csrf})
|
||||
assert response.status_code == 403
|
||||
|
||||
|
||||
def test_a_matching_csrf_token_is_accepted(client, make_user):
|
||||
user = make_user()
|
||||
login(client, user)
|
||||
assert client.post("/api/v1/auth/logout", headers=csrf_headers(client)).status_code == 204
|
||||
|
||||
|
||||
def test_reading_never_needs_a_csrf_token(client, make_user):
|
||||
"""A GET that needed one would be a GET that mutates."""
|
||||
login(client, make_user())
|
||||
assert client.get("/api/v1/auth/session").status_code == 200
|
||||
|
||||
|
||||
def test_logging_in_needs_no_csrf_token(client, make_user):
|
||||
"""There is no session cookie yet, so it is exempt without a special case
|
||||
-- which is why the middleware keys on the cookie rather than the path."""
|
||||
assert login(client, make_user()).status_code == 200
|
||||
|
||||
|
||||
def test_device_endpoints_are_not_subject_to_csrf(client):
|
||||
"""A camera has no way to obtain a CSRF token, and blocking /ingest would
|
||||
take the whole system down. Device requests carry a bearer token and no
|
||||
cookies, which is what the middleware keys on.
|
||||
"""
|
||||
response = client.post(
|
||||
"/api/v1/ingest",
|
||||
content=b"\xff\xd8\xff not really a jpeg",
|
||||
headers={"Authorization": "Bearer nonsense", "Content-Type": "image/jpeg"},
|
||||
)
|
||||
# 401 for the bad token -- the point is that it is not 403-for-CSRF.
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
# --- audit trail ------------------------------------------------------------
|
||||
|
||||
|
||||
def test_a_successful_login_is_audited(client, make_user, db):
|
||||
user = make_user()
|
||||
login(client, user)
|
||||
|
||||
actions = db.scalars(
|
||||
select(AuditLog.action).where(AuditLog.user_id == user.id).order_by(AuditLog.id)
|
||||
).all()
|
||||
assert "login" in actions
|
||||
|
||||
|
||||
def test_a_failed_login_is_audited_too(client, make_user, db):
|
||||
"""A log of only the successes cannot answer the question worth asking
|
||||
afterwards, which is how many times someone tried first."""
|
||||
user = make_user()
|
||||
login(client, user, password="wrong")
|
||||
login(client, user, password="wrong again")
|
||||
|
||||
actions = db.scalars(select(AuditLog.action).where(AuditLog.user_id == user.id)).all()
|
||||
assert actions.count("login_failed") == 2
|
||||
|
||||
|
||||
def test_the_audit_record_never_contains_the_password(client, make_user, db):
|
||||
user = make_user()
|
||||
login(client, user, password="hunter2-and-then-some")
|
||||
|
||||
rows = db.scalars(select(AuditLog).where(AuditLog.user_id == user.id)).all()
|
||||
assert rows
|
||||
for row in rows:
|
||||
assert "hunter2" not in str(row.after)
|
||||
|
||||
|
||||
def test_logout_is_audited(client, make_user, db):
|
||||
user = make_user()
|
||||
login(client, user)
|
||||
client.post("/api/v1/auth/logout", headers=csrf_headers(client))
|
||||
|
||||
actions = db.scalars(select(AuditLog.action).where(AuditLog.user_id == user.id)).all()
|
||||
assert "logout" in actions
|
||||
|
||||
|
||||
# --- housekeeping -----------------------------------------------------------
|
||||
|
||||
|
||||
def test_purge_expired_removes_only_expired_sessions(client, make_user, db):
|
||||
"""The sweep lives with the worker's other scheduled housekeeping, not in
|
||||
api/, so that the worker never imports from the HTTP layer."""
|
||||
from poorbird.worker.handlers import HANDLERS
|
||||
|
||||
user = make_user()
|
||||
live = UserSession(
|
||||
user_id=user.id,
|
||||
token_hash=uuid.uuid4().hex + uuid.uuid4().hex,
|
||||
csrf_token=secrets.token_hex(16),
|
||||
expires_at=datetime.now(UTC) + timedelta(days=1),
|
||||
)
|
||||
dead = UserSession(
|
||||
user_id=user.id,
|
||||
token_hash=uuid.uuid4().hex + uuid.uuid4().hex,
|
||||
csrf_token=secrets.token_hex(16),
|
||||
expires_at=datetime.now(UTC) - timedelta(days=1),
|
||||
)
|
||||
db.add_all([live, dead])
|
||||
db.commit()
|
||||
live_id = live.id
|
||||
|
||||
HANDLERS["purge_expired_sessions"](db, {})
|
||||
|
||||
remaining = db.scalars(select(UserSession).where(UserSession.user_id == user.id)).all()
|
||||
assert [r.id for r in remaining] == [live_id]
|
||||
Reference in new issue
Block a user