Fix the token check in auth middleware
Your task
An AI wrote auth middleware that wrapped token parsing in a try/catch and called next() in the catch. A request with no token, or a forged one, went through as if it were signed in. Your team rewrote the decision to fail closed: anything not fully verified is refused.
An assistant wrote authorize_requests(auth_headers, valid_tokens). It is in the editor. It has a bug. Find it and fix it.
Input and output:
auth_headers: each request'sAuthorizationheader, or""when there is none.valid_tokens: the tokens the service accepts, loaded from config. The list can be empty, for example when the config failed to load.- Return one verdict per request, in order.
Rules the tests check. Use the first that applies:
- An empty header:
"401 missing". - Split the header on single spaces, keeping empty pieces. Unless there are exactly two pieces, the first is exactly
Bearer(case matters) and the second is not empty:"401 malformed". So a double space, a leading space or an extra piece is malformed. - The token, the second piece, exactly matches one of
valid_tokens:"allow". Otherwise:"401 invalid". With an empty list, no token is valid.
Examples
authorize_requests(auth_headers: list[str], valid_tokens: list[str]) -> list[str]Example 1
Input
authorize_requests(["Bearer good1", "", "Bearer bad"], ["good1", "good2"])Output
["allow", "401 missing", "401 invalid"]Example 2
Input
authorize_requests(["Bearer"], ["good1"])Output
["401 malformed"]Example 3
Input
authorize_requests([], ["good1"])Output
[]