feat: login mit serverseitigen sessions
- POST /api/auth/login|logout, GET /api/auth/me - Session-Token nur gehasht gespeichert, Cookie HttpOnly/Secure/SameSite=Lax - Ablauf nach 30 Tagen Inaktivität bzw. spätestens 90 Tagen - Sessions pro Gerät auflisten und widerrufen, Rotation beim Login - Passwortänderung beendet alle anderen Sessions Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
04161bcf1d
commit
18f0d04ce9
11 files changed
+556
-3
No files matched your search
Whitespace-only changes.
@@ -57,3 +57,25 @@ def client(app_env) -> Iterator[TestClient]:
|
||||
# https so that Secure cookies are sent back by the test client
|
||||
with TestClient(create_app(), base_url="https://testserver") as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
PASSWORD = "correct horse battery"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_user(db):
|
||||
from app.models import Role
|
||||
from app.services.users import create_user
|
||||
|
||||
def _make(username: str = "anna", role: Role = Role.USER, password: str = PASSWORD):
|
||||
return create_user(db, username, password, role)
|
||||
|
||||
return _make
|
||||
|
||||
|
||||
def login(client: TestClient, username: str, password: str = PASSWORD):
|
||||
"""Log in and return the response; the CSRF token is set as default header."""
|
||||
response = client.post("/api/auth/login", json={"username": username, "password": password})
|
||||
if response.status_code == 200:
|
||||
client.headers["X-CSRF-Token"] = client.cookies["lc_csrf"]
|
||||
return response
|
||||
@@ -0,0 +1,219 @@
|
||||
from datetime import timedelta
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.models import LoginAttempt, UserSession, utcnow
|
||||
from tests.conftest import PASSWORD, login
|
||||
|
||||
|
||||
def test_login_sets_secure_cookies(client, make_user):
|
||||
make_user("anna")
|
||||
|
||||
response = login(client, "Anna")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["username"] == "anna"
|
||||
cookies = response.headers.get_list("set-cookie")
|
||||
session_cookie = next(c for c in cookies if c.startswith("lc_session="))
|
||||
csrf_cookie = next(c for c in cookies if c.startswith("lc_csrf="))
|
||||
for attr in ("HttpOnly", "Secure", "SameSite=lax", "Path=/"):
|
||||
assert attr.lower() in session_cookie.lower()
|
||||
assert "httponly" not in csrf_cookie.lower()
|
||||
assert "secure" in csrf_cookie.lower()
|
||||
|
||||
|
||||
def test_me_requires_login(client):
|
||||
assert client.get("/api/auth/me").status_code == 401
|
||||
|
||||
|
||||
def test_me_after_login(client, make_user):
|
||||
make_user("anna")
|
||||
login(client, "anna")
|
||||
|
||||
assert client.get("/api/auth/me").json()["username"] == "anna"
|
||||
|
||||
|
||||
def test_session_token_is_stored_hashed(client, make_user, db):
|
||||
make_user("anna")
|
||||
login(client, "anna")
|
||||
|
||||
token = client.cookies["lc_session"]
|
||||
stored = db.query(UserSession).one()
|
||||
assert stored.token_hash != token
|
||||
assert token not in stored.token_hash
|
||||
|
||||
|
||||
def test_wrong_password_and_unknown_user_look_identical(client, make_user):
|
||||
make_user("anna")
|
||||
|
||||
wrong_password = login(client, "anna", "wrong password!!")
|
||||
unknown_user = login(client, "nobody", "wrong password!!")
|
||||
|
||||
assert wrong_password.status_code == unknown_user.status_code == 401
|
||||
assert wrong_password.json() == unknown_user.json()
|
||||
|
||||
|
||||
def test_inactive_user_cannot_login(client, make_user, db):
|
||||
user = make_user("anna")
|
||||
user.is_active = False
|
||||
db.commit()
|
||||
|
||||
assert login(client, "anna").status_code == 401
|
||||
|
||||
|
||||
def test_login_attempts_are_recorded(client, make_user, db):
|
||||
make_user("anna")
|
||||
login(client, "anna", "wrong password!!")
|
||||
login(client, "anna")
|
||||
|
||||
attempts = db.query(LoginAttempt).order_by(LoginAttempt.id).all()
|
||||
assert [a.success for a in attempts] == [False, True]
|
||||
|
||||
|
||||
def test_logout_revokes_session(client, make_user, db):
|
||||
make_user("anna")
|
||||
login(client, "anna")
|
||||
token = client.cookies["lc_session"]
|
||||
|
||||
assert client.post("/api/auth/logout").status_code == 204
|
||||
assert db.query(UserSession).count() == 0
|
||||
|
||||
client.cookies.set("lc_session", token)
|
||||
assert client.get("/api/auth/me").status_code == 401
|
||||
|
||||
|
||||
def test_login_rotates_existing_session(client, make_user, db):
|
||||
make_user("anna")
|
||||
login(client, "anna")
|
||||
first = client.cookies["lc_session"]
|
||||
|
||||
login(client, "anna")
|
||||
|
||||
assert client.cookies["lc_session"] != first
|
||||
assert db.query(UserSession).count() == 1
|
||||
|
||||
|
||||
def test_expired_session_is_rejected(client, make_user, db):
|
||||
make_user("anna")
|
||||
login(client, "anna")
|
||||
session = db.query(UserSession).one()
|
||||
session.expires_at = utcnow() - timedelta(seconds=1)
|
||||
db.commit()
|
||||
|
||||
assert client.get("/api/auth/me").status_code == 401
|
||||
assert db.query(UserSession).count() == 0
|
||||
|
||||
|
||||
def test_idle_session_is_rejected(client, make_user, db):
|
||||
make_user("anna")
|
||||
login(client, "anna")
|
||||
session = db.query(UserSession).one()
|
||||
session.last_seen_at = utcnow() - timedelta(days=31)
|
||||
db.commit()
|
||||
|
||||
assert client.get("/api/auth/me").status_code == 401
|
||||
|
||||
|
||||
def test_deactivated_user_loses_session(client, make_user, db):
|
||||
user = make_user("anna")
|
||||
login(client, "anna")
|
||||
user.is_active = False
|
||||
db.commit()
|
||||
|
||||
assert client.get("/api/auth/me").status_code == 401
|
||||
|
||||
|
||||
def test_change_password(client, make_user):
|
||||
make_user("anna")
|
||||
login(client, "anna")
|
||||
|
||||
response = client.post(
|
||||
"/api/auth/password",
|
||||
json={"current_password": PASSWORD, "new_password": "brand new password"},
|
||||
)
|
||||
|
||||
assert response.status_code == 204
|
||||
assert client.get("/api/auth/me").status_code == 200 # current session survives
|
||||
client.post("/api/auth/logout")
|
||||
assert login(client, "anna", "brand new password").status_code == 200
|
||||
|
||||
|
||||
def test_change_password_requires_current(client, make_user):
|
||||
make_user("anna")
|
||||
login(client, "anna")
|
||||
|
||||
response = client.post(
|
||||
"/api/auth/password",
|
||||
json={"current_password": "wrong password!!", "new_password": "brand new password"},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_change_password_enforces_policy(client, make_user):
|
||||
make_user("anna")
|
||||
login(client, "anna")
|
||||
|
||||
response = client.post(
|
||||
"/api/auth/password", json={"current_password": PASSWORD, "new_password": "short"}
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "12 Zeichen" in response.json()["detail"]
|
||||
|
||||
|
||||
def test_change_password_revokes_other_devices(client, make_user, app_env):
|
||||
make_user("anna")
|
||||
login(client, "anna")
|
||||
with TestClient(client.app, base_url="https://testserver") as phone:
|
||||
login(phone, "anna")
|
||||
|
||||
client.post(
|
||||
"/api/auth/password",
|
||||
json={"current_password": PASSWORD, "new_password": "brand new password"},
|
||||
)
|
||||
|
||||
assert phone.get("/api/auth/me").status_code == 401
|
||||
|
||||
|
||||
def test_list_and_revoke_sessions(client, make_user):
|
||||
make_user("anna")
|
||||
login(client, "anna")
|
||||
with TestClient(client.app, base_url="https://testserver") as phone:
|
||||
phone.headers["User-Agent"] = "iPhone"
|
||||
login(phone, "anna")
|
||||
|
||||
sessions = client.get("/api/auth/sessions").json()
|
||||
assert len(sessions) == 2
|
||||
assert sum(s["current"] for s in sessions) == 1
|
||||
other = next(s for s in sessions if not s["current"])
|
||||
assert other["user_agent"] == "iPhone"
|
||||
|
||||
assert client.delete(f"/api/auth/sessions/{other['id']}").status_code == 204
|
||||
assert phone.get("/api/auth/me").status_code == 401
|
||||
|
||||
|
||||
def test_revoke_all_other_sessions(client, make_user):
|
||||
make_user("anna")
|
||||
login(client, "anna")
|
||||
with TestClient(client.app, base_url="https://testserver") as phone:
|
||||
login(phone, "anna")
|
||||
|
||||
assert client.delete("/api/auth/sessions").json() == {"revoked": 1}
|
||||
assert phone.get("/api/auth/me").status_code == 401
|
||||
assert client.get("/api/auth/me").status_code == 200
|
||||
|
||||
|
||||
def test_users_cannot_see_or_revoke_foreign_sessions(client, make_user):
|
||||
make_user("anna")
|
||||
make_user("bert")
|
||||
with TestClient(client.app, base_url="https://testserver") as bert:
|
||||
login(bert, "bert")
|
||||
bert_session_id = bert.get("/api/auth/sessions").json()[0]["id"]
|
||||
|
||||
login(client, "anna")
|
||||
anna_sessions = client.get("/api/auth/sessions").json()
|
||||
assert all(s["id"] != bert_session_id for s in anna_sessions)
|
||||
|
||||
assert client.delete(f"/api/auth/sessions/{bert_session_id}").status_code == 404
|
||||
assert bert.get("/api/auth/me").status_code == 200
|
||||
Reference in new issue
Block a user