Threat modeling and secure coding
What you will learn
A trust boundary separates data or code with different privileges. Threat modeling identifies what must be protected, who may act, where untrusted inputs cross a boundary, and which tests demonstrate that controls work. Start with a fictional tenant-owned document service.
- Map assets, trust boundaries and security invariants.
- Enforce resource-level authorization and finite resource/destination selection.
- Distinguish input validation, parameter binding and context-specific output encoding.
Plain Java 21: save each example as Main.java in a fresh directory, compile with javac --release 21 Main.java, then run java Main. Trusted local fixtures only. No network or third-party dependency is needed.
Check ownership and tenant
public class Main { record Actor(String tenant,String id,boolean reader) {} record Document(String tenant,String owner) {} static boolean canRead(Actor actor,Document document) { return actor != null && document != null && actor.reader() && actor.tenant()!=null && actor.id()!=null && actor.tenant().equals(document.tenant()) && actor.id().equals(document.owner()); } public static void main(String[] args) throws Exception { var doc=new Document("tenant-A","reader-1"); System.out.println(canRead(new Actor("tenant-A","reader-1",true),doc)); System.out.println(canRead(new Actor("tenant-B","reader-1",true),doc)); System.out.println(canRead(new Actor("tenant-A","reader-1",false),doc)); }}Expected output:
truefalsefalseA matching user ID in another tenant is insufficient. The model assumes the actor is already authenticated by trusted infrastructure.
Model the service
Assets: tenant documents, service credentials and audit records. Flow: authenticated caller → request validator → authorization decision → repository → response encoder. The server derives the actor from verified identity, not a request-body field. A user may read only their own document in their own tenant. Default deny if identity, ownership or permission is missing. Check every route, including downloads and background operations, and keep the decision near data access to avoid check/use races.
Keep data separate from commands
Use JDBC PreparedStatement with placeholders for values, e.g. SELECT title FROM documents WHERE tenant_id = ? AND owner_id = ? AND id = ?, then bind all three values with setString. The statement structure is fixed; identifiers or sort directions need a finite allowlist rather than placeholders. This snippet is source-reviewed, not a JDBC execution test. Validate lengths, types, ranges and business rules at ingress. Encode output for the actual HTML, attribute or JSON context using established framework encoders; input validation is not output encoding. Avoid untrusted Java deserialization; filters are defense in depth rather than a reason to accept arbitrary objects.
File and network boundaries
Use finite IDs mapped to server-owned resources, not caller-supplied filenames or URLs. Path.normalize is lexical, not symlink containment; for dynamic filesystem access use trusted directories, real-path checks and race-resistant access where supported. SSRF (server-side request forgery) means unintended outbound requests initiated by a server. Use fixed destinations, disable or revalidate redirects, control DNS/address resolution and egress, and apply authentication, deadlines and response-size limits. The URI example never performs DNS or network I/O; the file example never opens a file. Actual platform controls require separate testing.
Runtime is not a sandbox
Java type checks and bytecode verification do not isolate arbitrary hostile code from files, network or process resources. The Security Manager was deprecated for removal in Java 17 and permanently disabled starting in Java 24; do not rely on it for new isolation. Use independently reviewed OS/process isolation, least privilege, resource ceilings and network controls. The examples run only trusted source.
Map a finite resource identifier
public class Main { static java.nio.file.Path approvedPath(java.nio.file.Path base,String key) { return switch(key) { case "guide" -> base.resolve("guide.txt"); case "terms" -> base.resolve("terms.txt"); default -> throw new IllegalArgumentException("unknown resource"); }; } public static void main(String[] args) throws Exception { System.out.println(approvedPath(java.nio.file.Path.of("lab"),"guide").getFileName()); }}Expected output:
guide.txtOnly a server-owned constant filename is selected. No file access or symlink-safety claim is made.
Map a finite outbound service
public class Main { static java.net.URI destination(String service) { return switch(service) { case "catalog" -> java.net.URI.create("https://catalog.example.invalid/v1/items"); case "billing" -> java.net.URI.create("https://billing.example.invalid/v1/status"); default -> throw new IllegalArgumentException("unknown destination"); }; } public static void main(String[] args) throws Exception { System.out.println(destination("catalog").getHost()); }}Expected output:
catalog.example.invalidThe reserved invalid domain is never contacted. This prevents arbitrary URL selection in the model, not all real SSRF risks.
Common mistakes
Do not accept caller-supplied roles, use string concatenation for SQL values, trust a normalized path as proof of containment, or equate TLS with resource authorization. Never test controls against real systems without separate authorization.
Practice
Verify that a reader in tenant A cannot read another owner’s document, and that a missing actor is denied. Print false twice.
Expected output:
falsefalseCompare with the manual review criteria.
Further reading: Authorization · Path · SSRF · SQL · Security Manager · Java security. Independent editorial review remains pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Threat modeling and secure coding — knowledge check
Java security and software supply-chain reasoning.
Who supplies the trusted actor?
What does JDBC parameter binding protect?
A request supplies a normalized path under an allowed root. Why is that insufficient by itself for secure file access?
What reduces unintended outbound requests?
What happened to Security Manager in JDK 24?