diff --git a/Agents.md b/Agents.md index eb01ff3..c4ecc7f 100644 --- a/Agents.md +++ b/Agents.md @@ -64,6 +64,7 @@ Known prefixes: - `kri.swagger` - `kri.web` - `kri.web.mdc` +- `kri.http.bypass` - `kri.redis` - `kri.scheduling` - `kri.error.expose` @@ -81,6 +82,7 @@ Declared imports: - `com.kri.common.autoconfigure.swagger.KriSwaggerAutoConfiguration` - `com.kri.common.autoconfigure.redis.CommonRedisAutoConfiguration` - `com.kri.common.autoconfigure.scheduling.CommonSchedulingAutoConfiguration` +- `com.kri.common.autoconfigure.http.bypass.BypassAutoConfiguration` If a new auto-configuration must be active for consumers, add it to `AutoConfiguration.imports`. @@ -162,6 +164,21 @@ Behavior: - Requires `RedisTemplate` class and `RedisConnectionFactory` bean. - Registers `RedisQueueHelper`. +### HTTP Bypass + +- Public classes: `BypassClient`, `BypassRequest`, `BypassResponse`, `BypassContext`, `BypassForwardOptions`, `BypassRequestCustomizer`, `BypassResponseCustomizer` +- Runtime implementation: `DefaultBypassClient` +- Auto-config: `BypassAutoConfiguration` +- Config: `kri.http.bypass` +- Default enabled: `false` +- Requires servlet web classes. +- Consumer services define bypass controllers explicitly and call `BypassClient.forward(targetName, request, body)`. +- Targets are configured under `kri.http.bypass.targets.` with `base-url`, optional `strip-prefix`, `allowed-paths`, `request-customizers`, `response-customizers`, and timeout. +- Target customizers are referenced by Spring bean name and run before per-request customizers from `BypassForwardOptions`. +- Response bodies are returned as `byte[]`; preserve target `Content-Type` so frontends can parse JSON/text/blob correctly. +- Do not allow frontends to pass arbitrary full target URLs. Keep target base URLs server-side and use `allowed-paths`. +- Do not forward hop-by-hop headers such as `Host`, `Content-Length`, `Transfer-Encoding`, `Connection`, `Keep-Alive`, `Upgrade`, `Proxy-Authenticate`, `Proxy-Authorization`, `TE`, and `Trailer`. + ### Scheduling - Auto-config: `CommonSchedulingAutoConfiguration` diff --git a/README.md b/README.md index af411c1..7a3f499 100644 --- a/README.md +++ b/README.md @@ -183,6 +183,115 @@ ExternalApiResponse res = client.post(url, headers, jsonBody); 응답은 `statusCode`, `headers`, `body`를 제공합니다. +#### `BypassClient` + +Front에서 들어온 요청을 target API로 bypass하는 HTTP client입니다. 원본 method, query param, +header, body를 기반으로 target URL만 재조립하고, target 응답의 status/header/body bytes를 +`BypassResponse`로 반환합니다. 응답 controller에서는 `ResponseEntity`로 내려주면 +front는 `Content-Type`에 따라 JSON, text, blob 등을 처리할 수 있습니다. + +패키지: + +```java +import com.kri.common.feature.http.bypass.BypassClient; +import com.kri.common.feature.http.bypass.BypassForwardOptions; +import com.kri.common.feature.http.bypass.BypassRequestCustomizer; +import com.kri.common.feature.http.bypass.BypassResponse; +import com.kri.common.feature.http.bypass.BypassResponseCustomizer; +``` + +설정 예: + +```yaml +kri: + http: + bypass: + enabled: true + targets: + nice: + base-url: https://api.nice.example + strip-prefix: /api/bypass/nice + allowed-paths: + - /v1/** + request-customizers: + - niceAuthCustomizer + response-customizers: + - niceResponseCustomizer +``` + +Controller 예: + +```java +@RestController +@RequestMapping("/api/bypass/nice") +public class NiceBypassController { + + private final BypassClient bypassClient; + + public NiceBypassController(BypassClient bypassClient) { + this.bypassClient = bypassClient; + } + + @RequestMapping("/**") + public ResponseEntity bypass( + HttpServletRequest request, + @RequestBody(required = false) byte[] body + ) { + BypassResponse response = bypassClient.forward("nice", request, body); + + return ResponseEntity + .status(response.statusCode()) + .headers(response.httpHeaders()) + .body(response.body()); + } +} +``` + +Target별 request/response customizer는 소비 서비스에서 Bean으로 등록하고, +`application.yml`의 customizer bean name 목록에 연결합니다. + +```java +@Bean +BypassRequestCustomizer niceAuthCustomizer() { + return (request, context) -> request.toBuilder() + .header("Authorization", "Bearer ${token}") + .queryParam("clientId", "contact") + .build(); +} + +@Bean +BypassResponseCustomizer niceResponseCustomizer() { + return (response, context) -> response.toBuilder() + .header("X-Bypass-Target", context.targetName()) + .build(); +} +``` + +요청 1회성 customizer도 `BypassForwardOptions`로 추가할 수 있습니다. 적용 순서는 +target 설정 customizer가 먼저이고, per-request customizer가 마지막입니다. + +```java +BypassResponse response = bypassClient.forward( + "nice", + request, + body, + BypassForwardOptions.builder() + .attribute("loginUserId", user.userId()) + .requestCustomizer((bypassRequest, context) -> bypassRequest.toBuilder() + .header("X-User-Id", context.attribute("loginUserId", String.class)) + .build()) + .responseCustomizer((bypassResponse, context) -> bypassResponse.toBuilder() + .header("X-Handled-By", "contact-server") + .build()) + .build() +); +``` + +보안상 front가 full target URL을 직접 넘기지 않게 하고, controller에서는 `targetName`을 서버 +코드로 고정하는 것을 권장합니다. `allowed-paths`로 호출 가능한 path를 제한하고, 원본 요청의 +`Host`, `Content-Length`, `Transfer-Encoding`, `Connection` 같은 hop-by-hop header는 +전달하지 않습니다. + ### JSON #### `JsonUtil` diff --git a/build.gradle b/build.gradle index dcddc57..80686f4 100644 --- a/build.gradle +++ b/build.gradle @@ -4,7 +4,7 @@ plugins { } // 버전 변경은 여기서 -def commonVer = "beta.1.1.36" +def commonVer = "beta.1.2.0" group = 'com.kri.common' version = commonVer diff --git a/src/main/java/com/kri/common/autoconfigure/http/bypass/BypassAutoConfiguration.java b/src/main/java/com/kri/common/autoconfigure/http/bypass/BypassAutoConfiguration.java new file mode 100644 index 0000000..8c6fc6e --- /dev/null +++ b/src/main/java/com/kri/common/autoconfigure/http/bypass/BypassAutoConfiguration.java @@ -0,0 +1,37 @@ +package com.kri.common.autoconfigure.http.bypass; + +import com.kri.common.feature.http.bypass.BypassClient; +import com.kri.common.feature.http.bypass.BypassRequestCustomizer; +import com.kri.common.feature.http.bypass.BypassResponseCustomizer; +import com.kri.common.runtime.http.bypass.DefaultBypassClient; +import jakarta.servlet.http.HttpServletRequest; +import java.net.http.HttpClient; +import java.util.Map; +import org.springframework.beans.factory.ListableBeanFactory; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; + +@AutoConfiguration +@ConditionalOnClass({HttpServletRequest.class, HttpClient.class}) +@ConditionalOnExpression("${kri.http.bypass.enabled:false}") +@EnableConfigurationProperties(BypassProperties.class) +public class BypassAutoConfiguration { + + @Bean + @ConditionalOnMissingBean + public BypassClient bypassClient( + BypassProperties properties, + ListableBeanFactory beanFactory + ) { + Map requestCustomizers = + beanFactory.getBeansOfType(BypassRequestCustomizer.class); + Map responseCustomizers = + beanFactory.getBeansOfType(BypassResponseCustomizer.class); + + return new DefaultBypassClient(properties, requestCustomizers, responseCustomizers); + } +} diff --git a/src/main/java/com/kri/common/autoconfigure/http/bypass/BypassProperties.java b/src/main/java/com/kri/common/autoconfigure/http/bypass/BypassProperties.java new file mode 100644 index 0000000..f80c3ed --- /dev/null +++ b/src/main/java/com/kri/common/autoconfigure/http/bypass/BypassProperties.java @@ -0,0 +1,33 @@ +package com.kri.common.autoconfigure.http.bypass; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import lombok.Getter; +import lombok.Setter; +import org.springframework.boot.context.properties.ConfigurationProperties; + +@Getter +@Setter +@ConfigurationProperties(prefix = "kri.http.bypass") +public class BypassProperties { + + private boolean enabled = false; + private Duration connectTimeout = Duration.ofSeconds(10); + private Duration requestTimeout = Duration.ofSeconds(30); + private Map targets = new LinkedHashMap<>(); + + @Getter + @Setter + public static class Target { + + private String baseUrl; + private String stripPrefix; + private List allowedPaths = new ArrayList<>(); + private Duration requestTimeout; + private List requestCustomizers = new ArrayList<>(); + private List responseCustomizers = new ArrayList<>(); + } +} diff --git a/src/main/java/com/kri/common/feature/http/bypass/BypassClient.java b/src/main/java/com/kri/common/feature/http/bypass/BypassClient.java new file mode 100644 index 0000000..10f275b --- /dev/null +++ b/src/main/java/com/kri/common/feature/http/bypass/BypassClient.java @@ -0,0 +1,15 @@ +package com.kri.common.feature.http.bypass; + +import jakarta.servlet.http.HttpServletRequest; + +public interface BypassClient { + + BypassResponse forward(String targetName, HttpServletRequest servletRequest, byte[] body); + + BypassResponse forward( + String targetName, + HttpServletRequest servletRequest, + byte[] body, + BypassForwardOptions options + ); +} diff --git a/src/main/java/com/kri/common/feature/http/bypass/BypassContext.java b/src/main/java/com/kri/common/feature/http/bypass/BypassContext.java new file mode 100644 index 0000000..58377a2 --- /dev/null +++ b/src/main/java/com/kri/common/feature/http/bypass/BypassContext.java @@ -0,0 +1,56 @@ +package com.kri.common.feature.http.bypass; + +import jakarta.servlet.http.HttpServletRequest; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +public class BypassContext { + + private final String targetName; + private final BypassTarget target; + private final HttpServletRequest servletRequest; + private final Map attributes; + + public BypassContext( + String targetName, + BypassTarget target, + HttpServletRequest servletRequest, + Map attributes + ) { + this.targetName = targetName; + this.target = target; + this.servletRequest = servletRequest; + this.attributes = attributes == null + ? Collections.emptyMap() + : Collections.unmodifiableMap(new HashMap<>(attributes)); + } + + public String targetName() { + return targetName; + } + + public BypassTarget target() { + return target; + } + + public HttpServletRequest servletRequest() { + return servletRequest; + } + + public Map attributes() { + return attributes; + } + + public Object attribute(String name) { + return attributes.get(name); + } + + public T attribute(String name, Class type) { + Object value = attributes.get(name); + if (value == null) { + return null; + } + return type.cast(value); + } +} diff --git a/src/main/java/com/kri/common/feature/http/bypass/BypassForwardOptions.java b/src/main/java/com/kri/common/feature/http/bypass/BypassForwardOptions.java new file mode 100644 index 0000000..12880a9 --- /dev/null +++ b/src/main/java/com/kri/common/feature/http/bypass/BypassForwardOptions.java @@ -0,0 +1,107 @@ +package com.kri.common.feature.http.bypass; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class BypassForwardOptions { + + private static final BypassForwardOptions EMPTY = builder().build(); + + private final List requestCustomizers; + private final List responseCustomizers; + private final Map attributes; + private final String stripPrefix; + + private BypassForwardOptions(Builder builder) { + this.requestCustomizers = List.copyOf(builder.requestCustomizers); + this.responseCustomizers = List.copyOf(builder.responseCustomizers); + this.attributes = Collections.unmodifiableMap(new HashMap<>(builder.attributes)); + this.stripPrefix = builder.stripPrefix; + } + + public static BypassForwardOptions empty() { + return EMPTY; + } + + public static Builder builder() { + return new Builder(); + } + + public List requestCustomizers() { + return requestCustomizers; + } + + public List responseCustomizers() { + return responseCustomizers; + } + + public Map attributes() { + return attributes; + } + + public String stripPrefix() { + return stripPrefix; + } + + public static class Builder { + + private final List requestCustomizers = new ArrayList<>(); + private final List responseCustomizers = new ArrayList<>(); + private final Map attributes = new HashMap<>(); + private String stripPrefix; + + public Builder requestCustomizer(BypassRequestCustomizer customizer) { + if (customizer != null) { + this.requestCustomizers.add(customizer); + } + return this; + } + + public Builder requestCustomizers(List customizers) { + if (customizers != null) { + customizers.forEach(this::requestCustomizer); + } + return this; + } + + public Builder responseCustomizer(BypassResponseCustomizer customizer) { + if (customizer != null) { + this.responseCustomizers.add(customizer); + } + return this; + } + + public Builder responseCustomizers(List customizers) { + if (customizers != null) { + customizers.forEach(this::responseCustomizer); + } + return this; + } + + public Builder attribute(String name, Object value) { + if (name != null && !name.isBlank()) { + this.attributes.put(name, value); + } + return this; + } + + public Builder attributes(Map attributes) { + if (attributes != null) { + attributes.forEach(this::attribute); + } + return this; + } + + public Builder stripPrefix(String stripPrefix) { + this.stripPrefix = stripPrefix; + return this; + } + + public BypassForwardOptions build() { + return new BypassForwardOptions(this); + } + } +} diff --git a/src/main/java/com/kri/common/feature/http/bypass/BypassRequest.java b/src/main/java/com/kri/common/feature/http/bypass/BypassRequest.java new file mode 100644 index 0000000..41f9d7a --- /dev/null +++ b/src/main/java/com/kri/common/feature/http/bypass/BypassRequest.java @@ -0,0 +1,171 @@ +package com.kri.common.feature.http.bypass; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; + +public class BypassRequest { + + private final String method; + private final String path; + private final Map> queryParams; + private final Map> headers; + private final byte[] body; + + private BypassRequest(Builder builder) { + this.method = builder.method; + this.path = builder.path; + this.queryParams = immutableMultiValueMap(builder.queryParams); + this.headers = immutableMultiValueMap(builder.headers); + this.body = builder.body == null ? new byte[0] : builder.body.clone(); + } + + private static Map> immutableMultiValueMap(Map> source) { + Map> copy = new LinkedHashMap<>(); + source.forEach((key, values) -> copy.put(key, List.copyOf(values))); + return Collections.unmodifiableMap(copy); + } + + public static Builder builder() { + return new Builder(); + } + + public Builder toBuilder() { + return builder() + .method(method) + .path(path) + .queryParams(queryParams) + .headers(headers) + .body(body); + } + + public String method() { + return method; + } + + public String path() { + return path; + } + + public Map> queryParams() { + return queryParams; + } + + public Map> headers() { + return headers; + } + + public byte[] body() { + return body.clone(); + } + + public String bodyAsUtf8String() { + return new String(body, StandardCharsets.UTF_8); + } + + public Optional firstHeader(String name) { + if (name == null) { + return Optional.empty(); + } + return headers.entrySet().stream() + .filter(entry -> entry.getKey().equalsIgnoreCase(name)) + .flatMap(entry -> entry.getValue().stream()) + .findFirst(); + } + + public boolean isJsonBody() { + return firstHeader("Content-Type") + .map(value -> value.toLowerCase(Locale.ROOT).contains("application/json")) + .orElse(false); + } + + public static class Builder { + + private String method; + private String path = "/"; + private final Map> queryParams = new LinkedHashMap<>(); + private final Map> headers = new LinkedHashMap<>(); + private byte[] body = new byte[0]; + + public Builder method(String method) { + this.method = method; + return this; + } + + public Builder path(String path) { + this.path = path == null || path.isBlank() ? "/" : path; + return this; + } + + public Builder queryParam(String name, String value) { + add(queryParams, name, value); + return this; + } + + public Builder queryParams(Map> queryParams) { + if (queryParams != null) { + queryParams.forEach((key, values) -> { + if (values != null) { + values.forEach(value -> queryParam(key, value)); + } + }); + } + return this; + } + + public Builder header(String name, String value) { + add(headers, name, value); + return this; + } + + public Builder headers(Map> headers) { + if (headers != null) { + headers.forEach((key, values) -> { + if (values != null) { + values.forEach(value -> header(key, value)); + } + }); + } + return this; + } + + public Builder replaceHeader(String name, String value) { + if (name != null && !name.isBlank()) { + headers.keySet().removeIf(key -> key.equalsIgnoreCase(name)); + header(name, value); + } + return this; + } + + public Builder removeHeader(String name) { + if (name != null) { + headers.keySet().removeIf(key -> key.equalsIgnoreCase(name)); + } + return this; + } + + public Builder body(byte[] body) { + this.body = body == null ? new byte[0] : body.clone(); + return this; + } + + public BypassRequest build() { + if (method == null || method.isBlank()) { + throw new IllegalArgumentException("method must not be blank"); + } + return new BypassRequest(this); + } + + private static void add(Map> map, String name, String value) { + if (name == null || name.isBlank() || value == null) { + return; + } + map.computeIfAbsent(name, ignored -> new ArrayList<>()).add(value); + } + } +} diff --git a/src/main/java/com/kri/common/feature/http/bypass/BypassRequestCustomizer.java b/src/main/java/com/kri/common/feature/http/bypass/BypassRequestCustomizer.java new file mode 100644 index 0000000..69c9724 --- /dev/null +++ b/src/main/java/com/kri/common/feature/http/bypass/BypassRequestCustomizer.java @@ -0,0 +1,7 @@ +package com.kri.common.feature.http.bypass; + +@FunctionalInterface +public interface BypassRequestCustomizer { + + BypassRequest customize(BypassRequest request, BypassContext context) throws Exception; +} diff --git a/src/main/java/com/kri/common/feature/http/bypass/BypassResponse.java b/src/main/java/com/kri/common/feature/http/bypass/BypassResponse.java new file mode 100644 index 0000000..c7f9d7c --- /dev/null +++ b/src/main/java/com/kri/common/feature/http/bypass/BypassResponse.java @@ -0,0 +1,138 @@ +package com.kri.common.feature.http.bypass; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import org.springframework.http.HttpHeaders; + +public class BypassResponse { + + private final int statusCode; + private final Map> headers; + private final byte[] body; + + private BypassResponse(Builder builder) { + this.statusCode = builder.statusCode; + this.headers = immutableMultiValueMap(builder.headers); + this.body = builder.body == null ? new byte[0] : builder.body.clone(); + } + + private static Map> immutableMultiValueMap(Map> source) { + Map> copy = new LinkedHashMap<>(); + source.forEach((key, values) -> copy.put(key, List.copyOf(values))); + return Collections.unmodifiableMap(copy); + } + + public static Builder builder() { + return new Builder(); + } + + public Builder toBuilder() { + return builder() + .statusCode(statusCode) + .headers(headers) + .body(body); + } + + public int statusCode() { + return statusCode; + } + + public Map> headers() { + return headers; + } + + public HttpHeaders httpHeaders() { + HttpHeaders httpHeaders = new HttpHeaders(); + headers.forEach(httpHeaders::put); + return httpHeaders; + } + + public byte[] body() { + return body.clone(); + } + + public String bodyAsUtf8String() { + return new String(body, StandardCharsets.UTF_8); + } + + public Optional firstHeader(String name) { + if (name == null) { + return Optional.empty(); + } + return headers.entrySet().stream() + .filter(entry -> entry.getKey().equalsIgnoreCase(name)) + .flatMap(entry -> entry.getValue().stream()) + .findFirst(); + } + + public boolean isJsonBody() { + return firstHeader("Content-Type") + .map(value -> value.toLowerCase(Locale.ROOT).contains("application/json")) + .orElse(false); + } + + public static class Builder { + + private int statusCode = 200; + private final Map> headers = new LinkedHashMap<>(); + private byte[] body = new byte[0]; + + public Builder statusCode(int statusCode) { + this.statusCode = statusCode; + return this; + } + + public Builder header(String name, String value) { + add(headers, name, value); + return this; + } + + public Builder headers(Map> headers) { + if (headers != null) { + headers.forEach((key, values) -> { + if (values != null) { + values.forEach(value -> header(key, value)); + } + }); + } + return this; + } + + public Builder replaceHeader(String name, String value) { + if (name != null && !name.isBlank()) { + headers.keySet().removeIf(key -> key.equalsIgnoreCase(name)); + header(name, value); + } + return this; + } + + public Builder removeHeader(String name) { + if (name != null) { + headers.keySet().removeIf(key -> key.equalsIgnoreCase(name)); + } + return this; + } + + public Builder body(byte[] body) { + this.body = body == null ? new byte[0] : body.clone(); + return this; + } + + public BypassResponse build() { + return new BypassResponse(this); + } + + private static void add(Map> map, String name, String value) { + if (name == null || name.isBlank() || value == null) { + return; + } + map.computeIfAbsent(name, ignored -> new ArrayList<>()).add(value); + } + } +} diff --git a/src/main/java/com/kri/common/feature/http/bypass/BypassResponseCustomizer.java b/src/main/java/com/kri/common/feature/http/bypass/BypassResponseCustomizer.java new file mode 100644 index 0000000..eeb73b0 --- /dev/null +++ b/src/main/java/com/kri/common/feature/http/bypass/BypassResponseCustomizer.java @@ -0,0 +1,7 @@ +package com.kri.common.feature.http.bypass; + +@FunctionalInterface +public interface BypassResponseCustomizer { + + BypassResponse customize(BypassResponse response, BypassContext context) throws Exception; +} diff --git a/src/main/java/com/kri/common/feature/http/bypass/BypassTarget.java b/src/main/java/com/kri/common/feature/http/bypass/BypassTarget.java new file mode 100644 index 0000000..24a75f5 --- /dev/null +++ b/src/main/java/com/kri/common/feature/http/bypass/BypassTarget.java @@ -0,0 +1,47 @@ +package com.kri.common.feature.http.bypass; + +import java.time.Duration; +import java.util.List; + +public class BypassTarget { + + private final String name; + private final String baseUrl; + private final String stripPrefix; + private final List allowedPaths; + private final Duration timeout; + + public BypassTarget( + String name, + String baseUrl, + String stripPrefix, + List allowedPaths, + Duration timeout + ) { + this.name = name; + this.baseUrl = baseUrl; + this.stripPrefix = stripPrefix; + this.allowedPaths = allowedPaths == null ? List.of() : List.copyOf(allowedPaths); + this.timeout = timeout; + } + + public String getName() { + return name; + } + + public String getBaseUrl() { + return baseUrl; + } + + public String getStripPrefix() { + return stripPrefix; + } + + public List getAllowedPaths() { + return allowedPaths; + } + + public Duration getTimeout() { + return timeout; + } +} diff --git a/src/main/java/com/kri/common/runtime/http/bypass/DefaultBypassClient.java b/src/main/java/com/kri/common/runtime/http/bypass/DefaultBypassClient.java new file mode 100644 index 0000000..badbf7b --- /dev/null +++ b/src/main/java/com/kri/common/runtime/http/bypass/DefaultBypassClient.java @@ -0,0 +1,409 @@ +package com.kri.common.runtime.http.bypass; + +import com.kri.common.autoconfigure.http.bypass.BypassProperties; +import com.kri.common.feature.http.bypass.BypassClient; +import com.kri.common.feature.http.bypass.BypassContext; +import com.kri.common.feature.http.bypass.BypassForwardOptions; +import com.kri.common.feature.http.bypass.BypassRequest; +import com.kri.common.feature.http.bypass.BypassRequestCustomizer; +import com.kri.common.feature.http.bypass.BypassResponse; +import com.kri.common.feature.http.bypass.BypassResponseCustomizer; +import com.kri.common.feature.http.bypass.BypassTarget; +import com.kri.common.feature.web.BusinessException; +import jakarta.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.net.URI; +import java.net.URLEncoder; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Enumeration; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import org.springframework.util.AntPathMatcher; + +public class DefaultBypassClient implements BypassClient { + + private static final Set HOP_BY_HOP_HEADERS = Set.of( + "connection", + "keep-alive", + "proxy-authenticate", + "proxy-authorization", + "te", + "trailer", + "transfer-encoding", + "upgrade", + "host", + "content-length" + ); + + private final BypassProperties properties; + private final Map requestCustomizerBeans; + private final Map responseCustomizerBeans; + private final HttpClient httpClient; + private final AntPathMatcher pathMatcher = new AntPathMatcher(); + + public DefaultBypassClient( + BypassProperties properties, + Map requestCustomizerBeans, + Map responseCustomizerBeans + ) { + this.properties = properties; + this.requestCustomizerBeans = requestCustomizerBeans == null + ? Map.of() + : Map.copyOf(requestCustomizerBeans); + this.responseCustomizerBeans = responseCustomizerBeans == null + ? Map.of() + : Map.copyOf(responseCustomizerBeans); + this.httpClient = HttpClient.newBuilder() + .connectTimeout(defaultDuration(properties.getConnectTimeout(), Duration.ofSeconds(10))) + .build(); + } + + @Override + public BypassResponse forward(String targetName, HttpServletRequest servletRequest, byte[] body) { + return forward(targetName, servletRequest, body, BypassForwardOptions.empty()); + } + + @Override + public BypassResponse forward( + String targetName, + HttpServletRequest servletRequest, + byte[] body, + BypassForwardOptions options + ) { + BypassForwardOptions effectiveOptions = options == null ? BypassForwardOptions.empty() : options; + BypassProperties.Target targetProperties = resolveTargetProperties(targetName); + BypassTarget target = toTarget(targetName, targetProperties); + BypassContext context = new BypassContext( + targetName, + target, + servletRequest, + effectiveOptions.attributes() + ); + + BypassRequest bypassRequest = createRequest(servletRequest, body, target, effectiveOptions); + validateAllowedPath(target, bypassRequest.path()); + bypassRequest = applyRequestCustomizers(bypassRequest, context, targetProperties, effectiveOptions); + + BypassResponse bypassResponse = send(target, targetProperties, bypassRequest); + return applyResponseCustomizers(bypassResponse, context, targetProperties, effectiveOptions); + } + + private BypassProperties.Target resolveTargetProperties(String targetName) { + if (targetName == null || targetName.isBlank()) { + throw BusinessException.badRequest("BYPASS_TARGET_REQUIRED", "Bypass targetName is required."); + } + Map targets = properties.getTargets() == null + ? Collections.emptyMap() + : properties.getTargets(); + BypassProperties.Target target = targets.get(targetName); + if (target == null) { + throw BusinessException.badRequest("BYPASS_TARGET_NOT_FOUND", "Bypass target is not configured."); + } + if (target.getBaseUrl() == null || target.getBaseUrl().isBlank()) { + throw BusinessException.badRequest("BYPASS_TARGET_BASE_URL_REQUIRED", + "Bypass target base-url is required."); + } + return target; + } + + private BypassTarget toTarget(String targetName, BypassProperties.Target targetProperties) { + return new BypassTarget( + targetName, + targetProperties.getBaseUrl(), + targetProperties.getStripPrefix(), + targetProperties.getAllowedPaths(), + targetProperties.getRequestTimeout() + ); + } + + private BypassRequest createRequest( + HttpServletRequest servletRequest, + byte[] body, + BypassTarget target, + BypassForwardOptions options + ) { + String path = normalizePath(servletRequest.getRequestURI()); + String contextPath = servletRequest.getContextPath(); + if (contextPath != null && !contextPath.isBlank() && path.startsWith(contextPath)) { + path = normalizePath(path.substring(contextPath.length())); + } + path = stripPrefix(path, target.getStripPrefix()); + path = stripPrefix(path, options.stripPrefix()); + + return BypassRequest.builder() + .method(servletRequest.getMethod()) + .path(path) + .queryParams(parseQuery(servletRequest.getQueryString())) + .headers(readHeaders(servletRequest)) + .body(body) + .build(); + } + + private Map> readHeaders(HttpServletRequest request) { + Map> headers = new LinkedHashMap<>(); + Enumeration headerNames = request.getHeaderNames(); + while (headerNames != null && headerNames.hasMoreElements()) { + String name = headerNames.nextElement(); + if (isHopByHopHeader(name)) { + continue; + } + Enumeration values = request.getHeaders(name); + while (values.hasMoreElements()) { + add(headers, name, values.nextElement()); + } + } + return headers; + } + + private Map> parseQuery(String queryString) { + if (queryString == null || queryString.isBlank()) { + return Map.of(); + } + Map> queryParams = new LinkedHashMap<>(); + for (String pair : queryString.split("&")) { + if (pair.isBlank()) { + continue; + } + int idx = pair.indexOf('='); + String key = idx >= 0 ? pair.substring(0, idx) : pair; + String value = idx >= 0 ? pair.substring(idx + 1) : ""; + add(queryParams, decode(key), decode(value)); + } + return queryParams; + } + + private BypassRequest applyRequestCustomizers( + BypassRequest request, + BypassContext context, + BypassProperties.Target targetProperties, + BypassForwardOptions options + ) { + BypassRequest result = request; + for (String beanName : nullToEmpty(targetProperties.getRequestCustomizers())) { + result = customizeRequest(result, context, resolveRequestCustomizer(beanName)); + } + for (BypassRequestCustomizer customizer : options.requestCustomizers()) { + result = customizeRequest(result, context, customizer); + } + return result; + } + + private BypassResponse applyResponseCustomizers( + BypassResponse response, + BypassContext context, + BypassProperties.Target targetProperties, + BypassForwardOptions options + ) { + BypassResponse result = response; + for (String beanName : nullToEmpty(targetProperties.getResponseCustomizers())) { + result = customizeResponse(result, context, resolveResponseCustomizer(beanName)); + } + for (BypassResponseCustomizer customizer : options.responseCustomizers()) { + result = customizeResponse(result, context, customizer); + } + return result; + } + + private BypassRequestCustomizer resolveRequestCustomizer(String beanName) { + BypassRequestCustomizer customizer = requestCustomizerBeans.get(beanName); + if (customizer == null) { + throw BusinessException.internalError("BYPASS_REQUEST_CUSTOMIZER_NOT_FOUND", + "Bypass request customizer bean is not found: " + beanName); + } + return customizer; + } + + private BypassResponseCustomizer resolveResponseCustomizer(String beanName) { + BypassResponseCustomizer customizer = responseCustomizerBeans.get(beanName); + if (customizer == null) { + throw BusinessException.internalError("BYPASS_RESPONSE_CUSTOMIZER_NOT_FOUND", + "Bypass response customizer bean is not found: " + beanName); + } + return customizer; + } + + private BypassRequest customizeRequest( + BypassRequest request, + BypassContext context, + BypassRequestCustomizer customizer + ) { + try { + BypassRequest result = customizer.customize(request, context); + return result == null ? request : result; + } catch (Exception e) { + throw BusinessException.internalError("BYPASS_REQUEST_CUSTOMIZE_FAILED", + "Bypass request customize failed.").with("target", context.targetName()); + } + } + + private BypassResponse customizeResponse( + BypassResponse response, + BypassContext context, + BypassResponseCustomizer customizer + ) { + try { + BypassResponse result = customizer.customize(response, context); + return result == null ? response : result; + } catch (Exception e) { + throw BusinessException.internalError("BYPASS_RESPONSE_CUSTOMIZE_FAILED", + "Bypass response customize failed.").with("target", context.targetName()); + } + } + + private BypassResponse send( + BypassTarget target, + BypassProperties.Target targetProperties, + BypassRequest bypassRequest + ) { + try { + HttpRequest.Builder builder = HttpRequest.newBuilder() + .uri(buildUri(target.getBaseUrl(), bypassRequest)) + .timeout(resolveRequestTimeout(targetProperties)) + .method(bypassRequest.method(), bodyPublisher(bypassRequest)); + + bypassRequest.headers().forEach((name, values) -> { + if (isHopByHopHeader(name)) { + return; + } + values.forEach(value -> builder.header(name, value)); + }); + + HttpResponse response = httpClient.send( + builder.build(), + HttpResponse.BodyHandlers.ofByteArray() + ); + + return BypassResponse.builder() + .statusCode(response.statusCode()) + .headers(filterResponseHeaders(response.headers().map())) + .body(response.body()) + .build(); + } catch (IOException | InterruptedException e) { + if (e instanceof InterruptedException) { + Thread.currentThread().interrupt(); + } + throw BusinessException.internalError("BYPASS_CALL_FAILED", "Bypass target call failed."); + } + } + + private HttpRequest.BodyPublisher bodyPublisher(BypassRequest request) { + byte[] body = request.body(); + if (body.length == 0 && ("GET".equalsIgnoreCase(request.method()) + || "DELETE".equalsIgnoreCase(request.method()))) { + return HttpRequest.BodyPublishers.noBody(); + } + return HttpRequest.BodyPublishers.ofByteArray(body); + } + + private URI buildUri(String baseUrl, BypassRequest request) { + String normalizedBaseUrl = baseUrl.endsWith("/") + ? baseUrl.substring(0, baseUrl.length() - 1) + : baseUrl; + String url = normalizedBaseUrl + normalizePath(request.path()); + String query = buildQuery(request.queryParams()); + if (!query.isBlank()) { + url += "?" + query; + } + return URI.create(url); + } + + private String buildQuery(Map> queryParams) { + List pairs = new ArrayList<>(); + queryParams.forEach((name, values) -> { + if (values == null || values.isEmpty()) { + pairs.add(encode(name) + "="); + return; + } + values.forEach(value -> pairs.add(encode(name) + "=" + encode(value))); + }); + return String.join("&", pairs); + } + + private Map> filterResponseHeaders(Map> source) { + Map> headers = new LinkedHashMap<>(); + source.forEach((name, values) -> { + if (!isHopByHopHeader(name) && values != null) { + headers.put(name, List.copyOf(values)); + } + }); + return headers; + } + + private void validateAllowedPath(BypassTarget target, String path) { + List allowedPaths = target.getAllowedPaths(); + if (allowedPaths == null || allowedPaths.isEmpty()) { + return; + } + boolean matched = allowedPaths.stream() + .anyMatch(pattern -> pathMatcher.match(pattern, path)); + if (!matched) { + throw BusinessException.forbidden("BYPASS_PATH_NOT_ALLOWED", + "Bypass path is not allowed.").with("target", target.getName()); + } + } + + private Duration resolveRequestTimeout(BypassProperties.Target targetProperties) { + return defaultDuration( + targetProperties.getRequestTimeout(), + defaultDuration(properties.getRequestTimeout(), Duration.ofSeconds(30)) + ); + } + + private static Duration defaultDuration(Duration value, Duration defaultValue) { + return value == null || value.isZero() || value.isNegative() ? defaultValue : value; + } + + private static String normalizePath(String path) { + if (path == null || path.isBlank()) { + return "/"; + } + return path.startsWith("/") ? path : "/" + path; + } + + private static String stripPrefix(String path, String prefix) { + if (prefix == null || prefix.isBlank()) { + return normalizePath(path); + } + String normalizedPrefix = normalizePath(prefix); + String normalizedPath = normalizePath(path); + if (normalizedPath.equals(normalizedPrefix)) { + return "/"; + } + if (normalizedPath.startsWith(normalizedPrefix + "/")) { + return normalizePath(normalizedPath.substring(normalizedPrefix.length())); + } + return normalizedPath; + } + + private static boolean isHopByHopHeader(String name) { + return name != null && HOP_BY_HOP_HEADERS.contains(name.toLowerCase(Locale.ROOT)); + } + + private static List nullToEmpty(List values) { + return values == null ? List.of() : values; + } + + private static void add(Map> map, String name, String value) { + if (name == null || name.isBlank() || value == null) { + return; + } + map.computeIfAbsent(name, ignored -> new ArrayList<>()).add(value); + } + + private static String decode(String value) { + return java.net.URLDecoder.decode(value, StandardCharsets.UTF_8); + } + + private static String encode(String value) { + return URLEncoder.encode(value == null ? "" : value, StandardCharsets.UTF_8); + } +} diff --git a/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports index 17bb308..902e5ec 100644 --- a/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports +++ b/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -8,3 +8,4 @@ com.kri.common.autoconfigure.web.CommonWebAutoConfiguration com.kri.common.autoconfigure.swagger.KriSwaggerAutoConfiguration com.kri.common.autoconfigure.redis.CommonRedisAutoConfiguration com.kri.common.autoconfigure.scheduling.CommonSchedulingAutoConfiguration +com.kri.common.autoconfigure.http.bypass.BypassAutoConfiguration