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>
This commit is contained in:
Johan Lundberg 2026-06-05 13:40:30 +02:00
parent efb265a68b
commit baef5e0e2e
No known key found for this signature in database
GPG key ID: A6C152738D03C7D1
6 changed files with 96 additions and 10 deletions

View file

@ -86,7 +86,28 @@ async def logout(request: Request) -> Response:
return response
@router.get("/register/{token}")
@router.get("/register/{token}", response_class=HTMLResponse)
async def register_magic_link_page(request: Request, token: str) -> Response:
"""Show the registration confirmation page.
GET is side-effect free: it only validates the token (without consuming it)
and renders a form. The token is consumed by the POST below, so that simply
visiting the link (email scanners, prefetchers) cannot create a session.
"""
magic_link_service = request.app.state.magic_link_service
link = await magic_link_service.validate(token)
if link is None:
return HTMLResponse("<p>Invalid or expired registration link.</p>", status_code=400)
templates = request.app.state.templates
return templates.TemplateResponse(
request,
"register.html",
{"token": token, "username": link.username},
)
@router.post("/register/{token}")
async def register_magic_link(request: Request, token: str) -> Response:
magic_link_service = request.app.state.magic_link_service
user_repo = request.app.state.user_repo
@ -118,8 +139,7 @@ async def register_magic_link(request: Request, token: str) -> Response:
user = User(userid=userid, username=link.username, groups=["users"])
await user_repo.create(user)
request.session["userid"] = user.userid
request.session["username"] = user.username
_establish_authenticated_session(request, user)
return RedirectResponse("/manage/credentials?setup=1", status_code=303)

View file

@ -0,0 +1,14 @@
{% extends "base.html" %}
{% block title %}Set up your account — Porchlight{% endblock %}
{% block content %}
<h1>Set up your account</h1>
<p>You're about to set up the account for <strong>{{ username }}</strong>.</p>
<form method="post" action="/register/{{ token }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token_processor(request) }}">
<button type="submit">Continue</button>
</form>
{% endblock %}