diff --git a/Dockerfile b/Dockerfile
index 8ad619e..8ac89c7 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -7,7 +7,7 @@ COPY mvnw pom.xml ./
RUN chmod +x mvnw && ./mvnw --batch-mode dependency:go-offline
COPY src/ src/
-RUN ./mvnw --batch-mode clean package
+RUN ./mvnw --batch-mode clean package -DskipTests
FROM eclipse-temurin:21-jre-jammy
diff --git a/README.md b/README.md
index 1ee7276..70141d2 100644
--- a/README.md
+++ b/README.md
@@ -7,7 +7,8 @@ Spring Cloud Gateway entry point for the Digital Bank Java platform.
- Provide the platform HTTP entry point for client-facing API traffic.
- Route requests to internal services through Kubernetes Service DNS names.
- Keep downstream services private inside the cluster for normal manual testing.
-- Host future cross-cutting gateway policies such as rate limits, auth enforcement, and correlation propagation.
+- Host cross-cutting gateway policies such as route-level rate limits and downstream resilience.
+- Leave authentication, authorization, and correlation propagation to their planned security slices.
## Non-Responsibilities
@@ -64,7 +65,7 @@ For integrated gateway routing, deploy the Gateway in SIT and use the API Gatewa
## Build Image
```bash
-docker build --tag digital-bank-java/api-gateway:0.0.2 .
+docker build --tag digital-bank-java/api-gateway:0.0.3 .
```
The image runs as numeric non-root user and group `10001:10001`.
@@ -113,15 +114,27 @@ The centralized internal API documentation UI is available at:
http://localhost:8080/admin/docs/swagger-ui.html
```
+## Redis-backed Rate Limiting
+
+Public customer and account routes in SIT use the shared Redis service for route-level token-bucket limits. The current SIT policy allows 10 requested tokens per second with a burst capacity of 20 and one token per request. Requests that exceed the available bucket receive `429 Too Many Requests`.
+
+The policy is stored in `config-repo/api-gateway/api-gateway-sit.yml`, so limits can be tuned without rebuilding the gateway image. A gateway rollout is required after changing route configuration because route definitions are loaded during startup.
+
+The current unauthenticated SIT key is the request client IP address. With no trusted proxies configured, the gateway uses the socket peer and ignores `X-Forwarded-For`, so a client cannot spoof its rate-limit identity by sending that header. When the gateway is placed behind an approved ingress or load balancer, configure its proxy IP addresses or CIDR ranges through `gateway.rate-limit.trusted-proxies`; only then will the gateway parse the forwarding chain, from right to left, and select the first untrusted address. Once gateway authentication exists, the key should be changed to a trusted authenticated subject or tenant identity. Do not use arbitrary client-supplied headers as production rate-limit keys.
+
+Redis is a shared coordination dependency: all gateway replicas must use the same Redis service for consistent limits. Local SIT uses the in-cluster `redis` Service; UAT and production should use a managed Redis-compatible service with authentication, encryption, replication, failover, backups, and monitoring.
+
+The gateway applies a fail-closed policy to Redis rate-limit errors. Spring Cloud Gateway's Redis limiter uses a remaining-token value of `-1` when its Redis script cannot complete; this gateway converts that sentinel into a denied decision instead of silently allowing traffic. Redis health, error rates, and resulting `429` responses must be monitored so an unavailable limiter is restored quickly. This policy is intentionally local/SIT-safe and should be reviewed with the production platform team before promotion.
+
## Security And Environment Promotion
-The gateway is an internal Kubernetes `ClusterIP` Service in SIT. Circuit breaking and safe-read retries are implemented as cross-cutting availability controls. Authentication, authorization, Redis-backed rate limiting, and correlation propagation remain planned capabilities.
+The gateway is an internal Kubernetes `ClusterIP` Service in SIT. Circuit breaking, safe-read retries, and Redis-backed rate limiting are implemented as cross-cutting availability controls. Authentication, authorization, and correlation propagation remain planned capabilities.
## Downstream Resilience
The gateway applies a Resilience4j circuit breaker to downstream routes and returns a stable `503 Service Unavailable` Problem Details response when a downstream service cannot be reached. The fallback does not expose downstream hostnames or exception details.
-The built-in Gateway retry filter is restricted to `GET` requests and server-error responses. POST, PUT, PATCH, and DELETE requests are deliberately excluded because retrying a mutation can duplicate a business operation. Retry count and circuit-breaker thresholds are property-driven and can be overridden through the environment-specific Config Server repository later.
+The built-in Gateway retry filter is restricted to `GET`, `HEAD`, and `OPTIONS` requests and the explicit upstream statuses `500`, `502`, `503`, and `504`. It allows at most two retries with a bounded exponential backoff from 50 ms to 250 ms. POST, PUT, PATCH, and DELETE requests are deliberately excluded because retrying a mutation can duplicate a business operation. Retry count and circuit-breaker thresholds are property-driven and can be overridden through the environment-specific Config Server repository later.
The retry and circuit-breaker policies are availability controls, not replacements for idempotency keys, transactional guarantees, or service-level authorization.
diff --git a/helm/Chart.yaml b/helm/Chart.yaml
index 83a6513..052c987 100644
--- a/helm/Chart.yaml
+++ b/helm/Chart.yaml
@@ -2,5 +2,5 @@ apiVersion: v2
name: api-gateway
description: API gateway for the Digital Bank Java platform
type: application
-version: 0.2.0
-appVersion: "0.0.2"
+version: 0.3.0
+appVersion: "0.0.3"
diff --git a/helm/values.yaml b/helm/values.yaml
index 8f65732..8f18ad7 100644
--- a/helm/values.yaml
+++ b/helm/values.yaml
@@ -5,7 +5,7 @@ revisionHistoryLimit: 3
image:
repository: digital-bank-java/api-gateway
- tag: "0.0.2"
+ tag: "0.0.3"
pullPolicy: IfNotPresent
runtime:
diff --git a/pom.xml b/pom.xml
index 38f92c6..f4a5157 100644
--- a/pom.xml
+++ b/pom.xml
@@ -31,6 +31,10 @@
org.springframework.cloud
spring-cloud-starter-gateway-server-webflux
+
+ org.springframework.boot
+ spring-boot-starter-data-redis-reactive
+
org.springframework.cloud
spring-cloud-starter-circuitbreaker-reactor-resilience4j
@@ -51,6 +55,16 @@
spring-boot-starter-webflux-test
test
+
+ org.springframework.boot
+ spring-boot-testcontainers
+ test
+
+
+ org.testcontainers
+ testcontainers-junit-jupiter
+ test
+
diff --git a/src/main/java/com/digitalbank/apigateway/ClientAddressKeyResolver.java b/src/main/java/com/digitalbank/apigateway/ClientAddressKeyResolver.java
new file mode 100644
index 0000000..496ad83
--- /dev/null
+++ b/src/main/java/com/digitalbank/apigateway/ClientAddressKeyResolver.java
@@ -0,0 +1,145 @@
+package com.digitalbank.apigateway;
+
+import java.net.InetAddress;
+import java.util.List;
+
+import org.springframework.http.HttpHeaders;
+import org.springframework.web.server.ServerWebExchange;
+
+import reactor.core.publisher.Mono;
+
+/** Resolves a client address without trusting forwarding headers from an untrusted peer. */
+final class ClientAddressKeyResolver {
+
+ private static final String X_FORWARDED_FOR = "X-Forwarded-For";
+
+ private final List trustedProxies;
+
+ ClientAddressKeyResolver(List trustedProxyDefinitions) {
+ trustedProxies = trustedProxyDefinitions.stream()
+ .map(IpNetwork::parse)
+ .toList();
+ }
+
+ Mono resolve(ServerWebExchange exchange) {
+ var remoteAddress = exchange.getRequest().getRemoteAddress();
+ if (remoteAddress == null || remoteAddress.getAddress() == null) {
+ return Mono.empty();
+ }
+
+ var peer = remoteAddress.getAddress();
+ if (!isTrusted(peer)) {
+ return Mono.just(peer.getHostAddress());
+ }
+
+ return forwardedClientAddress(exchange.getRequest().getHeaders(), peer);
+ }
+
+ private Mono forwardedClientAddress(HttpHeaders headers, InetAddress peer) {
+ var value = headers.getFirst(X_FORWARDED_FOR);
+ if (value == null || value.isBlank()) {
+ return Mono.just(peer.getHostAddress());
+ }
+
+ var addresses = value.split(",", -1);
+ for (var index = addresses.length - 1; index >= 0; index--) {
+ var address = parseAddress(addresses[index]);
+ if (address == null) {
+ return Mono.empty();
+ }
+ if (!isTrusted(address)) {
+ return Mono.just(address.getHostAddress());
+ }
+ }
+ return Mono.just(peer.getHostAddress());
+ }
+
+ private boolean isTrusted(InetAddress address) {
+ return trustedProxies.stream().anyMatch(network -> network.contains(address));
+ }
+
+ private static InetAddress parseAddress(String value) {
+ var trimmed = value.trim();
+ if (trimmed.isBlank() || !trimmed.matches("[0-9a-fA-F:.]+")) {
+ return null;
+ }
+ try {
+ return InetAddress.getByName(trimmed);
+ }
+ catch (java.net.UnknownHostException exception) {
+ return null;
+ }
+ }
+
+ private record IpNetwork(InetAddress networkAddress, int prefixLength) {
+
+ static IpNetwork parse(String definition) {
+ var parts = definition.trim().split("/", 2);
+ if (parts.length == 0 || parts[0].isBlank()) {
+ throw new IllegalArgumentException("Trusted proxy address must not be blank");
+ }
+
+ var address = parseAddress(parts[0]);
+ if (address == null) {
+ throw new IllegalArgumentException("Invalid trusted proxy address: " + definition);
+ }
+ var addressBits = address.getAddress().length * 8;
+ var prefix = parts.length == 1 ? addressBits : parsePrefix(parts[1], definition);
+ if (prefix < 0 || prefix > addressBits) {
+ throw new IllegalArgumentException("Invalid trusted proxy CIDR: " + definition);
+ }
+
+ return new IpNetwork(mask(address, prefix), prefix);
+ }
+
+ boolean contains(InetAddress address) {
+ var candidate = address.getAddress();
+ var network = networkAddress.getAddress();
+ if (candidate.length != network.length) {
+ return false;
+ }
+
+ var completeBytes = prefixLength / 8;
+ var remainingBits = prefixLength % 8;
+ for (var index = 0; index < completeBytes; index++) {
+ if (candidate[index] != network[index]) {
+ return false;
+ }
+ }
+ if (remainingBits == 0) {
+ return true;
+ }
+
+ var mask = (byte) (0xff << (8 - remainingBits));
+ return (candidate[completeBytes] & mask) == (network[completeBytes] & mask);
+ }
+
+ private static int parsePrefix(String value, String definition) {
+ try {
+ return Integer.parseInt(value);
+ }
+ catch (NumberFormatException exception) {
+ throw new IllegalArgumentException("Invalid trusted proxy CIDR: " + definition, exception);
+ }
+ }
+
+ private static InetAddress mask(InetAddress address, int prefix) {
+ var bytes = address.getAddress();
+ var fullBytes = prefix / 8;
+ var remainingBits = prefix % 8;
+ if (remainingBits > 0 && fullBytes < bytes.length) {
+ bytes[fullBytes] = (byte) (bytes[fullBytes] & (0xff << (8 - remainingBits)));
+ fullBytes++;
+ }
+ while (fullBytes < bytes.length) {
+ bytes[fullBytes++] = 0;
+ }
+ try {
+ return InetAddress.getByAddress(bytes);
+ }
+ catch (java.net.UnknownHostException exception) {
+ throw new IllegalArgumentException("Invalid trusted proxy address", exception);
+ }
+ }
+ }
+}
diff --git a/src/main/java/com/digitalbank/apigateway/FailClosedRedisRateLimiter.java b/src/main/java/com/digitalbank/apigateway/FailClosedRedisRateLimiter.java
new file mode 100644
index 0000000..1c28018
--- /dev/null
+++ b/src/main/java/com/digitalbank/apigateway/FailClosedRedisRateLimiter.java
@@ -0,0 +1,31 @@
+package com.digitalbank.apigateway;
+
+import org.springframework.cloud.gateway.filter.ratelimit.RateLimiter;
+import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter;
+import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
+import org.springframework.data.redis.core.script.RedisScript;
+
+import reactor.core.publisher.Mono;
+
+/** Converts the Gateway Redis limiter's error sentinel into an explicit deny decision. */
+final class FailClosedRedisRateLimiter extends RedisRateLimiter {
+
+ FailClosedRedisRateLimiter(ReactiveStringRedisTemplate redisTemplate,
+ RedisScript> script,
+ org.springframework.cloud.gateway.support.ConfigurationService configurationService) {
+ super(redisTemplate, script, configurationService);
+ }
+
+ @Override
+ public Mono isAllowed(String routeId, String id) {
+ return super.isAllowed(routeId, id).map(FailClosedRedisRateLimiter::applyFailurePolicy);
+ }
+
+ static RateLimiter.Response applyFailurePolicy(RateLimiter.Response response) {
+ var remaining = response.getHeaders().get(RedisRateLimiter.REMAINING_HEADER);
+ if (response.isAllowed() && "-1".equals(remaining)) {
+ return new RateLimiter.Response(false, response.getHeaders());
+ }
+ return response;
+ }
+}
diff --git a/src/main/java/com/digitalbank/apigateway/GatewayRateLimitingConfiguration.java b/src/main/java/com/digitalbank/apigateway/GatewayRateLimitingConfiguration.java
new file mode 100644
index 0000000..1c845b0
--- /dev/null
+++ b/src/main/java/com/digitalbank/apigateway/GatewayRateLimitingConfiguration.java
@@ -0,0 +1,52 @@
+package com.digitalbank.apigateway;
+
+import java.util.List;
+
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
+import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter;
+import org.springframework.cloud.gateway.support.ConfigurationService;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Primary;
+import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
+import org.springframework.data.redis.core.script.RedisScript;
+
+/** Provides rate-limit identity and the explicit SIT Redis failure policy. */
+@Configuration(proxyBeanMethods = false)
+class GatewayRateLimitingConfiguration {
+
+ @Bean
+ @ConfigurationProperties("gateway.rate-limit")
+ GatewayRateLimitProperties gatewayRateLimitProperties() {
+ return new GatewayRateLimitProperties();
+ }
+
+ @Bean
+ @Primary
+ KeyResolver rateLimitKeyResolver(GatewayRateLimitProperties properties) {
+ var resolver = new ClientAddressKeyResolver(properties.getTrustedProxies());
+ return resolver::resolve;
+ }
+
+ @Bean
+ @Primary
+ RedisRateLimiter failClosedRedisRateLimiter(ReactiveStringRedisTemplate redisTemplate,
+ @Qualifier("redisRequestRateLimiterScript") RedisScript> script,
+ ConfigurationService configurationService) {
+ return new FailClosedRedisRateLimiter(redisTemplate, script, configurationService);
+ }
+
+ static final class GatewayRateLimitProperties {
+ private List trustedProxies = List.of();
+
+ public List getTrustedProxies() {
+ return trustedProxies;
+ }
+
+ public void setTrustedProxies(List trustedProxies) {
+ this.trustedProxies = trustedProxies == null ? List.of() : List.copyOf(trustedProxies);
+ }
+ }
+}
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index c01a995..c9b0528 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -9,16 +9,31 @@ spring:
- name: Retry
args:
retries: ${gateway.resilience.retry.retries:2}
- methods: GET
- series: SERVER_ERROR
+ methods: GET,HEAD,OPTIONS
+ statuses:
+ - INTERNAL_SERVER_ERROR
+ - BAD_GATEWAY
+ - SERVICE_UNAVAILABLE
+ - GATEWAY_TIMEOUT
+ backoff:
+ firstBackoff: ${gateway.resilience.retry.first-backoff:50ms}
+ maxBackoff: ${gateway.resilience.retry.max-backoff:250ms}
+ factor: ${gateway.resilience.retry.factor:2}
+ basedOnPreviousValue: ${gateway.resilience.retry.based-on-previous-value:true}
httpclient:
connect-timeout: ${gateway.resilience.timeout.connect-timeout:1000}
response-timeout: ${gateway.resilience.timeout.response-timeout:2s}
gateway:
+ rate-limit:
+ trusted-proxies: []
resilience:
retry:
retries: 2
+ first-backoff: 50ms
+ max-backoff: 250ms
+ factor: 2
+ based-on-previous-value: true
timeout:
connect-timeout: 1000
response-timeout: 2s
diff --git a/src/test/java/com/digitalbank/apigateway/ApiGatewayRouteIntegrationTests.java b/src/test/java/com/digitalbank/apigateway/ApiGatewayRouteIntegrationTests.java
index 90fbc04..bbe13c4 100644
--- a/src/test/java/com/digitalbank/apigateway/ApiGatewayRouteIntegrationTests.java
+++ b/src/test/java/com/digitalbank/apigateway/ApiGatewayRouteIntegrationTests.java
@@ -23,7 +23,8 @@
"resilience4j.circuitbreaker.configs.gatewayDownstream.slidingWindowSize=1",
"resilience4j.circuitbreaker.configs.gatewayDownstream.waitDurationInOpenState=1h",
"gateway.resilience.timeout.connect-timeout=100",
- "gateway.resilience.timeout.response-timeout=100ms" })
+ "gateway.resilience.timeout.response-timeout=100ms",
+ "management.health.redis.enabled=false" })
class ApiGatewayRouteIntegrationTests {
@LocalServerPort
@@ -103,7 +104,13 @@ void internalFallbackPathIsNotAnExposedGatewayEndpoint() {
@Test
void retryFilterOnlyTargetsSafeGetRequests() {
- assertEquals("GET", environment
+ assertEquals("GET,HEAD,OPTIONS", environment
.getProperty("spring.cloud.gateway.server.webflux.default-filters[0].args.methods"));
+ assertEquals("INTERNAL_SERVER_ERROR", environment
+ .getProperty("spring.cloud.gateway.server.webflux.default-filters[0].args.statuses[0]"));
+ assertEquals("GATEWAY_TIMEOUT", environment
+ .getProperty("spring.cloud.gateway.server.webflux.default-filters[0].args.statuses[3]"));
+ assertEquals("50ms", environment
+ .getProperty("spring.cloud.gateway.server.webflux.default-filters[0].args.backoff.firstBackoff"));
}
}
diff --git a/src/test/java/com/digitalbank/apigateway/ClientAddressKeyResolverTests.java b/src/test/java/com/digitalbank/apigateway/ClientAddressKeyResolverTests.java
new file mode 100644
index 0000000..0c22c86
--- /dev/null
+++ b/src/test/java/com/digitalbank/apigateway/ClientAddressKeyResolverTests.java
@@ -0,0 +1,46 @@
+package com.digitalbank.apigateway;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+import java.net.InetSocketAddress;
+import java.util.List;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
+import org.springframework.mock.web.server.MockServerWebExchange;
+
+class ClientAddressKeyResolverTests {
+
+ @Test
+ void usesSocketPeerWhenForwardingPeerIsNotTrusted() {
+ var resolver = new ClientAddressKeyResolver(List.of("10.0.0.0/8"));
+ var exchange = exchange("192.0.2.10", "198.51.100.20");
+
+ assertEquals("192.0.2.10", resolver.resolve(exchange).block());
+ }
+
+ @Test
+ void resolvesFirstUntrustedAddressFromTrustedProxyChain() {
+ var resolver = new ClientAddressKeyResolver(List.of("10.0.0.0/8"));
+ var exchange = exchange("10.1.2.3", "198.51.100.20, 10.9.8.7");
+
+ assertEquals("198.51.100.20", resolver.resolve(exchange).block());
+ }
+
+ @Test
+ void rejectsMalformedForwardingChainFromTrustedPeer() {
+ var resolver = new ClientAddressKeyResolver(List.of("10.0.0.0/8"));
+ var exchange = exchange("10.1.2.3", "not-an-ip");
+
+ assertNull(resolver.resolve(exchange).block());
+ }
+
+ private static MockServerWebExchange exchange(String peer, String forwardedFor) {
+ var request = MockServerHttpRequest.get("/")
+ .remoteAddress(new InetSocketAddress(peer, 1234))
+ .header("X-Forwarded-For", forwardedFor)
+ .build();
+ return MockServerWebExchange.from(request);
+ }
+}
diff --git a/src/test/java/com/digitalbank/apigateway/FailClosedRedisRateLimiterTests.java b/src/test/java/com/digitalbank/apigateway/FailClosedRedisRateLimiterTests.java
new file mode 100644
index 0000000..e5694ea
--- /dev/null
+++ b/src/test/java/com/digitalbank/apigateway/FailClosedRedisRateLimiterTests.java
@@ -0,0 +1,36 @@
+package com.digitalbank.apigateway;
+
+import static java.util.Map.of;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.cloud.gateway.filter.ratelimit.RateLimiter;
+import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter;
+
+class FailClosedRedisRateLimiterTests {
+
+ @Test
+ void convertsRedisErrorSentinelIntoDeniedResponse() {
+ var response = new RateLimiter.Response(true,
+ of(RedisRateLimiter.REMAINING_HEADER, "-1"));
+
+ var result = FailClosedRedisRateLimiter.applyFailurePolicy(response);
+
+ assertFalse(result.isAllowed());
+ assertEquals(response.getHeaders(), result.getHeaders());
+ }
+
+ @Test
+ void preservesNormalAllowedResponse() {
+ var response = new RateLimiter.Response(true,
+ of(RedisRateLimiter.REMAINING_HEADER, "19"));
+
+ var result = FailClosedRedisRateLimiter.applyFailurePolicy(response);
+
+ assertTrue(result.isAllowed());
+ assertSame(response, result);
+ }
+}
diff --git a/src/test/java/com/digitalbank/apigateway/GatewayRateLimitingIntegrationTests.java b/src/test/java/com/digitalbank/apigateway/GatewayRateLimitingIntegrationTests.java
new file mode 100644
index 0000000..83cca53
--- /dev/null
+++ b/src/test/java/com/digitalbank/apigateway/GatewayRateLimitingIntegrationTests.java
@@ -0,0 +1,89 @@
+package com.digitalbank.apigateway;
+
+import static java.util.Map.of;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.context.TestConfiguration;
+import org.springframework.boot.test.web.server.LocalServerPort;
+import org.springframework.cloud.gateway.event.FilterArgsEvent;
+import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
+import org.springframework.context.ApplicationEventPublisher;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Import;
+import org.springframework.test.context.DynamicPropertyRegistry;
+import org.springframework.test.context.DynamicPropertySource;
+import org.testcontainers.containers.GenericContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+import org.springframework.test.web.reactive.server.WebTestClient;
+
+import reactor.core.publisher.Mono;
+
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {
+ "spring.config.import=",
+ "spring.cloud.config.enabled=false",
+ "spring.cloud.gateway.server.webflux.routes[0].id=rate-limited-health",
+ "spring.cloud.gateway.server.webflux.routes[0].uri=forward:/actuator/health",
+ "spring.cloud.gateway.server.webflux.routes[0].predicates[0]=Path=/gateway-test/rate-limited-health",
+ "spring.cloud.gateway.server.webflux.routes[0].filters[0]=RequestRateLimiter",
+ "spring.cloud.gateway.server.webflux.routes[0].filters[0].args.key-resolver=#{@clientAddressKeyResolver}",
+ "spring.cloud.gateway.server.webflux.routes[0].filters[0].args.redis-rate-limiter.replenish-rate=1",
+ "spring.cloud.gateway.server.webflux.routes[0].filters[0].args.redis-rate-limiter.burst-capacity=1",
+ "spring.cloud.gateway.server.webflux.routes[0].filters[0].args.redis-rate-limiter.requested-tokens=1",
+ "management.health.redis.enabled=false" })
+@Import(GatewayRateLimitingIntegrationTests.TestRateLimitingConfiguration.class)
+@Testcontainers
+class GatewayRateLimitingIntegrationTests {
+
+ @Container
+ static final GenericContainer> redis = new GenericContainer<>("redis:7.4-alpine")
+ .withExposedPorts(6379);
+
+ @DynamicPropertySource
+ static void redisProperties(DynamicPropertyRegistry registry) {
+ registry.add("spring.data.redis.host", redis::getHost);
+ registry.add("spring.data.redis.port", redis::getFirstMappedPort);
+ }
+
+ @LocalServerPort
+ private int port;
+
+ @Autowired
+ private ApplicationEventPublisher applicationEventPublisher;
+
+ private WebTestClient client;
+
+ @BeforeEach
+ void setUp() {
+ applicationEventPublisher.publishEvent(new FilterArgsEvent(this, "rate-limited-health", of(
+ "redis-rate-limiter.replenishRate", "1",
+ "redis-rate-limiter.burstCapacity", "1",
+ "redis-rate-limiter.requestedTokens", "1")));
+ client = WebTestClient.bindToServer().baseUrl("http://localhost:" + port).build();
+ }
+
+ @Test
+ void routeRejectsRequestsAfterConfiguredBurstIsConsumed() {
+ client.get()
+ .uri("/gateway-test/rate-limited-health")
+ .exchange()
+ .expectStatus().isOk();
+
+ client.get()
+ .uri("/gateway-test/rate-limited-health")
+ .exchange()
+ .expectStatus().isEqualTo(429);
+ }
+
+ @TestConfiguration(proxyBeanMethods = false)
+ static final class TestRateLimitingConfiguration {
+
+ @Bean
+ KeyResolver clientAddressKeyResolver() {
+ return exchange -> Mono.just("test-client");
+ }
+ }
+}
diff --git a/src/test/java/com/digitalbank/apigateway/GatewayResilienceIntegrationTests.java b/src/test/java/com/digitalbank/apigateway/GatewayResilienceIntegrationTests.java
index 6b3cb38..5ff3c73 100644
--- a/src/test/java/com/digitalbank/apigateway/GatewayResilienceIntegrationTests.java
+++ b/src/test/java/com/digitalbank/apigateway/GatewayResilienceIntegrationTests.java
@@ -36,7 +36,8 @@
"gateway.resilience.circuit-breaker.sliding-window-size=2",
"gateway.resilience.circuit-breaker.failure-rate-threshold=50",
"gateway.resilience.timeout.connect-timeout=100",
- "gateway.resilience.timeout.response-timeout=50ms" })
+ "gateway.resilience.timeout.response-timeout=50ms",
+ "management.health.redis.enabled=false" })
@Import(GatewayResilienceIntegrationTests.TestRouteConfiguration.class)
class GatewayResilienceIntegrationTests {