The Audit: When "Working Code" Meets Production Reality
In Part 1 of this series, we looked at the macro-architecture of rebuilding our legacy exam monolith as a decoupled, high-concurrency platform using Java 21 LTS, Spring Boot 3.4, React 19, and Tailwind CSS v4 (open-sourced at mfarim/spring-elearning-react).
On the surface, the initial release was a great milestone:
- The UI was sleek and responsive across mobile and desktop devices.
- Spring Data JPA, Flyway migrations, and Redis caching were configured and running.
- Exams, classrooms, assignments, and real-time STOMP WebSockets were working in development.
However, when software moves from an attractive open-source repository to a mission-critical exam platform deployed in actual school districts, one question becomes crucial:
"Is this codebase truly production-ready, or does it harbor subtle security holes and runtime traps that will bring exam day crashing down?"
A thorough architectural review and security audit revealed several critical vulnerabilities, an exam-breaking session timeout bug, and infrastructure risks. In this article, I break down Pull Request #1: feat/production-readiness-and-security-hardening: the exact root causes, the security exploits, and the engineering fixes that brought the platform to enterprise-grade resilience.
Architectural Context: Clean Architecture vs. Pragmatic Modular Monolith
Before getting into the vulnerabilities, let's address an architectural question developers often ask:
Does this project adhere to Uncle Bob's Clean Architecture?
The short answer is No. This project does not use strict Clean Architecture (Hexagonal / Ports & Adapters). Instead, it is a Modular Monolith (Package-by-Feature) built on the classic Spring 3-Tier Layered Architecture (Controller → Service → Repository → Entity).
The Trade-Off: Academic Purity vs. Engineering Pragmatism
Textbook Clean Architecture requires domain entities to be pure POJOs with zero dependencies on database ORMs or frameworks. In theory, this lets you swap Spring or Hibernate for another framework without touching business logic.
In practice, though, for web applications where 75–85% of the features are administrative CRUD, learning material uploads, and transactional database updates:
- The Boilerplate Explosion: You must maintain duplicate domain models and JPA entities, plus bidirectional MapStruct mappers for every database operation.
- Fighting the Framework: You give up Spring Boot's greatest strengths: declarative transactions (
@Transactional), JPA dirty checking, pagination (Pageable), and Spring Security annotations (@PreAuthorize).
For academic platforms, a Modular Monolith (Package-by-Feature) is the battle-tested sweet spot. Still, a clean architecture does not excuse sloppy security or fragile infrastructure. Let's look at the critical bugs PR #1 uncovered.
Vulnerability 1: Critical Path Traversal in File Storage
The Flaw
Learning Management Systems handle a constant stream of file uploads: student homework, teacher syllabus PDFs, and CBT question diagrams. The original FileStorageService implemented file downloads like this:
// VULNERABLE CODE (Before PR #1)
public Resource loadFileAsResource(String filePath) {
try {
Path file = this.fileStorageLocation.resolve(filePath).normalize();
Resource resource = new UrlResource(file.toUri());
if (resource.exists() && resource.isReadable()) {
return resource;
}
...
Because SecurityConfig permitted public access to /api/v1/files/** (so browsers could display public attachments and teacher avatars), this implementation had a classic Arbitrary File Read / Path Traversal vulnerability:
GET /api/v1/files/..%2F..%2F..%2Fapplication.yml HTTP/1.1
Host: elearning.local
.normalize() resolved relative dot-segments (..), but nothing checked that the resolved path stayed inside the upload directory. An attacker could traverse out of storage/uploads and read server configuration files, database credentials, or private system keys.
File uploads and deletions had the same problem:
- An attacker setting
subDirectoryto../../etccould forceFiles.createDirectories()outside the sandbox. - An attacker passing
../../secret.txttodeleteFile()could delete arbitrary files on the server.
The Remediation
PR #1 adds strict, three-layer defense-in-depth boundary validation to FileStorageService:
// backend/src/main/java/com/elearning/common/service/FileStorageService.java
public String storeFile(MultipartFile file, String subDirectory) {
String originalFileName = StringUtils.cleanPath(Objects.requireNonNull(file.getOriginalFilename()));
// 1. Reject explicit path traversal sequences in original filename
if (originalFileName.contains("..")) {
throw new IllegalArgumentException("Filename contains invalid path sequence " + originalFileName);
}
String extension = "";
int i = originalFileName.lastIndexOf('.');
if (i >= 0) {
extension = originalFileName.substring(i);
}
String fileName = UUID.randomUUID() + extension;
try {
Path targetDir = this.fileStorageLocation;
if (subDirectory != null && !subDirectory.trim().isEmpty()) {
targetDir = this.fileStorageLocation.resolve(subDirectory).normalize();
// 2. Enforce sandbox boundary on target directory
if (!targetDir.startsWith(this.fileStorageLocation)) {
throw new SecurityException("Target sub-directory is outside base upload directory: " + subDirectory);
}
Files.createDirectories(targetDir);
}
Path targetLocation = targetDir.resolve(fileName).normalize();
// 3. Enforce sandbox boundary on target file
if (!targetLocation.startsWith(this.fileStorageLocation)) {
throw new SecurityException("Target file location is outside base upload directory");
}
Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
return (subDirectory != null && !subDirectory.trim().isEmpty() ? subDirectory + "/" : "") + fileName;
} catch (IOException ex) {
throw new RuntimeException("Could not store file " + fileName + ". Please try again!", ex);
}
}
loadFileAsResource and deleteFile got the same strict boundary assertions:
public Resource loadFileAsResource(String filePath) {
try {
Path file = this.fileStorageLocation.resolve(filePath).normalize();
// Block any path escaping the storage root
if (!file.startsWith(this.fileStorageLocation)) {
throw new SecurityException("Access to path outside upload directory is forbidden: " + filePath);
}
Resource resource = new UrlResource(file.toUri());
if (resource.exists() && resource.isReadable()) {
return resource;
} else {
throw new RuntimeException("File not found: " + filePath);
}
} catch (MalformedURLException ex) {
throw new RuntimeException("File not found: " + filePath, ex);
}
}
Automated Unit Testing with JUnit 5 & @TempDir
To make sure the path traversal fix never regresses, PR #1 added unit tests in FileStorageServiceTest.java that use JUnit 5's isolated @TempDir:
// backend/src/test/java/com/elearning/common/service/FileStorageServiceTest.java
@Test
void testStoreFile_PathTraversalInFilename_ThrowsException() {
MockMultipartFile file = new MockMultipartFile(
"file",
"../../etc/passwd.txt",
"text/plain",
"malicious content".getBytes()
);
assertThrows(IllegalArgumentException.class, () ->
fileStorageService.storeFile(file, "materials")
);
}
@Test
void testLoadFile_PathTraversal_ThrowsSecurityException() {
assertThrows(SecurityException.class, () ->
fileStorageService.loadFileAsResource("../../application.yml")
);
}
Vulnerability 2: Information Disclosure via Global Exception Handler
The Flaw
In Spring Boot APIs, unhandled exceptions typically hit a @RestControllerAdvice. In the original implementation, unexpected exceptions returned the raw message directly to the caller:
// VULNERABLE CODE (Before PR #1)
@ExceptionHandler(Exception.class)
public ResponseEntity<ApiResponse<Void>> handleGenericException(Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(ApiResponse.error("An unexpected error occurred: " + ex.getMessage()));
}
If a PostgreSQL constraint failed or a query timed out, ex.getMessage() returned internal database schema details:
{
"success": false,
"message": "An unexpected error occurred: ERROR: relation \"public.users\" does not exist; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException"
}
This is an Information Disclosure vulnerability (CWE-209). It hands attackers database engine versions, SQL dialect details, and table structures on a silver platter.
The Remediation
PR #1 updates GlobalExceptionHandler to log full stack traces internally with SLF4J and return a sanitized, static error message to clients:
// backend/src/main/java/com/elearning/common/exception/GlobalExceptionHandler.java
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(SecurityException.class)
public ResponseEntity<ApiResponse<Void>> handleSecurityException(SecurityException ex) {
return ResponseEntity.status(HttpStatus.FORBIDDEN)
.body(ApiResponse.error(ex.getMessage()));
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ApiResponse<Void>> handleGenericException(Exception ex) {
// Log sensitive diagnostics to server logs only
log.error("Unhandled server exception: ", ex);
// Return safe, opaque message to client
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(ApiResponse.error("An unexpected error occurred. Please contact the administrator."));
}
}
⏱️ The Exam-Breaking Trap: 15-Minute Token Expiry & Student Disconnections
The Catastrophic Scenario
Imagine this real-world exam hall disaster:
- 500 junior high school students begin a 90-minute national mathematics exam at 08:00 AM.
- In
application.yml, the JWT access token lifetime is set to 15 minutes (900000ms) for security compliance. - At exactly 08:15:01 AM, students answer question #15, and the browser sends
POST /api/v1/exams/{id}/answer. - Spring Security detects the expired access token and returns
HTTP 401 Unauthorized. - The frontend Axios interceptor catches the 401 error:
TYPESCRIPT
// BUGGY CODE (Before PR #1) if (error.response?.status === 401) { localStorage.removeItem('token'); window.location.href = '/login'; // KICK STUDENT OUT! } - Result: All 500 students are abruptly logged out and redirected to
/login. They lose unsaved exam answers, and the exam hall descends into panic.
Why Did This Happen?
The backend already generated a refreshToken at login, but the /api/v1/auth/refresh endpoint was never implemented in AuthController. The refresh token sat unused in localStorage while students were kicked out every quarter of an hour.
The Engineering Solution: Refresh Token Rotation with Axios Queue Interceptor
Update (Nov 2026): This was the first version of token refresh. Two later changes replace parts of the code below: refresh tokens are now registered in Redis and can be used only once (server-side rotation, real logout and revoke-all in Part 5), and the refresh token no longer lives in
localStorage: it travels in an httpOnly,SameSite=Strictcookie (Part 7). The queue-based Axios interceptor idea still applies.
To fix this without widening the access token's exposure window, PR #1 implements an end-to-end transparent token refresh flow:
1. Backend Endpoint & Validation
AuthService verifies the incoming refresh token and generates a fresh access/refresh pair:
// backend/src/main/java/com/elearning/modules/auth/service/AuthService.java
@Transactional
public AuthResponse refreshToken(String refreshToken) {
if (!jwtProvider.validateToken(refreshToken)) {
throw new IllegalArgumentException("Invalid or expired refresh token");
}
Long userId = jwtProvider.getUserIdFromToken(refreshToken);
User user = userRepository.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException("User not found with id: " + userId));
if (!user.isActive()) {
throw new IllegalArgumentException("User account is disabled");
}
UserPrincipal principal = UserPrincipal.create(user, null);
String newAccessToken = jwtProvider.generateAccessToken(principal);
String newRefreshToken = jwtProvider.generateRefreshToken(principal);
return AuthResponse.builder()
.accessToken(newAccessToken)
.refreshToken(newRefreshToken)
.tokenType("Bearer")
.userId(user.getId())
.name(user.getName())
.email(user.getEmail())
.roles(principal.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.toList()))
.active(user.isActive())
.build();
}
Note: This endpoint issues a new refresh token on every call, but it is not full rotation yet.
validateTokenaccepts any validly signed token, so an access token also passes as a refresh token, and old refresh tokens stay valid until they expire. A production version should add atypclaim (access/refresh) and check it here, and store refresh token IDs (jti) so each one is revoked once it has been used.
2. Frontend Axios Concurrency Queue Interceptor
In a real React 19 SPA, several parallel requests can fire in the same second (e.g., auto-saving an answer, polling the remaining exam time, and fetching question telemetry). If five requests fail with 401 at once, you must NOT fire five refresh requests. Instead:
- The first request sets
isRefreshing = trueand calls/api/v1/auth/refresh. - The remaining four requests are paused in a Promise queue (
failedQueue). - When the refresh resolves, all queued requests receive the new token and retry automatically:
// frontend/src/api/client.ts
let isRefreshing = false;
let failedQueue: Array<{
resolve: (token: string) => void;
reject: (err: any) => void;
}> = [];
const processQueue = (error: any, token: string | null = null) => {
failedQueue.forEach((prom) => {
if (error) {
prom.reject(error);
} else {
prom.resolve(token!);
}
});
failedQueue = [];
};
api.interceptors.response.use(
(response) => response,
async (error) => {
const originalRequest = error.config;
if (error.response?.status === 401 && !originalRequest._retry) {
if (
originalRequest.url?.includes('/auth/login') ||
originalRequest.url?.includes('/auth/register') ||
originalRequest.url?.includes('/auth/refresh')
) {
return Promise.reject(error);
}
const refreshToken = localStorage.getItem('refreshToken');
if (!refreshToken) {
localStorage.removeItem('token');
localStorage.removeItem('refreshToken');
if (window.location.pathname !== '/login') window.location.href = '/login';
return Promise.reject(error);
}
// If already refreshing, queue this request
if (isRefreshing) {
return new Promise((resolve, reject) => {
failedQueue.push({ resolve, reject });
})
.then((newToken) => {
originalRequest.headers.Authorization = `Bearer ${newToken}`;
return api(originalRequest);
})
.catch((err) => Promise.reject(err));
}
originalRequest._retry = true;
isRefreshing = true;
try {
const response = await axios.post('/api/v1/auth/refresh', { refreshToken });
const newAccessToken = response.data?.data?.accessToken;
const newRefreshToken = response.data?.data?.refreshToken;
if (newAccessToken) {
localStorage.setItem('token', newAccessToken);
if (newRefreshToken) localStorage.setItem('refreshToken', newRefreshToken);
api.defaults.headers.common.Authorization = `Bearer ${newAccessToken}`;
processQueue(null, newAccessToken);
originalRequest.headers.Authorization = `Bearer ${newAccessToken}`;
return api(originalRequest);
} else {
throw new Error('Refresh response missing token');
}
} catch (refreshErr) {
processQueue(refreshErr, null);
localStorage.removeItem('token');
localStorage.removeItem('refreshToken');
if (window.location.pathname !== '/login') window.location.href = '/login';
return Promise.reject(refreshErr);
} finally {
isRefreshing = false;
}
}
return Promise.reject(error);
}
);
With this mechanism, student exam sessions continue uninterrupted while access tokens still expire every 15 minutes.
DevOps & Production Container Resilience
1. Ephemeral Upload Storage Disaster
In the original docker-compose.yml, the backend container had no volume mount for uploaded files. If a teacher uploaded 50 PDF learning modules and the container was then restarted or updated (docker compose down && docker compose up), every uploaded file was permanently lost.
PR #1 adds a dedicated Docker named volume:
# docker-compose.yml
services:
backend:
volumes:
- backend_storage:/app/storage/uploads
volumes:
postgres_data:
redis_data:
minio_data:
backend_storage: # <--- Persistent Volume Guarantee
2. Spring Boot Actuator & Container Healthchecks
In production orchestration (Docker Swarm, Kubernetes, or AWS ECS), a container can show Running status while the JVM is still warming up or failing database migrations. Routing traffic to a container that isn't ready causes HTTP 502 Bad Gateway errors.
PR #1 added spring-boot-starter-actuator:
# backend/src/main/resources/application.yml
management:
endpoints:
web:
exposure:
include: health,info
endpoint:
health:
show-details: when-authorized
probes:
enabled: true
It also configures native container health checks in docker-compose.yml:
backend:
healthcheck:
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/actuator/health"]
interval: 10s
timeout: 5s
retries: 5
start_period: 30s
frontend:
depends_on:
backend:
condition: service_healthy # Nginx only starts when Spring Boot reports healthy!
This check runs wget inside the backend container, so the runtime image must include it (Alpine-based images ship it with BusyBox). If your image has no wget, install it in the Dockerfile or switch the test to an equivalent curl -f command.
Finally, the Nginx reverse proxy config was updated to expose the health endpoint safely:
# frontend/nginx.conf
location /actuator/ {
proxy_pass http://backend:8080/actuator/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
Open Source Governance & Reproducible Demo Seeding
To meet open-source governance standards, PR #1 added:
- Official MIT License (
LICENSE): Resolves the ambiguous copyright status. - Comprehensive Contribution Guide (
CONTRIBUTING.md): Documents Java 21 prerequisites, test commands, code style, and Git branch workflows. - One-Command Demo Database Seeding: Lets contributors test CBT exams immediately without registering dozens of users by hand. The script lives in
db/seed/, outside Flyway'sdb/migration/folder, so Flyway never treats it as a migration:BASHdocker exec -i elearning-postgres psql -U postgres -d elearning < backend/src/main/resources/db/seed/seed_demo_data.sql
Production Readiness Checklist
Before taking any Spring Boot + React application live, verify your stack against this security and resilience checklist:
| Category | Verification Item | Status in PR #1 |
|---|---|---|
| Storage Security | Strict .startsWith(uploadRoot) boundary check on file read, write, and delete | ✅ Resolved |
| Storage Persistence | Named Docker volume mounted to upload root to survive restarts | ✅ Resolved |
| Exception Safety | Sanitized generic exception handler concealing internal SQL schemas | ✅ Resolved |
| Session Integrity | Refresh endpoint issuing new token pairs, with asynchronous frontend request queueing | ✅ Resolved |
| Observability | Spring Boot Actuator liveness & readiness health checks exposed | ✅ Resolved |
| Container Startup | Orchestrator health check with condition: service_healthy | ✅ Resolved |
| Open Source | Official OSI-approved license & automated seed scripts | ✅ Resolved |
Conclusion & What's Next
Security hardening and production readiness are not checkboxes you tick at the end. They are core architectural disciplines. By eliminating path traversal vulnerabilities, adding a transparent token refresh flow, and locking down the Docker infrastructure, Spring E-Learning is now ready for real-world academic deployments.
In Part 3, we look at Enterprise Security Architecture: Stateless JWT, Method-Level RBAC & OWASP Top 10 Defense, exploring JJWT 0.12 cryptographic validation, declarative SpEL method authorization, and Bucket4j rate limiting.
- Explore Pull Request #1: github.com/mfarim/spring-elearning-react/pull/1
- Explore Full Source Code: github.com/mfarim/spring-elearning-react

Written by Muhammad Fari Madyan
Senior Backend Engineer and co-founder of LampungDev. I write up what I build so others can learn from it.
