Skip to content

Commit 22c9c87

Browse files
committed
Merge: gate email verify-link behind a POST to survive mail scanners
2 parents 653edb2 + 6429d61 commit 22c9c87

4 files changed

Lines changed: 222 additions & 37 deletions

File tree

‎fief/apps/auth/forms/verify_email.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,17 @@ class VerifyEmailForm(CSRFBaseForm):
99

1010
class Meta:
1111
id = "verify-email-form"
12+
13+
14+
class VerifyEmailLinkForm(CSRFBaseForm):
15+
"""Confirmation form for the one-click activation link.
16+
17+
The code travels in a hidden field pre-filled from the link's ``?code=``
18+
query param; verification only happens when this form is POSTed, so mail
19+
link scanners (which only GET) cannot consume the one-time code.
20+
"""
21+
22+
code = HiddenField(_("Verification code"), validators=[validators.InputRequired()])
23+
24+
class Meta:
25+
id = "verify-email-link-form"

‎fief/apps/auth/routers/auth.py‎

Lines changed: 75 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
from fief.apps.auth.forms.auth import ConsentForm, LoginForm
1313
from fief.apps.auth.forms.mfa import MfaRecoveryForm, TotpVerifyForm
14-
from fief.apps.auth.forms.verify_email import VerifyEmailForm
14+
from fief.apps.auth.forms.verify_email import VerifyEmailForm, VerifyEmailLinkForm
1515
from fief.dependencies.auth import (
1616
BaseContext,
1717
check_unsupported_request_parameter,
@@ -615,54 +615,90 @@ async def _generic_invalid_code_response():
615615
return await form_helper.get_response()
616616

617617

618-
@router.get("/verify-link", name="auth:verify_email_link")
618+
@router.api_route(
619+
"/verify-link", methods=["GET", "POST"], name="auth:verify_email_link"
620+
)
619621
async def verify_email_link(
620622
request: Request,
621-
code: str = Query(...),
623+
code: str | None = Query(default=None),
622624
user_manager: UserManager = Depends(get_user_manager),
623625
tenant: Tenant = Depends(get_current_tenant),
626+
context: BaseContext = Depends(get_base_context),
624627
ip_info: ClientIpInfo = Depends(get_client_ip_info),
625628
rate_limiter: RateLimiter = Depends(get_rate_limiter),
626629
audit_logger: AuditLogger = Depends(get_audit_logger),
627630
):
628-
"""Sessionless one-click email activation. The ``code`` query param is the
629-
secret (delivered to the address), so possession proves ownership and no
630-
login session is required — this is what makes the link clickable straight
631-
from the inbox. On success/failure we bounce to /login with a flag the
632-
template can surface."""
631+
"""Email activation from a one-click link, gated behind an explicit POST.
632+
633+
Verification is performed only when the confirmation page is *submitted*,
634+
never on the GET. Recipient-side mail-security scanners (Microsoft Safe
635+
Links, Gmail, corporate proxies) automatically follow the link's GET the
636+
instant the message is delivered; if that GET consumed the one-time code,
637+
the real user — clicking the button or typing the same code — would always
638+
land on an already-spent code and see ``verify_error=1``. Requiring a human
639+
form submission keeps the code intact until the recipient acts.
640+
641+
Possession of ``code`` (delivered to the address) is the proof of ownership,
642+
so no login session is required. ``tenant_id`` scopes the lookup so a code
643+
can only verify a user of the current tenant.
644+
"""
633645
login_url = tenant.url_path_for(request, "auth:login")
634646

635-
if settings.rate_limit_enabled:
647+
form_helper = FormHelper(
648+
VerifyEmailLinkForm,
649+
"auth/verify_email_link.html",
650+
request=request,
651+
context={**context},
652+
)
653+
654+
if request.method == "POST":
655+
if not await form_helper.is_submitted_and_valid():
656+
return await form_helper.get_response()
657+
658+
form = await form_helper.get_form()
659+
660+
if settings.rate_limit_enabled:
661+
try:
662+
await rate_limiter.check(
663+
scope="verify_ip",
664+
key=ip_info.rate_limit_key,
665+
window=RateLimitWindow(
666+
settings.rate_limit_verify_per_ip_per_min, 60
667+
),
668+
)
669+
except RateLimitExceeded:
670+
audit_logger(
671+
AuditLogMessage.USER_RATE_LIMIT_EXCEEDED,
672+
extra={
673+
"scope": "verify_ip",
674+
"key_hash": _hash_key(ip_info.rate_limit_key),
675+
"endpoint": "/verify-link",
676+
"client_ip": ip_info.raw,
677+
},
678+
)
679+
return RedirectResponse(login_url, status_code=status.HTTP_302_FOUND)
680+
636681
try:
637-
await rate_limiter.check(
638-
scope="verify_ip",
639-
key=ip_info.rate_limit_key,
640-
window=RateLimitWindow(settings.rate_limit_verify_per_ip_per_min, 60),
682+
await user_manager.verify_email_by_code(
683+
form.code.data, tenant_id=tenant.id, request=request
641684
)
642-
except RateLimitExceeded:
643-
audit_logger(
644-
AuditLogMessage.USER_RATE_LIMIT_EXCEEDED,
645-
extra={
646-
"scope": "verify_ip",
647-
"key_hash": _hash_key(ip_info.rate_limit_key),
648-
"endpoint": "/verify-link",
649-
"client_ip": ip_info.raw,
650-
},
685+
except InvalidEmailVerificationCodeError:
686+
return RedirectResponse(
687+
f"{login_url}?verify_error=1", status_code=status.HTTP_302_FOUND
651688
)
652-
return RedirectResponse(login_url, status_code=status.HTTP_302_FOUND)
653689

654-
try:
655-
await user_manager.verify_email_by_code(
656-
code, tenant_id=tenant.id, request=request
657-
)
658-
except InvalidEmailVerificationCodeError:
659690
return RedirectResponse(
660-
f"{login_url}?verify_error=1", status_code=status.HTTP_302_FOUND
691+
f"{login_url}?verified=1", status_code=status.HTTP_302_FOUND
661692
)
662693

663-
return RedirectResponse(
664-
f"{login_url}?verified=1", status_code=status.HTTP_302_FOUND
665-
)
694+
# GET: render the confirmation page WITHOUT verifying. A link scanner that
695+
# follows this GET only renders the page; the code is spent solely on POST.
696+
if code is None:
697+
return RedirectResponse(login_url, status_code=status.HTTP_302_FOUND)
698+
699+
form = await form_helper.get_form()
700+
form.code.data = code
701+
return await form_helper.get_response()
666702

667703

668704
# ---------------------------------------------------------------------------
@@ -1068,9 +1104,7 @@ async def mfa_recover(
10681104
# post-MFA cookie just minted by ``complete_login_after_mfa`` is
10691105
# passed in as ``current_session_id`` so it survives. Audit logged
10701106
# with ``trigger_reason="recovery_code_used"``.
1071-
new_session_token_id = (
1072-
authentication_flow.last_minted_session_token_id
1073-
)
1107+
new_session_token_id = authentication_flow.last_minted_session_token_id
10741108
await device_sessions_service.auto_revoke_others(
10751109
user.id,
10761110
current_session_id=new_session_token_id,
@@ -1218,12 +1252,16 @@ async def mfa_passkey_verify(
12181252
# ``reason=credential_not_found``; we just bump the counter to
12191253
# match the TOTP lockout ladder.
12201254
await _record_failed_mfa_attempt(login_session, login_session_repository)
1221-
return JSONResponse({"error": "invalid"}, status_code=status.HTTP_401_UNAUTHORIZED)
1255+
return JSONResponse(
1256+
{"error": "invalid"}, status_code=status.HTTP_401_UNAUTHORIZED
1257+
)
12221258
except InvalidAssertion:
12231259
# Service already audit-logged USER_PASSKEY_VERIFY_FAILED with
12241260
# ``reason=invalid_signature``.
12251261
await _record_failed_mfa_attempt(login_session, login_session_repository)
1226-
return JSONResponse({"error": "invalid"}, status_code=status.HTTP_401_UNAUTHORIZED)
1262+
return JSONResponse(
1263+
{"error": "invalid"}, status_code=status.HTTP_401_UNAUTHORIZED
1264+
)
12271265
except SignCountRollback:
12281266
# The credential is suspect, not the attempt — do NOT burn the
12291267
# user's lockout budget on a sign-count regression. The service
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
{% import "macros/buttons.html" as buttons %}
2+
{% import 'macros/forms.html' as forms %}
3+
4+
{% extends "auth/layout.html" %}
5+
6+
{% block head_title_content %}{{ _('Verify your email') }}{% endblock %}
7+
8+
{% block title %}{{ _('Verify your email') }}{% endblock %}
9+
10+
{% block auth_form %}
11+
{#
12+
Deliberately NOT auto-submitted: verification happens only on a real human
13+
click. Mail-security link scanners follow the GET that renders this page but
14+
do not submit the form, so the one-time code is preserved until the recipient
15+
clicks "Verify my email".
16+
#}
17+
<form
18+
id="{{ form.meta.id }}"
19+
method="POST"
20+
action="{{ tenant.url_path_for(request, 'auth:verify_email_link') }}"
21+
>
22+
<div class="space-y-4">
23+
<p class="text-justify text-sm">{{ _("You're almost there. Click the button below to confirm and verify your email address.") }}</p>
24+
</div>
25+
{{ form.code }}
26+
{{ forms.form_csrf_token(form) }}
27+
<div class="flex items-center justify-between mt-6">
28+
<a href="{{ tenant.url_path_for(request, 'auth:verify_email_request') }}" class="btn border-slate-200 hover:border-slate-300 text-primary">{{ _('Resend the code') }}</a>
29+
{% call buttons.submit('btn') %}
30+
{{ _("Verify my email") }}
31+
{% endcall %}
32+
</div>
33+
</form>
34+
{% endblock %}

‎tests/test_apps_auth_auth.py‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1005,6 +1005,105 @@ async def test_valid(
10051005
assert updated_user.email_verified is True
10061006

10071007

1008+
@pytest.mark.asyncio
1009+
class TestAuthVerifyEmailLink:
1010+
async def test_get_no_code_redirects_to_login(
1011+
self, tenant_params: TenantParams, test_client_auth: httpx.AsyncClient
1012+
):
1013+
response = await test_client_auth.get(
1014+
f"{tenant_params.path_prefix}/verify-link"
1015+
)
1016+
1017+
assert response.status_code == status.HTTP_302_FOUND
1018+
assert response.headers["Location"].endswith(
1019+
f"{tenant_params.path_prefix}/login"
1020+
)
1021+
1022+
async def test_get_renders_confirmation_without_verifying(
1023+
self,
1024+
test_client_auth: httpx.AsyncClient,
1025+
main_session: AsyncSession,
1026+
test_data: TestData,
1027+
):
1028+
"""A mail-security scanner following the GET must NOT consume the code:
1029+
the page renders, the verification row survives, the user stays
1030+
unverified until an explicit POST."""
1031+
user = test_data["users"]["not_verified_email"]
1032+
code = email_verification_codes["not_verified_email"][0]
1033+
email_verification = test_data["email_verifications"]["not_verified_email"]
1034+
tenant = user.tenant
1035+
path_prefix = tenant.slug if not tenant.default else ""
1036+
1037+
response = await test_client_auth.get(
1038+
f"{path_prefix}/verify-link", params={"code": code}
1039+
)
1040+
1041+
assert response.status_code == status.HTTP_200_OK
1042+
html = BeautifulSoup(response.text, features="html.parser")
1043+
form = html.find("form", id="verify-email-link-form")
1044+
assert form is not None
1045+
code_input = form.find("input", attrs={"name": "code"})
1046+
assert code_input is not None
1047+
assert code_input["value"] == code
1048+
1049+
# The GET neither consumed the code nor verified the user.
1050+
email_verification_repository = EmailVerificationRepository(main_session)
1051+
assert (
1052+
await email_verification_repository.get_by_id(email_verification.id)
1053+
is not None
1054+
)
1055+
user_repository = UserRepository(main_session)
1056+
unchanged_user = await user_repository.get_by_id(user.id)
1057+
assert unchanged_user is not None
1058+
assert unchanged_user.email_verified is False
1059+
1060+
async def test_post_invalid_code(
1061+
self,
1062+
tenant_params: TenantParams,
1063+
test_client_auth_csrf: httpx.AsyncClient,
1064+
csrf_token: str,
1065+
):
1066+
response = await test_client_auth_csrf.post(
1067+
f"{tenant_params.path_prefix}/verify-link",
1068+
data={"code": "INVALIDCODE", "csrf_token": csrf_token},
1069+
)
1070+
1071+
assert response.status_code == status.HTTP_302_FOUND
1072+
assert response.headers["Location"].endswith(
1073+
f"{tenant_params.path_prefix}/login?verify_error=1"
1074+
)
1075+
1076+
async def test_post_valid_verifies_and_consumes(
1077+
self,
1078+
test_client_auth_csrf: httpx.AsyncClient,
1079+
csrf_token: str,
1080+
main_session: AsyncSession,
1081+
test_data: TestData,
1082+
):
1083+
user = test_data["users"]["not_verified_email"]
1084+
code = email_verification_codes["not_verified_email"][0]
1085+
email_verification = test_data["email_verifications"]["not_verified_email"]
1086+
tenant = user.tenant
1087+
path_prefix = tenant.slug if not tenant.default else ""
1088+
1089+
response = await test_client_auth_csrf.post(
1090+
f"{path_prefix}/verify-link",
1091+
data={"code": code, "csrf_token": csrf_token},
1092+
)
1093+
1094+
assert response.status_code == status.HTTP_302_FOUND
1095+
assert response.headers["Location"].endswith(f"{path_prefix}/login?verified=1")
1096+
1097+
email_verification_repository = EmailVerificationRepository(main_session)
1098+
assert (
1099+
await email_verification_repository.get_by_id(email_verification.id) is None
1100+
)
1101+
user_repository = UserRepository(main_session)
1102+
updated_user = await user_repository.get_by_id(user.id)
1103+
assert updated_user is not None
1104+
assert updated_user.email_verified is True
1105+
1106+
10081107
@pytest.mark.asyncio
10091108
class TestAuthGetConsent:
10101109
@pytest.mark.parametrize(

0 commit comments

Comments
 (0)