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: 2 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ kubectl port-forward svc/api-gateway 8080:8080 -n digital-bank-sit

- Centralized Swagger/OpenAPI access should be exposed here, not by telling users to hit each downstream service directly.
- Admin documentation routes are internal tooling and should stay clearly separated from public customer APIs.
- Gateway authorization is feature-flagged with `gateway.security.enabled`; SIT enables it through Helm and injects the JWT secret from Kubernetes Secret.
- Keep JWT validation at the gateway aligned with downstream scopes: `admin.internal`, `mfa.internal`, `transaction.internal`, and `payment.internal`.

## Working Rules

Expand Down
19 changes: 17 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ Spring Cloud Gateway entry point for the Digital Bank Java platform.
- Business-domain logic.
- Persistence.
- Service discovery through Eureka.
- Authentication implementation in the initial slice.
- Domain authentication and token issuance. The gateway validates bearer tokens and applies route-level authorization.

## Runtime Model

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

## 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:

- `admin.internal` for `/admin/**` and centralized API documentation.
- `mfa.internal` for `/api/v1/mfa/**`.
- `transaction.internal` for `/internal/v1/transfer-workflows/**`.
- `payment.internal` for `/internal/v1/payment-instructions/**`.

Customer and account APIs require an authenticated token. Health endpoints and Auth login remain public. Requests that do not authenticate receive `401` Problem Details; authenticated requests without the required scope receive `403` Problem Details.

SIT uses a base64-encoded HMAC secret supplied through the Kubernetes `auth-service-secrets` Secret. UAT and PROD should use the same application contract with an AWS-managed secret or an OIDC/JWK issuer; no token secret belongs in Git. The chart keeps security disabled by default outside an explicitly enabled environment.

Circuit breaking and safe-read retries are independent availability controls. They do not replace service authorization, idempotency keys, transactional guarantees, or audit controls.

## 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`.
Expand All @@ -128,7 +143,7 @@ The gateway applies a fail-closed policy to Redis rate-limit errors. Spring Clou

## Security And Environment Promotion

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.
The gateway is an internal Kubernetes `ClusterIP` Service in SIT. Circuit breaking, safe-read retries, Redis-backed rate limiting, authentication, and authorization are cross-cutting controls. They do not replace service-level idempotency, transactional guarantees, or audit controls.

## Downstream Resilience

Expand Down
9 changes: 9 additions & 0 deletions helm/templates/deployment.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,15 @@ spec:
value: {{ .Values.runtime.configServerUrl | quote }}
- name: SPRING_PROFILES_ACTIVE
value: {{ .Values.runtime.profile | quote }}
- name: GATEWAY_SECURITY_ENABLED
value: {{ .Values.security.enabled | quote }}
{{- if .Values.security.enabled }}
- name: AUTH_JWT_SECRET
valueFrom:
secretKeyRef:
name: {{ .Values.security.secretName | quote }}
key: {{ .Values.security.secretKey | quote }}
{{- end }}
securityContext:
{{- toYaml .Values.containerSecurityContext | nindent 12 }}
ports:
Expand Down
3 changes: 3 additions & 0 deletions helm/values-sit.yaml
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
runtime:
profile: sit
configServerUrl: http://config-server:8888

security:
enabled: true
5 changes: 5 additions & 0 deletions helm/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ runtime:
profile: sit
configServerUrl: http://config-server:8888

security:
enabled: false
secretName: auth-service-secrets
secretKey: jwt-secret

service:
type: ClusterIP
port: 8080
Expand Down
8 changes: 8 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,14 @@
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-circuitbreaker-reactor-resilience4j</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webflux-ui</artifactId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package com.digitalbank.apigateway.security;

import java.util.Base64;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtValidators;
import org.springframework.security.oauth2.jwt.NimbusReactiveJwtDecoder;
import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder;
import org.springframework.security.oauth2.jwt.ReactiveJwtDecoders;
import org.springframework.util.StringUtils;

