Skip to content

Commit 032eb0f

Browse files
authored
fix(users): validate an invite password before accepting the invitation (#763) (#797)
* fix(users): validate an invite password before accepting the invitation (#763) Claude-Session: https://claude.ai/code/session_01M9neheZZEe3sVpDi2S3zT4 * fix: address code review findings (round 1, pass 1) Move invite acceptance into users.invites.accept; replay and no-hook tests; clarify hook timing in the changelog. Claude-Session: https://claude.ai/code/session_01M9neheZZEe3sVpDi2S3zT4 * fix: address code review findings (round 1, pass 1, maintainability) Claude-Session: https://claude.ai/code/session_01M9neheZZEe3sVpDi2S3zT4
1 parent ad27666 commit 032eb0f

6 files changed

Lines changed: 179 additions & 19 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,11 @@ All notable changes to this project are documented in this file. The format is b
3131
`account` or whose `azp` is another client (only `oidc` pins both).
3232

3333
### Fixed
34+
- Rejecting an invitation password leaves the invitation usable for a corrected
35+
retry. Acceptance now validates the password first, then writes verification
36+
and the new password in one update; error responses are unchanged.
37+
`UserManager.on_after_verify` now fires after the password is set, followed by
38+
`on_after_update` (#763). No migration.
3439
- Custom background task bases retain tenant validation and caller tenant/owner
3540
stamping in eager mode, preserving custom `apply_async` overrides and default
3641
headers. Incompatible bases fail clearly at registration (#765). No migration.

‎docs/modules/users.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,12 @@ The module is built on [`fastapi-users`](https://fastapi-users.github.io/) for p
2222
- Login lockout — see [Login lockout](#login-lockout). Shared across workers, source IPs and restarts.
2323
- `ThroughputLimiter` — per-IP rate limit across register / forgot-password / accept-invite / verify-token endpoints.
2424

25+
Invite acceptance validates the password before writing verification and the
26+
new password together. A rejected password returns `400 INVALID_PASSWORD: …`
27+
and leaves the invitation usable for a corrected retry. Invalid, expired or
28+
already-used tokens return `400 INVITE_BAD_TOKEN`. Successful acceptance still
29+
fires `on_after_verify` followed by `on_after_update`, then signs the user in.
30+
2531
### Auth endpoints
2632

2733
| Method + path | Body | Notes |

‎modules/users/tests/invites/test_users_invite_flow.py‎

Lines changed: 115 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@
99
import re
1010

1111
import pytest
12+
from fastapi_users.jwt import generate_jwt
13+
from sqlalchemy import select
14+
from users.manager import UserManager
15+
from users.models import User
1216

1317

1418
class TestInviteFlow:
@@ -64,9 +68,9 @@ async def test_accept_invite_with_stale_token_fails(self, anon_client):
6468

6569
@pytest.mark.anyio
6670
async def test_accept_invite_weak_password_fails(
67-
self, admin_client, anon_client, captured_mail
71+
self, admin_client, anon_client, captured_mail, users_app
6872
):
69-
"""Weak password during accept-invite should return 400."""
73+
"""Rejected passwords leave the durable invitation usable for a retry (#763)."""
7074
await admin_client.post(
7175
"/api/users/admin/invite",
7276
json={"email": "weakpw@example.com"},
@@ -79,13 +83,34 @@ async def test_accept_invite_weak_password_fails(
7983
).text,
8084
).group(1)
8185

86+
async with users_app.state.sm.db.session_factory() as db:
87+
user = await db.scalar(select(User).where(User.email == "weakpw@example.com"))
88+
original_password = user.hashed_password
89+
user_id = user.id
90+
8291
resp = await anon_client.post(
8392
"/api/users/auth/accept-invite",
8493
json={"token": token, "password": "short"},
8594
)
8695
assert resp.status_code == 400
8796
detail = resp.json()["detail"]
88-
assert "INVALID_PASSWORD" in detail or "password" in detail.lower()
97+
assert detail.startswith("INVALID_PASSWORD:")
98+
99+
async with users_app.state.sm.db.session_factory() as db:
100+
user = await db.get(User, user_id)
101+
assert user.is_verified is False
102+
assert user.hashed_password == original_password
103+
104+
resp = await anon_client.post(
105+
"/api/users/auth/accept-invite",
106+
json={"token": token, "password": "FreshSecure1!"},
107+
)
108+
assert resp.status_code == 204, resp.text
109+
110+
async with users_app.state.sm.db.session_factory() as db:
111+
user = await db.get(User, user_id)
112+
assert user.is_verified is True
113+
assert user.hashed_password != original_password
89114

90115
@pytest.mark.anyio
91116
async def test_invited_user_cannot_login_before_accepting(self, admin_client, anon_client):
@@ -101,3 +126,90 @@ async def test_invited_user_cannot_login_before_accepting(self, admin_client, an
101126
data={"username": "waiting@example.com", "password": "anything"},
102127
)
103128
assert resp.status_code in (400,)
129+
130+
@pytest.mark.anyio
131+
async def test_accept_invite_hooks_see_password_and_verification_together(
132+
self, admin_client, anon_client, captured_mail, users_app, monkeypatch
133+
):
134+
"""Both hooks run in order, after the complete acceptance is durable."""
135+
await admin_client.post("/api/users/admin/invite", json={"email": "hooks@example.com"})
136+
token = re.search(r"token=(\S+)", captured_mail.to("hooks@example.com")[-1].text).group(1)
137+
seen = []
138+
139+
async def after_verify(manager, user, request):
140+
async with users_app.state.sm.db.session_factory() as db:
141+
durable = await db.get(User, user.id)
142+
assert durable.is_verified is True
143+
assert manager.password_helper.verify_and_update(
144+
"FreshSecure1!", durable.hashed_password
145+
)[0]
146+
seen.append("verify")
147+
148+
async def after_update(manager, user, changes, request):
149+
assert changes == {"password": "FreshSecure1!", "full_name": "Invitee"}
150+
seen.append("update")
151+
152+
monkeypatch.setattr(UserManager, "on_after_verify", after_verify)
153+
monkeypatch.setattr(UserManager, "on_after_update", after_update)
154+
resp = await anon_client.post(
155+
"/api/users/auth/accept-invite",
156+
json={"token": token, "password": "FreshSecure1!", "full_name": " Invitee "},
157+
)
158+
assert resp.status_code == 204, resp.text
159+
assert seen == ["verify", "update"]
160+
161+
@pytest.mark.anyio
162+
@pytest.mark.parametrize(
163+
"claims, lifetime",
164+
[
165+
({}, -1),
166+
({"aud": "fastapi-users:reset"}, 3600),
167+
({"sub": "not-a-uuid"}, 3600),
168+
({"sub": "00000000-0000-0000-0000-000000000000"}, 3600),
169+
({"email": "missing@example.com"}, 3600),
170+
({"email": None}, 3600),
171+
({"sub": None}, 3600),
172+
],
173+
)
174+
async def test_accept_invite_rejects_invalid_claims(
175+
self, admin_client, anon_client, captured_mail, users_app, claims, lifetime
176+
):
177+
"""Only a current verify token matching both account ID and email can write."""
178+
resp = await admin_client.post(
179+
"/api/users/admin/invite", json={"email": "claims@example.com"}
180+
)
181+
token = generate_jwt(
182+
{
183+
"sub": resp.json()["id"],
184+
"email": "claims@example.com",
185+
"aud": UserManager.verification_token_audience,
186+
**claims,
187+
},
188+
users_app.state.users.settings.verification_token_secret,
189+
lifetime,
190+
)
191+
resp = await anon_client.post(
192+
"/api/users/auth/accept-invite", json={"token": token, "password": "FreshSecure1!"}
193+
)
194+
assert resp.status_code == 400, resp.text
195+
assert resp.json()["detail"] == "INVITE_BAD_TOKEN"
196+
197+
@pytest.mark.anyio
198+
async def test_rejected_password_fires_no_hooks(
199+
self, admin_client, anon_client, captured_mail, monkeypatch
200+
):
201+
"""Neither lifecycle hook runs for an acceptance that writes nothing."""
202+
await admin_client.post("/api/users/admin/invite", json={"email": "nohooks@example.com"})
203+
token = re.search(r"token=(\S+)", captured_mail.to("nohooks@example.com")[-1].text).group(1)
204+
seen = []
205+
206+
async def record(*args, **kwargs):
207+
seen.append(args)
208+
209+
monkeypatch.setattr(UserManager, "on_after_verify", record)
210+
monkeypatch.setattr(UserManager, "on_after_update", record)
211+
resp = await anon_client.post(
212+
"/api/users/auth/accept-invite", json={"token": token, "password": "short"}
213+
)
214+
assert resp.status_code == 400
215+
assert seen == []

‎modules/users/users/auth_local/api.py‎

Lines changed: 2 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@
4747
get_current_local_user,
4848
get_user_manager,
4949
)
50+
from users.invites.accept import complete_invite
5051
from users.manager import UserManager
5152
from users.token_storage import revoke_access_token
5253

@@ -193,23 +194,9 @@ async def accept_invite(
193194
):
194195
"""Verify an invite token, set the user's password, and log them in."""
195196
try:
196-
user = await user_manager.verify(body.token, request=request)
197+
user = await complete_invite(user_manager, body, request)
197198
except (fu_exceptions.InvalidVerifyToken, fu_exceptions.UserAlreadyVerified):
198199
raise HTTPException(status_code=400, detail="INVITE_BAD_TOKEN") from None
199-
200-
# A blank name leaves whatever the admin typed when minting the invite
201-
# alone: the field is pre-filled from it, so an untouched form must not
202-
# read as "clear this". Omitted rather than passed as None — ``UserUpdate``
203-
# dumps with ``exclude_unset``, so an explicit None would write the wipe.
204-
changes: dict[str, str] = {"password": body.password}
205-
if body.full_name and body.full_name.strip():
206-
changes["full_name"] = body.full_name.strip()
207-
try:
208-
await user_manager.update(
209-
UserUpdate(**changes), # ty: ignore[invalid-argument-type]
210-
user,
211-
request=request,
212-
)
213200
except fu_exceptions.InvalidPasswordException as e:
214201
raise HTTPException(status_code=400, detail=f"INVALID_PASSWORD: {e.reason}") from e
215202

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
"""Invitation creation, delivery, resend and preview."""
1+
"""Invitation creation, delivery, resend, preview and acceptance."""
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
"""Validate an invitation before atomically accepting it (#763)."""
2+
3+
from __future__ import annotations
4+
5+
import asyncio
6+
7+
import jwt
8+
from fastapi import Request
9+
from fastapi_users import exceptions
10+
from fastapi_users.jwt import decode_jwt
11+
12+
from users.contracts.schemas import AcceptInviteRequest
13+
from users.manager import UserManager
14+
from users.models import User
15+
16+
17+
async def complete_invite(
18+
manager: UserManager, body: AcceptInviteRequest, request: Request
19+
) -> User:
20+
"""Apply verification and password together; preserve both lifecycle hooks."""
21+
# Match BaseUserManager.verify's token checks without its committing write.
22+
try:
23+
data = decode_jwt(
24+
body.token, manager.verification_token_secret, [manager.verification_token_audience]
25+
)
26+
user_id, email = data["sub"], data["email"]
27+
if not isinstance(user_id, str) or not isinstance(email, str):
28+
raise exceptions.InvalidVerifyToken()
29+
user = await manager.get_by_email(email)
30+
parsed_id = manager.parse_id(user_id)
31+
except (jwt.PyJWTError, KeyError, exceptions.UserNotExists, exceptions.InvalidID):
32+
raise exceptions.InvalidVerifyToken() from None
33+
if parsed_id != user.id:
34+
raise exceptions.InvalidVerifyToken()
35+
if user.is_verified:
36+
raise exceptions.UserAlreadyVerified()
37+
38+
await manager.validate_password(body.password, user)
39+
# A blank name keeps what the admin typed when minting the invite: the form is
40+
# pre-filled from it, so an untouched field must not read as "clear this".
41+
profile: dict[str, str] = {}
42+
if body.full_name and body.full_name.strip():
43+
profile["full_name"] = body.full_name.strip()
44+
hashed_password = await asyncio.to_thread(manager.password_helper.hash, body.password)
45+
user = await manager.user_db.update(
46+
user, {**profile, "hashed_password": hashed_password, "is_verified": True}
47+
)
48+
await manager.on_after_verify(user, request)
49+
await manager.on_after_update(user, {"password": body.password, **profile}, request)
50+
return user

0 commit comments

Comments
 (0)