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
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Spring Cloud Gateway entry point for the Digital Bank Java platform.
- Route requests to internal services through Kubernetes Service DNS names.
- Keep downstream services private inside the cluster for normal manual testing.
- 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.
- Propagate a bounded correlation ID and emit structured request-completion logs without logging sensitive request data.

## Non-Responsibilities

Expand Down Expand Up @@ -114,6 +114,12 @@ The centralized internal API documentation UI is available at:
http://localhost:8080/admin/docs/swagger-ui.html
```

## Correlation And Request Logs

Every gateway exchange receives an `X-Correlation-ID` response header. A caller-provided value is reused only when it starts with an ASCII letter or digit and contains at most 96 ASCII letters, digits, `.`, `_`, `:`, or `-` characters. Invalid, blank, or oversized values are replaced with a generated UUID. The same value is added to the downstream request so service logs can correlate the exchange.

The gateway emits one ECS-formatted JSON completion event per exchange. It contains the service, environment, method, Gateway route ID, response status, correlation ID, duration, and reactive completion signal. Authorization headers, cookies, tokens, request bodies, account data, customer data, and payment data are deliberately excluded.

## Gateway Authorization And Environment Promotion

The gateway is an internal Kubernetes `ClusterIP` Service in SIT. When `gateway.security.enabled` is true, it validates JWTs and enforces these scopes:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package com.digitalbank.apigateway;

import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;

import reactor.core.publisher.Mono;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR;

/** Adds a bounded correlation identifier to every gateway exchange. */
@Component
@Order(-100)
public final class CorrelationIdWebFilter implements WebFilter {

static final String CORRELATION_ID_HEADER = "X-Correlation-ID";

private static final int MAX_CORRELATION_ID_LENGTH = 96;
private static final Pattern SAFE_CORRELATION_ID = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,95}");
private static final Logger LOGGER = LoggerFactory.getLogger(CorrelationIdWebFilter.class);

private final String environment;

public CorrelationIdWebFilter(
@Value("${digital-bank.service.runtime-profile:${spring.profiles.active:sit}}") String environment) {
this.environment = environment;
}

@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
String correlationId = resolveCorrelationId(exchange.getRequest().getHeaders().getFirst(CORRELATION_ID_HEADER));
ServerHttpRequest request = exchange.getRequest().mutate().header(CORRELATION_ID_HEADER, correlationId).build();
ServerWebExchange correlatedExchange = exchange.mutate().request(request).build();
correlatedExchange.getResponse().getHeaders().set(CORRELATION_ID_HEADER, correlationId);
long startedAt = System.nanoTime();

return chain.filter(correlatedExchange).doFinally(signalType -> logCompletion(correlatedExchange, correlationId,
startedAt, signalType.name()));
}

static String resolveCorrelationId(String candidate) {
if (candidate != null && candidate.length() <= MAX_CORRELATION_ID_LENGTH
&& SAFE_CORRELATION_ID.matcher(candidate).matches()) {
return candidate;
}
return UUID.randomUUID().toString();
}

private void logCompletion(ServerWebExchange exchange, String correlationId, long startedAt, String signal) {
int status = exchange.getResponse().getStatusCode() == null ? 500
: exchange.getResponse().getStatusCode().value();
Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
String routeId = route == null || route.getId() == null || route.getId().isBlank() ? "unmatched" : route.getId();
String method = exchange.getRequest().getMethod() == null ? "UNKNOWN" : exchange.getRequest().getMethod().name();

LOGGER.atInfo()
.addKeyValue("event.name", "gateway.request.completed")
.addKeyValue("digital_bank.environment", environment)
.addKeyValue("http.request.method", method)
.addKeyValue("http.route", routeId)
.addKeyValue("http.response.status_code", status)
.addKeyValue("correlation.id", correlationId)
.addKeyValue("event.duration_ms", TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startedAt))
.addKeyValue("reactor.signal", signal)
.log("Gateway request completed");
}
}
5 changes: 5 additions & 0 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,11 @@ springdoc:
swagger-ui:
enabled: false

logging:
structured:
format:
console: ecs

management:
endpoints:
web:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,30 @@ void healthEndpointReportsUp() {
.uri("/actuator/health")
.exchange()
.expectStatus().isOk()
.expectHeader().valueMatches(CorrelationIdWebFilter.CORRELATION_ID_HEADER,
"[A-Za-z0-9][A-Za-z0-9._:-]{0,95}")
.expectBody()
.jsonPath("$.status").isEqualTo("UP");
}

@Test
void validCorrelationIdIsReturnedAndInvalidValueIsReplaced() {
client.get()
.uri("/actuator/health")
.header(CorrelationIdWebFilter.CORRELATION_ID_HEADER, "insomnia-request-001")
.exchange()
.expectStatus().isOk()
.expectHeader().valueEquals(CorrelationIdWebFilter.CORRELATION_ID_HEADER, "insomnia-request-001");

client.get()
.uri("/actuator/health")
.header(CorrelationIdWebFilter.CORRELATION_ID_HEADER, "contains spaces")
.exchange()
.expectStatus().isOk()
.expectHeader().valueMatches(CorrelationIdWebFilter.CORRELATION_ID_HEADER,
"[A-Za-z0-9][A-Za-z0-9._:-]{0,95}");
}

@Test
void routeForwardsToConfiguredDownstreamService() {
client.get()
Expand Down Expand Up @@ -112,5 +132,6 @@ void retryFilterOnlyTargetsSafeGetRequests() {
.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"));
assertEquals("ecs", environment.getProperty("logging.structured.format.console"));
}
}