@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(name = "gateway.security.enabled", havingValue = "true")
class GatewayJwtDecoderConfiguration {

private static final int MINIMUM_HMAC_KEY_BYTES = 32;

@Bean
@ConditionalOnMissingBean(ReactiveJwtDecoder.class)
ReactiveJwtDecoder gatewayReactiveJwtDecoder(
@Value("${auth.jwt.issuer:}") String issuer,
@Value("${auth.jwt.secret:}") String secret,
@Value("${auth.jwt.jwk-set-uri:}") String jwkSetUri) {
if (StringUtils.hasText(secret)) {
return hmacDecoder(secret, issuer);
}
if (StringUtils.hasText(jwkSetUri)) {
return jwkDecoder(jwkSetUri, issuer);
}
if (StringUtils.hasText(issuer)) {
return ReactiveJwtDecoders.fromIssuerLocation(issuer);
}
throw new IllegalStateException(
"Gateway security is enabled but no auth.jwt.secret, auth.jwt.jwk-set-uri, or auth.jwt.issuer is configured");
}

private ReactiveJwtDecoder hmacDecoder(String encodedSecret, String issuer) {
final byte[] secret;
try {
secret = Base64.getDecoder().decode(encodedSecret);
} catch (IllegalArgumentException exception) {
throw new IllegalStateException("auth.jwt.secret must be a valid Base64 value", exception);
}
if (secret.length < MINIMUM_HMAC_KEY_BYTES) {
throw new IllegalStateException("auth.jwt.secret must decode to at least 32 bytes");
}
return configuredDecoder(new SecretKeySpec(secret, "HmacSHA256"), issuer);
}

private ReactiveJwtDecoder jwkDecoder(String jwkSetUri, String issuer) {
NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder.withJwkSetUri(jwkSetUri).build();
if (StringUtils.hasText(issuer)) {
decoder.setJwtValidator(JwtValidators.createDefaultWithIssuer(issuer));
}
return decoder;
}

private ReactiveJwtDecoder configuredDecoder(SecretKey key, String issuer) {
NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder.withSecretKey(key).build();
if (StringUtils.hasText(issuer)) {
OAuth2TokenValidator<Jwt> issuerValidator = JwtValidators.createDefaultWithIssuer(issuer);
decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(issuerValidator));
}
return decoder;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package com.digitalbank.apigateway.security;

import java.util.LinkedHashMap;
import java.util.Map;

import tools.jackson.core.JacksonException;
import tools.jackson.databind.ObjectMapper;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import reactor.core.publisher.Mono;

@Component
@ConditionalOnProperty(name = "gateway.security.enabled", havingValue = "true")
final class GatewayProblemDetailsWriter {

private final ObjectMapper objectMapper;

GatewayProblemDetailsWriter(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}

Mono<Void> write(ServerWebExchange exchange, int status, String title, String detail,
boolean includeAuthenticateHeader) {
exchange.getResponse().setStatusCode(HttpStatusCode.valueOf(status));
exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_PROBLEM_JSON);
if (includeAuthenticateHeader) {
exchange.getResponse().getHeaders().set(HttpHeaders.WWW_AUTHENTICATE, "Bearer");
}

Map<String, Object> problem = new LinkedHashMap<>();
problem.put("type", "https://digital-bank-java.local/problems/authorization-error");
problem.put("title", title);
problem.put("status", status);
problem.put("detail", detail);
problem.put("instance", exchange.getRequest().getPath().value());

final byte[] body;
try {
body = objectMapper.writeValueAsBytes(problem);
} catch (JacksonException exception) {
return Mono.error(exception);
}
var buffer = exchange.getResponse().bufferFactory().wrap(body);
return exchange.getResponse().writeWith(Mono.just(buffer));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package com.digitalbank.apigateway.security;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;

import static org.springframework.security.config.Customizer.withDefaults;

@Configuration(proxyBeanMethods = false)
@EnableWebFluxSecurity
@ConditionalOnProperty(name = "gateway.security.enabled", havingValue = "true")
class GatewaySecurityConfiguration {

@Bean
SecurityWebFilterChain gatewaySecurityWebFilterChain(ServerHttpSecurity http,
ServerAuthenticationEntryPoint authenticationEntryPoint,
ServerAccessDeniedHandler accessDeniedHandler) {
return http
.csrf(ServerHttpSecurity.CsrfSpec::disable)
.authorizeExchange(authorize -> authorize
.pathMatchers(
"/actuator/health/**",
"/actuator/info",
"/auth-service/actuator/health/**",
"/account-service/actuator/health/**",
"/config-server/actuator/health/**",
"/customer-service/actuator/health/**",
"/ledger-service/actuator/health/**",
"/mfa-service/actuator/health/**",
"/notification-service/actuator/health/**",
"/payment-service/actuator/health/**",
"/transaction-service/actuator/health/**",
"/error",
"/api/v1/auth/login")
.permitAll()
.pathMatchers("/api/v1/auth/**")
.authenticated()
.pathMatchers(
"/admin/**",
"/v3/api-docs/swagger-config",
"/swagger-ui/**",
"/swagger-ui.html")
.hasAuthority("SCOPE_admin.internal")
.pathMatchers("/api/v1/mfa/**")
.hasAuthority("SCOPE_mfa.internal")
.pathMatchers("/internal/v1/transfer-workflows", "/internal/v1/transfer-workflows/**")
.hasAuthority("SCOPE_transaction.internal")
.pathMatchers("/internal/v1/payment-instructions", "/internal/v1/payment-instructions/**")
.hasAuthority("SCOPE_payment.internal")
.pathMatchers("/api/v1/customers/**", "/api/v1/accounts/**")
.authenticated()
.anyExchange().denyAll())
.oauth2ResourceServer(oauth2 -> oauth2
.jwt(withDefaults())
.authenticationEntryPoint(authenticationEntryPoint)
.accessDeniedHandler(accessDeniedHandler))
.build();
}

@Bean
ServerAuthenticationEntryPoint gatewayAuthenticationEntryPoint(GatewayProblemDetailsWriter writer) {
return (exchange, exception) -> writer.write(exchange, 401, "Authentication required",
"A valid bearer token is required to access this resource.", true);
}

@Bean
ServerAccessDeniedHandler gatewayAccessDeniedHandler(GatewayProblemDetailsWriter writer) {
return (exchange, exception) -> writer.write(exchange, 403, "Access denied",
"The bearer token does not grant the required scope for this resource.", false);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.digitalbank.apigateway.security;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;

@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(name = "gateway.security.enabled", havingValue = "false", matchIfMissing = true)
class GatewaySecurityDisabledConfiguration {

@Bean
SecurityWebFilterChain gatewaySecurityDisabledWebFilterChain(ServerHttpSecurity http) {
return http
.csrf(ServerHttpSecurity.CsrfSpec::disable)
.authorizeExchange(authorize -> authorize.anyExchange().permitAll())
.build();
}
}
8 changes: 8 additions & 0 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ spring:
response-timeout: ${gateway.resilience.timeout.response-timeout:2s}

gateway:
security:
enabled: ${GATEWAY_SECURITY_ENABLED:false}
rate-limit:
trusted-proxies: []
resilience:
Expand All @@ -46,6 +48,12 @@ gateway:
permitted-number-of-calls-in-half-open-state: 2
automatic-transition-from-open-to-half-open-enabled: true

auth:
jwt:
issuer: ${AUTH_JWT_ISSUER:}
secret: ${AUTH_JWT_SECRET:}
jwk-set-uri: ${AUTH_JWT_JWK_SET_URI:}

resilience4j:
circuitbreaker:
configs:
Expand Down
Loading
Loading