Fix the CSRF check on an email change endpoint
Your task
An AI added a Flask endpoint that changes a user's account email. It read the user from the session cookie and had no CSRF check. CSRF (cross-site request forgery) is when a hidden form on another site makes the victim's browser send the request, cookie included. Your team now runs every request to this endpoint through an admission check first.
An assistant wrote classify_mutating_request(method, has_session, csrf_token, expected_token). It is in the editor. It has a bug. Find it and fix it.
Input and output:
method: the HTTP method as sent, like"POST". It can be in any case, have whitespace around it, or be empty.has_session: true when the request comes with a logged in session.csrf_token: the CSRF token submitted with the form. It can be empty or blank.expected_token: the CSRF token stored in the user's session. It can be empty or blank when the session never got one.- Return one of
"405_method_not_allowed","401_unauthenticated","403_csrf_failed"or"200_ok".
Rules the tests check:
- Return the first of these that applies:
"405_method_not_allowed"when the method, trimmed and in upper case, is notPOST."401_unauthenticated"whenhas_sessionis false."403_csrf_failed"when, after trimming whitespace at both ends of both tokens, the expected token is empty, the submitted token is empty, or the two differ. Tokens compare with case."200_ok"otherwise.
Examples
classify_mutating_request(method: str, has_session: bool, csrf_token: str, expected_token: str) -> strExample 1
Input
classify_mutating_request("POST", True, "tok_abc", "tok_abc")Output
"200_ok"Example 2
Input
classify_mutating_request("POST", True, "", "tok_abc")Output
"403_csrf_failed"Example 3
Input
classify_mutating_request("POST", False, "tok_abc", "tok_abc")Output
"401_unauthenticated"