From 65e31079ac763a596c5139f7ce8f50014694fa13 Mon Sep 17 00:00:00 2001 From: kric_jspark Date: Thu, 8 Oct 2026 10:58:29 +0900 Subject: [PATCH] =?UTF-8?q?261008=5F01=5FENH:=20=EC=99=B8=EB=B6=80=20API?= =?UTF-8?q?=20=EB=B0=8F=20bypass=20=EC=9B=90=EB=B3=B8=20=EC=98=A4=EB=A5=98?= =?UTF-8?q?=20=EC=9D=91=EB=8B=B5=20=EC=A0=84=ED=8C=8C=20=EA=B8=B0=EB=8A=A5?= =?UTF-8?q?=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../kri-common/platform-capabilities.md | 6 ++ .../platform-capabilities.md | 6 ++ .agent/consumer.md | 2 + AGENTS.md | 2 + README.md | 57 +++++++++++++++++ build.gradle | 2 +- .../ExternalApiErrorAutoConfiguration.java | 23 +++++++ .../http/bypass/BypassProperties.java | 1 + .../feature/http/ExternalApiClient.java | 8 +-- .../feature/http/ExternalApiResponse.java | 61 +++++++++++++++++++ .../http/ExternalApiResponseException.java | 41 +++++++++++++ .../feature/http/bypass/BypassResponse.java | 9 +++ .../http/bypass/DefaultBypassClient.java | 12 +++- .../web/ExternalApiResponseAdvice.java | 30 +++++++++ ...ot.autoconfigure.AutoConfiguration.imports | 1 + 15 files changed, 254 insertions(+), 7 deletions(-) create mode 100644 src/main/java/com/kri/common/autoconfigure/http/ExternalApiErrorAutoConfiguration.java create mode 100644 src/main/java/com/kri/common/feature/http/ExternalApiResponseException.java create mode 100644 src/main/java/com/kri/common/runtime/web/ExternalApiResponseAdvice.java diff --git a/.agent-harness/references/kri-common/platform-capabilities.md b/.agent-harness/references/kri-common/platform-capabilities.md index b383425..510ecac 100644 --- a/.agent-harness/references/kri-common/platform-capabilities.md +++ b/.agent-harness/references/kri-common/platform-capabilities.md @@ -23,6 +23,12 @@ Source: .agent/consumer-references/platform-capabilities.md - Redis and scheduling are opt-in through their `kri.*.enabled` settings and matching runtime dependencies. - HTTP bypass targets are server-configured. Never accept an arbitrary full target URL from a frontend; retain allowed-path checks and do not forward hop-by-hop headers. - The external API client returns response bodies as documented, while bypass responses preserve raw bytes and target `Content-Type`. +- Bypass filters all HTTP/2 pseudo headers (names starting with `:`) in addition to existing hop-by-hop headers; use the response status accessor instead of forwarding `:status`. +- `kri.http.bypass.targets..throw-on-error` defaults to `false`. When enabled, the final response after response customizers throws public `com.kri.common.feature.http.ExternalApiResponseException` for non-2xx status; existing targets retain response-return behavior by default. +- `BypassResponse.requireSuccess()` and `ExternalApiResponse.requireSuccess()` explicitly enforce the same non-2xx guard. `ExternalApiClient` keeps its existing default behavior and decoded `getBody()` API, and `getBodyBytes()` exposes a defensive copy of the original received bytes, including compressed and binary error bodies. +- A response customizer's `ExternalApiResponseException`, including one thrown by `requireSuccess()`, propagates unchanged; other customizer failures keep the existing `BYPASS_RESPONSE_CUSTOMIZE_FAILED` behavior. Response charset parsing ignores charset-like text inside other quoted `Content-Type` parameters and retains the UTF-8 fallback. +- With Spring MVC and Servlet API present and `kri.web.enabled=true` (default), `ExternalApiErrorAutoConfiguration` registers a handler for this dedicated exception before the general error advice. It relays the original status, body bytes, `Content-Type`, and `Content-Encoding`, including empty bodies; authentication, cookie, and transport headers are not relayed by the error handler. Enable this policy only for targets whose raw errors may be exposed to clients. Connection failures remain distinct from upstream HTTP errors. +- A consumer-provided error handler bean named `externalApiResponseAdvice` replaces the default without importing runtime types; explicitly caught/controller-handled exceptions also remain under the consumer's control. - `ExternalApiClient` multipart requests generate their own boundary and ignore a caller-supplied `Content-Type`. Multipart headers and `formField` values use UTF-8, while file bodies preserve the supplied bytes. - Multipart filenames, including non-ASCII names, are sent unchanged in the quoted `filename` parameter as raw UTF-8. No ASCII fallback or `filename*` parameter is added; CR/LF rejection and quote/backslash escaping still apply. - `JsonUtil` requires the consumer's explicit `ObjectMapper`; shared date/time helpers define KST as `Asia/Seoul` and also expose UTC semantics. diff --git a/.agent/consumer-references/platform-capabilities.md b/.agent/consumer-references/platform-capabilities.md index 06e5e4d..714f02b 100644 --- a/.agent/consumer-references/platform-capabilities.md +++ b/.agent/consumer-references/platform-capabilities.md @@ -17,6 +17,12 @@ - Redis and scheduling are opt-in through their `kri.*.enabled` settings and matching runtime dependencies. - HTTP bypass targets are server-configured. Never accept an arbitrary full target URL from a frontend; retain allowed-path checks and do not forward hop-by-hop headers. - The external API client returns response bodies as documented, while bypass responses preserve raw bytes and target `Content-Type`. +- Bypass filters all HTTP/2 pseudo headers (names starting with `:`) in addition to existing hop-by-hop headers; use the response status accessor instead of forwarding `:status`. +- `kri.http.bypass.targets..throw-on-error` defaults to `false`. When enabled, the final response after response customizers throws public `com.kri.common.feature.http.ExternalApiResponseException` for non-2xx status; existing targets retain response-return behavior by default. +- `BypassResponse.requireSuccess()` and `ExternalApiResponse.requireSuccess()` explicitly enforce the same non-2xx guard. `ExternalApiClient` keeps its existing default behavior and decoded `getBody()` API, and `getBodyBytes()` exposes a defensive copy of the original received bytes, including compressed and binary error bodies. +- A response customizer's `ExternalApiResponseException`, including one thrown by `requireSuccess()`, propagates unchanged; other customizer failures keep the existing `BYPASS_RESPONSE_CUSTOMIZE_FAILED` behavior. Response charset parsing ignores charset-like text inside other quoted `Content-Type` parameters and retains the UTF-8 fallback. +- With Spring MVC and Servlet API present and `kri.web.enabled=true` (default), `ExternalApiErrorAutoConfiguration` registers a handler for this dedicated exception before the general error advice. It relays the original status, body bytes, `Content-Type`, and `Content-Encoding`, including empty bodies; authentication, cookie, and transport headers are not relayed by the error handler. Enable this policy only for targets whose raw errors may be exposed to clients. Connection failures remain distinct from upstream HTTP errors. +- A consumer-provided error handler bean named `externalApiResponseAdvice` replaces the default without importing runtime types; explicitly caught/controller-handled exceptions also remain under the consumer's control. - `ExternalApiClient` multipart requests generate their own boundary and ignore a caller-supplied `Content-Type`. Multipart headers and `formField` values use UTF-8, while file bodies preserve the supplied bytes. - Multipart filenames, including non-ASCII names, are sent unchanged in the quoted `filename` parameter as raw UTF-8. No ASCII fallback or `filename*` parameter is added; CR/LF rejection and quote/backslash escaping still apply. - `JsonUtil` requires the consumer's explicit `ObjectMapper`; shared date/time helpers define KST as `Asia/Seoul` and also expose UTC semantics. diff --git a/.agent/consumer.md b/.agent/consumer.md index c17b217..94e8124 100644 --- a/.agent/consumer.md +++ b/.agent/consumer.md @@ -3,6 +3,8 @@ - Consume KriCommon as `com.kri.common:starter:` through the repository's established Gradle version-management convention. - Import service-facing APIs from `com.kri.common.feature.*`; treat `com.kri.common.runtime.*` as internal. - Prefer a shared feature or approved extension point over duplicating authentication, HTTP, error, enum, Excel, Redis, JSON, date/time, JPA, crypto, or utility behavior locally. +- For HTTP/2 header safety and original upstream error propagation, use the shared HTTP/bypass features documented in the routed platform-capabilities reference instead of implementing consumer-local header filters and raw-response exception handlers. +- Response customizers may call `requireSuccess()`; its upstream exception propagates unchanged. Response charset parsing ignores charset-like text inside other quoted header parameters. - Do not modify KriCommon or another consumer repository unless it is explicitly included in the approved task scope. ### Required Shared References diff --git a/AGENTS.md b/AGENTS.md index b7c3455..d2aa3a3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -232,6 +232,8 @@ When implementation is complete, report in Korean: - Consume KriCommon as `com.kri.common:starter:` through the repository's established Gradle version-management convention. - Import service-facing APIs from `com.kri.common.feature.*`; treat `com.kri.common.runtime.*` as internal. - Prefer a shared feature or approved extension point over duplicating authentication, HTTP, error, enum, Excel, Redis, JSON, date/time, JPA, crypto, or utility behavior locally. +- For HTTP/2 header safety and original upstream error propagation, use the shared HTTP/bypass features documented in the routed platform-capabilities reference instead of implementing consumer-local header filters and raw-response exception handlers. +- Response customizers may call `requireSuccess()`; its upstream exception propagates unchanged. Response charset parsing ignores charset-like text inside other quoted header parameters. - Do not modify KriCommon or another consumer repository unless it is explicitly included in the approved task scope. ### Required Shared References diff --git a/README.md b/README.md index 760bef5..14e28e9 100644 --- a/README.md +++ b/README.md @@ -206,6 +206,20 @@ Content-Disposition: form-data; name="file"; filename="한글-파일.txt" 응답은 `statusCode`, `headers`, `body`를 제공합니다. +`getBody()`는 기존처럼 `Content-Type`의 charset(없거나 알 수 없으면 UTF-8)으로 +해석한 문자열을 반환하며, `getBodyBytes()`는 수신한 원본 바이트의 복사본을 반환합니다. +charset 추출 시 다른 매개변수의 따옴표 내부 문자열은 charset 선언으로 취급하지 않습니다. +직접 호출도 오류에서 후속 작업을 중단하려면 `requireSuccess()`를 사용합니다. + +```java +ExternalApiResponse response = client.put(url, headers, json).requireSuccess(); +String bulkSendKey = response.getBody(); +``` + +`requireSuccess()`는 2xx에서 같은 응답을 반환하고, 그 외 상태에서는 +`com.kri.common.feature.http.ExternalApiResponseException`을 던집니다. +기존 호출은 명시적으로 검증하지 않으면 오류 상태도 응답 객체로 반환합니다. + #### `BypassClient` Front에서 들어온 요청을 target API로 bypass하는 HTTP client입니다. 원본 method, query param, @@ -315,6 +329,47 @@ BypassResponse response = bypassClient.forward( `Host`, `Content-Length`, `Transfer-Encoding`, `Connection` 같은 hop-by-hop header는 전달하지 않습니다. +HTTP/2 전용 `:status` 등 `:`로 시작하는 헤더도 전달하지 않습니다. 상태값은 +`BypassResponse.statusCode()`를 사용하며 일반 응답 헤더와 원본 바디는 유지합니다. + +#### 원본 오류 응답 전달 + +대상별 `throw-on-error`의 기본값은 `false`이며, 기존처럼 비정상 HTTP 상태도 +`BypassResponse`로 반환합니다. 내부 서비스 처리에서 오류 이후 실행을 중단하려면 +해당 대상에만 활성화할 수 있습니다. + +```yaml +kri: + http: + bypass: + enabled: true + targets: + nice: + base-url: https://api.nice.example + allowed-paths: + - /v1/** + throw-on-error: true +``` + +활성화하면 응답 customizer 적용 후 최종 상태가 2xx가 아닐 때 +`ExternalApiResponseException`을 던집니다. 호출별 명시적 검증은 +`bypassClient.forward(...).requireSuccess()`로도 가능합니다. 연결 실패는 기존 +`BYPASS_CALL_FAILED` 처리이며, 원본 HTTP 응답이 없는 경우와 구분합니다. +response customizer 안에서 `requireSuccess()`를 호출하거나 `ExternalApiResponseException`을 +던지면 그 예외를 그대로 전파합니다. 일반 customizer 실패는 기존 오류 처리를 유지합니다. + +Spring MVC와 Servlet API가 있고 `kri.web.enabled=true`(기본값)이면 +`ExternalApiErrorAutoConfiguration`이 원본 응답 처리기를 자동 등록합니다. +원본 HTTP 상태와 바디 바이트, `Content-Type`, `Content-Encoding`을 그대로 반환하므로 +상위 서비스의 오류 필드와 압축된 바디를 유지합니다. 쿠키·인증·전송 헤더는 오류 +처리기가 전달하지 않습니다. 오류 바디가 비어 있으면 빈 바디를 그대로 반환합니다. + +공통 처리기는 이 전용 예외만 처리하며 일반 공통 오류 처리보다 먼저 적용됩니다. +소비 서비스가 `externalApiResponseAdvice`라는 이름으로 자체 오류 처리기 Bean을 +제공하면 기본 등록을 대체할 수 있으며 runtime 구현에 의존할 필요가 없습니다. +예외를 컨트롤러에서 명시적으로 처리할 수도 있습니다. Web이 비활성화되었거나 없는 환경에서는 +직접 예외를 처리해야 합니다. 원본 오류 바디의 외부 노출이 적절한 대상에만 활성화하세요. + ### 암호화와 해시 공개 API는 `com.kri.common.feature.crypto.*`에 있습니다. 중앙 키 DB를 사용하지 않으며, @@ -764,6 +819,8 @@ other paths require both an allowed client IP and authentication. Exact IPs, CID - `CommonWebAutoConfiguration` - `ErrorAdvice` +- `ExternalApiErrorAutoConfiguration` +- `ExternalApiResponseAdvice` - `TraceFilter` - `ServiceMdcAspect` - `RequestUserContextArgumentResolver` diff --git a/build.gradle b/build.gradle index 0a82a37..08b8421 100644 --- a/build.gradle +++ b/build.gradle @@ -4,7 +4,7 @@ plugins { } // 버전 변경은 여기서 -def commonVer = "beta.1.6.7" +def commonVer = "beta.1.6.8" group = 'com.kri.common' version = commonVer diff --git a/src/main/java/com/kri/common/autoconfigure/http/ExternalApiErrorAutoConfiguration.java b/src/main/java/com/kri/common/autoconfigure/http/ExternalApiErrorAutoConfiguration.java new file mode 100644 index 0000000..544fcce --- /dev/null +++ b/src/main/java/com/kri/common/autoconfigure/http/ExternalApiErrorAutoConfiguration.java @@ -0,0 +1,23 @@ +package com.kri.common.autoconfigure.http; + +import com.kri.common.runtime.web.ExternalApiResponseAdvice; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; + +@AutoConfiguration +@ConditionalOnClass(name = { + "jakarta.servlet.http.HttpServletRequest", + "org.springframework.web.servlet.DispatcherServlet" +}) +@ConditionalOnProperty(prefix = "kri.web", name = "enabled", havingValue = "true", matchIfMissing = true) +public class ExternalApiErrorAutoConfiguration { + + @Bean + @ConditionalOnMissingBean(value = ExternalApiResponseAdvice.class, name = "externalApiResponseAdvice") + public ExternalApiResponseAdvice externalApiResponseAdvice() { + return new ExternalApiResponseAdvice(); + } +} 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 index f80c3ed..3d1dc80 100644 --- a/src/main/java/com/kri/common/autoconfigure/http/bypass/BypassProperties.java +++ b/src/main/java/com/kri/common/autoconfigure/http/bypass/BypassProperties.java @@ -27,6 +27,7 @@ public class BypassProperties { private String stripPrefix; private List allowedPaths = new ArrayList<>(); private Duration requestTimeout; + private boolean throwOnError = false; private List requestCustomizers = new ArrayList<>(); private List responseCustomizers = new ArrayList<>(); } diff --git a/src/main/java/com/kri/common/feature/http/ExternalApiClient.java b/src/main/java/com/kri/common/feature/http/ExternalApiClient.java index 210a08a..a7ef119 100644 --- a/src/main/java/com/kri/common/feature/http/ExternalApiClient.java +++ b/src/main/java/com/kri/common/feature/http/ExternalApiClient.java @@ -89,8 +89,8 @@ public class ExternalApiClient { } HttpRequest request = builder.build(); - HttpResponse resp = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - return ExternalApiResponse.of(resp.statusCode(), resp.headers(), resp.body()); + HttpResponse resp = httpClient.send(request, HttpResponse.BodyHandlers.ofByteArray()); + return ExternalApiResponse.ofBytes(resp.statusCode(), resp.headers(), resp.body()); } catch (IOException | InterruptedException e) { if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); @@ -114,8 +114,8 @@ public class ExternalApiClient { builder.header("Content-Type", "multipart/form-data; boundary=" + boundary); HttpRequest request = builder.build(); - HttpResponse resp = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - return ExternalApiResponse.of(resp.statusCode(), resp.headers(), resp.body()); + HttpResponse resp = httpClient.send(request, HttpResponse.BodyHandlers.ofByteArray()); + return ExternalApiResponse.ofBytes(resp.statusCode(), resp.headers(), resp.body()); } catch (IOException | InterruptedException e) { if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); diff --git a/src/main/java/com/kri/common/feature/http/ExternalApiResponse.java b/src/main/java/com/kri/common/feature/http/ExternalApiResponse.java index dc21f77..54ac537 100644 --- a/src/main/java/com/kri/common/feature/http/ExternalApiResponse.java +++ b/src/main/java/com/kri/common/feature/http/ExternalApiResponse.java @@ -1,28 +1,89 @@ package com.kri.common.feature.http; import java.net.http.HttpHeaders; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * 외부 API 호출 결과를 단순하게 담는 DTO. */ public class ExternalApiResponse { + private static final Pattern CONTENT_TYPE_PARAMETER = + Pattern.compile("(?:^|;)\\s*([^;=\\s]+)\\s*=\\s*(?:\"((?:\\\\.|[^\"\\\\])*+)\"|([^;\"\\s]+))\\s*(?=;|$)"); + private final int statusCode; private final Map> headers; private final String body; + private final byte[] bodyBytes; public ExternalApiResponse(int statusCode, Map> headers, String body) { + this(statusCode, headers, body, + body == null ? new byte[0] : body.getBytes(resolveCharset(headers))); + } + + private ExternalApiResponse(int statusCode, Map> headers, + String body, byte[] bodyBytes) { this.statusCode = statusCode; this.headers = headers; this.body = body; + this.bodyBytes = bodyBytes.clone(); } public static ExternalApiResponse of(int status, HttpHeaders headers, String body) { return new ExternalApiResponse(status, headers.map(), body); } + /** Preserve the received bytes while keeping the existing decoded string API. */ + public static ExternalApiResponse ofBytes(int status, HttpHeaders headers, byte[] body) { + byte[] bytes = body == null ? new byte[0] : body; + return new ExternalApiResponse(status, headers.map(), + new String(bytes, resolveCharset(headers.map())), bytes); + } + + /** Return this response for 2xx, or throw with the original upstream response. */ + public ExternalApiResponse requireSuccess() { + if (statusCode < 200 || statusCode >= 300) { + throw new ExternalApiResponseException(statusCode, headers, bodyBytes); + } + return this; + } + + public byte[] getBodyBytes() { + return bodyBytes.clone(); + } + + private static Charset resolveCharset(Map> headers) { + if (headers != null) { + for (Map.Entry> entry : headers.entrySet()) { + if (entry.getKey() != null && entry.getKey().equalsIgnoreCase("Content-Type") + && entry.getValue() != null && !entry.getValue().isEmpty() && entry.getValue().get(0) != null) { + // Consume each complete parameter so quoted values cannot introduce a fake charset. + Matcher matcher = CONTENT_TYPE_PARAMETER.matcher(entry.getValue().get(0)); + while (matcher.find()) { + if (!matcher.group(1).equalsIgnoreCase("charset")) { + continue; + } + String charset = matcher.group(2) == null ? matcher.group(3) + : matcher.group(2).replaceAll("\\\\(.)", "$1"); + try { + return Charset.forName(charset); + } catch (IllegalArgumentException ignored) { + // Match the JDK string body handler's UTF-8 fallback for an unknown charset. + return StandardCharsets.UTF_8; + } + } + break; + } + } + } + return StandardCharsets.UTF_8; + } + public int getStatusCode() { return statusCode; } diff --git a/src/main/java/com/kri/common/feature/http/ExternalApiResponseException.java b/src/main/java/com/kri/common/feature/http/ExternalApiResponseException.java new file mode 100644 index 0000000..c6a3ea7 --- /dev/null +++ b/src/main/java/com/kri/common/feature/http/ExternalApiResponseException.java @@ -0,0 +1,41 @@ +package com.kri.common.feature.http; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** An upstream HTTP error whose response can be relayed without rewriting its body. */ +public class ExternalApiResponseException extends RuntimeException { + + private final int statusCode; + private final Map> headers; + private final byte[] body; + + public ExternalApiResponseException(int statusCode, Map> headers, byte[] body) { + super("External API returned HTTP " + statusCode); + this.statusCode = statusCode; + Map> copy = new LinkedHashMap<>(); + if (headers != null) { + headers.forEach((name, values) -> { + if (name != null && values != null) { + copy.put(name, List.copyOf(values)); + } + }); + } + this.headers = Collections.unmodifiableMap(copy); + this.body = body == null ? new byte[0] : body.clone(); + } + + public int getStatusCode() { + return statusCode; + } + + public Map> getHeaders() { + return headers; + } + + public byte[] getBody() { + return body.clone(); + } +} 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 index c7f9d7c..4d4d2fd 100644 --- a/src/main/java/com/kri/common/feature/http/bypass/BypassResponse.java +++ b/src/main/java/com/kri/common/feature/http/bypass/BypassResponse.java @@ -1,5 +1,6 @@ package com.kri.common.feature.http.bypass; +import com.kri.common.feature.http.ExternalApiResponseException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; @@ -43,6 +44,14 @@ public class BypassResponse { return statusCode; } + /** Return this response for 2xx, or throw with the original upstream response. */ + public BypassResponse requireSuccess() { + if (statusCode < 200 || statusCode >= 300) { + throw new ExternalApiResponseException(statusCode, headers, body); + } + return this; + } + public Map> headers() { return headers; } 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 index badbf7b..8215220 100644 --- a/src/main/java/com/kri/common/runtime/http/bypass/DefaultBypassClient.java +++ b/src/main/java/com/kri/common/runtime/http/bypass/DefaultBypassClient.java @@ -1,6 +1,7 @@ package com.kri.common.runtime.http.bypass; import com.kri.common.autoconfigure.http.bypass.BypassProperties; +import com.kri.common.feature.http.ExternalApiResponseException; import com.kri.common.feature.http.bypass.BypassClient; import com.kri.common.feature.http.bypass.BypassContext; import com.kri.common.feature.http.bypass.BypassForwardOptions; @@ -94,7 +95,11 @@ public class DefaultBypassClient implements BypassClient { bypassRequest = applyRequestCustomizers(bypassRequest, context, targetProperties, effectiveOptions); BypassResponse bypassResponse = send(target, targetProperties, bypassRequest); - return applyResponseCustomizers(bypassResponse, context, targetProperties, effectiveOptions); + bypassResponse = applyResponseCustomizers(bypassResponse, context, targetProperties, effectiveOptions); + if (targetProperties.isThrowOnError()) { + bypassResponse.requireSuccess(); + } + return bypassResponse; } private BypassProperties.Target resolveTargetProperties(String targetName) { @@ -253,6 +258,8 @@ public class DefaultBypassClient implements BypassClient { try { BypassResponse result = customizer.customize(response, context); return result == null ? response : result; + } catch (ExternalApiResponseException e) { + throw e; } catch (Exception e) { throw BusinessException.internalError("BYPASS_RESPONSE_CUSTOMIZE_FAILED", "Bypass response customize failed.").with("target", context.targetName()); @@ -385,7 +392,8 @@ public class DefaultBypassClient implements BypassClient { } private static boolean isHopByHopHeader(String name) { - return name != null && HOP_BY_HOP_HEADERS.contains(name.toLowerCase(Locale.ROOT)); + return name != null && (name.startsWith(":") + || HOP_BY_HOP_HEADERS.contains(name.toLowerCase(Locale.ROOT))); } private static List nullToEmpty(List values) { diff --git a/src/main/java/com/kri/common/runtime/web/ExternalApiResponseAdvice.java b/src/main/java/com/kri/common/runtime/web/ExternalApiResponseAdvice.java new file mode 100644 index 0000000..ae56c19 --- /dev/null +++ b/src/main/java/com/kri/common/runtime/web/ExternalApiResponseAdvice.java @@ -0,0 +1,30 @@ +package com.kri.common.runtime.web; + +import com.kri.common.feature.http.ExternalApiResponseException; +import java.util.List; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.http.HttpHeaders; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +@Order(Ordered.HIGHEST_PRECEDENCE) +@RestControllerAdvice +public class ExternalApiResponseAdvice { + + @ExceptionHandler(ExternalApiResponseException.class) + public ResponseEntity handleExternalApiResponse(ExternalApiResponseException exception) { + HttpHeaders headers = new HttpHeaders(); + // Forward representation headers only; transport and authentication headers stay upstream. + for (String name : List.of(HttpHeaders.CONTENT_TYPE, HttpHeaders.CONTENT_ENCODING)) { + exception.getHeaders().entrySet().stream() + .filter(entry -> entry.getKey().equalsIgnoreCase(name)) + .findFirst() + .ifPresent(entry -> headers.put(name, entry.getValue())); + } + return ResponseEntity.status(exception.getStatusCode()) + .headers(headers) + .body(exception.getBody()); + } +} 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 851b0f7..39fbb6e 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 @@ -10,3 +10,4 @@ com.kri.common.autoconfigure.redis.CommonRedisAutoConfiguration com.kri.common.autoconfigure.scheduling.CommonSchedulingAutoConfiguration com.kri.common.autoconfigure.http.bypass.BypassAutoConfiguration com.kri.common.autoconfigure.crypto.CryptoAutoConfiguration +com.kri.common.autoconfigure.http.ExternalApiErrorAutoConfiguration