Reviewing AI-Written Spring Code for Security: Four Questions for Every Diff
An agent writes a CSV export for Relay in two minutes. It compiles and works, and it has four holes: no owner check, glued SQL that returns all 50 tickets, a token in the log with a key in the config, and two e-mail columns nobody asked for. Find them with four questions and prove every fix.
What you will learn
- Review a diff with four questions: access, parameters, secrets, output
- Prove a missing owner check and a SQL injection with real requests
- Fix glued SQL with a typed parameter and a repository method
- Use an AI as a hostile second reviewer without handing it the decision
Before you start
- Method Security in Spring: @PreAuthorize and Ownership
- Spring Data Query Methods
We asked an AI agent for one feature: a signed CSV export of tickets by status, for logged-in users only. Two minutes later it's done. It compiles, it runs, and Liam (an agent) gets his file:
HTTP/1.1 200
Content-Type: text/csv
X-Export-Signature: ...
id,subject,status,priority,customer_email,agent_email
3,How do I export my data to CSV?,OPEN,MEDIUM,olivia.bennett@example.com,
5,App crashes when I upload a photo,OPEN,HIGH,james.walker@example.com,sophia.reed@relay.example
7,How do I add a team member?,OPEN,HIGH,olivia.bennett@example.com,
...
Twenty open tickets. It all looks right, and that's exactly when a review pays off. Here's the agent's controller and the heart of its service:
@GetMapping("/api/tickets/export")
public ResponseEntity<String> export(@RequestParam String status,
@RequestHeader("Authorization") String auth)
throws GeneralSecurityException {
log.info("Export {} requested, Authorization: {}", status, auth);
String csv = export.csv(status);
return ResponseEntity.ok()
.header("Content-Type", "text/csv")
.header("X-Export-Signature", export.sign(csv))
.body(csv);
}
public String csv(String status) {
String sql = "select t.id, t.subject, t.status, t.priority, "
+ "c.email as customer_email, a.email as agent_email "
+ "from ticket t join customer c on c.id = t.customer_id "
+ "left join agent a on a.id = t.assignee_id "
+ "where t.status = '" + status + "' order by t.id";
// ... each row becomes a CSV line
}
And two lines it added to application.yaml: relay.export.secret: relay-export-key-..., a signing key in plain text.
Four questions, asked of every diff
1. Access: nobody asks whose tickets these are
Olivia is a customer. Her token is valid, so the chain lets her in. She calls the same export:
id,subject,status,priority,customer_email,agent_email
3,How do I export my data to CSV?,OPEN,MEDIUM,olivia.bennett@example.com,
5,App crashes when I upload a photo,OPEN,HIGH,james.walker@example.com,sophia.reed@relay.example
7,How do I add a team member?,OPEN,HIGH,olivia.bennett@example.com,
8,Email notifications arrive late,OPEN,LOW,noah.carter@example.com,
...
Twenty rows from five different customers. Noah's tickets are in her file. The controller never asks who is calling. "Logged-in users only" was in the prompt, and the agent did exactly that, nothing more. It never learned that customers see only their own tickets, so we have to tell it.
2. Parameters: the status text becomes part of the SQL
Look at + status +. The user writes part of our query. Olivia sends status=OPEN' or '1'='1 (URL-encoded):
curl -i "http://localhost:8080/api/tickets/export?status=OPEN%27%20or%20%271%27=%271" -H "Authorization: Bearer <Olivia's accessToken>"
200, and 50 tickets of every status. The where clause became "status is OPEN, or one equals one", which is always true. That's SQL injection, and it's the oldest hole in the book.
3. Secrets: a token in the log, a key in the file
The agent helpfully logs the whole Authorization header:
INFO ExportController : Export OPEN requested, Authorization: Bearer eyJ...
The real line carries Olivia's full token. Anyone who can read the logs can now act as Olivia until it expires. And the signing key sits in application.yaml, so anyone with the repository can sign fake exports.
4. Output: the whole row goes out
The select asks for c.email as customer_email, a.email as agent_email. Every line of the file carries two e-mail addresses that nobody asked for. Send only what the caller needs.
The fixes
The controller takes a typed Status and the Authentication the chain made, logs only the name, and decides the owner:
@GetMapping("/api/tickets/export")
public ResponseEntity<String> export(@RequestParam Status status,
Authentication login) throws GeneralSecurityException {
log.info("Export {} requested by {}", status, login.getName());
boolean customer = login.getAuthorities().stream()
.anyMatch(a -> a.getAuthority().equals("ROLE_CUSTOMER"));
String csv = export.csv(status, customer ? login.getName() : null);
return ResponseEntity.ok()
.header("Content-Type", "text/csv")
.header("X-Export-Signature", export.sign(csv))
.body(csv);
}
The service uses two repository methods (no glued text) and a small record:
List<Ticket> findByStatusOrderById(Status status);
List<Ticket> findByStatusAndCustomerEmailOrderById(Status status, String email);
public String csv(Status status, String owner) {
List<Ticket> found = owner == null
? tickets.findByStatusOrderById(status)
: tickets.findByStatusAndCustomerEmailOrderById(status, owner);
StringBuilder csv = new StringBuilder("id,subject,status,priority\n");
for (Ticket t : found) {
csv.append(ExportRow.of(t).line());
}
return csv.toString();
}
public record ExportRow(Long id, String subject,
Status status, Priority priority) {
static ExportRow of(Ticket t) {
return new ExportRow(t.getId(), t.getSubject(), t.getStatus(), t.getPriority());
}
String line() {
return id + "," + subject + "," + status + "," + priority + "\n";
}
}
And the key comes from the environment: relay.export.secret: ${EXPORT_SECRET}.
Prove every fix
A fix you haven't proven is a guess. Run the same requests again:
Olivia OPEN -> 200, 6 tickets, all hers (columns: id,subject,status,priority)
Noah OPEN -> 200, 6 tickets, none of them Olivia's
Liam OPEN -> 200, 20 tickets (staff see all)
Olivia status=OPEN' or '1'='1 -> 400 Failed to convert 'status' with value: 'OPEN' or '1'='1'
no token -> 401
The injection now dies before any SQL exists: Spring can't turn that text into a Status enum, so it's a 400. The log line is Export OPEN requested by [email protected]. A name, never a token.
Let the AI attack its own work
A useful second pass: give the diff back to an AI with a prompt that makes it a hostile auditor, walking the same four questions and answering pass or fail for each. It's fast at spotting glued SQL, a missing owner check, secrets and fields that shouldn't go out. But it doesn't know your business rules. You decide who should see which tickets, and you run the proving requests again yourself.
Common mistakes
- "The tests pass" as a review. The agent's tests check what it built, not what it forgot.
Stringparameters for fixed values. A typed enum rejects anything else for free.- Logging headers "for debugging". Log the user name and the action. Never a token.
- Accepting a fix without the request that proves it.
Try it yourself
In the finished project, the last line of ExportService is a commented // BREAK IT: query with the glued where t.status = '" + status + "'. Put it back, run the injection call, count the rows, and undo it. Which of the four questions would have caught it?
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
A Registration Form With Bean Validation in Spring Boot: @Valid, BindingResult and th:errors
A RegisterForm record with three annotations checks the name, email and password at the door. Bad data goes back to the form with a message under each field; good data becomes an Account row. And the password is still stored as plain text, which the next step fixes.
Spring Security 7 Form Login, BCrypt and a UserDetailsService on the Account Table
A guard at the gate and a hash in the table. A SecurityFilterChain lists the open pages and sends everything else to /login, a BCrypt PasswordEncoder bean hashes every password, and a UserDetailsService answers 'who is this email?' from the ACCOUNT table.
Roles and Authorities at Login in Spring Security: From a ROLE Column to hasRole("ADMIN")
Until now every login got .roles("USER") typed into the code. A Role enum on Account, one changed line in the UserDetailsService and one hasRole rule let Chaand open /admin while Emma gets a 403 and a visitor is sent to log in.
Menus per Role With Thymeleaf Security Tags: sec:authorize, sec:authentication and an Edit Button for the Author
One header file, three menus: a visitor sees Register and Login, Emma sees her email and Logout, Chaand also gets Admin. Then each post knows its author through @ManyToOne, and the Edit button shows only for the author or an admin.
