Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 31 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,16 @@

REST API for managing clients, technicians and service orders (help desk style), built with Spring Boot.

## Live demo

- API: https://service-order-management-nxil.onrender.com
- Swagger UI: https://service-order-management-nxil.onrender.com/swagger-ui.html

The demo runs on free tiers ([Render](https://render.com) for the API and [Neon](https://neon.com) for PostgreSQL), so
the API goes to sleep after 15 minutes without traffic and the first request afterwards can take about a minute. The
administrator credentials are private; to try the API yourself, run it locally (see below), where an administrator is
created for you.

## Features

- Endpoints for **clients** and **technicians** with bean validation
Expand Down Expand Up @@ -90,6 +100,25 @@ SPRING_PROFILES_ACTIVE=prod \
./mvnw spring-boot:run
```

## Deploying to Render and Neon

The live demo is a Render **Web Service** built from the `Dockerfile` (Docker runtime, free plan) that connects to a
Neon PostgreSQL database. Set these environment variables on the service:

| Variable | Value |
|------------------------------------|------------------------------------------------------------------------------|
| `SPRING_PROFILES_ACTIVE` | `prod` |
| `DB_URL` | `jdbc:postgresql://<neon-host>/<database>?sslmode=require` (direct host, not the `-pooler` one) |
| `DB_USERNAME`, `DB_PASSWORD` | The database credentials shown by Neon |
| `JWT_SECRET` | A random secret of at least 32 characters |
| `ADMIN_EMAIL`, `ADMIN_PASSWORD` | The initial administrator |
| `SPRINGDOC_API_DOCS_ENABLED`, `SPRINGDOC_SWAGGER_UI_ENABLED` | `true` to expose Swagger UI (off by default in `prod`) |
| `SERVER_FORWARD_HEADERS_STRATEGY` | `native`, so the application knows it is served over HTTPS behind a proxy |
| `APP_CLIENT_IP_HEADER` | `CF-Connecting-IP`, so the login rate limit sees the visitor's real IP (Render sits behind Cloudflare) |

Render provides the `PORT` variable by itself, and the application listens on it. Leave `APP_CLIENT_IP_HEADER` unset
anywhere the application is not behind a proxy that overwrites that header, otherwise clients could spoof their IP.

## Authentication and authorization

The API uses stateless **JWT** authentication. Log in to get a token and send it in every request:
Expand Down Expand Up @@ -117,12 +146,11 @@ In Swagger UI, log in through `POST /auth/login`, click **Authorize** and paste
`admin12345`) and the JWT secret has a development value. These defaults exist for local use only. The `prod` profile
has **no defaults** and refuses to start without `JWT_SECRET`, `ADMIN_EMAIL` and `ADMIN_PASSWORD`.

Tokens are signed with HS256, Access tokens are signed with HS256 and expire after 15 minutes. Refresh tokens are opaque random strings, valid for
7 days, and can be exchanged for a new pair at `POST /auth/refresh` (each exchange rotates the refresh token — the
Access tokens are signed with HS256 and expire after 15 minutes. Refresh tokens are opaque random strings, valid for
7 days, and can be exchanged for a new pair at `POST /auth/refresh` (each exchange rotates the refresh token: the
old one stops working). `POST /auth/logout` revokes a refresh token immediately. Passwords are stored as BCrypt
hashes.


After 5 failed login attempts from the same IP address within 15 minutes, further attempts (even with the correct
password) are rejected with `429 Too Many Requests` and a `Retry-After` header, until the window passes. A successful
login resets the counter.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.serviceOrder.Management.config;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

// Decides which IP address identifies the caller (used by the login rate limiter).
// By default only the socket address is used: a client-supplied header could be spoofed.
// Behind a CDN that overwrites a header with the real client IP (Cloudflare's CF-Connecting-IP on Render),
// set app.client-ip-header to that header name.
@Component
public class ClientIpResolver {

private final String clientIpHeader;

public ClientIpResolver(@Value("${app.client-ip-header:}") String clientIpHeader) {
this.clientIpHeader = clientIpHeader.trim();
}

public String resolve(HttpServletRequest request) {
if (!clientIpHeader.isEmpty()) {
String value = request.getHeader(clientIpHeader);
if (value != null && !value.isBlank()) {
return value.trim();
}
}
return request.getRemoteAddr();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http,
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
// The first matching rule wins, so the specific rules come before anyRequest().
.authorizeHttpRequests(auth -> auth
.requestMatchers("/auth/login", "/auth/refresh", "/auth/logout").permitAll() .requestMatchers("/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs/**").permitAll()
.requestMatchers("/auth/login", "/auth/refresh", "/auth/logout").permitAll()
.requestMatchers("/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs/**").permitAll()
.requestMatchers(HttpMethod.PUT, "/users/me/password").authenticated()
.requestMatchers("/users/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.PUT, "/clients/**", "/technicians/**").hasRole("ADMIN")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.serviceOrder.Management.controllers;

import com.serviceOrder.Management.config.ClientIpResolver;
import com.serviceOrder.Management.controllers.exceptions.InvalidCredentialsException;
import com.serviceOrder.Management.dtos.CurrentUserDTO;
import com.serviceOrder.Management.dtos.LoginRequestDTO;
Expand Down Expand Up @@ -31,12 +32,14 @@ public class AuthController {
private final AuthService service;
private final LoginAttemptService loginAttemptService;
private final RefreshTokenService refreshTokenService;
private final ClientIpResolver clientIpResolver;

public AuthController(AuthService service, LoginAttemptService loginAttemptService,
RefreshTokenService refreshTokenService) {
RefreshTokenService refreshTokenService, ClientIpResolver clientIpResolver) {
this.service = service;
this.loginAttemptService = loginAttemptService;
this.refreshTokenService = refreshTokenService;
this.clientIpResolver = clientIpResolver;
}

@Operation(summary = "Logs in",
Expand All @@ -54,10 +57,8 @@ public AuthController(AuthService service, LoginAttemptService loginAttemptServi
@PostMapping(value = "/login")
public ResponseEntity<TokenResponseDTO> login(@Valid @RequestBody LoginRequestDTO dto,
HttpServletRequest request) {
// Not trusting a client-supplied X-Forwarded-For here, since this app has no trusted reverse
// proxy in front of it that would overwrite it: an attacker could otherwise spoof a new IP
// on every request and bypass the limit entirely.
String clientIp = request.getRemoteAddr();
// Client-supplied headers are ignored unless app.client-ip-header names one that a trusted CDN overwrites.
String clientIp = clientIpResolver.resolve(request);
loginAttemptService.checkAllowed(clientIp);

try {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.serviceOrder.Management.config;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletRequest;

import static org.junit.jupiter.api.Assertions.assertEquals;

class ClientIpResolverTest {

private MockHttpServletRequest requestFrom(String remoteAddr, String headerName, String headerValue) {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRemoteAddr(remoteAddr);
if (headerName != null) {
request.addHeader(headerName, headerValue);
}
return request;
}

@Test
@DisplayName("should ignore client headers when no header is configured")
void shouldUseRemoteAddressWhenNoHeaderIsConfigured() {
ClientIpResolver resolver = new ClientIpResolver("");

assertEquals("10.0.0.1", resolver.resolve(requestFrom("10.0.0.1", "CF-Connecting-IP", "203.0.113.5")));
}

@Test
@DisplayName("should use the configured header when it is present")
void shouldUseConfiguredHeader() {
ClientIpResolver resolver = new ClientIpResolver("CF-Connecting-IP");

assertEquals("203.0.113.5", resolver.resolve(requestFrom("10.0.0.1", "CF-Connecting-IP", " 203.0.113.5 ")));
}

@Test
@DisplayName("should fall back to the remote address when the configured header is missing or blank")
void shouldFallBackToRemoteAddress() {
ClientIpResolver resolver = new ClientIpResolver("CF-Connecting-IP");

assertEquals("10.0.0.1", resolver.resolve(requestFrom("10.0.0.1", null, null)));
assertEquals("10.0.0.1", resolver.resolve(requestFrom("10.0.0.1", "CF-Connecting-IP", " ")));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ void loginShouldReturnToken() throws Exception {
.andExpect(status().isOk())
.andExpect(jsonPath("$.accessToken").isNotEmpty())
.andExpect(jsonPath("$.tokenType").value("Bearer"))
.andExpect(jsonPath("$.expiresIn").value(900)); }
.andExpect(jsonPath("$.expiresIn").value(900));
}

@Test
@DisplayName("POST /auth/login should return 401 when the password is wrong")
Expand Down
Loading