Your Admin Check Was an assert and Production Ran Python With -O
The refund endpoint was for staff only. The check was one tidy line. def issue_refund(request, order_id): assert request.user.is_staff, "staff only" ... In tests it worked. A customer account got an Assertion
The refund endpoint
was for staff only.
The check
was one tidy line.
def issue_refund(request, order_id):
assert request.user.is_staff, "staff only"
...
In tests it worked.
A customer account
got an AssertionError.
A staff account
got a refund.
Green.
Months later
someone tuned the container.
Smaller memory,
faster start.
They added one line
to the image:
ENV PYTHONOPTIMIZE=1
Nothing broke.
Every test still passed,
because the tests
ran on laptops
without it.
And from that release on,
any logged in customer
could issue a refund.
Here is the mechanism.
assert is not a check.
It is a debugging aid.
When Python runs with -O,
or with PYTHONOPTIMIZE set,
every assert statement
is removed
before the code runs.
Not skipped.
Removed.
The line is simply
not in the program anymore.
That is the documented behaviour.
The idea is that asserts
state things
that should already be true,
so a finished program
can leave them out.
Who is allowed to refund
is not something
that should already be true.
It is something
a stranger is trying
to make false.
It is the whole question.
The same goes for
input validation,
ownership checks,
and limits on amounts.
Anything that stops
a request
that someone sent on purpose.
The fix is plain:
if not request.user.is_staff:
raise PermissionDenied("staff only")
Or your framework's own
permission decorator,
which no flag
can switch off.
And do not catch
AssertionError
as your way of saying no.
A handler for an error
that can no longer happen
is just more code
that looks like protection.
Then make the scanner
say it for you.
Bandit reports
every assert in your code
as B101.
Ruff has the same rule
as S101.
Allow it in the tests folder.
Fail the build everywhere else.
And run your security tests once
the way production runs.
Same image.
Same environment.
Same flags.
A permission check that only exists
in debug mode
is a permission check
for the people
who were never going to attack you.
– Serguey Asael Shinder
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.