fix(security): store only a hash of magic-link tokens

Magic-link tokens were persisted in plaintext, so a database read disclosed
usable login/invite tokens. The service now hashes tokens (HMAC-SHA256 when a
pepper is configured, else SHA-256 of the high-entropy token) and persists
only the hash; the raw token is exposed solely in the registration URL and is
re-attached to objects returned to callers.

Refs: porchlight-42h

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Johan Lundberg 2026-06-04 10:36:18 +02:00
parent cdde3e3754
commit 91a2277664
No known key found for this signature in database
GPG key ID: A6C152738D03C7D1
3 changed files with 65 additions and 62 deletions

View file

@ -1,3 +1,5 @@
import hashlib
import hmac
import secrets
from datetime import UTC, datetime, timedelta
@ -6,11 +8,23 @@ from porchlight.store.protocols import MagicLinkRepository
class MagicLinkService:
"""Magic link token lifecycle management."""
"""Magic link token lifecycle management.
def __init__(self, repo: MagicLinkRepository, ttl: int = 86400) -> None:
The raw token is only ever exposed to the user (in the registration URL).
Only a hash of the token is persisted, so a database disclosure does not
yield usable tokens. A pepper, when configured, keys the hash (HMAC);
otherwise a plain SHA-256 of the high-entropy token is stored.
"""
def __init__(self, repo: MagicLinkRepository, ttl: int = 86400, pepper: str | None = None) -> None:
self._repo = repo
self._ttl = ttl
self._pepper = pepper
def _hash_token(self, token: str) -> str:
if self._pepper:
return hmac.new(self._pepper.encode(), token.encode(), hashlib.sha256).hexdigest()
return hashlib.sha256(token.encode()).hexdigest()
async def create(
self,
@ -18,34 +32,39 @@ class MagicLinkService:
created_by: str | None = None,
note: str | None = None,
) -> MagicLink:
"""Generate and store a new magic link for the given username."""
"""Generate and store a new magic link for the given username.
Persists only the hashed token; the returned MagicLink carries the raw
token so the caller can build the registration URL.
"""
token = secrets.token_urlsafe(32)
expires_at = datetime.now(UTC) + timedelta(seconds=self._ttl)
link = MagicLink(
token=token,
stored = MagicLink(
token=self._hash_token(token),
username=username,
expires_at=expires_at,
created_by=created_by,
note=note,
)
return await self._repo.create(link)
await self._repo.create(stored)
return stored.model_copy(update={"token": token})
async def validate(self, token: str) -> MagicLink | None:
"""Validate a magic link token.
Returns the MagicLink if it exists, is not used, and has not expired.
Returns None otherwise.
Returns the MagicLink (with the raw token re-attached) if it exists, is
not used, and has not expired. Returns None otherwise.
"""
link = await self._repo.get_by_token(token)
link = await self._repo.get_by_token(self._hash_token(token))
if link is None or link.used:
return None
if link.expires_at < datetime.now(UTC):
return None
return link
return link.model_copy(update={"token": token})
async def mark_used(self, token: str) -> bool:
"""Mark a magic link as used. Returns True if found and marked."""
return await self._repo.mark_used(token)
return await self._repo.mark_used(self._hash_token(token))
async def cleanup_expired(self) -> int:
"""Delete expired unused links. Returns count deleted."""