Practice: security code review
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.
Three questions find most security bugs in a Spring API: what goes out, who may touch it, and what gets written down. This page practises each one on small programs, then ranks the findings.
Review step 1: what goes out
Step 1 asks what leaves the server. The code compares returning every field of an entity with an allow-list.
Example 1 · Step 1 in code: an allow-list instead of every field
import java.util.LinkedHashMap;import java.util.List;import java.util.Map;
public class AllowListDemo { // What the entity holds static Map<String, Object> userRow() { Map<String, Object> row = new LinkedHashMap<>(); row.put("id", 2); row.put("email", "asha.rao@example.com"); row.put("passwordHash", "{bcrypt}$2a$10$tf367IbGb5L..."); row.put("enabled", true); row.put("failedLogins", 3); row.put("roles", List.of("CUSTOMER")); return row; }
// What the contract says GET /api/v1/me returns static final List<String> ALLOWED = List.of("id", "email", "roles");
static Map<String, Object> toResponse(Map<String, Object> row) { Map<String, Object> out = new LinkedHashMap<>(); for (String field : ALLOWED) { out.put(field, row.get(field)); } return out; }
public static void main(String[] args) { System.out.println("Entity as JSON: " + userRow().keySet()); System.out.println("DTO as JSON: " + toResponse(userRow()).keySet()); }}Entity as JSON: [id, email, passwordHash, enabled, failedLogins, roles] DTO as JSON: [id, email, roles]
What this code does
- Returning the entity sends every field, including the hash and internal counters.
- An allow-list (a DTO record in Spring) sends only the named fields; a new column never leaks by itself.
- In the review, compare each response with the contract field by field.
A security code review reads a change with one question per risk, instead of only "does it work?". Start with what leaves the server: every response body and every error. Ask:
- Does every controller return a response DTO, never an entity?
- Do request records hold only fields the client may set (no
role, nocustomerId)? - Does the catch-all error handler send a fixed sentence?
- Is there one login failure message for every cause?
Each red flag sends more than the caller should see: entities returned from controllers, records without an allow-list of fields, ex.getMessage() copied into an error, and different texts for "no such user" and "wrong password".
Review step 2: who may touch it
Step 2 asks who may touch an object. The same request runs before and after the owner check.
Example 2 · Step 2 in code: the same request before and after the owner check
import java.util.Map;
public class OwnerCheckReviewDemo { record Order(int id, int customerId, String status) { }
static final Map<Integer, Order> ORDERS = Map.of(14, new Order(14, 2, "SHIPPED"), 1, new Order(1, 1, "DELIVERED"));
static String before(int orderId, int callerCustomerId) { Order o = ORDERS.get(orderId); return o == null ? "404" : "200 " + o; }
static String after(int orderId, int callerCustomerId) { Order o = ORDERS.get(orderId); return o == null || o.customerId() != callerCustomerId ? "404" : "200 " + o; }
public static void main(String[] args) { System.out.println("Before, customer 1 asks for 14: " + before(14, 1)); System.out.println("After, customer 1 asks for 14: " + after(14, 1)); System.out.println("After, customer 1 asks for 1: " + after(1, 1)); }}Before, customer 1 asks for 14: 200 Order[id=14, customerId=2, status=SHIPPED] After, customer 1 asks for 14: 404 After, customer 1 asks for 1: 200 Order[id=1, customerId=1, status=DELIVERED]
What this code does
- The review question is simple: is
callerCustomerIdused? Inbeforeit is not. - After the fix a stranger gets the same 404 as for a missing order.
- The owner still gets their order, which proves the fix did not break the normal case.
Follow every id. For each endpoint that takes an id in the path, query or body, find the line that loads the object and the check that compares its owner with the caller from the token.
Check writes as carefully as reads: cancel, update and delete. Nested URLs such as /orders/{id}/items must check the parent. Login must have a limit on failed attempts.
Review step 3: what is written down
Step 3 asks what is written down. A scanner reads config and log lines and flags literal secrets.
Example 3 · Step 3 in code: scanning config and log lines for secrets
import java.util.List;import java.util.regex.Pattern;
public class WrittenDownReviewDemo { record Rule(String name, Pattern pattern) { }
static final List<Rule> RULES = List.of( new Rule("literal secret in config", Pattern.compile("(?i)(password|secret)\\s*=\\s*(?!\\$\\{)\\S+")), new Rule("token in a log", Pattern.compile("Bearer [A-Za-z0-9._-]{10,}")), new Rule("password in a log", Pattern.compile("password=(?!\\*\\*\\*|\\$\\{)[^,\\]\\s]+")));
public static void main(String[] args) { List<String> lines = List.of( "application.properties: spring.datasource.password=${DB_PASSWORD}", "application.properties: shoplite.jwt.secret=my-team-secret-2026", "app.log: LOGIN_FAILED email=a***@example.com ip=203.0.113.7", "app.log: headers=[Authorization:\"Bearer eyJhbGciOiJIUzI1NiJ9.e30.abc\"]", "app.log: Login attempt: LoginRequest[email=asha.rao@example.com, password=asha-dev-password]"); for (String line : lines) { for (Rule rule : RULES) { if (rule.pattern().matcher(line).find()) { System.out.println("FINDING (" + rule.name() + "): " + line.substring(0, line.indexOf(':'))); } } } }}FINDING (literal secret in config): application.properties FINDING (token in a log): app.log FINDING (literal secret in config): app.log FINDING (password in a log): app.log
What this code does
- A placeholder such as
${DB_PASSWORD}passes; a literal JWT secret does not. - The last log line matches two rules, because
password=asha-dev-passwordlooks like a config line too: scanners often report one problem twice. - Real tools such as gitleaks work the same way, with many more rules.
Read what the change writes to places other people can see: configuration files, Git and logs. A literal password in application.properties, a log.debug("{}", request) on a record with a password, or a request-logging filter with bodies are all findings.
Also open pom.xml: a newly pinned version of a Spring-managed library, or a library nobody has upgraded for years, is a finding too.
Ranking findings by risk
A risk score is impact (how bad if it is used, 1 to 3) multiplied by likelihood (how easy to find and use, 1 to 3). Fix the highest scores first, and never ship a 9.
Four findings, each with an impact and a likelihood, sorted by score.
Example 4 · Ranking findings by impact × likelihood
import java.util.Comparator;import java.util.List;
public class RiskRankingDemo { record Finding(String where, String what, int impact, int likelihood) { int score() { return impact * likelihood; } }
public static void main(String[] args) { List<Finding> findings = List.of( new Finding("LoginRequest", "toString prints the password", 2, 1), new Finding("OrderService.cancel", "no owner check: any customer cancels any order", 3, 3), new Finding("AuthService.login", "no limit on failed logins", 3, 2), new Finding("GlobalExceptionHandler", "500 detail shows SQL", 2, 2)); findings.stream() .sorted(Comparator.comparingInt(Finding::score).reversed()) .forEach(f -> System.out.println(f.score() + " " + f.where() + ": " + f.what())); }}9 OrderService.cancel: no owner check: any customer cancels any order 6 AuthService.login: no limit on failed logins 4 GlobalExceptionHandler: 500 detail shows SQL 2 LoginRequest: toString prints the password
What this code does
- The IDOR on cancel wins: anyone signed in can change data, and finding it takes one changed number.
- Ties and close scores still need judgement; the score only orders the discussion.
- Every finding names a place and a consequence, which makes the fix easy to check.
An IDOR on cancel (anyone signed in can change any order, found by changing one number) is impact 3 × likelihood 3 = 9. A toString() that would print a password only if someone adds a debug line scores lower.
Write each finding as: where, what can happen, the fix, the score.
Finish up
Mark complete & continue
Next: Mini project: ShopLite security review