- Lab
-
Libraries: If you want this lab, consider one of these libraries.
- Core Tech
Fix a Vulnerable Java Patient Records API
An API can pass every test and still hand attackers its most sensitive data. In this guided Code Lab, you'll prove it by attacking a Java patient records API yourself: reading files it should never serve, forging a JSON Web Token that logs you in as someone else, and hiding a script in a patient's record. Then you'll switch sides and fix every flaw you exploited, along with weak password storage, unscanned dependencies, and the flaws an AI coding assistant slipped into a new endpoint. Each fix is proven by a test that attacks your code, so you'll leave with defenses you can trust and take back to your own Java services.
Lab Info
Table of Contents
-
Challenge
Step 1: Meet the Patient Records API
Fix the API before the audit
Globomantics clinics use the Patient Records API to look up patients, read visit summaries, and download documents such as lab results. An external security audit is coming up, and an internal review just found classic flaws throughout the API. On top of that, a new AI-assisted visit summary feature was merged without a security review.
You're the developer asked to fix everything before the auditors arrive. For each flaw, you'll see it in action, often by attacking the API yourself, and then fix the code. Tests that send malicious payloads prove each fix. ### What you will learn
- Eliminate input and output handling flaws in a Java REST API: path traversal and cross-site scripting
- Upgrade authentication and session handling: Argon2id password hashes, strict JSON Web Token (JWT) validation, and a logout that revokes the token
- Secure the build and review AI-generated code: a dependency scan, a software bill of materials (SBOM), and fail-closed error handling with masked logs ### Before you begin
The API is a Java 25 application built with Javalin and Maven. Run every command in the Terminal, from the workspace folder.
To start the API, or to restart it after you change the code, run:
./run-api.shThe API runs in the background on port 7070 and writes its log to
api.log. Most endpoints need a signed-in user. To sign in as the cliniciannurse.joyand save the token in theTOKENvariable, run:TOKEN=$(curl -s -d '{"username":"nurse.joy","password":"Wint3r-Morning!"}' http://localhost:7070/api/login | cut -d'"' -f4)Tokens last an hour and survive restarts of the API. If a request answers
Sign in to continue., run the sign-in command again. To run one test class, run:./mvnw test -Dtest=DocumentTraversalTest./mvnwis the Maven Wrapper, which runs the Maven version the project pins. The lab has no internet access, so every library, and the vulnerability database for the dependency scan, is already downloaded.README.mdlists the API's endpoints and the test accounts. Thesolutionfolder holds the solution for every task, in a folder named after the task, such assolution/task-2.3. -
Challenge
Step 2: Close the path traversal hole in document downloads
How the document endpoint finds files
Clinicians download documents, such as
lab-results-1001.txt, fromGET /api/documents?file=<name>. The documents live indata/documents. Right next to that folder,data/privateholds a nightly export of every patient, with insurance numbers.DocumentService.resolve, insrc/main/java/com/globomantics/patients/DocumentService.java, tries to block path traversal by removing../from the name:String cleaned = fileName.replace("../", ""); return baseDir.resolve(cleaned);Start the API, and sign in:
./run-api.sh TOKEN=$(curl -s -d '{"username":"nurse.joy","password":"Wint3r-Morning!"}' http://localhost:7070/api/login | cut -d'"' -f4) ``` ### Why the filter failed > **Note:** The filter removes `../` in a single pass. In `....//`, it removes the `../` in the > middle, and the characters on either side join up into a new `../`. Filters that strip > bad input are easy to get around, so the fix in this step checks where the path ends up > instead. `DocumentTraversalTest` sends payloads to the document endpoint. Its only payload is one that the filter already blocks, so the test passes even though the API is vulnerable: ```java @ValueSource(strings = { "../private/patient-export.csv" }) ``` ### Check where the path ends up Run the test: ```bash ./mvnw test -Dtest=DocumentTraversalTestThe two new payloads fail, which proves that the test catches the attack.
To fix path traversal, check where the path ends up, not what it contains:
- Resolve the name against the documents folder.
- Normalize the result, which removes every
.and..step. - Reject the result unless it's still inside the documents folder.
Resolving an absolute path such as
/etc/passwdreturns that path unchanged, so step 3 catches it too.Steps 1 and 2 canonicalize the path: they turn every way of writing it into one standard form, so you can compare it with the documents folder. If a folder can contain symbolic links, use
Path.toRealPath()instead, which also follows links, so a link can't point outside the folder. It throws an exception for a file that doesn't exist. The documents folder has no links, sonormalize()is enough here.Tip:
Path.toAbsolutePath()makes a path absolute,Path.normalize()removes.and..steps, andPath.startsWith(Path)compares whole folder names, not characters. Thrownew HttpError(400, "That file name isn't allowed.")to reject a name. ### Confirm the fixRun the test again, and all three payloads pass:
./mvnw test -Dtest=DocumentTraversalTestTo see the fix in the running API, restart it with
./run-api.sh, and then request the export with a plain../:curl -H "Authorization: Bearer $TOKEN" "http://localhost:7070/api/documents?file=../private/patient-export.csv"The API answers
That file name isn't allowed. -
Challenge
Step 3: Stop stored cross-site scripting in patient notes
How the summary page shows notes
Clinicians write notes with
PUT /api/patients/{id}/notes, and the summary page at/patients/{id}/summaryshows them, both between tags and inside thevalueattribute of a text box. To block cross-site scripting (XSS),SummaryPage, insrc/main/java/com/globomantics/patients/SummaryPage.java, removes script tags from the notes first:private static String removeScriptTags(String text) { return text.replace("<script>", "").replace("</script>", ""); }A script doesn't need a
<script>tag, though. An image with anonerrorhandler runs JavaScript too. ### Watch the script runTo watch it run, save the summary page as a file:
curl -s -H "Authorization: Bearer $TOKEN" http://localhost:7070/patients/1001/summary -o summary.htmlOpen
summary.html- {{localhost}}/summary.html
- In the Web Browser tab, enter
localhost:8080/summary.html
A dialog box that says
XSSappears: the browser ran the attacker's JavaScript, which could just as well have sent a clinician's data somewhere else.XssTeststores payloads as notes and checks that the summary page shows them only as text. Its only payload is a<script>tag, which the filter removes, so the test passes:@ValueSource(strings = { "<script>alert('xss')</script>" }) ``` ### Encode for the context Run the test: ```bash ./mvnw test -Dtest=XssTestThe two new payloads fail. Instead of hunting for dangerous tags, encode every value for the place it goes. Between tags,
<must become<; inside a quoted attribute,"must become". The OWASP Java Encoder, already inpom.xml, has an encoder for each context.Tip: Import
org.owasp.encoder.Encode.Encode.forHtml(String)encodes a value that goes between tags, andEncode.forHtmlAttribute(String)encodes a value that goes inside a quoted attribute. Once every value is encoded, the script-tag filter has no job left, so delete it. ### Confirm the fixRun
XssTestagain, and every payload passes../mvnw test -Dtest=XssTestThe reference check for this task also tries
<scr<script>ipt>: the old filter would have removed the inner tag and rebuilt a working<script>from the pieces. -
Challenge
Step 4: Migrate password hashes to Argon2id
Why one round of SHA-256 isn't enough
The API stores each password as one round of SHA-256, with no salt. Two users with the same password get the same hash, and an attacker who steals the hashes can test billions of guesses per second. Argon2id is a password hashing function that's slow and uses a lot of memory by design, and it gives every hash its own random salt.
PasswordHasher, insrc/main/java/com/globomantics/patients/auth/PasswordHasher.java, already has what you need, built on Bouncy Castle:argon2id(password, salt, memoryKb, iterations, parallelism, hashLength)computes an Argon2id hash.encode(salt, hash)stores the settings and the salt with the hash, as a string that starts with$argon2id$.MEMORY_KB,ITERATIONS, andPARALLELISMhold the minimum settings that OWASP recommends, andverifyalready checks both formats.
Only the method that creates hashes still uses the old format:
public String hash(String password) { return legacyHash(password); }Tip: Create the salt with
new byte[SALT_LENGTH], and fill it withRANDOM.nextBytes(salt), which uses aSecureRandom. Pass the same salt toargon2idand toencode. ### Upgrade old hashes as users sign inYou can't convert the old hashes, because you don't know the passwords they came from. Instead, replace each old hash the next time its owner signs in with the right password.
AuthService.login, insrc/main/java/com/globomantics/patients/auth/AuthService.java, checks the password here:User user = users.find(username); if (user == null || !hasher.verify(password, user.passwordHash())) { throw new HttpError(401, "Wrong username or password."); }Right after this check is the only moment the API knows that the password is correct.
Tip:
hasher.isLegacy(String storedHash)returnstruefor an old SHA-256 hash, andusers.updatePasswordHash(String username, String newHash)saves a new hash. ### Confirm the upgradeGET /api/admin/usersreports the hash format of each account. Restart the API to run your changes, and then sign in asnurse.joy:./run-api.sh TOKEN=$(curl -s -d '{"username":"nurse.joy","password":"Wint3r-Morning!"}' http://localhost:7070/api/login | cut -d'"' -f4)The endpoint is for administrators only, so sign in as
admin, and then list the accounts:ADMIN_TOKEN=$(curl -s -d '{"username":"admin","password":"Adm1n-Only-Secret"}' http://localhost:7070/api/login | cut -d'"' -f4) curl -H "Authorization: Bearer $ADMIN_TOKEN" http://localhost:7070/api/admin/usersnurse.joyandadminshowargon2id, because each just signed in.dr.adamsstill showslegacy-sha256until that user signs in. -
Challenge
Step 5: Harden token validation and add logout
How the API checks tokens
When you sign in, the API returns a JSON Web Token (JWT) signed with its RSA private key, which is the RS256 algorithm.
JwtVerifier.verify, insrc/main/java/com/globomantics/patients/auth/JwtVerifier.java, uses the Nimbus JOSE + JWT library to check each token, and it lets the token's header decide how:JWT jwt = JWTParser.parse(token); // Check the signature with whichever algorithm the token's header names. if (jwt instanceof SignedJWT signed) { JWSAlgorithm algorithm = signed.getHeader().getAlgorithm(); JWSVerifier verifier = JWSAlgorithm.Family.HMAC_SHA.contains(algorithm) ? new MACVerifier(publicKey.getEncoded()) : new RSASSAVerifier(publicKey); ... } else if (!(jwt instanceof PlainJWT)) {The program
attacks/ForgeToken.javaforges two tokens for the realadminaccount, without its password or the API's private key, and calls the admin-onlyGET /api/admin/usersendpoint with each one. ### Pin the algorithm and the keyNote: The
nonetoken claims it needs no signature, and Nimbus parses it as aPlainJWT, which the verifier accepts. Theconfusiontoken claims HS256 and is signed with the API's public key, which anyone can download, as the secret. Both attacks work because the token chooses how it's checked.The fix is to pin both the algorithm and the key: this API only ever issues RS256 tokens signed with its own key, so it accepts nothing else.
JwtValidationTestsends both forged tokens, plus a real token whose payload was changed after signing.Tip:
SignedJWT.parse(token)accepts only signed tokens, so it throws aParseExceptionfor anonetoken. Comparesigned.getHeader().getAlgorithm()withJWSAlgorithm.RS256, and check the signature withsigned.verify(new RSASSAVerifier(publicKey)). Thrownew InvalidTokenException("...")to reject a token. ### Revoke tokens on the serverThe API has no way to log out, so a stolen token works until it expires an hour later. Because a JWT is valid on its own, logging out has to happen on the server: the API must remember which tokens it revoked.
Each token carries a unique ID, its
jticlaim.AuthService.endSession(tokenId)records that the session is over, andAuthService.authenticatealready rejects tokens from sessions that ended. All that's missing is the endpoint.PatientApi.register, insrc/main/java/com/globomantics/patients/PatientApi.java, has a placeholder for it:// Task 5.3: add the logout endpoint here.Tip: Register the endpoint with
routes.post("/api/logout", ctx -> { ... }). Inside it,auth.requireRole(ctx.header("Authorization"), CLINICIAN, ADMIN)returns the caller'sClaims, andclaims.tokenId()is the token's ID. Finish withctx.status(204). -
Challenge
Step 6: Add a dependency scan and an SBOM to the build
Scan what you ship
Your own code is only part of what you ship. A dependency scan checks every library the build uses against known vulnerabilities: OWASP Dependency-Check compares them with the National Vulnerability Database (NVD). A software bill of materials (SBOM) lists every library and its version, so when a new vulnerability is announced, you know at once whether you're affected. CycloneDX writes one during the build.
The CI workflow in
.github/workflows/ci.ymlruns./mvnw -B verify, so anything you add to the Maven build runs in CI too, and on any laptop. Both plugins are already pinned in the<pluginManagement>section ofpom.xml, so you only need to switch them on in the<plugins>section:<plugins> <!-- Task 6.1: add the dependency scan and the SBOM plugins here. --> </plugins>Tip: Each plugin needs its
groupIdandartifactId(org.owaspanddependency-check-maven,org.cyclonedxandcyclonedx-maven-plugin), and an<executions>element with an<execution>that lists its goal under<goals>. Dependency-Check's goal ischeck, which runs in theverifyphase by itself; give it a<configuration>with<formats>listingHTMLandJSON, and<nvdApiKeyEnvironmentVariable>NVD_API_KEY</nvdApiKeyEnvironmentVariable>for CI. CycloneDX's goal ismakeBom; set its<phase>topackage. ### Read the reportsBuild the project the way CI does. The tests for steps 7 and 8 still fail, so skip the tests for now:
./mvnw verify -DskipTestsThe scan uses the copy of the NVD that was downloaded for this lab, so it takes a little while.
Open
target/dependency-check-report.html:- {{localhost}}/target/dependency-check-report.html
- In the Web Browser tab, enter
localhost:8080/target/dependency-check-report.html
You'll see each library and any known vulnerabilities in it.
Open
target/bom.jsonin the file tree: each entry undercomponentsis a library, with its version and a package URL such aspkg:maven/io.javalin/[email protected]?type=jar.Note: In CI, the same build downloads fresh vulnerability data, using an NVD API key stored as the
NVD_API_KEYrepository secret. In this lab, the data is a snapshot, so a library can have vulnerabilities announced after the snapshot was taken. -
Challenge
Step 7: Review the AI-generated visit summary endpoint
Review the generated endpoint
A teammate asked an AI coding assistant for an endpoint that summarizes a patient's latest visit, and merged the result without a review.
MockModelClientstands in for the language model, so the lab works offline. Here's the generatedAiVisitSummaryEndpoint.handle, insrc/main/java/com/globomantics/patients/ai/AiVisitSummaryEndpoint.java:public void handle(Context ctx) { Patient patient = patients.find(ctx.pathParam("id")); ... String summary = model.complete("Summarize this patient's latest visit:\n" + patient.notes()); switch (format) { case "text" -> ctx.result(summary); case "html" -> ctx.html("<h1>Visit summary</h1><p>" + Encode.forHtml(summary) + "</p>"); default -> ctx.status(400).html("<h1>Unsupported format: " + format + "</h1>"); } }Review it the way you'd review a teammate's code, starting with who can call it. Request a summary without a token:
curl http://localhost:7070/api/patients/1001/visit-summaryThe API tells anyone about a patient's visit.
Tip: Every other patient endpoint starts with
auth.requireRole(ctx.header("Authorization"), CLINICIAN, ADMIN), which throws anHttpErrorwith status401or403when the caller isn't allowed. The role constants are inAuthService. ### Find the reflected XSSThe assistant encoded the model's reply in the
htmlbranch, but not theformatvalue in the error response. Whatever a link puts informatcomes back as markup. This is reflected XSS.Before Task 7.1, anyone could open this URL, so an attacker could send a clinician a link with a script in it. Encode the value anyway: if the API later signs users in with a cookie, or another client renders this error page, the script runs.
Tip: Use
Encode.forHtmlfromorg.owasp.encoder.Encode, as in Step 3. Encode only the inserted value, not the page's own tags. -
Challenge
Step 8: Fail closed with safe, masked logging
Find the fail-open handler
AuthService.requireRole, insrc/main/java/com/globomantics/patients/auth/AuthService.java, decides whether a request may proceed. When the token check itself crashes, it logs the wholeAuthorizationheader and lets the request through:} catch (RuntimeException e) { // The token check itself crashed. Keep the clinic running and let the request through. LOG.warning("Token check crashed for header " + authorizationHeader + ": " + e); return new Claims("unverified", allowedRoles[0], "none", 0); }A header with the word
Bearerand no token crashes the check. Send one to the admin endpoint:curl -H "Authorization: Bearer" http://localhost:7070/api/admin/usersThe API lists every account. This is failing open. Security checks must fail closed: when you can't tell whether a request is allowed, deny it. The log line is a second problem: for any other header, it records a complete token that anyone who reads the log could reuse.
Tip: Throw
new HttpError(401, "Sign in to continue."), the same generic response that an invalid token gets. In the log message, useMasker.mask(authorizationHeader), which keeps only the last four characters (importcom.globomantics.patients.Masker), ande.getClass().getSimpleName(), which names the kind of error without its details. ### Run the whole buildRun the whole build the way CI does:
./mvnw verifyEvery test passes, and the build scans your dependencies and writes a fresh SBOM.
-
Challenge
Step 9: Review what you fixed
What you fixed
You attacked the Patient Records API the way an attacker would, and then closed every hole you found, before the auditors could. Each fix follows a principle that applies to any Java service: check where input ends up instead of filtering it, encode output for the place it goes, store passwords with a slow, salted hash, let the server decide how tokens are checked, revoke tokens on the server, scan what your build ships, treat AI-generated code as untrusted, fail closed, and keep secrets out of logs.
Note: The tests you ran are now part of the build. Keep them there, so that a later change that reopens one of these holes fails the build before it reaches production. ### Going further
- Make the build fail on serious findings: add
<failBuildOnCVSS>7</failBuildOnCVSS>to Dependency-Check's configuration, and see what it takes to get the build passing again. - Add more payloads to
DocumentTraversalTestandXssTest, such as a backslash in a file name or an<iframe>in the notes, and check that your fixes still hold. - Fix the header parsing in
AuthService.bearerToken, which acceptsBearerwithout a space. Failing closed made the crash harmless, but it's still a bug. - Read the OWASP Password Storage Cheat Sheet, the OWASP JSON Web Token Cheat Sheet, and the OWASP Cross Site Scripting Prevention Cheat Sheet.
- Continue the path with the Secure Coding in Spring Framework course and the Harden a Spring Boot Banking Admin App lab, which apply these defenses in Spring.
- Make the build fail on serious findings: add
About the author
Real skill practice before real-world application
Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.
Learn by doing
Engage hands-on with the tools and technologies you’re learning. You pick the skill, we provide the credentials and environment.
Follow your guide
All labs have detailed instructions and objectives, guiding you through the learning process and ensuring you understand every step.
Turn time into mastery
On average, you retain 75% more of your learning if you take time to practice. Hands-on labs set you up for success to make those skills stick.