Fix the CSRF check on an email change endpoint

Review the AI's codeEasy10 min

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:
    1. "405_method_not_allowed" when the method, trimmed and in upper case, is not POST.
    2. "401_unauthenticated" when has_session is false.
    3. "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.
    4. "200_ok" otherwise.

Examples

classify_mutating_request(method: str, has_session: bool, csrf_token: str, expected_token: str) -> str
Example 1
Inputclassify_mutating_request("POST", True, "tok_abc", "tok_abc")
Output"200_ok"
Example 2
Inputclassify_mutating_request("POST", True, "", "tok_abc")
Output"403_csrf_failed"
Example 3
Inputclassify_mutating_request("POST", False, "tok_abc", "tok_abc")
Output"401_unauthenticated"