Video in progress
How do you protect authorization rules (who can access which resource) from regressions?
For every endpoint I write a role-and-ownership "permission matrix" with parameterized tests: anonymous, an ordinary user, another user's resource, a moderator, an admin. I set it up so that a new endpoint that isn't in the matrix makes the test fail.
📖 Answer
Authorization bugs usually look like "it works": the endpoint returns 200, just to the wrong person. Functional tests are written as an admin and don't see this.
A parameterized matrix:
@ParameterizedTest(name = "{0} {1} as {2} -> {3}")
@CsvSource({
"GET, /api/admin/payouts, ANON, 401",
"GET, /api/admin/payouts, STUDENT, 403",
"GET, /api/admin/payouts, MODERATOR, 403",
"GET, /api/admin/payouts, ADMIN, 200",
"GET, /api/orders/{own}, STUDENT, 200",
"GET, /api/orders/{foreign}, STUDENT, 404",
})
void accessMatrix(String method, String path, Role role, int expected) throws Exception {
mvc.perform(request(method, resolve(path)).with(as(role)))
.andExpect(status().is(expected));
}
Note the 404 for someone else's order: a 403 would reveal that the resource exists. That decision is pinned down in the test too.
The case most often missed is IDOR: /api/orders/{id} checks only "is the user logged in", not "does this order belong to this person". That's why "own" and "foreign" are always separate rows in the matrix.
So that new endpoints aren't forgotten: the test takes all the mappings from RequestMappingHandlerMapping and fails if it finds one that isn't in the matrix. This holds the "default deny" principle at the test level too.
If there's method-level @PreAuthorize, I test the service layer separately as well: there are internal calls (scheduler, listener) that bypass the controller.
Sign up to mark studied questions and save your progress.