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
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
21 changes: 17 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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`.
Expand Down Expand Up @@ -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.

Expand Down
4 changes: 2 additions & 2 deletions helm/Chart.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
2 changes: 1 addition & 1 deletion helm/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ revisionHistoryLimit: 3

image:
repository: digital-bank-java/api-gateway
tag: "0.0.2"
tag: "0.0.3"
pullPolicy: IfNotPresent

runtime:
Expand Down
14 changes: 14 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway-server-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-circuitbreaker-reactor-resilience4j</artifactId>
Expand All @@ -51,6 +55,16 @@
<artifactId>spring-boot-starter-webflux-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-testcontainers</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
Expand Down
Original file line number Diff line number Diff line change
@@ -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<IpNetwork> trustedProxies;

ClientAddressKeyResolver(List<String> trustedProxyDefinitions) {
trustedProxies = trustedProxyDefinitions.stream()
.map(IpNetwork::parse)
.toList();
}

Mono<String> 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<String> 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);
}
}
}
}
Original file line number Diff line number Diff line change
@@ -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<java.util.List<Long>> script,
org.springframework.cloud.gateway.support.ConfigurationService configurationService) {
super(redisTemplate, script, configurationService);
}

@Override
public Mono<RateLimiter.Response> 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;
}
}
Original file line number Diff line number Diff line change
@@ -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<List<Long>> script,
ConfigurationService configurationService) {
return new FailClosedRedisRateLimiter(redisTemplate, script, configurationService);
}

static final class GatewayRateLimitProperties {
private List<String> trustedProxies = List.of();

public List<String> getTrustedProxies() {
return trustedProxies;
}

public void setTrustedProxies(List<String> trustedProxies) {
this.trustedProxies = trustedProxies == null ? List.of() : List.copyOf(trustedProxies);
}
}
}
19 changes: 17 additions & 2 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"));
}
}
Loading
Loading