fix(csrf): validate against the presented session, not the most recent (6c-3)
RequireCSRF looked up csrf_token by user_id ORDER BY created_at DESC LIMIT 1 — the newest session, not the one whose Bearer token was presented. Two consequences: created_at's 1-second resolution made two same-second sessions a coin-flip (phantom 403s), and conceptually it accepted "any valid CSRF for this user" rather than the one bound to this session. Now queried by token_hash = SHA256(bearer) AND user_id. Authenticate already located this row + checked expiry, so the expiry clause is dropped. Signature unchanged. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user