Practice: roles and permissions
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Most authorisation bugs come from four habits: rules in the wrong order, no deny-by-default rule, ids loaded without an owner check, and 401, 403 and 404 mixed up. A permission table catches all four.
Turning a permission table into rules
A permission table lists every endpoint with the expected answer for each kind of caller. ShopLite's lives in SECURITY.md, and every URL rule and owner check comes from one of its rows.
A small plain-Java model follows ShopLite's table: the first matching rule decides 401 or 403, then an owner check may still say 404.
Example 1 · AccessTableDemo: a model of first-match rules and owner checks
import java.util.List;import java.util.Map;
/** Who is calling: no role for a guest; customerId only for customers. */record Caller(String name, String role, Integer customerId) { boolean isGuest() { return role == null; }}
record Request(String method, String path) {}
/** * One URL rule: which requests it matches, which roles it lets in (null = everyone), * and whether the service then checks the order's owner. */record Rule(String method, String pattern, List<String> roles, boolean ownerChecked) {
boolean matches(Request request) { boolean methodOk = method == null || method.equals(request.method()); return methodOk && pathMatches(pattern.split("/"), request.path().split("/")); }
/** A small model of path patterns: "*" is one segment, "**" at the end is the rest. */ private static boolean pathMatches(String[] pattern, String[] path) { for (int i = 0; i < pattern.length; i++) { if (pattern[i].equals("**")) { return true; } if (i >= path.length || !(pattern[i].equals("*") || pattern[i].equals(path[i]))) { return false; } } return pattern.length == path.length; }}
public class AccessTableDemo {
static final List<String> ANYONE = null;
/** The same order as ShopLite's SecurityConfig: the first matching rule decides. */ static final List<Rule> RULES = List.of( new Rule("GET", "/api/v1/products/**", ANYONE, false), new Rule(null, "/api/v1/products/**", List.of("ADMIN"), false), new Rule(null, "/api/v1/me/**", List.of("CUSTOMER"), false), new Rule("GET", "/api/v1/orders/*", List.of("CUSTOMER", "ADMIN"), true), new Rule("POST", "/api/v1/orders/*/cancel", List.of("CUSTOMER", "ADMIN"), true), new Rule(null, "/api/v1/orders/**", List.of("ADMIN"), false), new Rule(null, "/**", List.of(), false)); // deny by default: no role is enough
/** Owner of each seed order (order id -> customer id): Asha is customer 1, Ravi customer 2. */ static final Map<Integer, Integer> ORDER_OWNER = Map.of(1, 1, 14, 2, 15, 6);
static int status(Caller caller, Request request) { Rule rule = RULES.stream().filter(r -> r.matches(request)).findFirst().orElseThrow(); if (rule.roles() != null && (caller.isGuest() || !rule.roles().contains(caller.role()))) { return caller.isGuest() ? 401 : 403; // unknown caller vs known but not allowed } return rule.ownerChecked() ? ownerCheck(caller, request) : 200; }
/** The service's rule for one order: the owner or an admin, otherwise 404 like a missing order. */ static int ownerCheck(Caller caller, Request request) { String[] parts = request.path().split("/"); // "", "api", "v1", "orders", "14", ... Integer owner = ORDER_OWNER.get(Integer.valueOf(parts[4])); if (owner == null) { return 404; } boolean allowed = "ADMIN".equals(caller.role()) || owner.equals(caller.customerId()); return allowed ? 200 : 404; }
public static void main(String[] args) { List<Caller> callers = List.of(new Caller("guest", null, null), new Caller("asha", "CUSTOMER", 1), new Caller("ravi", "CUSTOMER", 2), new Caller("admin", "ADMIN", null)); List<Request> requests = List.of( new Request("GET", "/api/v1/products/6"), new Request("PATCH", "/api/v1/products/6"), new Request("GET", "/api/v1/me/orders"), new Request("GET", "/api/v1/orders/1"), new Request("GET", "/api/v1/orders/14"), new Request("GET", "/api/v1/orders/99"), new Request("POST", "/api/v1/orders/15/ship"), new Request("GET", "/api/v1/reports"));
System.out.printf("%-30s", "request"); callers.forEach(c -> System.out.printf("%7s", c.name())); System.out.println(); for (Request request : requests) { System.out.printf("%-30s", request.method() + " " + request.path()); for (Caller caller : callers) { System.out.printf("%7d", status(caller, request)); } System.out.println(); } }}request guest asha ravi admin GET /api/v1/products/6 200 200 200 200 PATCH /api/v1/products/6 401 403 403 200 GET /api/v1/me/orders 401 200 200 403 GET /api/v1/orders/1 401 200 404 200 GET /api/v1/orders/14 401 404 200 200 GET /api/v1/orders/99 401 404 404 404 POST /api/v1/orders/15/ship 401 403 403 200 GET /api/v1/reports 401 403 403 403
What this code does
statusfinds the first rule that matches; a guest who fails it gets 401, a signed-in caller 403. This is whatAuthorizationFilterandExceptionTranslationFilterdo together.- Rules marked
ownerCheckedpass the request on toownerCheck, the model ofOrderService.loadVisible: Ravi's order 14 is 404 for Asha, exactly like order 99. - The last rule
/**with no roles is deny-by-default:/api/v1/reportsis 401 for a guest and 403 for everyone else, even the admin.
The model is not Spring itself, but its answers match the real app for these requests. Turning the table into code is mechanical: public rows become permitAll(), role-only rows become hasRole or hasAnyRole URL rules, and rows that say "own" get a URL rule plus an owner check in the service.
Write the rules from most specific to most general and end with anyRequest().denyAll(), so a row missing from the table fails closed, not open.
Predicting 401, 403 or 404
Three questions in order predict an access answer: is the caller known (no: 401), does the role pass the first matching rule (no: 403), and does the data belong to the caller or is the caller an admin (no: 404, the same as a missing id).
Check each prediction against the running app. This script calls every request as each user and prints only the status codes.
Example 2 · matrix.sh: every request as every user against the running app
Runs in: the shoplite-api Spring Boot project
# usage: matrix.sh -> status codes for guest, asha, admin (and sneha when SNEHA=1) on a list of requestssource "$(dirname "$0")/env.sh"ASHA=$(login asha.rao@example.com asha-dev-password)ADMIN=$(login admin@shoplite.example shoplite-admin-dev)call() { # method path token body local args=(-s -o "$D/r.json" -w "%{http_code}" -X "$1" "$B$2") [ -n "$3" ] && args+=(-H "Authorization: Bearer $3") [ -n "$4" ] && args+=(-H "Content-Type: application/json" -d "$4") curl "${args[@]}"}REQS=( "GET|/api/v1/products/6|" "PATCH|/api/v1/products/6|{\"price\": 1199.00}" "GET|/api/v1/products?includeInactive=true|" "GET|/api/v1/me/orders|" "GET|/api/v1/orders/1|" "GET|/api/v1/orders/14|" "GET|/api/v1/orders/14/items|" "POST|/api/v1/orders/14/cancel|" "POST|/api/v1/orders/14/ship|" "GET|/api/v1/orders|" "GET|/api/v1/customers/1|" "GET|/api/v1/reports|" "GET|/api/v1/orders/14/|")printf "%-45s %6s %6s %6s\n" REQUEST guest asha adminfor r in "${REQS[@]}"; do IFS='|' read -r m p b <<< "$r" g=$(call "$m" "$p" "" "$b"); a=$(call "$m" "$p" "$ASHA" "$b"); d=$(call "$m" "$p" "$ADMIN" "$b") printf "%-45s %6s %6s %6s\n" "$m $p" "$g" "$a" "$d"done$ bash matrix.sh REQUEST guest asha admin GET /api/v1/products/6 200 200 200 PATCH /api/v1/products/6 401 403 200 GET /api/v1/products?includeInactive=true 401 403 200 GET /api/v1/me/orders 401 200 403 GET /api/v1/orders/1 401 200 200 GET /api/v1/orders/14 401 404 200 GET /api/v1/orders/14/items 401 404 200 POST /api/v1/orders/14/cancel 401 404 409 POST /api/v1/orders/14/ship 401 403 409 GET /api/v1/orders 401 403 200 GET /api/v1/customers/1 401 403 200 GET /api/v1/reports 401 403 403 GET /api/v1/orders/14/ 401 403 404
What this code does
- The script logs in as Asha and the admin with the dev accounts, then prints only
%{http_code}for each request and caller. - Admin answers of 409 on order 14 come from the order rules, not security: access passed, but order 14 is SHIPPED.
- The last row is the trailing-slash pitfall:
/orders/14/does not match/orders/*, falls to the admin rule (403 for Asha), and has no controller (404 for the admin).
After those three questions the normal API rules apply: 400 for a bad body, 409 for a wrong state, 422 for another customer's address. That is why the admin gets 409 for cancelling order 14: access is fine, but the order is SHIPPED.
Predict the output
Predict 401, 403 or 404
Asha is customer 1, Ravi is customer 2. Order 14 is Ravi's and SHIPPED.
Round 1 of 4
Which status does the admin get?
Finding missing owner checks
A missing owner check is an endpoint that loads data by an id from the request and returns it without asking whose it is. The URL rule passes, so every signed-in customer can reach every id.
A missing check looks harmless in review: a controller method with @PathVariable Integer id that calls service.get(id). List every endpoint that takes an id and ask "whose is this, and where is that checked?"
Nested URLs (/orders/{id}/items), actions (/orders/{id}/cancel) and writes need the check as much as the plain read.
Also check the order of checks. The owner check must come straight after loading, before status rules, so another customer's order cannot leak its status through a 409.
Find the bug
Find the missing owner check
Each snippet lets a customer reach data that is not theirs. Tap the wrong line.
A nested endpoint for the items of an order.
Round 1 of 3Proving the table with a test matrix
A test matrix is one parameterized test with a row per caller, request and expected status, copied from the permission table. A new endpoint is one more line, and a broken rule shows up as a failing row.
ShopLite's AccessMatrixIT turns the access table into a test with @CsvSource: one row per caller and request.
Example 3 · src/test/java/com/shoplite/AccessMatrixIT.java
Runs in: the shoplite-api Spring Boot project
package com.shoplite;
import static org.assertj.core.api.Assertions.assertThat;import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt;
import java.util.List;import java.util.Map;
import org.junit.jupiter.params.ParameterizedTest;import org.junit.jupiter.params.provider.CsvSource;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;import org.springframework.http.HttpMethod;import org.springframework.http.MediaType;import org.springframework.security.core.authority.SimpleGrantedAuthority;import org.springframework.test.context.ActiveProfiles;import org.springframework.test.web.servlet.assertj.MockMvcTester;import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;import org.springframework.test.web.servlet.request.RequestPostProcessor;import org.springframework.transaction.annotation.Transactional;
/** * The access table of SECURITY.md as a test: every row is one request by one caller and the status it must get. * Seed data: Asha is customer 1 (orders 1, 3, 10), Ravi is customer 2 (orders 2, 7, 14), address 3 is Ravi's. * Each test runs in a transaction that is rolled back, so a 200 on a write changes nothing. */@SpringBootTest@AutoConfigureMockMvc@ActiveProfiles("test")@Transactionalclass AccessMatrixIT {
private static final Map<String, RequestPostProcessor> CALLERS = Map.of( "guest", request -> request, "asha", customer(2, 1), "ravi", customer(3, 2), "admin", jwt().jwt(t -> t.subject("1").claim("roles", List.of("ADMIN"))) .authorities(new SimpleGrantedAuthority("ROLE_ADMIN")));
private static final Map<String, String> BODIES = Map.of( "price", "{\"price\": 1199.00}", "myOrder", "{\"addressId\": 1, \"items\": [{\"productId\": 9, \"quantity\": 1}]}", "ravisAddress", "{\"addressId\": 3, \"items\": [{\"productId\": 9, \"quantity\": 1}]}");
@Autowired private MockMvcTester mvc;
private static RequestPostProcessor customer(int userId, int customerId) { return jwt().jwt(t -> t.subject(String.valueOf(userId)) .claim("roles", List.of("CUSTOMER")).claim("customerId", customerId)) .authorities(new SimpleGrantedAuthority("ROLE_CUSTOMER")); }
@ParameterizedTest(name = "{0} {1} {2} -> {4}") @CsvSource(delimiter = '|', textBlock = """ guest | GET | /api/v1/products/6 | | 200 asha | GET | /api/v1/products/6 | | 200 guest | PATCH | /api/v1/products/6 | price | 401 asha | PATCH | /api/v1/products/6 | price | 403 admin | PATCH | /api/v1/products/6 | price | 200 guest | GET | /api/v1/products?includeInactive=true | | 401 asha | GET | /api/v1/products?includeInactive=true | | 403 admin | GET | /api/v1/products?includeInactive=true | | 200 asha | DELETE | /api/v1/categories/7 | | 403 guest | GET | /api/v1/me/orders | | 401 asha | GET | /api/v1/me/orders | | 200 admin | GET | /api/v1/me/orders | | 403 asha | POST | /api/v1/me/orders | myOrder | 201 asha | POST | /api/v1/me/orders | ravisAddress | 422 asha | GET | /api/v1/orders/1 | | 200 ravi | GET | /api/v1/orders/1 | | 404 admin | GET | /api/v1/orders/1 | | 200 asha | GET | /api/v1/orders/14/items | | 404 ravi | GET | /api/v1/orders/14/items | | 200 asha | POST | /api/v1/orders/14/cancel | | 404 asha | POST | /api/v1/orders/15/ship | | 403 admin | POST | /api/v1/orders/15/ship | | 200 asha | GET | /api/v1/orders | | 403 admin | GET | /api/v1/orders | | 200 asha | GET | /api/v1/customers/2 | | 403 admin | GET | /api/v1/customers/2 | | 200 guest | GET | /api/v1/reports | | 401 admin | GET | /api/v1/reports | | 403 """) void callerGetsTheStatusFromTheAccessTable(String caller, String method, String path, String body, int expected) { MockHttpServletRequestBuilder request = MockMvcRequestBuilders .request(HttpMethod.valueOf(method), path) .with(CALLERS.get(caller)); if (body != null) { request.contentType(MediaType.APPLICATION_JSON).content(BODIES.get(body)); } assertThat(mvc.perform(request)).hasStatus(expected); }}$ ./mvnw verify ... [INFO] Running com.shoplite.AccessMatrixIT [INFO] Tests run: 28, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 50.63 s -- in com.shoplite.AccessMatrixIT [INFO] Running com.shoplite.order.OrderOwnershipIT [INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.094 s -- in com.shoplite.order.OrderOwnershipIT [INFO] [INFO] Results: [INFO] [INFO] Tests run: 33, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] BUILD SUCCESS
What this code does
- Each
@CsvSourcerow is one line of the access table: caller, method, path, optional body name, expected status. CALLERSmaps names to request post-processors: the guest sends nothing, the others get ajwt()with ShopLite's claims and the matching authority.@Transactionalrolls back each test, so the admin's PATCH and Asha's new order do not change the seed data the other rows rely on.
The test uses real controllers, services and MySQL seed data, with jwt() tokens for a guest, Asha, Ravi and the admin. Each test runs in a rolled-back transaction, so rows that change data leave nothing behind.
Finish up
Mark complete & continue
Next: Mini project: ShopLite roles and ownership