porchlight/tests/test_password_change.py
Johan Lundberg baef5e0e2e
fix(security): require CSRF-protected POST to consume a registration link
GET /register/{token} consumed the magic-link token and created a session, so
a side-effecting state change happened on a safe method — link prefetchers,
email scanners, or a cross-site GET could trigger account setup/login.

Split the flow: GET validates the token (without consuming) and renders a
confirmation form; POST /register/{token} consumes the token, runs the
existing checks, and establishes the session. The POST carries a CSRF token
and the session is reset on login as for other auth paths.

Refs: porchlight-9k0

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-05 13:40:30 +02:00

127 lines
4.2 KiB
Python

from datetime import UTC, datetime
import pytest
from httpx import AsyncClient
from porchlight.authn.password import PasswordHasher, PasswordService
from porchlight.models import PasswordCredential, User
from tests.conftest import get_csrf_token
async def _login_user_with_password(client: AsyncClient) -> str:
"""Create user with password, login, return CSRF token."""
app = client._transport.app
user_repo = app.state.user_repo
cred_repo = app.state.credential_repo
user = User(
userid="pw-user-01",
username="pwuser",
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
)
await user_repo.create(user)
svc = PasswordService(hasher=PasswordHasher(time_cost=1, memory_cost=8192))
await cred_repo.create_password(PasswordCredential(user_id=user.userid, password_hash=svc.hash("OldPass123!ok")))
token = await get_csrf_token(client)
await client.post(
"/login/password",
data={"username": "pwuser", "password": "OldPass123!ok"},
headers={"HX-Request": "true", "X-CSRF-Token": token},
)
# Login resets the session (fixation defense); fetch a fresh CSRF token.
return await get_csrf_token(client)
async def _login_user_without_password(client: AsyncClient) -> str:
"""Create user without password, simulate session login, return CSRF token."""
app = client._transport.app
user_repo = app.state.user_repo
user = User(
userid="pw-user-02",
username="newuser",
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
)
await user_repo.create(user)
# Simulate session login via magic link (GET shows the form, POST consumes)
token = await get_csrf_token(client)
magic_link_service = app.state.magic_link_service
link = await magic_link_service.create(username="newuser", created_by="admin", note="test")
await client.post(
f"/register/{link.token}",
headers={"X-CSRF-Token": token},
follow_redirects=False,
)
# Re-fetch CSRF token after session change
token = await get_csrf_token(client)
return token
@pytest.mark.asyncio
async def test_change_password_requires_current(client: AsyncClient) -> None:
token = await _login_user_with_password(client)
response = await client.post(
"/manage/credentials/password",
data={
"password": "NewStrong!Pass99",
"confirm": "NewStrong!Pass99",
},
headers={"X-CSRF-Token": token},
)
assert "alert" in response.text
assert "urrent password" in response.text
@pytest.mark.asyncio
async def test_change_password_wrong_current_rejected(client: AsyncClient) -> None:
token = await _login_user_with_password(client)
response = await client.post(
"/manage/credentials/password",
data={
"current_password": "WrongPassword",
"password": "NewStrong!Pass99",
"confirm": "NewStrong!Pass99",
},
headers={"X-CSRF-Token": token},
)
assert "alert" in response.text
assert "incorrect" in response.text.lower() or "Invalid" in response.text or "current" in response.text.lower()
@pytest.mark.asyncio
async def test_change_password_correct_current_succeeds(client: AsyncClient) -> None:
token = await _login_user_with_password(client)
response = await client.post(
"/manage/credentials/password",
data={
"current_password": "OldPass123!ok",
"password": "NewStrong!Pass99",
"confirm": "NewStrong!Pass99",
},
headers={"X-CSRF-Token": token},
)
assert "updated" in response.text.lower() or "status" in response.text
@pytest.mark.asyncio
async def test_set_password_no_current_needed(client: AsyncClient) -> None:
"""First-time password setup should not require current password."""
token = await _login_user_without_password(client)
response = await client.post(
"/manage/credentials/password",
data={
"password": "FirstPass!Strong99",
"confirm": "FirstPass!Strong99",
},
headers={"X-CSRF-Token": token},
)
assert "updated" in response.text.lower() or "status" in response.text