diff --git a/CODE_AUDIT.md b/CODE_AUDIT.md index 67c2826..7f5fff3 100644 --- a/CODE_AUDIT.md +++ b/CODE_AUDIT.md @@ -668,6 +668,13 @@ prochain démarrage. ### 6c-3. 🟡 Le CSRF est validé contre la mauvaise session +> ✅ **RÉSOLU 2026-07-16.** `RequireCSRF` lit désormais `csrf_token WHERE +> token_hash = :th AND user_id = :uid` (la session présentée), plus de +> `ORDER BY created_at DESC LIMIT 1`. `ExtractBearerToken`/`SHA256Hex` déjà +> utilisés par `Authenticate` dans la même unité ; signature inchangée, aucun +> call-site touché. Le re-test d'expiry est retiré (Authenticate tourne avant +> et l'a déjà fait, désormais sur la même base UTC après §6c-2). + [`RequireCSRF`](delphi-backend/Source/PM.Session.pas:120) cherche le `csrf_token` par `user_id ORDER BY created_at DESC LIMIT 1` — la session la plus récente, **pas celle réellement présentée**. Deux conséquences : diff --git a/delphi-backend/Source/PM.Session.pas b/delphi-backend/Source/PM.Session.pas index 57549ad..1fc31f5 100644 --- a/delphi-backend/Source/PM.Session.pas +++ b/delphi-backend/Source/PM.Session.pas @@ -101,7 +101,7 @@ end; procedure RequireCSRF(ARequest: TIdHTTPRequestInfo; AResponse: TIdHTTPResponseInfo; AUserId: Integer); var - LSubmitted, LStored: string; + LSubmitted, LStored, LTokenHash: string; LQ: TFDQuery; begin if SameText(ARequest.Command, 'GET') then Exit; @@ -113,6 +113,14 @@ begin raise ESessionRejected.Create('missing csrf'); end; + // Bind the CSRF check to the session actually PRESENTED (token_hash), not + // "the user's most recent session" (§6c-3). The old ORDER BY created_at + // could read a different session's token — and created_at's 1-second + // resolution made two same-second sessions a coin-flip → phantom 403s. + // user_id stays as a filter (defense in depth). Expiry isn't re-checked: + // Authenticate always runs before RequireCSRF and already did it. + LTokenHash := SHA256Hex(ExtractBearerToken(ARequest)); + DB.Lock; try LQ := TFDQuery.Create(nil); @@ -120,8 +128,8 @@ begin LQ.Connection := DB.Connection; LQ.SQL.Text := 'SELECT csrf_token FROM sessions ' + - 'WHERE user_id = :uid AND expires_at > datetime(''now'') ' + - 'ORDER BY created_at DESC LIMIT 1'; + 'WHERE token_hash = :th AND user_id = :uid'; + LQ.ParamByName('th').AsString := LTokenHash; LQ.ParamByName('uid').AsInteger := AUserId; LQ.Open; if LQ.IsEmpty then