Files
karaoke-gen/backend/tests/test_magic_link_status.py
T
Andrew Beveridge ☄️ d84a827be3 feat(auth): show already-used/expired message upfront on verify page (#871)
@coderabbitai ignore

Follow-up to #870. That PR added the "Complete Sign-In" gate so email
link-scanners can't burn a magic link before the user clicks. This PR
improves the case where the link is **genuinely already used or
expired**: instead of showing a "Complete Sign-In" button that only
fails when clicked, the verify page now shows the "link expired or
already used" message (with one-click resend) **upfront**.

### How it stays scanner-safe

The decision uses a **read-only** status probe that does **not** consume
the token:

- New `GET /api/users/auth/link-status` +
`UserService.get_magic_link_status()` return `valid` / `used` /
`expired` / `invalid` without mutating the doc (verified by a unit test
asserting `update`/`set` are never called).
- The verify page calls it on mount:
- `valid` → show the **Complete Sign-In** gate (token still spent only
on the explicit click).
- `used`/`expired`/`invalid` → show the failure UI + resend immediately.
- probe **errors** → fall back to the gate, so a transient
status-endpoint failure never blocks a user holding a valid link.

Because the probe is non-mutating, a scanner rendering the page still
can't burn a valid token — consumption remains gated behind the click,
exactly as in #870.

### Notes

- Reuses existing i18n strings (`pleaseWait`, `verifyingWait`,
`linkExpiredOrUsed`) — no new translation keys.
- The status endpoint is an unauthenticated read, same trust model as
`/auth/verify` (the 256-bit token is the only credential); it reveals
only valid/used/expired for a token the caller already holds.

### Testing

- **Backend (9):** service returns correct status for
valid/used/expired/missing/empty **and does not consume** a valid token;
endpoint returns the status and short-circuits empty tokens without
hitting Firestore.
- **Frontend (8):** valid → gate, no verify on mount; dead link →
failure UI upfront with no gate and no verify call; probe-error → gate
fallback; resend recovery intact.
- Full frontend suite green (1072); backend auth suite green (75); `tsc`
+ `eslint` clean; CodeRabbit local: 0 findings.
- Version `0.190.1 → 0.190.2`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-07-03 19:40:52 +00:00

133 lines
5.5 KiB
Python

"""
Unit tests for UserService.get_magic_link_status.
This is a READ-ONLY status check used by the verify page to decide, on load,
whether to show the "Complete Sign-In" gate (valid link) or an "already used /
expired" message (dead link). It must NEVER consume the token — otherwise an
email link-scanner that renders the verify page would burn a valid link before
the real user clicks, which is exactly the bug this whole feature prevents.
"""
import sys
from datetime import datetime, timedelta
from unittest.mock import MagicMock, patch
import pytest
# Mock Firestore before importing modules that use it.
sys.modules.setdefault('google.cloud.firestore', MagicMock())
sys.modules.setdefault('google.cloud.firestore_v1', MagicMock())
from fastapi.testclient import TestClient
def _service_with_doc(mock_fs, mock_settings, doc_dict, exists=True):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
mock_doc = MagicMock()
mock_doc.exists = exists
mock_doc.to_dict.return_value = doc_dict
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
from backend.services.user_service import UserService
return UserService(), mock_db
def _link_dict(**overrides):
d = {
'token': 'tok123',
'email': 'user@example.com',
'created_at': datetime.utcnow(),
'expires_at': datetime.utcnow() + timedelta(hours=1),
'used': False,
'used_at': None,
}
d.update(overrides)
return d
class TestGetMagicLinkStatus:
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_valid_link_returns_valid(self, mock_fs, mock_settings):
service, _ = _service_with_doc(mock_fs, mock_settings, _link_dict())
assert service.get_magic_link_status('tok123') == 'valid'
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_valid_link_is_not_consumed(self, mock_fs, mock_settings):
"""The scanner-safety guarantee: a status check must not mutate the token."""
service, mock_db = _service_with_doc(mock_fs, mock_settings, _link_dict())
service.get_magic_link_status('tok123')
doc_ref = mock_db.collection.return_value.document.return_value
doc_ref.update.assert_not_called()
doc_ref.set.assert_not_called()
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_used_link_returns_used(self, mock_fs, mock_settings):
service, _ = _service_with_doc(
mock_fs, mock_settings, _link_dict(used=True, used_at=datetime.utcnow())
)
assert service.get_magic_link_status('tok123') == 'used'
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_expired_link_returns_expired(self, mock_fs, mock_settings):
service, _ = _service_with_doc(
mock_fs, mock_settings, _link_dict(expires_at=datetime.utcnow() - timedelta(minutes=1))
)
assert service.get_magic_link_status('tok123') == 'expired'
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_missing_link_returns_invalid(self, mock_fs, mock_settings):
service, _ = _service_with_doc(mock_fs, mock_settings, {}, exists=False)
assert service.get_magic_link_status('missing') == 'invalid'
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_empty_token_returns_invalid(self, mock_fs, mock_settings):
service, _ = _service_with_doc(mock_fs, mock_settings, _link_dict())
assert service.get_magic_link_status(' ') == 'invalid'
class TestLinkStatusEndpoint:
"""GET /api/users/auth/link-status — thin, read-only wrapper over the service."""
def _client(self, status_value):
from backend.main import app
from backend.services.user_service import get_user_service
svc = MagicMock()
svc.get_magic_link_status.return_value = status_value
app.dependency_overrides[get_user_service] = lambda: svc
return TestClient(app), app, svc
def test_endpoint_returns_status_for_valid(self):
client, app, svc = self._client("valid")
try:
r = client.get("/api/users/auth/link-status", params={"token": "tok123"})
assert r.status_code == 200
assert r.json()["status"] == "valid"
svc.get_magic_link_status.assert_called_once_with("tok123")
finally:
app.dependency_overrides.clear()
def test_endpoint_returns_used(self):
client, app, svc = self._client("used")
try:
r = client.get("/api/users/auth/link-status", params={"token": "burned"})
assert r.status_code == 200
assert r.json()["status"] == "used"
finally:
app.dependency_overrides.clear()
def test_endpoint_returns_invalid_for_empty_token_without_touching_firestore(self):
client, app, svc = self._client("valid") # service would say valid, but route must short-circuit
try:
r = client.get("/api/users/auth/link-status", params={"token": " "})
assert r.status_code == 200
assert r.json()["status"] == "invalid"
svc.get_magic_link_status.assert_not_called()
finally:
app.dependency_overrides.clear()