-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathauth.py
More file actions
856 lines (760 loc) · 37 KB
/
Copy pathauth.py
File metadata and controls
856 lines (760 loc) · 37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
import uuid
from datetime import datetime, timezone
from typing import Annotated
import jwt
from fastapi import Body, Depends, Header, Request
from pydantic import ValidationError
from apps.audit import AuditEvent, EventAction, http_audit_fields, log
from apps.authentication.deps import get_current_token, get_current_user
from apps.authentication.domain.login import MFARequiredResponse, MFATOTPVerifyRequest, UserLogin, UserLoginRequest
from apps.authentication.domain.logout import UserLogoutRequest
from apps.authentication.domain.recovery_code import RecoveryCodeVerifyRequest
from apps.authentication.domain.token import (
InternalToken,
JWTClaim,
RefreshAccessTokenRequest,
Token,
TokenPayload,
TokenPurpose,
)
from apps.authentication.errors import (
AuthenticationError,
InvalidCredentials,
InvalidRefreshToken,
InvalidTOTPCodeError,
MFAGlobalLockoutError,
MFASessionNotFoundError,
MFATokenExpiredError,
MFATokenInvalidError,
MFATokenMalformedError,
TooManyTOTPAttemptsError,
)
from apps.authentication.services.mfa_helpers import extract_request_metadata
from apps.authentication.services.mfa_notifications import MFANotificationService
from apps.authentication.services.mfa_session import MFASessionService
from apps.authentication.services.recovery_codes import send_recovery_code_notifications, verify_recovery_code_service
from apps.authentication.services.rotation import TokenRotationService
from apps.authentication.services.security import AuthenticationService
from apps.shared.domain.response import Response
from apps.shared.exception import BaseError
from apps.shared.response import EmptyResponse
from apps.users import UsersCRUD
from apps.users.domain import AppInfoOS, PublicUser, User, UserDeviceCreate
from apps.users.errors import RecoveryCodeInvalidError, RecoveryCodeNotFoundError, UserNotFound
from apps.users.services.totp import TOTPService
from apps.users.services.user_device import UserDeviceService
from config import settings
from infrastructure.database import atomic
from infrastructure.database.deps import get_session
from infrastructure.http.deps import get_optional_mindlogger_content_source
from infrastructure.http.domain import MindloggerContentSource
from infrastructure.logger import logger
def client_token_claims(content_source: MindloggerContentSource | None) -> dict:
"""Extra claims recording which client the tokens are issued to; empty when unknown."""
return {JWTClaim.client: content_source} if content_source else {}
async def revoke_token_family_if_web_admin(session, token: InternalToken) -> None:
"""On logout of a rotating (web/admin) token, revoke its whole family so a superseded
refresh token in the same chain cannot keep the session alive."""
if token.payload.family and token.payload.client in (
MindloggerContentSource.web,
MindloggerContentSource.admin,
):
await TokenRotationService(session).revoke_family(token.payload.family, token.payload.sub)
async def get_token(
request: Request,
user_login_schema: UserLoginRequest = Body(...),
session=Depends(get_session),
os_name: Annotated[str | None, Header()] = None,
os_version: Annotated[str | None, Header()] = None,
app_version: Annotated[str | None, Header()] = None,
content_source: MindloggerContentSource | None = Depends(get_optional_mindlogger_content_source),
) -> Response[UserLogin | MFARequiredResponse]:
"""Generate the JWT access token."""
try:
async with atomic(session):
try:
user: User = await AuthenticationService(session).authenticate_user(user_login_schema)
if user_login_schema.device_id:
await UserDeviceService(session, user.id).add_device(
UserDeviceCreate(
device_id=user_login_schema.device_id,
os=AppInfoOS(name=os_name, version=os_version) if os_name and os_version else None,
app_version=app_version,
)
)
except UserNotFound:
raise InvalidCredentials(email=user_login_schema.email)
if user.email_encrypted != user_login_schema.email:
user = await UsersCRUD(session).update_encrypted_email(user, user_login_schema.email)
except BaseError as e:
await log(
AuditEvent(
user_id=None,
user_email=user_login_schema.email,
event_action=EventAction.USER_SESSION_LOGIN,
**http_audit_fields(request, e),
)
)
raise
# MFA-required branch returns MFARequiredResponse; user:session:login fires from the MFA verify endpoints.
if user.mfa_secret:
mfa_service = MFASessionService()
mfa_session_id = await mfa_service.create_session(user_id=user.id)
logger.info(f"MFA required for login user_id={user.id} email={user.email_encrypted}")
mfa_token = AuthenticationService.create_mfa_token(mfa_session_id=mfa_session_id)
return Response(
result=MFARequiredResponse(
mfa_required=True,
mfa_session_id=mfa_session_id,
mfa_token=mfa_token,
user_id=str(user.id),
user_email=user.email_encrypted,
)
)
rjti = str(uuid.uuid4())
refresh_token = AuthenticationService.create_refresh_token(
{JWTClaim.sub: str(user.id), JWTClaim.jti: rjti, JWTClaim.family: rjti, **client_token_claims(content_source)}
)
access_token = AuthenticationService.create_access_token(
{
JWTClaim.sub: str(user.id),
JWTClaim.rjti: rjti,
JWTClaim.family: rjti,
**client_token_claims(content_source),
}
)
token = Token(access_token=access_token, refresh_token=refresh_token)
public_user = PublicUser.from_user(user)
await log(
AuditEvent(
user_id=user.id,
event_action=EventAction.USER_SESSION_LOGIN,
**http_audit_fields(request),
)
)
return Response(
result=UserLogin(
token=token,
user=public_user,
)
)
async def verify_mfa_totp(
request: Request,
verify_request: MFATOTPVerifyRequest = Body(...),
session=Depends(get_session),
os_name: Annotated[str | None, Header()] = None,
os_version: Annotated[str | None, Header()] = None,
app_version: Annotated[str | None, Header()] = None,
content_source: MindloggerContentSource | None = Depends(get_optional_mindlogger_content_source),
) -> Response[UserLogin]:
"""Verify TOTP code during MFA and return tokens."""
user_id: uuid.UUID | None = None
try:
# Validate MFA token and get session info
mfa_service = MFASessionService()
try:
mfa_session_id, user_id, purpose = await mfa_service.validate_and_get_session(verify_request.mfa_token)
except (
MFATokenExpiredError,
MFATokenMalformedError,
MFATokenInvalidError,
MFASessionNotFoundError,
) as e:
# Re-raise specific MFA token/session errors with detailed feedback
raise e
# Check global lockout FIRST (prevents bypassing per-session limits)
is_locked = await mfa_service.is_globally_locked_out(user_id)
if is_locked:
logger.warning(f"User globally locked out from MFA attempts user_id={user_id}")
await mfa_service.delete_session(mfa_session_id)
raise MFAGlobalLockoutError(
global_attempts_remaining=0,
)
# Check if max attempts exceeded BEFORE attempting verification
session_data = await mfa_service.get_session(mfa_session_id)
if session_data and session_data.has_exceeded_max_attempts(settings.redis.mfa_max_attempts):
global_remaining = await mfa_service.get_remaining_global_attempts(user_id)
logger.warning(
f"MFA max attempts exceeded user_id={user_id} "
f"failed_attempts={session_data.failed_totp_attempts} max_attempts={settings.redis.mfa_max_attempts}"
)
# Delete session to force re-login
await mfa_service.delete_session(mfa_session_id)
raise TooManyTOTPAttemptsError(
session_attempts_remaining=0,
global_attempts_remaining=global_remaining,
lockout_reason="session_limit",
)
# Get user from DB
async with atomic(session):
user: User = await UsersCRUD(session).get_by_id(user_id)
if not user.mfa_secret:
# Edge case: user disabled MFA between login and verification
raise MFATokenInvalidError()
totp_service = TOTPService()
# Verify TOTP code with replay protection
try:
decrypted_secret = totp_service.decrypt_secret(user.mfa_secret)
except Exception:
raise InvalidTOTPCodeError()
# Get user's last used time step for replay protection
last_step = user.last_totp_time_step
# Verify with replay protection
is_valid, time_step_used = totp_service.verify_with_replay_check(
secret=decrypted_secret, code=verify_request.totp_code, last_used_step=last_step
)
if not is_valid:
# Increment both per-session and global failed attempts counters
new_attempt_count = await mfa_service.increment_failed_totp_attempts(mfa_session_id)
global_attempt_count = await mfa_service.increment_global_failed_attempts(user.id)
# Calculate remaining attempts using service methods
session_remaining = await mfa_service.get_remaining_session_attempts(mfa_session_id)
global_remaining = await mfa_service.get_remaining_global_attempts(user.id)
logger.warning(
f"Invalid TOTP code provided user_id={user.id} email={user.email_encrypted} "
f"failed_attempts={new_attempt_count} global_failed_attempts={global_attempt_count}"
)
# Send warning email if global attempts hit threshold
if global_attempt_count == settings.mfa.failed_attempts_warning_threshold:
notification_service = MFANotificationService()
global_remaining = settings.redis.mfa_global_lockout_attempts - global_attempt_count
await notification_service.send_failed_attempts_warning(
user=user,
failed_attempts=global_attempt_count,
max_attempts=settings.redis.mfa_global_lockout_attempts,
remaining_attempts=global_remaining,
)
# Check if global lockout threshold reached
if global_attempt_count >= settings.redis.mfa_global_lockout_attempts:
logger.warning(
f"User globally locked out after max failed attempts user_id={user.id} "
f"email={user.email_encrypted} global_failed_attempts={global_attempt_count}"
)
await mfa_service.delete_session(mfa_session_id)
# Send account locked notification
notification_service = MFANotificationService()
await notification_service.send_account_locked_email(
user=user,
lockout_reason="Too many failed MFA verification attempts",
failed_attempts=global_attempt_count,
lockout_ttl_seconds=settings.redis.mfa_global_lockout_ttl,
)
raise MFAGlobalLockoutError(
global_attempts_remaining=0,
)
# If this was the last allowed attempt for this session, delete session
if new_attempt_count is not None and new_attempt_count >= settings.redis.mfa_max_attempts:
logger.warning(
f"User locked out after max failed TOTP attempts for session user_id={user.id} "
f"email={user.email_encrypted} failed_attempts={new_attempt_count}"
)
await mfa_service.delete_session(mfa_session_id)
raise TooManyTOTPAttemptsError(
session_attempts_remaining=0,
global_attempts_remaining=global_remaining,
lockout_reason="session_limit",
)
# Otherwise, raise normal invalid code error with remaining attempts
raise InvalidTOTPCodeError(
session_attempts_remaining=session_remaining,
global_attempts_remaining=global_remaining,
)
# TOTP is valid - Update last used time step for replay protection
assert time_step_used is not None # Always set when is_valid is True
await UsersCRUD(session).update_last_totp_time_step(user.id, time_step_used)
# Clear global lockout counter and delete MFA session
await mfa_service.clear_global_lockout(user.id)
await mfa_service.delete_session(mfa_session_id)
logger.info(
f"MFA verification successful user_id={user.id} email={user.email_encrypted} "
f"device_id={verify_request.device_id} client={content_source}"
)
# Register device if device_id provided
if verify_request.device_id:
await UserDeviceService(session, user.id).add_device(
UserDeviceCreate(
device_id=verify_request.device_id,
os=AppInfoOS(name=os_name, version=os_version) if os_name and os_version else None,
app_version=app_version,
)
)
# Issue refresh and access tokens
rjti = str(uuid.uuid4())
refresh_token = AuthenticationService.create_refresh_token(
{
JWTClaim.sub: str(user.id),
JWTClaim.jti: rjti,
JWTClaim.family: rjti,
**client_token_claims(content_source),
}
)
access_token = AuthenticationService.create_access_token(
{
JWTClaim.sub: str(user.id),
JWTClaim.rjti: rjti,
JWTClaim.family: rjti,
**client_token_claims(content_source),
}
)
except BaseError as e:
await log(
AuditEvent(
user_id=user_id,
event_action=EventAction.USER_SESSION_LOGIN,
**http_audit_fields(request, e),
)
)
raise
token = Token(access_token=access_token, refresh_token=refresh_token)
public_user = PublicUser.from_user(user)
await log(
AuditEvent(
user_id=user.id,
event_action=EventAction.USER_SESSION_LOGIN,
**http_audit_fields(request),
)
)
return Response(
result=UserLogin(
token=token,
user=public_user,
)
)
async def verify_mfa_recovery_code(
request: Request,
verify_request: RecoveryCodeVerifyRequest = Body(...),
session=Depends(get_session),
os_name: Annotated[str | None, Header()] = None,
os_version: Annotated[str | None, Header()] = None,
app_version: Annotated[str | None, Header()] = None,
content_source: MindloggerContentSource | None = Depends(get_optional_mindlogger_content_source),
) -> Response[UserLogin]:
"""Verify recovery code during MFA and return tokens."""
user_id: uuid.UUID | None = None
try:
# Validate MFA token and get session info
mfa_service = MFASessionService()
try:
mfa_session_id, user_id, purpose = await mfa_service.validate_and_get_session(verify_request.mfa_token)
except (
MFATokenExpiredError,
MFATokenMalformedError,
MFATokenInvalidError,
MFASessionNotFoundError,
) as e:
# Re-raise specific MFA token/session errors with detailed feedback
raise e
# Check global lockout FIRST (prevents bypassing per-session limits)
is_locked = await mfa_service.is_globally_locked_out(user_id)
if is_locked:
logger.warning(f"User globally locked out from MFA attempts user_id={user_id}")
raise MFAGlobalLockoutError(
global_attempts_remaining=0,
)
# Check if max per-session attempts exceeded BEFORE attempting verification
session_data = await mfa_service.get_session(mfa_session_id)
if session_data and session_data.has_exceeded_max_attempts(settings.redis.mfa_max_attempts):
global_remaining = await mfa_service.get_remaining_global_attempts(user_id)
logger.warning(
f"MFA max attempts exceeded user_id={user_id} "
f"failed_attempts={session_data.failed_totp_attempts} max_attempts={settings.redis.mfa_max_attempts}"
)
# Delete session to force re-login
await mfa_service.delete_session(mfa_session_id)
raise TooManyTOTPAttemptsError(
session_attempts_remaining=0,
global_attempts_remaining=global_remaining,
lockout_reason="session_limit",
)
# Get user and verify recovery code
async with atomic(session):
user: User = await UsersCRUD(session).get_by_id(user_id)
# Verify and mark recovery code as used
try:
await verify_recovery_code_service(session, user_id, verify_request.code)
# Extract request metadata for security notification
request_metadata = extract_request_metadata(request)
# Send recovery code notifications (used + warning if needed)
await send_recovery_code_notifications(
session=session,
user=user,
used_at=datetime.now(timezone.utc),
request_info=request_metadata,
)
except RecoveryCodeNotFoundError as e:
await log(
AuditEvent(
event_action=EventAction.USER_MFA_RECOVERY_USE,
user_id=user_id,
user_target_id=user_id,
**http_audit_fields(request, e),
)
)
# No unused codes exist - increment both counters
session_count = await mfa_service.increment_failed_totp_attempts(mfa_session_id)
global_count = await mfa_service.increment_global_failed_attempts(user_id)
# Calculate remaining attempts using service methods
global_remaining = await mfa_service.get_remaining_global_attempts(user_id)
logger.warning(
f"Recovery code verification failed - no unused codes user_id={user_id} "
f"email={user.email_encrypted} failed_attempts={session_count} "
f"global_failed_attempts={global_count} "
f"warning_threshold={settings.mfa.failed_attempts_warning_threshold}"
)
# Send warning email if global attempts hit threshold
if global_count == settings.mfa.failed_attempts_warning_threshold:
logger.info(
f"Sending failed attempts warning email user_id={user_id} "
f"global_count={global_count} threshold={settings.mfa.failed_attempts_warning_threshold}"
)
notification_service = MFANotificationService()
global_remaining = settings.redis.mfa_global_lockout_attempts - global_count
await notification_service.send_failed_attempts_warning(
user=user,
failed_attempts=global_count,
max_attempts=settings.redis.mfa_global_lockout_attempts,
remaining_attempts=global_remaining,
)
logger.info(f"Failed attempts warning email sent user_id={user_id}")
# Check if global lockout threshold reached
if global_count >= settings.redis.mfa_global_lockout_attempts:
logger.warning(
f"User globally locked out after max failed attempts user_id={user_id} "
f"email={user.email_encrypted} global_failed_attempts={global_count}"
)
await mfa_service.delete_session(mfa_session_id)
raise MFAGlobalLockoutError(
global_attempts_remaining=0,
)
# Check if per-session lockout threshold reached
if session_count is not None and session_count >= settings.redis.mfa_max_attempts:
logger.warning(
f"User locked out after max failed recovery code attempts for session "
f"user_id={user_id} email={user.email_encrypted} failed_attempts={session_count}"
)
await mfa_service.delete_session(mfa_session_id)
raise TooManyTOTPAttemptsError(
session_attempts_remaining=0,
global_attempts_remaining=global_remaining,
lockout_reason="session_limit",
)
raise
except RecoveryCodeInvalidError as e:
await log(
AuditEvent(
event_action=EventAction.USER_MFA_RECOVERY_USE,
user_id=user_id,
user_target_id=user_id,
**http_audit_fields(request, e),
)
)
# Invalid code - increment both per-session and global counters
session_count = await mfa_service.increment_failed_totp_attempts(mfa_session_id)
global_count = await mfa_service.increment_global_failed_attempts(user_id)
# Calculate remaining attempts using service methods
global_remaining = await mfa_service.get_remaining_global_attempts(user_id)
session_remaining = await mfa_service.get_remaining_session_attempts(mfa_session_id)
logger.warning(
f"Invalid recovery code provided user_id={user_id} email={user.email_encrypted} "
f"failed_attempts={session_count} global_failed_attempts={global_count} "
f"warning_threshold={settings.mfa.failed_attempts_warning_threshold}"
)
# Send warning email if global attempts hit threshold
if global_count == settings.mfa.failed_attempts_warning_threshold:
logger.info(
f"Sending failed attempts warning email user_id={user_id} "
f"global_count={global_count} threshold={settings.mfa.failed_attempts_warning_threshold}"
)
notification_service = MFANotificationService()
global_remaining = settings.redis.mfa_global_lockout_attempts - global_count
await notification_service.send_failed_attempts_warning(
user=user,
failed_attempts=global_count,
max_attempts=settings.redis.mfa_global_lockout_attempts,
remaining_attempts=global_remaining,
)
logger.info(f"Failed attempts warning email sent user_id={user_id}")
# Check if global lockout threshold reached
if global_count >= settings.redis.mfa_global_lockout_attempts:
logger.warning(
f"User globally locked out after max failed recovery code attempts "
f"user_id={user_id} email={user.email_encrypted} global_failed_attempts={global_count}"
)
await mfa_service.delete_session(mfa_session_id)
# Send account locked notification
notification_service = MFANotificationService()
await notification_service.send_account_locked_email(
user=user,
lockout_reason="Too many failed recovery code attempts",
failed_attempts=global_count,
lockout_ttl_seconds=settings.redis.mfa_global_lockout_ttl,
)
raise MFAGlobalLockoutError(
global_attempts_remaining=0,
)
# Check if per-session lockout threshold reached
if session_count is not None and session_count >= settings.redis.mfa_max_attempts:
logger.warning(
f"User locked out after max failed recovery code attempts for session "
f"user_id={user_id} email={user.email_encrypted} failed_attempts={session_count}"
)
await mfa_service.delete_session(mfa_session_id)
raise TooManyTOTPAttemptsError(
session_attempts_remaining=0,
global_attempts_remaining=global_remaining,
lockout_reason="session_limit",
)
# Re-raise with metadata to inform frontend of remaining attempts
raise RecoveryCodeInvalidError(
metadata={
"session_attempts_remaining": session_remaining if session_remaining is not None else 0,
"global_attempts_remaining": global_remaining if global_remaining is not None else 0,
}
)
# Recovery code valid - clear lockout and delete MFA session
await mfa_service.clear_global_lockout(user_id)
await mfa_service.delete_session(mfa_session_id)
logger.info(
f"MFA recovery code verification successful user_id={user_id} email={user.email_encrypted} "
f"device_id={verify_request.device_id} client={content_source}"
)
# Step 5: Register device if device_id provided
if verify_request.device_id:
await UserDeviceService(session, user_id).add_device(
UserDeviceCreate(
device_id=verify_request.device_id,
os=AppInfoOS(name=os_name, version=os_version) if os_name and os_version else None,
app_version=app_version,
)
)
# Step 6: Issue refresh and access tokens
rjti = str(uuid.uuid4())
refresh_token = AuthenticationService.create_refresh_token(
{
JWTClaim.sub: str(user_id),
JWTClaim.jti: rjti,
JWTClaim.family: rjti,
**client_token_claims(content_source),
}
)
access_token = AuthenticationService.create_access_token(
{
JWTClaim.sub: str(user_id),
JWTClaim.rjti: rjti,
JWTClaim.family: rjti,
**client_token_claims(content_source),
}
)
except BaseError as e:
await log(
AuditEvent(
event_action=EventAction.USER_SESSION_LOGIN,
user_id=user_id,
**http_audit_fields(request, e),
)
)
raise
# Step 7: Return response
await log(
AuditEvent(
event_action=EventAction.USER_MFA_RECOVERY_USE,
user_id=user.id,
user_target_id=user.id,
**http_audit_fields(request),
)
)
await log(
AuditEvent(
event_action=EventAction.USER_SESSION_LOGIN,
user_id=user.id,
**http_audit_fields(request),
)
)
token = Token(access_token=access_token, refresh_token=refresh_token)
public_user = PublicUser.from_user(user)
return Response(
result=UserLogin(
token=token,
user=public_user,
)
)
async def refresh_access_token(
request: Request,
schema: RefreshAccessTokenRequest = Body(...),
session=Depends(get_session),
) -> Response[Token]:
"""Refresh access token."""
user_id: uuid.UUID | None = None
reuse_family: str | None = None
refresh_outcome = "reused"
try:
async with atomic(session):
try:
regenerate_refresh_token = False
try:
payload = jwt.decode(
schema.refresh_token,
settings.authentication.refresh_token.secret_key,
algorithms=[settings.authentication.algorithm],
)
except jwt.PyJWTError:
# check transition key
transition_key = settings.authentication.refresh_token.transition_key
transition_expire_date = settings.authentication.refresh_token.transition_expire_date
today = datetime.now(timezone.utc).date()
if not (transition_key and transition_expire_date and transition_expire_date > today):
raise
payload = jwt.decode(
schema.refresh_token,
str(transition_key),
algorithms=[settings.authentication.algorithm],
)
regenerate_refresh_token = True
token_data = TokenPayload(**payload)
except (jwt.PyJWTError, ValidationError) as e:
raise InvalidRefreshToken() from e
user_id = token_data.sub
family = token_data.family or token_data.jti
is_web_admin = token_data.client in (MindloggerContentSource.web, MindloggerContentSource.admin)
if is_web_admin:
# Rotating clients: slide the refresh window by issuing a fresh token each time,
# with a grace window that idempotently redeems the old token, and reuse detection
# that revokes the whole family.
rotation = TokenRotationService(session)
if await rotation.is_family_revoked(family):
raise AuthenticationError
replacement = await rotation.get_rotation_replacement(token_data.jti)
if replacement is not None:
# Within the grace window: hand back the same replacement pair.
access_token = replacement.access_token
refresh_token = replacement.refresh_token
refresh_outcome = "grace_redeemed"
elif await AuthenticationService(session).is_revoked(InternalToken(payload=token_data)):
# Old token replayed after its grace window -> treat as theft. Defer the
# family revocation to its own committed transaction (raising here would roll
# back this atomic block and undo it).
reuse_family = family
else:
new_rjti = str(uuid.uuid4())
refresh_token = AuthenticationService.create_refresh_token(
{
JWTClaim.sub: str(user_id),
JWTClaim.jti: new_rjti,
JWTClaim.family: family,
**client_token_claims(token_data.client),
}
)
access_token = AuthenticationService.create_access_token(
{
JWTClaim.sub: str(user_id),
JWTClaim.rjti: new_rjti,
JWTClaim.family: family,
**client_token_claims(token_data.client),
}
)
# Mark the old refresh token used, and record the replacement for the grace window.
await AuthenticationService(session).revoke_token(
InternalToken(payload=token_data), TokenPurpose.REFRESH
)
await rotation.store_rotation_record(
token_data.jti,
Token(access_token=access_token, refresh_token=refresh_token),
)
refresh_outcome = "rotated"
else:
# Mobile / unknown / legacy: reuse the same refresh token (unchanged behavior).
revoked = await AuthenticationService(session).is_revoked(InternalToken(payload=token_data))
if revoked:
raise AuthenticationError
rjti = token_data.jti
refresh_token = schema.refresh_token
if regenerate_refresh_token:
# blacklist current refresh token
await AuthenticationService(session).revoke_token(
InternalToken(payload=token_data), TokenPurpose.REFRESH
)
rjti = str(uuid.uuid4())
refresh_token = AuthenticationService.create_refresh_token(
{
JWTClaim.sub: str(user_id),
JWTClaim.jti: rjti,
JWTClaim.exp: token_data.exp,
**client_token_claims(token_data.client),
}
)
access_token = AuthenticationService.create_access_token(
{
JWTClaim.sub: str(user_id),
JWTClaim.rjti: rjti,
**client_token_claims(token_data.client),
}
)
if reuse_family is not None:
# Commit the family revocation in its own transaction, then reject the request.
logger.warning(f"Refresh token reuse detected; revoking family user_id={user_id} family={reuse_family}")
async with atomic(session):
await TokenRotationService(session).revoke_family(reuse_family, user_id)
raise AuthenticationError
except BaseError as e:
await log(
AuditEvent(
event_action=EventAction.USER_SESSION_REFRESH,
user_id=user_id,
**http_audit_fields(request, e),
)
)
raise
logger.info(f"Token refresh succeeded user_id={user_id} outcome={refresh_outcome}")
await log(
AuditEvent(
event_action=EventAction.USER_SESSION_REFRESH,
user_id=user_id,
**http_audit_fields(request),
)
)
return Response(result=Token(access_token=access_token, refresh_token=refresh_token))
async def delete_access_token(
request: Request,
schema: UserLogoutRequest | None = Body(default=None),
token: InternalToken = Depends(get_current_token()),
user: User = Depends(get_current_user),
session=Depends(get_session),
) -> EmptyResponse:
"""Add token to the blacklist."""
try:
async with atomic(session):
await AuthenticationService(session).revoke_token(token, TokenPurpose.ACCESS)
await revoke_token_family_if_web_admin(session, token)
async with atomic(session):
if schema and schema.device_id:
await UserDeviceService(session, user.id).remove_device(schema.device_id)
except BaseError as e:
await log(
AuditEvent(
event_action=EventAction.USER_SESSION_LOGOUT,
user_id=user.id,
**http_audit_fields(request, e),
)
)
raise
await log(
AuditEvent(
event_action=EventAction.USER_SESSION_LOGOUT,
user_id=user.id,
**http_audit_fields(request),
)
)
return EmptyResponse()
async def delete_refresh_token(
schema: UserLogoutRequest | None = Body(default=None),
token: InternalToken = Depends(get_current_token(TokenPurpose.REFRESH)),
session=Depends(get_session),
) -> EmptyResponse:
"""Add token to the blacklist."""
async with atomic(session):
await AuthenticationService(session).revoke_token(token, TokenPurpose.REFRESH)
await revoke_token_family_if_web_admin(session, token)
if schema and schema.device_id:
async with atomic(session):
await UserDeviceService(session, token.payload.sub).remove_device(schema.device_id)
return EmptyResponse()