ProjectHub is a Spring Boot project tracker that gets a lot right: JWT authentication on every request, membership checks that stop IDOR, CSRF tokens on every form, an allowlist on task updates, typed MongoDB queries, and FreeMarker HTML auto-escaping.
It still lets the lowest-privileged project member run shell commands on the server. The way in is the friendliest-looking feature in the app: the customizable status report template.
This post walks through the full review: how the app works, where user input goes, which defenses hold, which one is missing, a working exploit, and the fix. Every code snippet you need is included, so you don't have to open the repo to follow along. Each snippet links to its exact lines on GitHub if you want more context.
🎥 Prefer video? The full walkthrough is on YouTube:
What is the Secure Code Review Challenge?
It's a free, biweekly series. Each challenge is a complete, realistic application with its own database, backend and UI, and one vulnerability planted on purpose, based on a real-world CVE or writeup. You review it the way you'd review a real codebase, then compare your reasoning with the published solution.
Every solution follows the same 7-step methodology:
- 🗺️ Understand the application: architecture and main user stories
- 🚪 Identify entry points: where user input comes in
- 🎯 Identify dangerous sinks: where input could change behavior (queries, templates, HTML, redirects, …)
- 🧩 Build a threat model: business-logic risks (authN/authZ) and source-to-sink risks (injection)
- 🔍 Review mitigations: which threats are actually closed, and which aren't
- 🧪 Exploit: prove the unmitigated one is real
- 🛠️ Fix: a primary fix plus defense-in-depth
📌 Repo: https://github.com/mohamed-osama-aboelkheir/the-secure-code-review-challenge
📌 Challenge #9 source: https://github.com/mohamed-osama-aboelkheir/the-secure-code-review-challenge/tree/main/challenges/009-projecthub
⚠️ Spoiler warning: if you want to try ProjectHub yourself first, stop here and come back later.
1. 🗺️ Understanding the application
ProjectHub is a small team project-management service. Users register, create projects, invite each other, move tasks across a board, and generate a status report from a per-project template.
- Backend: Spring Boot 3.3.5 on Java 21, with Spring Security
- Two front doors, one server: a JSON API under
/api, and a server-rendered HTML UI built with FreeMarker templates - Database: MongoDB, through Spring Data MongoDB
- Auth: a JWT, sent as a bearer token to the API and kept in an HTTP-only cookie for the UI
- Authorization: project membership and role (
owner/admin/member) - Packaging: Docker Compose
The README describes the feature that matters most:
"Each project has a customizable **status report template* that members can edit and use to generate a report at any time."*
Keep the word members in mind. A good way to understand a codebase is to read it as a set of stories. Here there are four: what happens when the app starts, register & log in, invite a member & accept, and generate a status report.
🚀 Story 1: what happens when the app starts
If you're new to Spring, this is the thing to internalize: almost nothing is wired up by an explicit call you can grep for. You start at one main(), and from there an annotation scans the package and auto-registers every annotated class (@RestController, @Service, @Configuration, …) as a managed object, a "bean". So to find how requests get authenticated, you don't look for code that calls the security setup. You look for the class that declares it.
docker-compose.yml starts two containers: a stock mongo:7 and the app, built from the local Dockerfile. The app gets its secrets (including JWT_SECRET) from .env:
services: mongo: image: mongo:7 app: build: . environment: MONGODB_URI: mongodb://mongo:27017/projecthub env_file: - .env The Dockerfile is a two-stage build. Maven (Java's equivalent of npm + a build tool, configured in pom.xml) compiles everything into one self-contained "fat jar", which then runs as a non-root appuser:
FROM maven:3.9-eclipse-temurin-21 AS build RUN mvn -q -B package -DskipTests # → target/projecthub.jar FROM eclipse-temurin:21-jre COPY --from=build /build/target/projecthub.jar app.jar USER appuser CMD ["java", "-jar", "app.jar"] java -jar calls the app's main, which is one tiny class:
@SpringBootApplication(exclude = UserDetailsServiceAutoConfiguration.class) public class ProjectHubApplication { public static void main(String[] args) { SpringApplication.run(ProjectHubApplication.class, args); } } ProjectHubApplication.java#L7-L12
SpringApplication.run reads application.properties (port, Mongo URI, and the JWT secret from the environment):
server.port=${PORT:3000} spring.data.mongodb.uri=${MONGODB_URI:mongodb://localhost:27017/projecthub} app.jwt-secret=${JWT_SECRET} Then @SpringBootApplication scans com.projecthub and registers every controller, service and config class. The most important one is SecurityConfig. Its SecurityFilterChain bean is the policy Spring Security applies to every incoming request, a bit like global middleware in Express:
@Bean public SecurityFilterChain filterChain(HttpSecurity http, JwtService jwtService) throws Exception { http .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .csrf(csrf -> csrf .csrfTokenRepository(new CookieCsrfTokenRepository()) .sessionAuthenticationStrategy(new NullAuthenticatedSessionStrategy()) .ignoringRequestMatchers(API)) .authorizeHttpRequests(auth -> auth .requestMatchers("/login", "/register", "/css/**", "/health", "/error").permitAll() .requestMatchers(HttpMethod.POST, "/api/auth/register", "/api/auth/login").permitAll() .anyRequest().authenticated()) ... .addFilterBefore(new JwtAuthFilter(jwtService), UsernamePasswordAuthenticationFilter.class); return http.build(); } The custom JwtAuthFilter is what turns a token into a logged-in user. For /api/** it reads the Bearer header, otherwise the token cookie, and sets the principal only if the token verifies:
String token = request.getRequestURI().startsWith("/api/") ? bearerToken(request) : cookieToken(request); if (token != null) { jwtService.verify(token).ifPresent(userId -> SecurityContextHolder.getContext().setAuthentication( new UsernamePasswordAuthenticationToken(userId, null, List.of()))); } chain.doFilter(request, response); From here every feature follows the same layering:
@RestController (/api/...) ─┐ ├─▶ @Service (business rules, auth checks) ─▶ Store (MongoTemplate) @Controller (HTML pages) ──┘ └─ returns a view name, e.g. "project" → templates/project.ftlh (FreeMarker) The page controllers use Spring MVC: a handler returns a string like "project", and Spring renders templates/project.ftlh with FreeMarker, filling in values like ${project.name}. Spring Boot auto-configures that FreeMarker engine at startup. Remember it: the same FreeMarker configuration gets reused somewhere else.
🔐 Story 2: register & log in
AuthService.register checks lengths and uniqueness, then stores only a BCrypt hash. login returns the same 401 whether the user or the password is wrong, and issues a JWT whose subject is the user id:
User user = users.findByUsername(username); if (user == null || !passwordEncoder.matches(password, user.getPasswordHash())) { throw new ApiException(HttpStatus.UNAUTHORIZED, "Invalid credentials"); } return jwtService.issue(user.getId()); The token is signed with HS256 and a 24-hour expiry (JwtService.java#L27-L35). The UI stores it in an HttpOnly, SameSite=Lax cookie (PageController.java#L283-L291). Note that one shared secret signs every session. Whoever holds it can mint a token for any user.
🤝 Story 3: invite a member & accept
Whoever creates a project is its owner. An owner or admin invites another user by username, as member or admin, via POST /api/projects/{id}/members. The service centralizes the role check in requireAdmin, which first enforces membership:
private Project requireAdmin(String projectId, String userId, String message) { Project project = getForMember(projectId, userId); if (!isAdmin(project, userId)) { throw new ApiException(HttpStatus.FORBIDDEN, message); } return project; } A pending invitation is stored. When the invitee calls POST /api/invitations/{id}/accept, the service checks the invitation really belongs to them (we'll see that check in step 4), marks it accepted, and pushes them onto the project's members array (ProjectStore.java#L43-L45).
📄 Story 4: generate a status report
Any member can generate a report, optionally sending an ad-hoc template string in the body:
@PostMapping("/{projectId}/report") public Map<String, String> generateReport(@PathVariable String projectId, @RequestBody(required = false) Map<String, Object> body) { String template = body != null ? optionalString(body, "template") : null; return Map.of("report", projectService.generateReport(projectId, CurrentUser.id(), template)); } ProjectController.java#L55-L60
The service checks membership (any role is enough), prefers the caller's template over the saved one, and hands it to ReportService:
public String generateReport(String projectId, String userId, String template) { Project project = getForMember(projectId, userId); String templateSource = template != null ? template : project.getReportTemplate(); ... return reports.render(templateSource, project); } And ReportService compiles that string as a FreeMarker template, using the same FreeMarker configuration Spring set up for the HTML views:
public ReportService(FreeMarkerConfig freeMarkerConfig) { this.freemarker = freeMarkerConfig.getConfiguration(); } public String render(String templateSource, Project project) { try { Template template = new Template("report", new StringReader(templateSource), freemarker); StringWriter out = new StringWriter(); template.process(Map.of("project", project), out); return out.toString(); } catch (IOException | TemplateException e) { throw new ApiException(HttpStatus.BAD_REQUEST, "Report template could not be rendered"); } } The default template is a simple field-substitution string, and the UI even advertises the fields as ${project.name}, ${project.status}, ${project.description}:
public static final String DEFAULT_TEMPLATE = "Project: ${project.name}\nStatus: ${project.status}\nDescription: ${project.description}"; The same flow exists in the UI: the project page has a "Report template" textarea that posts to POST /projects/{id}/report (PageController.java#L149-L153).
🧠 The key observation from step 1
FreeMarker is used for two very different jobs:
HTML views: template = project.ftlh (written by the developers) + data = user input Reports: template = request body (written by ANY member) + data = the project A template engine has two inputs: the template and the context (the data). For the HTML views, the template is trusted and only the context comes from users. For reports, the user writes the template itself. Everything about the report's safety depends on one assumption: that ${project.name} is just a placeholder, and not the tip of a full expression language.
2. 🚪 Entry points
All /api/** routes need a bearer JWT and all page routes need the token cookie, except the auth routes.
-
POST /api/auth/register,POST /api/auth/login(and the/register,/loginforms): public, takeusername,password -
GET /api/projects,POST /api/projects,GET /api/projects/{id}: any user (create) / project member (read), take projectname,description,status -
PUT /api/projects/{id}/templateandPOST /projects/{id}/template: project member, take a report template string -
POST /api/projects/{id}/reportandPOST /projects/{id}/report: project member, take an ad-hoc report template string -
GET/POST/PUT/DELETE /api/projects/{id}/tasks[/{taskId}]: project member, take tasktitle,description,status,assigned_to -
GET/POST/PATCH/DELETE /api/projects/{id}/members[/{memberUserId}]: member (read) / owner or admin (changes), takeusername,role, member id -
GET /api/invitations,POST /api/invitations/{id}/accept|decline: the invited user, take the invitation id
3. 🎯 Dangerous sinks
- S1: FreeMarker compiling a template from request input (
ReportService.render) → server-side template injection (SSTI), which in most engines means remote code execution. - S2: MongoDB queries and updates built from request input (stores using
Criteria.where(...),TaskStore.updateiterating a map intoUpdate.set) → NoSQL operator injection and mass assignment. - S3: FreeMarker rendering stored data into the HTML UI (
${project.name}, task titles, the report in<pre>${report}</pre>) → stored XSS. - S4: redirects built from request data (
"redirect:/projects/" + projectId) → open redirect.
Notice that one library, FreeMarker, shows up twice with two different risks: XSS when it renders data into a page, and SSTI when it compiles user input as the template.
4 & 5. 🧩 Threat model & 🔍 mitigation review
🔓 Business logic
Authentication ✅. Every route except the auth pages, /css/** and /health hits .anyRequest().authenticated(). JwtAuthFilter sets the principal only when jwtService.verify succeeds, and verify uses verifyWith(key).parseSignedClaims(...), which rejects tampered and unsigned (alg: none) tokens:
return Optional.ofNullable(Jwts.parser() .verifyWith(key) .build() .parseSignedClaims(token) .getPayload() .getSubject()); In the video, removing or corrupting the cookie on a page request just redirects to /login, which is the expected behavior.
Authorization / IDOR ✅. If I know the ID of a project I'm not in, can I read it? If I'm in project A, can I edit a task that belongs to project B? Can I accept an invitation sent to someone else? Every service re-checks the relationship and answers 404 when it doesn't hold:
// ProjectService.getForMember: non-members get 404, never the object if (project == null || !isMember(project, userId)) { throw new ApiException(HttpStatus.NOT_FOUND, "Project not found"); } // TaskService.requireTaskInProject: the task must belong to the project in the URL if (task == null || !task.getProjectId().equals(projectId)) { throw new ApiException(HttpStatus.NOT_FOUND, "Task not found"); } // InvitationService.requirePending: the invitation must be addressed to the caller if (invitation == null || !invitation.getInvitedUserId().equals(userId)) { throw new ApiException(HttpStatus.NOT_FOUND, "Invitation not found"); } ProjectService.java#L57-L63 · TaskService.java#L102-L108 · InvitationService.java#L51-L60
Privileged member operations (invite, change role, remove) go through requireAdmin, shown in story 3.
CSRF ✅. The UI is cookie-authenticated, so a malicious page could make your browser send a mutating request with your cookie attached. Spring Security's CookieCsrfTokenRepository (a stateless double-submit token) is on for every page route, and every form includes the token through one macro:
<#macro csrfField> <input type="hidden" name="${csrf.parameterName}" value="${csrf.token}"> </#macro> CSRF is turned off only for /api/**, which takes a bearer header the browser never adds by itself. In the video, sending a page request with a wrong CSRF value returns 403 Forbidden.
Mass assignment ✅. Could a task update also rewrite the task's projectId or creator, and move it into a project I can't see? TaskService.update starts from an empty changes map and copies in exactly four named, type-checked fields. Any other key in the body is ignored:
Map<String, Object> changes = new HashMap<>(); if (body.containsKey("title")) changes.put("title", title); // + must be a non-blank String if (body.containsKey("description")) changes.put("description", description); if (body.containsKey("status")) changes.put("status", status); // + requireValidStatus if (body.containsKey("assigned_to")) changes.put("assignedTo", assignedTo); // + requireAssignable if (!changes.isEmpty()) tasks.update(taskId, changes); 



