JAVA-290 · Lesson 9 of 12 · 36 min
Security review
▶ Video coming soon A video version of this lesson is on the way.
On Thursday, July 27, 2028, the first evening of sprint 5, Leif Quarmby ran a security review of the website in the back room, with the team, Ingrid and, for the first hour, Odile. Leif had insisted on it in May as a condition of running the site, and the team had planned for it: the review came after the features were complete, so there was something real to review, and before the release, so there was a whole sprint to fix what it found. A review the week before launch finds problems nobody has time to fix; a review in the first week finds nothing because nothing exists yet.
Noemi brought the checklist from her web security and accessibility course, and Hamza brought the findings of the booking API's own review in March, when Leif had found a database password in Git and walked through the OWASP API Security Top 10 with a printout. The website was different in one important way: the API had been used by one program, the counter app, while the website would be used by anyone on the internet, through a browser, with forms, cookies and pages that display what other people typed.
Defensive, scoped and written down
A security review in this sense is a defensive activity: the people who build and run the system examine its design, code and configuration to find weaknesses before anyone else does, and fix them. Everything the team tried was done on staging, which held only generated data, or on a developer's laptop, with Odile's written permission as the system's owner. Leif's first slide set out the scope: the site adapter, the new use cases, the staff sign-in, the new tables, the Caddy configuration for the new host name, and the pipeline changes. The booking API's REST endpoints, reviewed in March, were out of scope except where the website changed them.
The review had three parts. First a threat model: what is worth protecting, who might attack it, and where. Then a walk through the OWASP Top 10, 2025 edition, the list Noemi's course had used, asking for each category how the website stood. Then hands-on checks on staging. Each finding got a severity, an owner and a date, and nothing was closed until someone other than the person who fixed it had checked the fix.
The threat model
Leif started with a data flow diagram: the customer's browser, Caddy, the booking service with its site and REST adapters, PostgreSQL, the SMS provider and the staff's browsers, joined by arrows showing which data moves where. Dashed lines marked the trust boundaries, the places where data crosses from something the shop does not control into something it does. Every arrow that crosses a boundary is a place where an attacker can send whatever they like, so that is where the threat model looks first.
For each crossing, the team went through STRIDE, a mnemonic that Loren Kohnfelder and Praerit Garg introduced at Microsoft in 1999 for the kinds of threat to consider: Spoofing someone's identity, Tampering with data, Repudiation of an action, Information disclosure, Denial of service and Elevation of privilege. The mnemonic's value is that it makes a group consider threats it would not think of naturally. Nobody in the room had thought about repudiation until Odile asked how the shop would know who had marked a customer as a no-show if the customer complained.
| No. | Crossing | Threat (STRIDE) | Existing defense | Gap? |
|---|---|---|---|---|
| 1 | Browser to my-booking | Information disclosure: guessing references to see bookings | Reference and phone both required; uniform answer | No limit on attempts |
| 2 | Browser to waiting list | Denial of service and abuse: adding other people's numbers so the shop texts them | One entry per phone per day | No proof the phone belongs to the person |
| 3 | Browser to booking form | Tampering: script in a note shown on the staff page | Thymeleaf escapes th:text | Check every template |
| 4 | Staff browser to /staff | Spoofing and elevation: guessing a staff password; a counter user reaching manager pages | Form login, roles | Password rules, lockout, role checks per route |
| 5 | Outbox to SMS provider | Information disclosure: phone numbers and names in logs | Redaction from the API course | New log lines unchecked |
| 6 | Staff actions | Repudiation: who marked a no-show | None | No record of which staff user changed a booking |
Threat 2 was the one nobody had seen. The waiting list sends a text when a start frees up, to whatever phone number someone typed when joining. A person with a grudge, or a bored teenager, could add a stranger's number to every day's waiting list and make the shop text them repeatedly. That is harassment of the stranger, a cost to the shop, which pays for each text, and a risk to the shop's sending number, which carriers block if people report it as spam. It is a design flaw, not a coding bug, which is why OWASP gives insecure design a category of its own.
The OWASP Top 10, category by category
With the threats listed, the team walked through the ten categories. For most of them the existing design already had an answer, and the point of the walk was to confirm that the answer was real, with a test or a configuration line to point to, rather than assumed. Where there was no answer, the category produced a finding.
| Category (2025) | How the website stands | Finding |
|---|---|---|
| A01 Broken Access Control | /staff requires a role; my-booking needs reference and phone; booking IDs never in URLs | Manager-only figures page reachable by COUNTER role |
| A02 Security Misconfiguration | Actuator only on the management port | Spring's default error page showed an exception class; no content security policy |
| A03 Software Supply Chain Failures | Dependabot; image digest checked at deploy | Image scanning, a finding from May, still not added |
| A04 Cryptographic Failures | TLS by Caddy; staff passwords hashed | Confirm the hash algorithm and its settings |
| A05 Injection | JPA parameters; Thymeleaf escaping | One template used th:utext for the footer |
| A06 Insecure Design | Uniform lookup answers | Threats 1 and 2 |
| A07 Authentication Failures | Form login, sessions, CSRF tokens | No lockout; 8-character minimum password |
| A08 Software or Data Integrity Failures | Images built by the pipeline, digests recorded | None |
| A09 Security Logging and Alerting Failures | Structured logs, Grafana alerts | Failed staff logins not logged or alerted; threats 5 and 6 |
| A10 Mishandling of Exceptional Conditions | Use cases return results, not exceptions, for expected refusals | The outbox job stopped entirely on one malformed row |
The A10 finding was a good example of a category that did not exist in older lists. The 2025 edition added Mishandling of Exceptional Conditions for systems that fail in unsafe ways when something unexpected happens. Thierry had found, in testing the outbox, that a row with an empty phone number, which only a bug could create, made the sending job throw an exception and stop, so every later reminder waited behind it. The fix was to mark that row as failed with its reason, raise an alert and carry on with the others: a system should fail one item safely, not the whole job.
Staff passwords
The staff sign-in was the only place the website held passwords, and the review checked it closely. Passwords are stored as the output of a password hashing function, designed to be slow and to use a random salt per password, so that a stolen table of hashes is expensive to attack and identical passwords produce different hashes. OWASP's password storage guidance prefers Argon2id, and accepts PBKDF2 with HMAC-SHA256 and at least 600,000 iterations where Argon2 is not available. Spring Security supports both through its password encoders; the team used its delegating encoder, which writes the algorithm's name in front of each hash so that the algorithm can be changed later without breaking existing accounts.
The example shows what PBKDF2 does, with the JDK's own implementation. It uses a fixed salt so that its output is the same every time; in real use the salt comes from SecureRandom for each password and is stored beside the hash. It also shows how a stored hash is checked: by hashing the typed password with the stored salt and iteration count and comparing the results in constant time, so that the time taken does not reveal how many bytes matched.
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.MessageDigest;
import java.util.*;
public class Main {
static final int ITERATIONS = 600_000;
static byte[] pbkdf2(char[] password, byte[] salt, int iterations) throws Exception {
PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, 256);
try {
return SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).getEncoded();
} finally {
spec.clearPassword();
}
}
static String encode(char[] password, byte[] salt) throws Exception {
Base64.Encoder b64 = Base64.getEncoder().withoutPadding();
return "pbkdf2-sha256$" + ITERATIONS + "$" + b64.encodeToString(salt) + "$" + b64.encodeToString(pbkdf2(password, salt, ITERATIONS));
}
static boolean matches(char[] typed, String stored) throws Exception {
String[] p = stored.split("\\$");
byte[] salt = Base64.getDecoder().decode(p[2]);
byte[] expected = Base64.getDecoder().decode(p[3]);
byte[] actual = pbkdf2(typed, salt, Integer.parseInt(p[1]));
return MessageDigest.isEqual(expected, actual); // constant-time comparison
}
public static void main(String[] args) throws Exception {
byte[] demoSalt = "demo-salt-only!!".getBytes(); // fixed for the example; use SecureRandom in real code
String stored = encode("correct horse battery staple".toCharArray(), demoSalt);
System.out.println("stored: " + stored);
System.out.println("right password: " + matches("correct horse battery staple".toCharArray(), stored));
System.out.println("wrong password: " + matches("correct horse battery stapler".toCharArray(), stored));
byte[] otherSalt = "another-salt-16!".getBytes();
String sameWordOtherSalt = encode("correct horse battery staple".toCharArray(), otherSalt);
System.out.println("same password, other salt, same hash? " + stored.equals(sameWordOtherSalt));
}
}stored: pbkdf2-sha256$600000$ZGVtby1zYWx0LW9ubHkhIQ$7t7J+36jBFkbke1df2Eu5JZh19iZlKegeI4Mpxj+IM0 right password: true wrong password: false same password, other salt, same hash? false
What this code does
PBEKeySpec takes the password as a char array, which can be cleared after use, unlike a String, and the finally block clears it. The stored form records the algorithm, the iteration count, the salt and the hash, so a future change of settings can still check old hashes, and matches compares with MessageDigest.isEqual, which takes the same time whether the first byte or the last one differs. The last line shows why salts matter: the same password with a different salt gives an unrelated hash, so equal passwords cannot be spotted in a stolen table.
Running the example takes a noticeable fraction of a second, and that is the point: 600,000 iterations cost a defender a moment at each sign-in and cost an attacker the same for every guess. The review's password findings were about policy, not storage. The minimum length was raised from 8 to 15 characters, in line with the 2025 revision of NIST's digital identity guidelines for accounts where the password is the only factor, with no rules about mixing character types, which mainly produce predictable substitutions. New passwords are checked against a list of commonly used and breached passwords that ships with the application. And repeated failures now lock the account for fifteen minutes after five attempts, with an alert to Leif after twenty failures in an hour across all accounts, which would suggest someone trying many accounts at once.
@Bean
SecurityFilterChain site(HttpSecurity http) throws Exception {
http.securityMatcher("/**")
.authorizeHttpRequests(a -> a
.requestMatchers("/", "/book", "/booked/*", "/my-booking/**", "/waitlist/**", "/css/**", "/error").permitAll()
.requestMatchers("/staff/figures/**").hasRole("MANAGER")
.requestMatchers("/staff/**").hasAnyRole("COUNTER", "MECHANIC", "MANAGER")
.anyRequest().denyAll())
.formLogin(f -> f.loginPage("/staff/login").defaultSuccessUrl("/staff/today").permitAll())
.logout(l -> l.logoutUrl("/staff/logout").logoutSuccessUrl("/"))
.sessionManagement(s -> s.sessionFixation(fix -> fix.newSession()))
.headers(h -> h
.contentSecurityPolicy(c -> c.policyDirectives(
"default-src 'self'; img-src 'self'; style-src 'self'; script-src 'self'; frame-ancestors 'none'; form-action 'self'"))
.referrerPolicy(r -> r.policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.SAME_ORIGIN)));
return http.build();
}What this code does
The rules are read in order, so the manager-only figures route comes before the general staff rule, which fixed the A01 finding, and anything not listed is denied rather than allowed. CSRF protection is on by default and Thymeleaf adds the token to every form, so it needs no line here. The content security policy allows scripts, styles and images only from the site itself, which means an injected script tag would not run even if escaping failed somewhere.
Limiting attempts
Threat 1 had a partial defense already: a booking reference has about a trillion possible values and is useless without the phone number. But a lookup page with no limit on attempts invites someone to try, and every attempt costs the server a database query. The fix was a rate limiter with two keys, the client's address and the reference being looked up, so that one person cannot make many attempts and many people cannot attack one reference. The team used the token bucket algorithm: each key has a bucket that holds a few tokens and refills slowly, each attempt takes a token, and an attempt with no token left is refused with the same page and a polite message to wait.
import java.time.*;
import java.util.*;
public class Main {
static class TokenBucket {
private final int capacity; private final Duration refillEvery;
private final Map<String, double[]> state = new HashMap<>(); // key -> {tokens, lastSeconds}
TokenBucket(int capacity, Duration refillEvery) { this.capacity = capacity; this.refillEvery = refillEvery; }
boolean tryTake(String key, Instant now) {
double t = now.getEpochSecond();
double[] s = state.computeIfAbsent(key, k -> new double[] {capacity, t});
s[0] = Math.min(capacity, s[0] + (t - s[1]) / refillEvery.toSeconds());
s[1] = t;
if (s[0] < 1) return false;
s[0] -= 1;
return true;
}
}
public static void main(String[] args) {
TokenBucket perAddress = new TokenBucket(5, Duration.ofMinutes(3)); // 5 at once, then one per 3 minutes
TokenBucket perReference = new TokenBucket(10, Duration.ofHours(2));
Instant t0 = Instant.parse("2028-07-28T14:00:00Z");
StringBuilder line = new StringBuilder();
for (int i = 0; i < 8; i++) {
Instant at = t0.plusSeconds(i * 5);
boolean ok = perAddress.tryTake("203.0.113.7", at) && perReference.tryTake("K7QF-29XM", at);
line.append(ok ? "ok " : "WAIT ");
}
System.out.println("8 tries in 40 s from one address: " + line.toString().trim());
System.out.println("3 minutes later: " + (perAddress.tryTake("203.0.113.7", t0.plusSeconds(35 + 180)) ? "ok" : "WAIT"));
int refused = 0;
for (int i = 0; i < 12; i++) {
String address = "198.51.100." + (10 + i);
if (!(perAddress.tryTake(address, t0) && perReference.tryTake("P3WD-8HKT", t0))) refused++;
}
System.out.println("12 addresses trying one reference: " + refused + " refused");
}
}8 tries in 40 s from one address: ok ok ok ok ok WAIT WAIT WAIT 3 minutes later: ok 12 addresses trying one reference: 2 refused
What this code does
Each bucket stores, per key, its current tokens and when it was last used; on every attempt it first adds the tokens earned since then, up to the capacity, so refilling needs no timer. An attempt must pass both buckets, the one for the address and the one for the reference, which is why the run from twelve different addresses is still stopped after ten tries at the same reference. The addresses come from the ranges reserved for documentation, and the clock is passed in, so the run never depends on the real time.
The real limiter lives in a servlet filter in front of the my-booking and waiting-list routes and keeps its buckets in memory, which is enough for a single server; if the shop ever ran several copies, the buckets would need a shared store. Leif checked one detail that is easy to get wrong behind a proxy: the client's address must come from the X-Forwarded-For header that Caddy sets, and only because the application is configured to trust Caddy alone, or anyone could send that header themselves and get a fresh bucket for every request.
Threat 2 needed a design change, not a limiter, because the harm was done by a single text to the wrong person. Joining the waiting list now sends one text to the number given, with a short link to confirm, and the entry is not active until the link is followed; unconfirmed entries vanish after thirty minutes. A number can be added at most three times a week, and the confirmation text says plainly who sent it and how to stop further texts. The cost is one extra step for real customers, which Odile accepted once she understood that the alternative was the shop's number being used to harass people.
Output encoding and the one th:utext
Threat 3 was cross-site scripting: text typed by one person, such as a booking note, displayed on a page that another person, a staff member, views, in a way that lets the browser treat it as code. The defense is output encoding, replacing the characters that have meaning in HTML when the text is inserted into the page, and the rule from lesson 7 was that th:text does this automatically. The review searched every template for the places that do not escape, and found one: Noemi had used th:utext in the shared footer to insert the shop's address with a line break in it. The footer's text came from configuration, not from customers, so it was not exploitable, but Leif asked for it to be changed anyway, because the next person to copy that line might not check where the text came from.
import java.util.*;
public class Main {
static String esc(String s) {
return s.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """).replace("'", "'");
}
public static void main(String[] args) {
String note = "Brakes squeal <img src=x onerror=\"alert(document.cookie)\">";
String unsafe = "<td>" + note + "</td>";
String safe = "<td>" + esc(note) + "</td>";
System.out.println("inserted as is: " + unsafe);
System.out.println("escaped: " + safe);
System.out.println("browser sees an img element in the first? " + unsafe.contains("<img"));
System.out.println("browser sees an img element in the second? " + safe.contains("<img"));
String name = "Dana\" autofocus onfocus=\"alert(1)";
System.out.println("attribute, escaped: <input value=\"" + esc(name) + "\">");
}
}inserted as is: <td>Brakes squeal <img src=x onerror="alert(document.cookie)"></td> escaped: <td>Brakes squeal <img src=x onerror="alert(document.cookie)"></td> browser sees an img element in the first? true browser sees an img element in the second? false attribute, escaped: <input value="Dana" autofocus onfocus="alert(1)">
What this code does
The note is the classic test input: an image tag whose error handler would run script in the staff member's browser if the note were inserted unchanged. After escaping, the angle brackets and quotes are character references, so the browser shows the note as text and creates no element. The last line shows the same encoding protecting a value inside a quoted attribute, where an unescaped quote would let the text break out and add attributes of its own.
The example's input is the kind of string that Noemi added to the browser tests: a booking made with that note, then the staff page opened and checked for an img element. It is a test of the defense, run on a developer's laptop and on staging, never on production. With the content security policy from the configuration above, a second layer stands behind the first: even if a template somewhere failed to escape, the browser would refuse to run the inline handler.
Headers, cookies and errors
The hands-on part of the review started with the response headers of every page, fetched from staging with curl. Security headers tell the browser to apply protections that it would not otherwise apply, and session cookie flags decide when the browser sends the cookie. Thierry turned the review's checklist into a test that runs against staging after every deployment, so that a configuration change could not quietly remove one.
import java.util.*;
public class Main {
record Rule(String header, String mustContain, String why) {}
static final List<Rule> RULES = List.of(
new Rule("Strict-Transport-Security", "max-age=", "browsers keep using HTTPS"),
new Rule("Content-Security-Policy", "default-src 'self'", "injected scripts do not run"),
new Rule("Content-Security-Policy", "frame-ancestors 'none'", "pages cannot be framed by other sites"),
new Rule("X-Content-Type-Options", "nosniff", "files are not reinterpreted as scripts"),
new Rule("Referrer-Policy", "same-origin", "page addresses are not sent to other sites"));
static List<String> check(Map<String, String> headers) {
List<String> out = new ArrayList<>();
Map<String, String> h = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
h.putAll(headers);
for (Rule r : RULES) {
String v = h.get(r.header());
if (v == null || !v.contains(r.mustContain())) out.add(r.header() + " should contain " + r.mustContain() + " so that " + r.why());
}
String cookie = h.getOrDefault("Set-Cookie", "");
if (!cookie.isEmpty())
for (String flag : List.of("Secure", "HttpOnly", "SameSite=Lax"))
if (!cookie.contains(flag)) out.add("session cookie lacks " + flag);
if (h.containsKey("Server") && h.get("Server").matches(".*\\d.*")) out.add("Server header reveals a version: " + h.get("Server"));
return out;
}
public static void main(String[] args) {
Map<String, String> before = Map.of(
"Strict-Transport-Security", "max-age=31536000",
"X-Content-Type-Options", "nosniff",
"Set-Cookie", "JSESSIONID=8F2C...; Path=/; HttpOnly",
"Server", "Caddy");
Map<String, String> after = Map.of(
"strict-transport-security", "max-age=31536000",
"content-security-policy", "default-src 'self'; img-src 'self'; style-src 'self'; script-src 'self'; frame-ancestors 'none'; form-action 'self'",
"x-content-type-options", "nosniff",
"referrer-policy", "same-origin",
"set-cookie", "JSESSIONID=1D9A...; Path=/; Secure; HttpOnly; SameSite=Lax");
System.out.println("staff login page on July 27:");
check(before).forEach(p -> System.out.println(" - " + p));
System.out.println("after the fixes: " + (check(after).isEmpty() ? "all checks pass" : check(after)));
}
}staff login page on July 27: - Content-Security-Policy should contain default-src 'self' so that injected scripts do not run - Content-Security-Policy should contain frame-ancestors 'none' so that pages cannot be framed by other sites - Referrer-Policy should contain same-origin so that page addresses are not sent to other sites - session cookie lacks Secure - session cookie lacks SameSite=Lax after the fixes: all checks pass
What this code does
Header names are case-insensitive in HTTP, so the check copies them into a TreeMap with a case-insensitive order before looking them up, which is why the second response with lower-case names still passes. Each rule says why it matters, so a failure message explains itself to whoever reads the deployment log. The missing Secure flag on the cookie was the review's most surprising find: behind Caddy, the application saw plain HTTP from the proxy and did not mark the cookie secure until it was told to trust the forwarded protocol header.
The last hands-on check was to make the application fail. Leif requested a page with a malformed date in its query string, then stopped the staging database for a minute and loaded the free-times page. The first showed Spring's default error page with the name of the exception class; the second showed the same page with a status of 500. Neither leaked anything serious, but both told an attacker which framework the site used and how it failed. The fix was a plain error template, with the shop's phone number and no technical detail, and a log entry, with the detail, for Leif.
Logs without personal data
Threat 5 was an old friend. In March, Tamsin had found customers' phone numbers in the booking API's logs, and Hamza had added redaction to the logging configuration. The website's new log lines, in the outbox job and the waiting list, had been written since, and Thierry checked them with the same redaction rules applied to a sample of staging's logs, which contained only generated numbers. Two new lines logged a full phone number, both in error messages for failed texts. Redaction keeps the last two digits, which is enough for a person matching a complaint to a log line and not enough to identify anyone.
import java.util.*;
import java.util.regex.*;
public class Main {
static final Pattern PHONE = Pattern.compile("(\\+?1[\\s.-]?)?\\(?\\d{3}\\)?[\\s.-]?\\d{3}[\\s.-]?\\d{2}(\\d{2})\\b");
static String redact(String line) {
return PHONE.matcher(line).replaceAll(m -> "***-***-**" + m.group(2));
}
public static void main(String[] args) {
List<String> lines = List.of(
"outbox: send failed for +19055550142 (attempt 3): provider timeout",
"waitlist: confirmation sent to (905) 555-0163 for 2028-07-29",
"booking 2311 created, source WEB, kind GEARS",
"staff login failed for user kofi from 203.0.113.7",
"customer typed 905.555.0188 in the note field");
for (String l : lines) System.out.println(redact(l));
}
}outbox: send failed for ***-***-**42 (attempt 3): provider timeout waitlist: confirmation sent to ***-***-**63 for 2028-07-29 booking 2311 created, source WEB, kind GEARS staff login failed for user kofi from 203.0.113.7 customer typed ***-***-**88 in the note field
What this code does
The pattern accepts the formats phone numbers appear in, with or without the country code, brackets, spaces, dots or hyphens, and captures the last two digits separately. replaceAll with a function builds each replacement from the match, keeping those two digits and masking the rest. Lines without a phone number, such as the booking number and the staff login failure with its documentation address, pass through unchanged, because a redaction rule that also hid booking numbers would make the logs useless.
Threat 6 got the simplest fix of the evening: every staff action that changes a booking now writes a row to a small audit table with the staff username, the action and the time, through a new migration, V11, in the same transaction as the change. Odile's question about who marked a no-show could now be answered, and the table was added to the retention job, keeping entries for a year.
Findings and follow-up
| ID | Finding | Severity | Owner | Status on Aug 9 |
|---|---|---|---|---|
| S1 | Waiting list can be used to text any phone number | High | Hamza | Fixed: confirmation link; three adds per number per week |
| S2 | No limit on booking lookups | Medium | Thierry | Fixed: token buckets per address and per reference |
| S3 | Session cookie not Secure behind Caddy | Medium | Hamza | Fixed: forwarded headers trusted from Caddy only |
| S4 | No content security policy | Medium | Noemi | Fixed: policy in the config; inline styles moved to the style sheet |
| S5 | COUNTER role can open the manager figures page | Medium | Hamza | Fixed: rule order; test added |
| S6 | Staff password minimum 8, no lockout, failed logins not logged | Medium | Thierry | Fixed: 15 characters, breached list, lockout, alert |
| S7 | Default error page reveals the framework | Low | Noemi | Fixed: plain error template |
| S8 | Two log lines contain full phone numbers | Low | Thierry | Fixed: redaction rule extended; test on log output |
| S9 | No record of staff changes to bookings | Low | Thierry | Fixed: audit table V11 |
| S10 | th:utext in the footer | Low | Noemi | Fixed: th:text with a line-break fragment |
| S11 | Outbox job stops on one malformed row | Low | Thierry | Fixed: row marked failed, alert, job continues |
| S12 | Container images not scanned for known vulnerabilities | Low | Leif | Fixed: scan job in the release workflow |
Twelve findings sounds like a lot, and Hamza was briefly discouraged. Leif's view was the opposite: a review that finds nothing usually means the reviewers did not look, and none of these findings had reached a real customer. Each fix came with a test that would fail if the problem returned, and each was re-checked by someone other than its owner before the status changed to fixed. The image scanning finding, S12, had been on Leif's own list since the deployment course's review in May, and he fixed it himself in the same sprint, which the team found encouraging.
Exercises
Try it yourself
Mask phone numbers in logs
Complete redact so that every ten-digit phone number written as 555-555-0142, (555) 555-0142 or 555.555.0142 is replaced by ***-***-** followed by its last two digits. Other numbers, such as booking IDs, must be left alone.
import java.util.*;
import java.util.regex.*;
public class Main {
static String redact(String line) {
return line;
}
public static void main(String[] args) {
for (String l : List.of("sent to 555-555-0142", "confirm (555) 555-0163 for 2028-07-29",
"booking 2311 for 555.555.0188", "nothing personal here, booking 2312"))
System.out.println(redact(l));
}
}Try it yourself
Check the session cookie
Complete missing so that it returns, in the order Secure, HttpOnly, SameSite, the flags a Set-Cookie value lacks. A SameSite flag counts only if it is SameSite=Lax or SameSite=Strict. Flag names are case-insensitive.
import java.util.*;
public class Main {
static List<String> missing(String setCookie) {
return List.of();
}
public static void main(String[] args) {
for (String c : List.of("JSESSIONID=1D9A; Path=/; Secure; HttpOnly; SameSite=Lax",
"JSESSIONID=8F2C; Path=/; HttpOnly",
"JSESSIONID=77AB; Path=/; secure; httponly; SameSite=None",
"JSESSIONID=3C1E; Path=/; Secure; HttpOnly; samesite=strict"))
System.out.println(c.substring(0, 15) + " missing " + missing(c));
}
}Common mistakes
MistakeReviewing security the week before launch.
InsteadReview once the features exist and leave a sprint to fix the findings.
MistakeLooking only for coding bugs.
InsteadModel threats at each trust boundary, including design flaws such as a feature that texts any number.
MistakeStoring passwords with a fast hash or no salt.
InsteadUse Argon2id or PBKDF2 with a random salt and a high work factor, through the framework's encoder.
MistakeLeaving lookup pages without limits.
InsteadRate-limit by client and by the thing being looked up, and read the client address only from a trusted proxy.
MistakeUsing unescaped output because the text seems safe.
InsteadEscape everything by default, keep a content security policy as a second layer, and test with hostile input.
MistakeClosing a finding when its owner says it is fixed.
InsteadAdd a test that fails if it returns and have someone else check the fix.
Summary and key terms
- Leif's security review on July 27 came after the features were complete and before the release, was defensive and limited to staging with generated data, and had three parts: a threat model, a walk through the OWASP Top 10, 2025 edition, and hands-on checks.
- The data flow diagram marked trust boundaries, and STRIDE at each crossing found six threats, including a design flaw that let anyone make the shop text any phone number from the waiting list and a missing record of staff actions.
- Staff passwords are hashed with a slow, salted function compared in constant time; the policy became 15 characters, a breached-password list, lockout and alerts.
- Lookups are limited by token buckets per address and per reference, with the address read only from the trusted proxy.
- Joining the waiting list now needs a confirmation link.
- Escaping by default, a content security policy and tests with hostile input defend against cross-site scripting.
- Headers, cookie flags and error pages are checked after every deployment, logs redact phone numbers, and an audit table records staff changes.
- All twelve findings were fixed, tested and re-checked by someone other than their owner.
- Security review
- A defensive examination of a system's design, code and configuration by the people who build and run it.
- Threat model
- A structured description of what to protect, from whom and where it can be attacked.
- Trust boundary
- A line where data passes from something not controlled into something controlled.
- STRIDE
- Spoofing, tampering, repudiation, information disclosure, denial of service and elevation of privilege.
- Insecure design
- A weakness in what the system is designed to do, rather than in how it was coded.
- Salt
- Random data stored with a password hash so equal passwords give different hashes.
- Constant-time comparison
- Comparing secrets in a time that does not depend on where they differ.
- Token bucket
- A rate-limiting algorithm in which each attempt takes a token from a slowly refilling bucket.
- Content security policy
- A response header telling the browser which sources of scripts, styles and other content to allow.
- Output encoding
- Replacing characters that have meaning in the output context so data is shown as text.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Why was the review held at the start of sprint 5 rather than just before launch?
Show answer
The features were complete enough to review and there was a whole sprint left to fix the findings.
Why was the waiting-list threat a design flaw rather than a bug?
Show answer
The code did what it was designed to do; the design itself let anyone make the shop text any number.
Why does the stored password record include the algorithm, iterations and salt?
Show answer
So the hash can be checked later and the settings can change without breaking old accounts.
Why must the client address come from the proxy's header only when the proxy is trusted?
Show answer
Otherwise anyone could send the header themselves and get a new rate-limit bucket for every request.
What two layers protect the staff page from a script in a booking note?
Show answer
Escaping when the note is inserted, and a content security policy that refuses inline scripts.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.