feat(mfa): #64 WebAuthn complet — enregistrement/clé/verify login + gestion clés dans Sécurité (backend+frontend+i18n+tests)

This commit is contained in:
2026-09-07 23:55:35 -04:00
parent 7042307955
commit ab795ec9e0
9 changed files with 1029 additions and 12 deletions
+198 -5
View File
@@ -5,7 +5,7 @@
import logging
import re
from fastapi import APIRouter, Depends, HTTPException, Request, Response
from fastapi import APIRouter, Body, Depends, HTTPException, Request, Response
from pydantic import BaseModel, validator
from backend.ratelimit import is_rate_limited
@@ -147,12 +147,13 @@ async def login(body: LoginRequest, response: Response, request: Request):
# Success — clear rate limits
rl_record_success(client_ip)
# If MFA is enabled, don't issue token yet — require TOTP verification
if user.get("mfa_enabled") and user.get("mfa_secret"):
logger.info(f"User '{body.username}' login deferred — MFA required")
# If MFA is enabled, don't issue token yet — require second factor
if user.get("mfa_enabled"):
method = "totp" if user.get("mfa_secret") else _preferred_mfa_method(user)
logger.info(f"User '{body.username}' login deferred — MFA required ({method})")
return {
"mfa_required": True,
"mfa_method": "totp",
"mfa_method": method,
"username": body.username,
"remember_me": body.remember_me,
}
@@ -434,6 +435,196 @@ async def mfa_totp_disable(
return {"mfa_enabled": False}
# ── WebAuthn endpoints (ROADMAP #64) ─────────────────────────────────
def _preferred_mfa_method(user: dict) -> str:
"""Which second factor to offer at login: webauthn when keys exist, else totp."""
if user.get("webauthn_credentials"):
return "webauthn"
return "totp"
class WebauthnRegisterRequest(BaseModel):
credential: dict
label: str = ""
class WebauthnVerifyRequest(BaseModel):
username: str
credential: dict
remember_me: bool = False
class WebauthnRemoveRequest(BaseModel):
credential_id: str
password: str
@router.post("/mfa/webauthn/register/options")
async def mfa_webauthn_register_options(current_user=Depends(require_auth)):
"""Start WebAuthn key enrolment — returns publicKey creation options for the browser."""
from .webauthn_mfa import begin_registration
options = begin_registration(current_user["username"],
current_user.get("display_name", ""))
return {"options": options}
@router.post("/mfa/webauthn/register")
async def mfa_webauthn_register(
req: WebauthnRegisterRequest,
current_user=Depends(require_auth),
):
"""Verify the created credential, store it, and enable MFA if not already on.
Returns recovery codes when MFA is newly enabled (they were never issued).
"""
from datetime import datetime, timezone
from .user_store import get_user, update_user
from .webauthn_mfa import complete_registration
user = get_user(current_user["username"])
try:
record = complete_registration(current_user["username"], req.credential,
label=req.label)
except ValueError as e:
raise HTTPException(400, str(e))
except Exception as e:
logger.warning(f"WebAuthn registration failed for {current_user['username']}: {e}")
raise HTTPException(400, "Validation du credential WebAuthn échouée")
record["registered_at"] = datetime.now(timezone.utc).isoformat()
creds = list(user.get("webauthn_credentials", []))
creds = [c for c in creds if c.get("credential_id") != record["credential_id"]]
creds.append(record)
updates: dict = {"webauthn_credentials": creds}
issued_recovery: list[str] = []
if not user.get("mfa_enabled"):
issued_recovery = generate_recovery_codes()
updates.update({
"mfa_enabled": True,
"mfa_method": "webauthn",
"mfa_recovery_codes": [hash_recovery_code(c) for c in issued_recovery],
})
update_user(current_user["username"], updates)
logger.info(f"WebAuthn credential registered for user '{current_user['username']}' "
f"({record['label']})")
return {
"ok": True,
"credentials": user_credentials_response(creds),
"mfa_enabled": True,
"recovery_codes": issued_recovery,
}
def user_credentials_response(creds: list[dict]) -> list[dict]:
from .webauthn_mfa import credentials_for_api
return credentials_for_api(creds)
@router.get("/mfa/webauthn/credentials")
async def mfa_webauthn_list(current_user=Depends(require_auth)):
from .user_store import get_user
user = get_user(current_user["username"])
return {"credentials": user_credentials_response(user.get("webauthn_credentials", []))}
@router.post("/mfa/webauthn/credentials/remove")
async def mfa_webauthn_remove(
req: WebauthnRemoveRequest,
current_user=Depends(require_auth),
):
"""Remove a WebAuthn key. Requires password. Disables MFA if no second factor remains."""
from .user_store import get_user, update_user
from .webauthn_mfa import clear_pending
user = get_user(current_user["username"])
if not verify_password(req.password, user["password_hash"]):
raise HTTPException(400, "Mot de passe incorrect")
creds = [c for c in user.get("webauthn_credentials", [])
if c.get("credential_id") != req.credential_id]
if len(creds) == len(user.get("webauthn_credentials", [])):
raise HTTPException(404, "Credential inconnu")
updates: dict = {"webauthn_credentials": creds}
if not creds and not user.get("mfa_secret"):
updates.update({"mfa_enabled": False, "mfa_method": None, "mfa_recovery_codes": []})
elif not creds and user.get("mfa_secret"):
updates["mfa_method"] = "totp"
update_user(current_user["username"], updates)
clear_pending(current_user["username"])
return {"ok": True, "credentials": user_credentials_response(creds),
"mfa_enabled": bool(updates.get("mfa_enabled", user.get("mfa_enabled"))) and bool(creds or user.get("mfa_secret"))}
@router.post("/mfa/webauthn/options")
async def mfa_webauthn_login_options(body: dict = Body(...)):
"""Unauthenticated: begin the login assertion for a user with registered keys.
Returns null options (mfa_method 'totp') when the user has no WebAuthn keys.
"""
username = str(body.get("username", ""))
user = get_user(username)
if not user or not user.get("mfa_enabled"):
raise HTTPException(400, "MFA non activé pour cet utilisateur")
creds = user.get("webauthn_credentials", [])
if not creds:
return {"mfa_method": "totp", "options": None}
from .webauthn_mfa import begin_authentication
options = begin_authentication(username, creds)
if options is None:
return {"mfa_method": "totp", "options": None}
return {"mfa_method": "webauthn", "options": options}
@router.post("/mfa/webauthn/verify")
async def mfa_webauthn_verify(
body: WebauthnVerifyRequest,
response: Response,
request: Request,
):
"""Unauthenticated: verify the WebAuthn assertion and issue JWT tokens."""
from .user_store import get_user, update_user
from .webauthn_mfa import complete_authentication
user = get_user(body.username)
if not user:
hash_password("dummy_timing_protection")
raise HTTPException(401, "Identifiants invalides")
if not user.get("mfa_enabled"):
raise HTTPException(400, "MFA non activé pour cet utilisateur")
creds = user.get("webauthn_credentials", [])
try:
credential_id = body.credential.get("id", "")
stored = next((c for c in creds if c.get("credential_id") == credential_id), None)
if stored is None:
raise ValueError("Credential non enregistré")
new_count = complete_authentication(body.username, body.credential, stored)
except ValueError as e:
raise HTTPException(401, str(e))
except Exception as e:
logger.warning(f"WebAuthn verification failed for {body.username}: {e}")
raise HTTPException(401, "Vérification WebAuthn échouée")
updated = [dict(c) for c in creds]
for c in updated:
if c.get("credential_id") == body.credential.get("id"):
c["sign_count"] = new_count
update_user(body.username, {"webauthn_credentials": updated})
client_ip = request.client.host if request.client else "unknown"
rl_record_success(client_ip)
logger.info(f"User '{body.username}' logged in via WebAuthn")
return _issue_tokens(user, body.username, body.remember_me, response)
@router.get("/mfa/status")
async def mfa_status(current_user=Depends(require_auth)):
"""Return current user's MFA status."""
@@ -442,6 +633,8 @@ async def mfa_status(current_user=Depends(require_auth)):
return {
"mfa_enabled": user.get("mfa_enabled", False),
"mfa_method": user.get("mfa_method"),
"totp_enabled": bool(user.get("mfa_secret")),
"webauthn_credentials": len(user.get("webauthn_credentials", [])),
}