Fix the CORS headers for a cookie-based API
Your task
Your Node API serves user data to a browser app and keeps sessions in cookies. The frontend kept hitting CORS errors, so an assistant rewrote how the API answers cross-site requests. CORS (cross-origin resource sharing) headers tell a browser which other sites may read a response.
An assistant wrote cors_response_headers(request_origin, allowed_origins, with_credentials). It is in the editor. It has a bug. Find it and fix it.
Input and output:
request_origin: the request'sOriginheader, such ashttps://app.example.com, or""when there is none.allowed_origins: the configured origins. The entry*means any origin.with_credentials: true when the response is for a request that carries cookies.- Return the response's CORS headers as a list of strings, in the order shown below, or
[]for none.
Rules the tests check:
- No origin (
"") returns[]: a same-origin request needs no CORS headers. - An origin is listed when it equals an entry exactly, case included.
https://app.example.com.evil.comis nothttps://app.example.com. The entry*never makes an origin listed. - With credentials,
*does not count at all. A listed origin gets["Access-Control-Allow-Origin: <origin>", "Access-Control-Allow-Credentials: true", "Vary: Origin"]. Anything else gets[]. - Without credentials, if
*is in the list, return["Access-Control-Allow-Origin: *"], even when the origin is also listed. Otherwise a listed origin gets["Access-Control-Allow-Origin: <origin>", "Vary: Origin"], and anything else gets[]. nullis an origin string like any other.
Examples:
cors_response_headers("https://app.example.com", ["https://app.example.com"], true)returns["Access-Control-Allow-Origin: https://app.example.com", "Access-Control-Allow-Credentials: true", "Vary: Origin"].cors_response_headers("https://evil.example", ["https://app.example.com"], true)returns[].cors_response_headers("https://anything.test", ["*"], false)returns["Access-Control-Allow-Origin: *"]: a public response with no cookies.
Then, in a sentence or two: how would you catch this kind of bug in review?
Examples
cors_response_headers(request_origin: str, allowed_origins: list[str], with_credentials: bool) -> list[str]Example 1
Input
cors_response_headers("https://app.example.com", ["https://app.example.com"], True)Output
["Access-Control-Allow-Origin: https://app.example.com", "Access-Control-Allow-Credentials: true", "Vary: Origin"]Example 2
Input
cors_response_headers("https://evil.example", ["https://app.example.com"], True)Output
[]Example 3
Input
cors_response_headers("https://anything.test", ["*"], False)Output
["Access-Control-Allow-Origin: *"]