Check Who Can See What
Kitty now has accounts, and other flats have started using it. While testing, you log in as yourself and open /flats/12/expenses, your own flat. Out of curiosity you change the 12 to 13 in the address bar, and you see a stranger's grocery bills. Your login worked perfectly. What was missing was a different check entirely.
The rule
Login proves who you are; every request must still check what you may do.
Two words are easy to mix up:
- Authentication answers "who are you?" It is the login: a password checked, a session started.
- Authorisation answers "are you allowed to do this, to this thing?" It has to be asked again on every request, for every flat, expense and payment it touches.
Assistants often build a solid login and then forget authorisation, because the feature "works" when you test it with your own data. The fix is a check inside every function that reads or changes data:
def list_expenses(db, current_user, flat_id):
is_member = db.execute(
"SELECT 1 FROM members WHERE flat_id = ? AND user_id = ?",
(flat_id, current_user.id),
).fetchone()
if is_member is None:
raise PermissionError("You are not a member of this flat")
return db.execute(
"SELECT * FROM expenses WHERE flat_id = ?", (flat_id,)
).fetchall()Two more rules. Deny by default: a new action is forbidden until a rule allows it, not allowed until a rule forbids it. And hiding a button is not protection. If the delete button is hidden but the server accepts the delete request, anyone who sends that request directly can still delete.