Fix the route that fetches an invoice by id
Your task
Your billing API has a route that lets a logged-in user fetch one of their invoices by id. Login middleware runs first and passes in the caller's user id. The team's tests only ever fetch the owner's own invoice.
An assistant wrote fetch_invoice(invoice_rows, requested_id, caller_user_id). It is in the editor. It has a bug. Find it and fix it.
Input and output:
invoice_rows: the invoice table, one string per row:"invoice_id|owner_user_id|amount_cents".requested_id: the invoice id from the URL.caller_user_id: the logged-in user's id, or""when nobody is logged in.- Return
"200:<amount_cents>"with the amount text exactly as it appears in the row,"404"or"401".
Rules the tests check:
- An empty
caller_user_idreturns"401", before anything else. - Otherwise, an empty
requested_idreturns"404". - Skip any row that does not split on
|into exactly 3 parts. - A row matches only when its invoice id equals
requested_idand its owner equalscaller_user_id. Both comparisons are exact: case matters, anduser_70is notuser_7. - Return the first matching row. Ids can repeat with different owners, so keep looking past a row that has the right id and the wrong owner.
- No match returns
"404". An invoice that exists but belongs to someone else also returns"404", so the response never reveals which ids exist.
Examples, with the rows ["inv_1|user_7|4200", "inv_2|user_9|999"]:
fetch_invoice(rows, "inv_1", "user_7")returns"200:4200".fetch_invoice(rows, "inv_2", "user_7")returns"404": inv_2 belongs to user_9.fetch_invoice(rows, "inv_3", "user_7")returns"404": there is no inv_3.
Then, in a sentence or two: how would you catch this kind of bug in review?
Examples
fetch_invoice(invoice_rows: list[str], requested_id: str, caller_user_id: str) -> strExample 1
Input
fetch_invoice(["inv_1|user_7|4200", "inv_2|user_9|999"], "inv_1", "user_7")Output
"200:4200"Example 2
Input
fetch_invoice(["inv_1|user_7|4200", "inv_2|user_9|999"], "inv_2", "user_7")Output
"404"Example 3
Input
fetch_invoice(["inv_1|user_7|4200", "inv_2|user_9|999"], "inv_3", "user_7")Output
"404"