From bf0a634b2b44b2cc9810e7c598113e12bddea107 Mon Sep 17 00:00:00 2001 From: Ismael Neto <114830206+otaldoneto@users.noreply.github.com> Date: Wed, 23 Sep 2026 14:23:54 -0300 Subject: [PATCH] feat: live demo docs and real client IP behind Cloudflare for the login rate limit --- README.md | 34 ++++++++++++-- .../Management/config/ClientIpResolver.java | 29 ++++++++++++ .../Management/config/SecurityConfig.java | 3 +- .../controllers/AuthController.java | 11 ++--- .../config/ClientIpResolverTest.java | 44 +++++++++++++++++++ .../controllers/AuthenticationTest.java | 3 +- 6 files changed, 114 insertions(+), 10 deletions(-) create mode 100644 src/main/java/com/serviceOrder/Management/config/ClientIpResolver.java create mode 100644 src/test/java/com/serviceOrder/Management/config/ClientIpResolverTest.java diff --git a/README.md b/README.md index f7a8f8e..582ca24 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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:///?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: @@ -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. diff --git a/src/main/java/com/serviceOrder/Management/config/ClientIpResolver.java b/src/main/java/com/serviceOrder/Management/config/ClientIpResolver.java new file mode 100644 index 0000000..cbbd152 --- /dev/null +++ b/src/main/java/com/serviceOrder/Management/config/ClientIpResolver.java @@ -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(); + } +} diff --git a/src/main/java/com/serviceOrder/Management/config/SecurityConfig.java b/src/main/java/com/serviceOrder/Management/config/SecurityConfig.java index 1a6f1eb..a614896 100644 --- a/src/main/java/com/serviceOrder/Management/config/SecurityConfig.java +++ b/src/main/java/com/serviceOrder/Management/config/SecurityConfig.java @@ -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") diff --git a/src/main/java/com/serviceOrder/Management/controllers/AuthController.java b/src/main/java/com/serviceOrder/Management/controllers/AuthController.java index 65faa7a..5f2b7b4 100644 --- a/src/main/java/com/serviceOrder/Management/controllers/AuthController.java +++ b/src/main/java/com/serviceOrder/Management/controllers/AuthController.java @@ -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; @@ -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", @@ -54,10 +57,8 @@ public AuthController(AuthService service, LoginAttemptService loginAttemptServi @PostMapping(value = "/login") public ResponseEntity 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 { diff --git a/src/test/java/com/serviceOrder/Management/config/ClientIpResolverTest.java b/src/test/java/com/serviceOrder/Management/config/ClientIpResolverTest.java new file mode 100644 index 0000000..217c240 --- /dev/null +++ b/src/test/java/com/serviceOrder/Management/config/ClientIpResolverTest.java @@ -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", " "))); + } +} diff --git a/src/test/java/com/serviceOrder/Management/controllers/AuthenticationTest.java b/src/test/java/com/serviceOrder/Management/controllers/AuthenticationTest.java index 08a7247..ff9915f 100644 --- a/src/test/java/com/serviceOrder/Management/controllers/AuthenticationTest.java +++ b/src/test/java/com/serviceOrder/Management/controllers/AuthenticationTest.java @@ -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")