Compare commits
46 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5a943e3399 | |||
| 3090f745ba | |||
| af6b84f57d | |||
| 90633b3d26 | |||
| 822072147e | |||
| 3527884e31 | |||
| 8df8a73175 | |||
| 5d9676b504 | |||
| 40f496cfba | |||
| efc06e6023 | |||
| a923ff3f9f | |||
| ab9b86e7cf | |||
| d78e422368 | |||
| 3cc66fcaa8 | |||
| 73ed49372a | |||
| 3574ad9e0c | |||
| 49eb8fbe85 | |||
| 253716f4b2 | |||
| 02e282c7ba | |||
| 180ea8cac1 | |||
| 2c21c691df | |||
| 0da31a8de2 | |||
| 46d88d77f2 | |||
| 51967284ba | |||
| a218291748 | |||
| 96fae0c53e | |||
| 30b04e6e19 | |||
| fef16d1b99 | |||
| cf8756053e | |||
| 3fcc112113 | |||
| b85301763f | |||
| 3ebe90d595 | |||
| bf03a97fa3 | |||
| 756523c5c3 | |||
| ec48226671 | |||
| 44e3f686a4 | |||
| 5551affe3e | |||
| a616cd6334 | |||
| 05a456b461 | |||
| 056583b542 | |||
| 2ed893e70d | |||
| 23eaf725b6 | |||
| 2354af516c | |||
| 209c1ba15d | |||
| 895d346bb6 | |||
| 940e5bb90c |
@@ -142,6 +142,7 @@ dependencies {
|
||||
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test:2.6.15'
|
||||
testImplementation 'junit:junit:4.4'
|
||||
testImplementation files('libs/damo-manager.jar', 'libs/kjb-safedb.jar')
|
||||
}
|
||||
|
||||
test {
|
||||
|
||||
Binary file not shown.
@@ -5,13 +5,47 @@ import java.util.Properties;
|
||||
import com.eactive.eai.common.message.EAIMessage;
|
||||
|
||||
public interface AdapterErrorMessageHandler {
|
||||
/**
|
||||
* 비표준 -> 표준 거래
|
||||
* 아웃바운드 DefaultProcess에서 응답 표준헤더에 에러응답이 세팅되어 있는 경우, 비표준 응답 메시지 생성용
|
||||
*/
|
||||
public Object generateNonStandardErrorResponseMessage(String inboudnAdapterGroupName, String inboudnAdapterName,
|
||||
Properties callProp, Object outboundRequestData, EAIMessage resEaiMsg) throws Exception;
|
||||
|
||||
/**
|
||||
* 비표준 -> 표준 거래
|
||||
* GW 내부 오류가 발생한 경우, RequestPrcessor에서 에러 응답을 생성하는 경우, ExceptionHandler에 의해 호출, 비표준 응답 메시지 생성용
|
||||
*/
|
||||
public Object generateNonStandardInternalErrorResponseMessage(String inboudnAdapterGroupName,
|
||||
String inboudnAdapterName, Properties callProp, Object inboundRequestData, EAIMessage resEaiMsg)
|
||||
throws Exception;
|
||||
|
||||
public Object generateNonStandardInboundErrorResponseMessage(String adapterGroupName, String adapterName,
|
||||
Properties callProp, Object inboundRequestData, Object inboundResponseData, Throwable e) throws Exception;
|
||||
/**
|
||||
* 비표준 -> 표준 거래
|
||||
* GW RequestProcess 호출 전에 Adapter(Filter)에서 오류가 발생한 경우, ApiAdapterController에 Exception에 맞추어, 비표준 응답 메시지 생성용
|
||||
*/
|
||||
public Object generateNonStandardInboundErrorResponseMessage(String inboudnAdapterGroupName,
|
||||
String inboudnAdapterName, Properties callProp, Object inboundRequestData, Object inboundResponseData,
|
||||
Throwable e) throws Exception;
|
||||
|
||||
/**
|
||||
* 표준 -> 비표준 거래
|
||||
* 아웃바운드 어댑터에서 Exception이 발생했을 때, Outbound 어댑터에 의해서 호출하여 응답 메시지 생성
|
||||
* 수신한 응답 메시지가 있을 수도 있고 없을 수도 있다.
|
||||
*/
|
||||
default public Object generateOutboundErrorResponseMessage(String outboundadapterGroupName,
|
||||
String outboundadapterName, Properties callProp, Object outboundRequestData, Object outboundResponseData,
|
||||
Throwable e) throws Exception {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 표준 -> 비표준 거래
|
||||
* 아웃바운드 어댑터에서 Exception이 발생했을 때, Outbound Process 응답 메시지 생성
|
||||
*/
|
||||
default public Object generateOutboundErrorResponseMessage(String outboundadapterGroupName,
|
||||
String outboundadapterName, Properties callProp, Object outboundRequestData, EAIMessage resEaiMsg)
|
||||
throws Exception {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ import com.eactive.eai.adapter.AdapterManager;
|
||||
import com.eactive.eai.adapter.AdapterPropManager;
|
||||
import com.eactive.eai.adapter.AdapterVO;
|
||||
import com.eactive.eai.adapter.http.HttpStatusException;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.FilterCryptoException;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||
import com.eactive.eai.common.message.EAIMessage;
|
||||
import com.eactive.eai.common.property.PropManager;
|
||||
@@ -89,7 +90,7 @@ public class TemplateAdapterErrorMsgHandler implements AdapterErrorMessageHandle
|
||||
|
||||
private static final Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
/** AdapterPropManager 에서 템플릿을 조회할 프로퍼티 그룹 이름 */
|
||||
/** PropManager 에서 템플릿을 조회할 프로퍼티 그룹 이름 */
|
||||
static final String PROP_GROUP = "AdapterErrorMessageHandler";
|
||||
|
||||
/** callProp 참조 변수 접두어: ${callprop.키} */
|
||||
@@ -429,7 +430,9 @@ public class TemplateAdapterErrorMsgHandler implements AdapterErrorMessageHandle
|
||||
String adptMsgType = adapterVO.getAdapterGroupVO().getMessageType();
|
||||
String encode = StringUtils.defaultIfBlank(adapterGroupVO.getMessageEncode(), "UTF-8");
|
||||
|
||||
if (e instanceof HttpStatusException) {
|
||||
if (e instanceof FilterCryptoException) {
|
||||
return genInboundErrorResponse(adapterGroupName, callProp, httpProp, adptMsgType, encode, e, 550);
|
||||
} else if (e instanceof HttpStatusException) {
|
||||
HttpStatusException e1 = (HttpStatusException) e;
|
||||
int httpCode = e1.getStatus();
|
||||
|
||||
@@ -443,6 +446,22 @@ public class TemplateAdapterErrorMsgHandler implements AdapterErrorMessageHandle
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 표준 -> 비표준 거래
|
||||
* 아웃바운드 어댑터에서 Exception이 발생했을 때, Outbound Process 응답 메시지 생성
|
||||
*/
|
||||
@Override
|
||||
public Object generateOutboundErrorResponseMessage(String outboundadapterGroupName,
|
||||
String outboundadapterName, Properties callProp, Object outboundRequestData, EAIMessage resEaiMsg)
|
||||
throws Exception {
|
||||
String templateKey = outboundadapterGroupName + ".template";
|
||||
String template = PropManager.getInstance().getProperty(PROP_GROUP, templateKey);
|
||||
if (StringUtils.isBlank(template)) {
|
||||
return null;
|
||||
}
|
||||
return render(template, resEaiMsg.getStandardMessage(), callProp);
|
||||
}
|
||||
|
||||
private Object genInboundErrorResponse(String adapterGroupName, Properties callProp, Properties httpProp,
|
||||
String adptMsgType, String encode, Throwable e1, int httpCode) {
|
||||
String templateKey = adapterGroupName + ".in." + httpCode + ".template";
|
||||
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
package com.eactive.eai.adapter.handler;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.eactive.eai.common.message.EAIMessage;
|
||||
import com.eactive.eai.common.property.PropManager;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
|
||||
public class TemplateCodeConvertAdapterErrorMsgHandler extends TemplateAdapterErrorMsgHandler {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
/** PropManager 에서 코드 변환 설정을 조회할 프로퍼티 그룹 이름 */
|
||||
static final String PROP_GROUP = "AdapterErrorMessageHandler{CODE_CONVERT}";
|
||||
|
||||
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
||||
|
||||
@Override
|
||||
public Object generateNonStandardErrorResponseMessage(
|
||||
String inboundAdapterGroupName,
|
||||
String inboundAdapterName,
|
||||
Properties callProp,
|
||||
Object outboundRequestData,
|
||||
EAIMessage resEaiMsg) throws Exception {
|
||||
|
||||
Object responseMsessage = super.generateNonStandardErrorResponseMessage(
|
||||
inboundAdapterGroupName,
|
||||
inboundAdapterName,
|
||||
callProp,
|
||||
outboundRequestData,
|
||||
resEaiMsg);
|
||||
|
||||
logger.debug("generateNonStandardErrorResponseMessage - {}", responseMsessage);
|
||||
|
||||
if (!(responseMsessage instanceof String)) {
|
||||
return responseMsessage;
|
||||
}
|
||||
|
||||
String jsonStr = (String) responseMsessage;
|
||||
if (StringUtils.isBlank(jsonStr)) {
|
||||
return responseMsessage;
|
||||
}
|
||||
|
||||
Properties props = PropManager.getInstance().getProperties(PROP_GROUP);
|
||||
if (props == null) {
|
||||
return responseMsessage;
|
||||
}
|
||||
|
||||
String fieldsKey = inboundAdapterGroupName + ".convert.fields";
|
||||
String fieldsValue = props.getProperty(fieldsKey);
|
||||
if (StringUtils.isBlank(fieldsValue)) {
|
||||
return responseMsessage;
|
||||
}
|
||||
|
||||
JsonNode rootNode = OBJECT_MAPPER.readTree(jsonStr);
|
||||
boolean modified = false;
|
||||
|
||||
for (String rawField : fieldsValue.split(",")) {
|
||||
String fieldPath = rawField.trim();
|
||||
if (StringUtils.isBlank(fieldPath)) continue;
|
||||
|
||||
String currentValue = getJsonValue(rootNode, fieldPath);
|
||||
if (currentValue == null) continue;
|
||||
|
||||
// key: inboundAdapterGroupName.{fieldPath}.{현재값} → 폴백: ...{fieldPath}.default
|
||||
String mappingKey = inboundAdapterGroupName + "." + fieldPath + "." + currentValue;
|
||||
String newValue = props.getProperty(mappingKey);
|
||||
if (newValue == null) {
|
||||
String defaultKey = inboundAdapterGroupName + "." + fieldPath + ".default";
|
||||
newValue = props.getProperty(defaultKey);
|
||||
}
|
||||
if (newValue == null) continue;
|
||||
|
||||
setJsonValue(rootNode, fieldPath, newValue);
|
||||
modified = true;
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("code convert: field={}, {} -> {}", fieldPath, currentValue, newValue);
|
||||
}
|
||||
}
|
||||
|
||||
if (modified) {
|
||||
responseMsessage = OBJECT_MAPPER.writeValueAsString(rootNode);
|
||||
}
|
||||
|
||||
return responseMsessage;
|
||||
}
|
||||
|
||||
/**
|
||||
* dot 구분 경로로 JsonNode 에서 값을 꺼낸다.
|
||||
* 최종 노드가 값 노드(primitive)가 아니면 null 반환.
|
||||
*/
|
||||
private String getJsonValue(JsonNode node, String fieldPath) {
|
||||
JsonNode current = node;
|
||||
for (String part : fieldPath.split("\\.", -1)) {
|
||||
if (current == null || !current.isObject()) return null;
|
||||
current = current.get(part);
|
||||
}
|
||||
if (current == null || current.isNull() || !current.isValueNode()) return null;
|
||||
return current.asText();
|
||||
}
|
||||
|
||||
/**
|
||||
* dot 구분 경로로 ObjectNode 의 최종 필드 값을 newValue 로 교체한다.
|
||||
* 중간 경로가 ObjectNode 가 아니면 무시한다.
|
||||
*/
|
||||
private void setJsonValue(JsonNode rootNode, String fieldPath, String newValue) {
|
||||
String[] parts = fieldPath.split("\\.", -1);
|
||||
JsonNode current = rootNode;
|
||||
for (int i = 0; i < parts.length - 1; i++) {
|
||||
if (current == null || !current.isObject()) return;
|
||||
current = current.get(parts[i]);
|
||||
}
|
||||
if (current instanceof ObjectNode) {
|
||||
((ObjectNode) current).put(parts[parts.length - 1], newValue);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -41,6 +41,12 @@ public class HttpStatusException extends Exception {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public HttpStatusException(String msg, String code, int status, Throwable cause) {
|
||||
super(msg, cause);
|
||||
this.setCode(code);
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public int getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
+679
@@ -0,0 +1,679 @@
|
||||
package com.eactive.eai.adapter.http.client.impl;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ConnectException;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.BitSet;
|
||||
import java.util.Formatter;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.time.StopWatch;
|
||||
import org.apache.hc.client5.http.classic.HttpClient;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpDelete;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpGet;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpPost;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpPut;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
|
||||
import org.apache.hc.client5.http.config.RequestConfig;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
|
||||
import org.apache.hc.core5.http.Header;
|
||||
import org.apache.hc.core5.http.HttpStatus;
|
||||
import org.apache.hc.core5.http.io.entity.ByteArrayEntity;
|
||||
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
||||
import org.apache.hc.core5.http.protocol.BasicHttpContext;
|
||||
import org.apache.hc.core5.http.protocol.HttpContext;
|
||||
import org.json.simple.JSONArray;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.JSONValue;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.util.UriComponents;
|
||||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
|
||||
import com.eactive.eai.adapter.http.HttpMemoryLogger;
|
||||
import com.eactive.eai.adapter.http.HttpMethodType;
|
||||
import com.eactive.eai.adapter.http.client.HttpClient5AdapterServiceSupport;
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterVO;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.dynamic.impl.HttpAdapterServiceBypass;
|
||||
import com.eactive.eai.common.TransactionContextKeys;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.util.CommonLib;
|
||||
import com.jayway.jsonpath.DocumentContext;
|
||||
import com.jayway.jsonpath.JsonPath;
|
||||
import com.openbanking.eai.common.token.AccessTokenManager;
|
||||
import com.openbanking.eai.common.token.AccessTokenVO;
|
||||
import com.openbanking.eai.common.token.OAuth2AccessTokenVO;
|
||||
|
||||
public class HttpClient5AdapterServiceBypass extends HttpClient5AdapterServiceSupport
|
||||
implements HttpClientAdapterServiceKey {
|
||||
public static final String TYPE_BYPASS_REQUEST = "bypassRequest";
|
||||
public static final String REST_OPTION = "REST_OPTION";
|
||||
|
||||
protected boolean doSendUrlFragment = true;
|
||||
protected boolean doHandleCompression = false;
|
||||
protected boolean doForwardIP = false;
|
||||
|
||||
@SuppressWarnings({ "unchecked" })
|
||||
public Object execute(Properties prop, Object data, Properties tempProp) throws Exception {
|
||||
HttpClientAdapterVO vo = super.setting(prop, tempProp);
|
||||
|
||||
boolean useAdapterToken = StringUtils.equalsIgnoreCase(prop.getProperty("ADAPTER_TOKEN_USE_YN", "N"), "Y");
|
||||
|
||||
// ex) $.dataHeader.GW_RSLT_CD
|
||||
String tokenErrorCodeKey = prop.getProperty("ADAPTER_TOKEN_ERROR_CODE_KEY");
|
||||
String tokenErrorCodeValues = prop.getProperty("ADAPTER_TOKEN_ERROR_CODE_VALUES");
|
||||
String tokenErrorHttpStatusCode = prop.getProperty("ADAPTER_TOKEN_ERROR_HTTP_STATUS_CODE"); // 200 or 400번대
|
||||
|
||||
/**
|
||||
* @formatter:off
|
||||
* TSEAIHE02.RESTOPTION 정보 => JSON 형태로 구성
|
||||
* - type : simpleRequest, variableUrlRequest
|
||||
* - extraPath : 어댑터 프로퍼티 URL에 추가될 HTTP REST URL
|
||||
* - method : get, delete, post, put
|
||||
* - contentType : application/json, application/x-www-form-urlencoded
|
||||
* - adapterTokenUseYn: Y, N(default)
|
||||
* ex)
|
||||
* {"type":"variableUrlRequest","extraPath":"/aaa/{userId}","uriVariables":["userId"]}
|
||||
* @formatter:on
|
||||
*/
|
||||
String restOptionData = tempProp.getProperty(REST_OPTION, "{}");
|
||||
|
||||
JSONObject restOptionObject = parseJson(restOptionData);
|
||||
|
||||
String adapterTokenUseYn = (String) restOptionObject.get("adapterTokenUseYn");
|
||||
if (StringUtils.isNotBlank(adapterTokenUseYn)) { // interface 에 설정된게 우선한다.
|
||||
useAdapterToken = StringUtils.equalsIgnoreCase(adapterTokenUseYn, "Y");
|
||||
}
|
||||
|
||||
String inboundMethod = tempProp.getProperty(HttpAdapterServiceKey.INBOUND_METHOD, "POST");
|
||||
String inboundRewritePath = tempProp.getProperty(HttpAdapterServiceKey.INBOUND_REWRITE_PATH, "");
|
||||
String inboundQueryString = tempProp.getProperty(HttpAdapterServiceKey.INBOUND_QUERY_STRING, "");
|
||||
Properties inboundHeaders = (Properties) tempProp.get(HttpAdapterServiceKey.INBOUND_HEADER);
|
||||
Map<String, String> inboundPathVariables = (Map<String, String>) tempProp
|
||||
.get(HttpAdapterServiceKey.INBOUND_PATH_VARIABLES);
|
||||
|
||||
String restMethod = (String) restOptionObject.get("method");
|
||||
if (StringUtils.isBlank(restMethod)) {
|
||||
restMethod = inboundMethod;
|
||||
}
|
||||
|
||||
String url = getRewriteUrl(vo, inboundRewritePath, inboundQueryString, restOptionObject, inboundPathVariables);
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClient5AdapterServiceBypass] url = [" + url + "]");
|
||||
}
|
||||
|
||||
HttpClient mclient = this.client;
|
||||
HttpUriRequestBase method = generateMethod(restMethod, url);
|
||||
|
||||
assignRequestHeaders(method, inboundHeaders, tempProp);
|
||||
|
||||
if (hasBody(data, method)) {
|
||||
byte[] bodyBytes;
|
||||
if (data instanceof byte[]) {
|
||||
bodyBytes = (byte[]) data;
|
||||
} else if (data instanceof String) {
|
||||
bodyBytes = ((String) data).getBytes(vo.getEncode());
|
||||
} else {
|
||||
bodyBytes = new byte[0];
|
||||
}
|
||||
method.setEntity(new ByteArrayEntity(bodyBytes, null));
|
||||
}
|
||||
|
||||
String contentType = (String) restOptionObject.get("contentType");
|
||||
if (StringUtils.isBlank(contentType) && inboundHeaders != null) {
|
||||
contentType = getIgnoreCaseProp(inboundHeaders, HttpHeaders.CONTENT_TYPE);
|
||||
contentType = StringUtils.substringBefore(contentType, ";");
|
||||
}
|
||||
|
||||
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
|
||||
configureHttpClient(requestConfigBuilder, vo, method);
|
||||
|
||||
OAuth2AccessTokenVO accessToken = null;
|
||||
if (useAdapterToken) {
|
||||
AccessTokenManager tokenManager = AccessTokenManager.getInstance();
|
||||
accessToken = (OAuth2AccessTokenVO) tokenManager.getAccessTokenVO(vo.getAdapterGroupName());
|
||||
|
||||
// 토큰이 없거나 만료 됐으면 재발급
|
||||
if (accessToken == null || accessToken.isExpired()) {
|
||||
String oldToken = accessToken == null ? null : accessToken.getAccessToken();
|
||||
accessToken = (OAuth2AccessTokenVO) tokenManager.retryAccessTokenVO(vo.getAdapterGroupName(), prop,
|
||||
oldToken);
|
||||
}
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClient5AdapterServiceBypass] SEND (" + vo.getAdapterGroupName() + ") TOKEN = ["
|
||||
+ accessToken + "]");
|
||||
}
|
||||
|
||||
setAuthHeaders(method, accessToken);
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClient5AdapterServiceBypass] SEND (" + vo.getAdapterGroupName()
|
||||
+ ") RequestHeader [Authorization=" + method.getFirstHeader("Authorization") + "]");
|
||||
}
|
||||
}
|
||||
|
||||
// 로깅 인터셉터에 전달할 컨텍스트 정보 설정
|
||||
String uuid = tempProp.getProperty(TransactionContextKeys.TRANSACTION_UUID);
|
||||
HttpContext context = new BasicHttpContext();
|
||||
context.setAttribute(TransactionContextKeys.TRANSACTION_UUID, uuid);
|
||||
context.setAttribute(HttpClientAdapterServiceKey.ADAPTER_GROUP_NAME, vo.getAdapterGroupName());
|
||||
context.setAttribute(HttpClientAdapterServiceKey.ADAPTER_NAME, vo.getAdapterName());
|
||||
Integer logProcessNo = (Integer) tempProp.get(HttpClientAdapterServiceKey.LOG_PROCESS_NO);
|
||||
if (logProcessNo != null && logProcessNo > 0) {
|
||||
context.setAttribute(HttpClientAdapterServiceKey.LOG_PROCESS_NO, logProcessNo);
|
||||
}
|
||||
|
||||
int status = -1;
|
||||
|
||||
try {
|
||||
StopWatch stopWatch = new StopWatch();
|
||||
stopWatch.start();
|
||||
|
||||
byte[] responseMessage = null;
|
||||
Header[] responseHeaders = null;
|
||||
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.txlog(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"SEND [Bypass Request..]" + CommonLib.getDumpMessage(data));
|
||||
}
|
||||
try {
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("[method getName]" + method.getMethod());
|
||||
logger.debug("[method getRequestHeaders]" + java.util.Arrays.toString(method.getHeaders()));
|
||||
logger.debug("[method getURI]" + method.getPath());
|
||||
}
|
||||
try (CloseableHttpResponse response = (CloseableHttpResponse) mclient.execute(method, context)) {
|
||||
status = response.getCode();
|
||||
responseHeaders = response.getHeaders();
|
||||
responseMessage = EntityUtils.toByteArray(response.getEntity());
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("[received status]" + status);
|
||||
}
|
||||
}
|
||||
} catch (ConnectException e) {
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClient5AdapterServiceBypass] responseType =" + vo.getResponseType());
|
||||
logger.debug("HttpClient5AdapterServiceBypass] RECV (" + vo.getAdapterGroupName() + ") = "
|
||||
+ CommonLib.getDumpMessage(responseMessage));
|
||||
}
|
||||
throw new Exception("excuteMethod java.net.ConnectException = " + e.getMessage());
|
||||
}
|
||||
|
||||
stopWatch.stop();
|
||||
|
||||
/**
|
||||
* @formatter:off
|
||||
* OAuth 토큰 응답 체크(Adapter properties로 설정)
|
||||
* 응답코드에 따라 유효한 토큰 확인(토큰 재발급 여부 확인)
|
||||
* API 서비스 마다 정책이 다름(보통 400대에서 체크하나 200에서도 체크할 수 있음)
|
||||
*
|
||||
* TOKEN_ERROR_CODE_KEY: 응답 json error code key
|
||||
* __ex) $.dataHeader.resultCode
|
||||
* TOKEN_ERROR_CODE_VALUES: 토큰 재발급이 필요한 응답 error codes(ex: O0001,O0002,O0003)
|
||||
* TOKEN_ERROR_HTTP_STATUS_CODE: 보통 400대에서 체크하나 API 제공자에 따라 200에서도 체클할수 있음
|
||||
* ex) TOKEN_ERROR_HTTP_STATUS_CODE = 200
|
||||
* @formatter:on
|
||||
*/
|
||||
boolean needReissue = false;
|
||||
|
||||
if (status == 200) {
|
||||
if (useAdapterToken && StringUtils.equals(tokenErrorHttpStatusCode, "200")) {
|
||||
needReissue = checkTokenRetry(responseMessage, tokenErrorCodeKey, tokenErrorCodeValues,
|
||||
vo.getEncode());
|
||||
}
|
||||
} else if (status >= 400 && status < 500) {
|
||||
if (useAdapterToken) {
|
||||
needReissue = checkTokenRetry(responseMessage, tokenErrorCodeKey, tokenErrorCodeValues,
|
||||
vo.getEncode());
|
||||
}
|
||||
|
||||
if (!needReissue) {
|
||||
// body 값이 없을때만 exception 처리하고, body가 있으면 bypass 한다.
|
||||
if (responseMessage == null || responseMessage.length == 0) {
|
||||
String errMsg = String.format(
|
||||
"http receive status fail value=%d adapterName=%s.%s uri=%s method=%s response Data=%s",
|
||||
status, vo.getAdapterGroupName(), vo.getAdapterName(), url, restMethod, responseMessage);
|
||||
throw new Exception(errMsg);
|
||||
}
|
||||
}
|
||||
} else if (status != 200) {
|
||||
responseMessage = responseMessage != null ? responseMessage : new byte[0];
|
||||
// body 값이 없을때만 exception 처리하고, body가 있으면 bypass 한다.
|
||||
if (responseMessage.length == 0) {
|
||||
String errMsg = String.format(
|
||||
"http receive status fail value=%d adapterName=%s.%s uri=%s method=%s response Data=%s",
|
||||
status, vo.getAdapterGroupName(), vo.getAdapterName(), url, restMethod, responseMessage);
|
||||
throw new Exception(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
if (useAdapterToken) {
|
||||
if (responseMessage == null) {
|
||||
throw new Exception("responseMessage is NULL, HttpStatus=" + status);
|
||||
}
|
||||
|
||||
// OAuth 토큰 재요청 코드 확인
|
||||
if (needReissue) {
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClient5AdapterServiceBypass] retry access token response code = ["
|
||||
+ vo.getResponseType() + "] message = [" + new String(responseMessage, vo.getEncode())
|
||||
+ "]");
|
||||
}
|
||||
|
||||
// 토큰 재발급
|
||||
AccessTokenManager tokenManager = AccessTokenManager.getInstance();
|
||||
String oldToken = accessToken == null ? null : accessToken.getAccessToken();
|
||||
OAuth2AccessTokenVO newAccessToken = (OAuth2AccessTokenVO) tokenManager
|
||||
.retryAccessTokenVO(vo.getAdapterGroupName(), prop, oldToken);
|
||||
method.setHeader("Authorization", newAccessToken.getAuthorization());
|
||||
setAuthHeaders(method, newAccessToken);
|
||||
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClient5AdapterServiceBypass] SEND (" + vo.getAdapterGroupName()
|
||||
+ ") RETRY TOKEN = [" + newAccessToken + "]");
|
||||
}
|
||||
|
||||
try (CloseableHttpResponse retryResponse = (CloseableHttpResponse) mclient.execute(method, context)) {
|
||||
status = retryResponse.getCode();
|
||||
responseHeaders = retryResponse.getHeaders();
|
||||
responseMessage = EntityUtils.toByteArray(retryResponse.getEntity());
|
||||
} catch (IOException e) {
|
||||
throw new Exception("retry excuteMethod Exception = " + e.getMessage());
|
||||
}
|
||||
|
||||
if (status != 200) {
|
||||
responseMessage = responseMessage != null ? responseMessage : new byte[0];
|
||||
if (responseMessage.length == 0) {
|
||||
String errMsg = String.format(
|
||||
"http receive status fail value=%d adapterName=%s.%s uri=%s method=%s response Data=%s",
|
||||
status, vo.getAdapterGroupName(), vo.getAdapterName(), url, restMethod,
|
||||
responseMessage);
|
||||
throw new Exception(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClient5AdapterServiceBypass] RETRY responseType =" + vo.getResponseType());
|
||||
logger.debug("HttpClient5AdapterServiceBypass] RETRY RECV (" + vo.getAdapterGroupName() + ") = "
|
||||
+ CommonLib.getDumpMessage(responseMessage));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.txlog(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"RECV [Bypass Request..]" + CommonLib.getDumpMessage(responseMessage));
|
||||
}
|
||||
// 응답 Content-Type charset 기반 인코딩 결정, 없으면 어댑터 encoding 사용
|
||||
String responseEncode = vo.getEncode();
|
||||
if (responseHeaders != null) {
|
||||
for (Header header : responseHeaders) {
|
||||
if (StringUtils.equalsIgnoreCase(header.getName(), HttpHeaders.CONTENT_TYPE)) {
|
||||
try {
|
||||
MediaType mediaType = MediaType.parseMediaType(header.getValue());
|
||||
if (mediaType.getCharset() != null) {
|
||||
responseEncode = mediaType.getCharset().name();
|
||||
}
|
||||
} catch (Exception ignored) {}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
assignRelayDataToInbound(tempProp, responseHeaders, status);
|
||||
return responseMessage != null ? new String(responseMessage, responseEncode) : "";
|
||||
} catch (SocketTimeoutException ste) {
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"HttpClient5AdapterServiceBypass] SocketTimeoutException (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ste.toString(),
|
||||
ste);
|
||||
}
|
||||
logger.error("HttpClient5AdapterServiceBypass] SocketTimeoutException (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ste.toString(), ste);
|
||||
throw ste;
|
||||
} catch (ConnectException ce) {
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"HttpClient5AdapterServiceBypass] Connection Exception (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ce.toString(),
|
||||
ce);
|
||||
}
|
||||
logger.error("HttpClient5AdapterServiceBypass] Connection Exception (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ce.toString(), ce);
|
||||
throw ce;
|
||||
} catch (Exception e) {
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(), e.toString(), e);
|
||||
}
|
||||
logger.error(
|
||||
"HttpClient5AdapterServiceBypass] Exception (" + vo.getAdapterGroupName() + ") : " + e.toString(),
|
||||
e);
|
||||
throw e;
|
||||
} finally {
|
||||
if (status != HttpStatus.SC_OK) {
|
||||
String[] msgArgs = new String[1];
|
||||
msgArgs[0] = String.valueOf(status);
|
||||
String resMsg = ExceptionUtil.make("RDCEAIAHA013", msgArgs);
|
||||
if (logger.isDebug()) {
|
||||
logger.debug(resMsg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean hasBody(Object data, HttpUriRequestBase method) {
|
||||
if (data == null) {
|
||||
return false;
|
||||
}
|
||||
// GET, DELETE는 표준 HTTP에서 body를 지원하지 않음
|
||||
return method instanceof HttpPost || method instanceof HttpPut;
|
||||
}
|
||||
|
||||
private HttpUriRequestBase generateMethod(String restMethod, String url) {
|
||||
switch (HttpMethodType.getValue(restMethod)) {
|
||||
case GET:
|
||||
return new HttpGet(url);
|
||||
case DELETE:
|
||||
return new HttpDelete(url);
|
||||
case POST:
|
||||
return new HttpPost(url);
|
||||
case PUT:
|
||||
return new HttpPut(url);
|
||||
default:
|
||||
return new HttpPost(url);
|
||||
}
|
||||
}
|
||||
|
||||
private String getRewriteUrl(HttpClientAdapterVO vo, String inboundRewritePath, String queryString,
|
||||
JSONObject restOptionObject, Map<String, String> inboundPathVariables) {
|
||||
String fragment = null;
|
||||
if (StringUtils.isNotBlank(queryString)) {
|
||||
int fragIdx = queryString.indexOf('#');
|
||||
if (fragIdx >= 0) {
|
||||
fragment = queryString.substring(fragIdx + 1);
|
||||
queryString = queryString.substring(0, fragIdx);
|
||||
}
|
||||
}
|
||||
|
||||
String restExtraPath = (String) restOptionObject.get("extraPath");
|
||||
if (StringUtils.isBlank(restExtraPath)) {
|
||||
StringBuilder uri = new StringBuilder(500);
|
||||
String baseUrl = StringUtils.removeEnd(vo.getUrl(), "/");
|
||||
String rewritePath = inboundRewritePath != null && !inboundRewritePath.startsWith("/")
|
||||
? "/" + inboundRewritePath : inboundRewritePath;
|
||||
uri.append(baseUrl).append(StringUtils.defaultString(rewritePath));
|
||||
|
||||
if (StringUtils.isNotBlank(queryString)) {
|
||||
uri.append('?');
|
||||
uri.append(encodeUriQuery(queryString, false));
|
||||
}
|
||||
|
||||
if (doSendUrlFragment && fragment != null) {
|
||||
uri.append('#');
|
||||
uri.append(encodeUriQuery(fragment, false));
|
||||
}
|
||||
|
||||
return uri.toString();
|
||||
} else {
|
||||
String type = (String) restOptionObject.get("type");
|
||||
String url = getUrl(vo.getUrl(), restExtraPath);
|
||||
|
||||
if (StringUtils.equalsIgnoreCase(type, HttpClientAdapterServiceRest.TYPE_VARIABLE_URL_REQUEST)) {
|
||||
inboundPathVariables = mergeInboundPathVariables(inboundPathVariables, queryString);
|
||||
List<String> urlVariableValueList = new ArrayList<>();
|
||||
JSONArray uriVariables = (JSONArray) restOptionObject.get("uriVariables");
|
||||
if (uriVariables != null && !uriVariables.isEmpty() && inboundPathVariables != null
|
||||
&& !inboundPathVariables.isEmpty()) {
|
||||
for (Object tempObject : uriVariables) {
|
||||
String urlVaribleId = (String) tempObject;
|
||||
String uriVariableValue = inboundPathVariables.get(urlVaribleId);
|
||||
urlVariableValueList.add(uriVariableValue);
|
||||
}
|
||||
|
||||
if (!urlVariableValueList.isEmpty()) {
|
||||
UriComponents uriComponents = UriComponentsBuilder.fromUriString(url).build();
|
||||
Object[] urls = urlVariableValueList.toArray();
|
||||
url = uriComponents.expand(urls).toUriString();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (StringUtils.isNotBlank(queryString)) {
|
||||
url += "?" + encodeUriQuery(queryString, false);
|
||||
}
|
||||
|
||||
if (doSendUrlFragment && fragment != null) {
|
||||
url += "#" + encodeUriQuery(fragment, false);
|
||||
}
|
||||
}
|
||||
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, String> mergeInboundPathVariables(Map<String, String> inboundPathVariables,
|
||||
String queryString) {
|
||||
if (StringUtils.isBlank(queryString)) {
|
||||
return inboundPathVariables;
|
||||
}
|
||||
|
||||
if (inboundPathVariables == null) {
|
||||
inboundPathVariables = new LinkedHashMap<>();
|
||||
}
|
||||
|
||||
String[] pairs = queryString.split("&");
|
||||
for (String pair : pairs) {
|
||||
int idx = pair.indexOf("=");
|
||||
inboundPathVariables.put(pair.substring(0, idx), pair.substring(idx + 1));
|
||||
}
|
||||
|
||||
return inboundPathVariables;
|
||||
}
|
||||
|
||||
private String getUrl(String baseUrl, String extraPath) {
|
||||
if (StringUtils.isBlank(extraPath)) {
|
||||
return baseUrl;
|
||||
}
|
||||
|
||||
if (StringUtils.contains(extraPath, "http://") || StringUtils.contains(extraPath, "https://")) {
|
||||
return extraPath;
|
||||
}
|
||||
|
||||
String targetUrl = baseUrl;
|
||||
if (!targetUrl.endsWith("/")) {
|
||||
targetUrl += "/";
|
||||
}
|
||||
if (extraPath.startsWith("/")) {
|
||||
targetUrl += extraPath.substring(1);
|
||||
} else {
|
||||
targetUrl += extraPath;
|
||||
}
|
||||
|
||||
return targetUrl;
|
||||
}
|
||||
|
||||
protected CharSequence encodeUriQuery(CharSequence in, boolean encodePercent) {
|
||||
StringBuilder outBuf = null;
|
||||
Formatter formatter = null;
|
||||
for (int i = 0; i < in.length(); i++) {
|
||||
char c = in.charAt(i);
|
||||
boolean escape = true;
|
||||
if (c < 128) {
|
||||
if (asciiQueryChars.get(c) && !(encodePercent && c == '%')) {
|
||||
escape = false;
|
||||
}
|
||||
} else if (!Character.isISOControl(c) && !Character.isSpaceChar(c)) {
|
||||
escape = false;
|
||||
}
|
||||
if (!escape) {
|
||||
if (outBuf != null)
|
||||
outBuf.append(c);
|
||||
} else {
|
||||
if (outBuf == null) {
|
||||
outBuf = new StringBuilder(in.length() + 5 * 3);
|
||||
outBuf.append(in, 0, i);
|
||||
formatter = new Formatter(outBuf);
|
||||
}
|
||||
formatter.format("%%%02X", (int) c);
|
||||
}
|
||||
}
|
||||
return outBuf != null ? outBuf : in;
|
||||
}
|
||||
|
||||
protected static final BitSet asciiQueryChars;
|
||||
static {
|
||||
char[] c_unreserved = "_-!.~'()*".toCharArray();
|
||||
char[] c_punct = ",;:$&+=".toCharArray();
|
||||
char[] c_reserved = "/@".toCharArray();
|
||||
asciiQueryChars = new BitSet(128);
|
||||
for (char c = 'a'; c <= 'z'; c++)
|
||||
asciiQueryChars.set(c);
|
||||
for (char c = 'A'; c <= 'Z'; c++)
|
||||
asciiQueryChars.set(c);
|
||||
for (char c = '0'; c <= '9'; c++)
|
||||
asciiQueryChars.set(c);
|
||||
for (char c : c_unreserved)
|
||||
asciiQueryChars.set(c);
|
||||
for (char c : c_punct)
|
||||
asciiQueryChars.set(c);
|
||||
for (char c : c_reserved)
|
||||
asciiQueryChars.set(c);
|
||||
asciiQueryChars.set('%');
|
||||
}
|
||||
|
||||
private void assignRelayDataToInbound(Properties prop, Header[] responseHeaders, int status) {
|
||||
Properties headerProp = new Properties();
|
||||
if (responseHeaders != null) {
|
||||
for (Header header : responseHeaders) {
|
||||
String name = header.getName();
|
||||
String value = header.getValue();
|
||||
String existing = headerProp.getProperty(name);
|
||||
if (existing != null) {
|
||||
// 동일 이름의 헤더가 여러 개인 경우 콤마로 합침 (RFC 7230)
|
||||
headerProp.put(name, existing + ", " + value);
|
||||
} else {
|
||||
headerProp.put(name, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
headerProp.put(HttpAdapterServiceBypass.HTTP_STATUS, String.valueOf(status));
|
||||
|
||||
Map<String, Object> map = new HashMap<String, Object>();
|
||||
map.put(HttpAdapterServiceKey.OUTBOUND_RESPONSE_HEADERS, headerProp);
|
||||
|
||||
prop.put(HttpAdapterServiceKey.OUTBOUND_PROPERTY_MAP, map);
|
||||
}
|
||||
|
||||
private void setAuthHeaders(HttpUriRequestBase method, OAuth2AccessTokenVO accessToken) throws Exception {
|
||||
method.setHeader("Authorization",
|
||||
String.format("%s %s", AccessTokenVO.BEARER_TYPE, accessToken.getAccessToken()));
|
||||
}
|
||||
|
||||
private boolean checkTokenRetry(byte[] responseMessage, String tokenErrorCodeKey, String tokenErrorCodeValues,
|
||||
String encode) {
|
||||
if (responseMessage == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(tokenErrorCodeKey)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(tokenErrorCodeValues)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
DocumentContext jsonContext = JsonPath.parse(new String(responseMessage, encode));
|
||||
String responseCode = jsonContext.read(tokenErrorCodeKey);
|
||||
if (StringUtils.isBlank(responseCode)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String[] arr = org.springframework.util.StringUtils.tokenizeToStringArray(tokenErrorCodeValues, ",");
|
||||
return ArrayUtils.contains(arr, responseCode);
|
||||
} catch (Exception e) {
|
||||
logger.error("HttpClient5AdapterServiceBypass] checkTokenRetry error=" + e.getMessage());
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private void assignRequestHeaders(HttpUriRequestBase method, Properties headerProp, Properties inProp) {
|
||||
if (headerProp == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (Entry<Object, Object> e : headerProp.entrySet()) {
|
||||
String key = (String) e.getKey();
|
||||
String value = (String) e.getValue();
|
||||
|
||||
if (StringUtils.equalsAnyIgnoreCase(key, HttpAdapterServiceBypass.HOP_BY_HOP_HEADERS)
|
||||
|| StringUtils.equalsIgnoreCase(key, HttpHeaders.CONTENT_LENGTH)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (doHandleCompression && StringUtils.equalsIgnoreCase(key, HttpHeaders.ACCEPT_ENCODING)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
method.addHeader(key, value);
|
||||
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("Request Header :" + key + "=[" + value + "]");
|
||||
}
|
||||
}
|
||||
|
||||
if (doForwardIP) {
|
||||
String forHeaderName = "X-Forwarded-For";
|
||||
String forHeader = inProp.getProperty(HttpAdapterServiceKey.INBOUND_REMOTE_ADDR);
|
||||
if (StringUtils.isNotBlank(forHeader)) {
|
||||
String existingForHeader = headerProp.getProperty(forHeaderName);
|
||||
if (existingForHeader != null) {
|
||||
forHeader = existingForHeader + ", " + forHeader;
|
||||
}
|
||||
method.addHeader(forHeaderName, forHeader);
|
||||
}
|
||||
|
||||
String protoHeaderName = "X-Forwarded-Proto";
|
||||
String protoHeader = inProp.getProperty(HttpAdapterServiceKey.INBOUND_SCHEME);
|
||||
if (StringUtils.isNotBlank(protoHeader)) {
|
||||
method.addHeader(protoHeaderName, protoHeader);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private JSONObject parseJson(String message) throws Exception {
|
||||
if (message == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (JSONObject) JSONValue.parse(message);
|
||||
}
|
||||
|
||||
public static final String getIgnoreCaseProp(Properties prop, String key) {
|
||||
if (prop == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (Entry<Object, Object> e : prop.entrySet()) {
|
||||
if (StringUtils.equalsIgnoreCase(key, (String) e.getKey())) {
|
||||
return (String) e.getValue();
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+129
-639
File diff suppressed because it is too large
Load Diff
+8
-2
@@ -9,6 +9,9 @@ import org.json.simple.JSONObject;
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.client.impl.filter.HttpClient5AdapterFilterFactory;
|
||||
import com.eactive.eai.adapter.http.client.impl.filter.HttpClientAdapterFilter;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
/**
|
||||
* 1. 기능 : HttpClient5AdapterServiceRest 호출 전후 Filter 적용할 수 있는 기능을 제공한다.<br>
|
||||
@@ -34,6 +37,8 @@ public class HttpClient5AdapterServiceRestAddFilter extends HttpClient5AdapterSe
|
||||
// // Adapter에서 Exception이 발생한 경우, 처리할 필터
|
||||
// static final String EXCEPTION_FILTER = "EXCEPTION_FILTER";
|
||||
|
||||
private ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
/**
|
||||
* 1. 기능 : HttpClient 호출 전후 Filter 적용용 2. 처리 개요 : <br>
|
||||
* 3. 주의사항 <br>
|
||||
@@ -54,8 +59,9 @@ public class HttpClient5AdapterServiceRestAddFilter extends HttpClient5AdapterSe
|
||||
adapterResponse = doPostFilters(adptGrpName, adptName, prop, adapterResponse, tempProp);
|
||||
if (adapterResponse instanceof JSONObject)
|
||||
adapterResponse = ((JSONObject) adapterResponse).toJSONString();
|
||||
|
||||
if (adapterResponse instanceof Node)
|
||||
else if (adapterResponse instanceof ObjectNode)
|
||||
adapterResponse = mapper.writeValueAsString((ObjectNode) adapterResponse);
|
||||
else if (adapterResponse instanceof Node)
|
||||
adapterResponse = ((Node) adapterResponse).asXML();
|
||||
|
||||
return adapterResponse;
|
||||
|
||||
@@ -31,7 +31,15 @@ public class OutCryptoFilter extends AbstractCryptoFilter implements HttpClientA
|
||||
* 서브클래스에서 오버라이드하여 tempProp으로부터 값을 추출할 수 있다.
|
||||
*/
|
||||
protected Map<String, String> buildRuntimeContext(Properties prop, Properties tempProp) {
|
||||
return new HashMap<>();
|
||||
Map<String, String> context = new HashMap<>();
|
||||
for (String key : prop.stringPropertyNames()) {
|
||||
context.put(key, prop.getProperty(key));
|
||||
}
|
||||
|
||||
for (String key : tempProp.stringPropertyNames()) {
|
||||
context.put(key, tempProp.getProperty(key));
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -39,11 +47,10 @@ public class OutCryptoFilter extends AbstractCryptoFilter implements HttpClientA
|
||||
* 미설정 또는 값 없으면 null을 반환하여 GCM 기본 동작(IV를 AAD 대체값으로 사용)을 따른다.
|
||||
*/
|
||||
protected byte[] buildAad(Properties prop, Properties tempProp) {
|
||||
String propKey = prop.getProperty(PROP_AAD_HEADER);
|
||||
if (StringUtils.isBlank(propKey) || tempProp == null) {
|
||||
if (tempProp == null) {
|
||||
return null;
|
||||
}
|
||||
String value = tempProp.getProperty(propKey);
|
||||
String value = tempProp.getProperty(PROP_AAD_HEADER);
|
||||
return StringUtils.isBlank(value) ? null : value.getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
|
||||
+897
@@ -0,0 +1,897 @@
|
||||
package com.eactive.eai.adapter.http.client.impl.kjb;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
import java.math.BigDecimal;
|
||||
import java.net.ConnectException;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.time.StopWatch;
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.apache.hc.client5.http.classic.HttpClient;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpDelete;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpGet;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpPost;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpPut;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
|
||||
import org.apache.hc.client5.http.config.RequestConfig;
|
||||
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
|
||||
import org.apache.hc.core5.http.*;
|
||||
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
||||
import org.apache.hc.core5.http.io.entity.StringEntity;
|
||||
import org.apache.hc.core5.http.message.BasicNameValuePair;
|
||||
import org.apache.hc.core5.http.protocol.BasicHttpContext;
|
||||
import org.apache.hc.core5.http.protocol.HttpContext;
|
||||
import org.apache.hc.core5.net.URIBuilder;
|
||||
import org.dom4j.Document;
|
||||
import org.dom4j.Element;
|
||||
import org.dom4j.io.SAXReader;
|
||||
import org.json.simple.JSONArray;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.JSONValue;
|
||||
import org.json.simple.parser.JSONParser;
|
||||
import org.json.simple.parser.ParseException;
|
||||
import org.springframework.web.util.UriComponents;
|
||||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
|
||||
import com.eactive.eai.adapter.http.HttpMemoryLogger;
|
||||
import com.eactive.eai.adapter.http.HttpMethodType;
|
||||
import com.eactive.eai.adapter.http.client.HttpClient5AdapterServiceSupport;
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterVO;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
import com.eactive.eai.common.TransactionContextKeys;
|
||||
import com.eactive.eai.common.authoutbound.AccessTokenManagerByDB;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.message.MessageType;
|
||||
import com.eactive.eai.common.util.CommonLib;
|
||||
import com.jayway.jsonpath.DocumentContext;
|
||||
import com.jayway.jsonpath.JsonPath;
|
||||
import com.openbanking.eai.common.token.AccessTokenManager;
|
||||
import com.openbanking.eai.common.token.AccessTokenVO;
|
||||
import com.openbanking.eai.common.token.OAuth2AccessTokenVO;
|
||||
|
||||
import com.eactive.eai.common.property.PropManager;
|
||||
|
||||
public class HttpClient5AdapterServiceBase64 extends HttpClient5AdapterServiceSupport
|
||||
implements HttpClientAdapterServiceKey {
|
||||
|
||||
public static final String TYPE_VARIABLE_URL_REQUEST = "variableUrlRequest";
|
||||
public static final String TYPE_SIMPLE_REQUEST = "simpleRequest";
|
||||
public static final String REST_OPTION = "REST_OPTION";
|
||||
//public static final String HEADER_CONTENT_TYPE = "Content-Type";
|
||||
public static final String HEADER_GROUP = "HEADER_GROUP";
|
||||
public static final String HTTP_STATUS = "HTTP_STATUS";
|
||||
public static final String HEADER_KEYS = "HEADER_KEYS";
|
||||
public static final String AUTH_TOKEN = "AUTH_TOKEN";
|
||||
|
||||
/**
|
||||
* 1. 기능 : REST API 통신에 사용 <br>
|
||||
* 2. 처리 개요 : - 속성 정보를 설정 하고 수동 시스템 서비스를 호출 한다. <br>
|
||||
* 3. 주의사항 <br>
|
||||
*
|
||||
* @param prop Http Adapter 속성 정보
|
||||
* @return 반환 된 Object
|
||||
* @exception Exception 수동 시스템 간 통신 중 발생
|
||||
**/
|
||||
@SuppressWarnings({ "unchecked" })
|
||||
public Object execute(Properties prop, Object data, Properties tempProp) throws Exception {
|
||||
HttpClientAdapterVO vo = super.setting(prop, tempProp);
|
||||
|
||||
// 2025.04.09 Authorization 헤더값을 프로퍼티(AUTH_TOKEN)에서 지정하여 설정할 수 있도록 수정
|
||||
String bizCode = "";
|
||||
String authToken = "";
|
||||
try {
|
||||
Properties authProp = PropManager.getInstance().getProperties(AUTH_TOKEN); //Authorization
|
||||
bizCode = vo.getAdapterGroupName().substring(1, 4);
|
||||
authToken = authProp.getProperty(bizCode, "");
|
||||
} catch (Exception e) {
|
||||
logger.debug("Property Group AUTH_TOKEN is not Exist !!");
|
||||
}
|
||||
|
||||
logger.debug("authToken :::::::::::::::::::::::::::::::::::" + authToken);
|
||||
|
||||
String headerGroupName = prop.getProperty(HEADER_GROUP);
|
||||
String relayResponseHeaderKeys = prop.getProperty(HEADER_KEYS, "");
|
||||
boolean useAdapterToken = StringUtils.equalsIgnoreCase(prop.getProperty("ADAPTER_TOKEN_USE_YN", "N"), "Y");
|
||||
|
||||
boolean useForwardProxy = StringUtils.equalsIgnoreCase(prop.getProperty("FORWARD_PROXY_USE_YN", "N"), "Y");
|
||||
String forwardProxyUrl = prop.getProperty("FORWARD_PROXY_URL");
|
||||
|
||||
// ex) $.dataHeader.GW_RSLT_CD
|
||||
String tokenErrorCodeKey = prop.getProperty("ADAPTER_TOKEN_ERROR_CODE_KEY");
|
||||
String tokenErrorCodeValues = prop.getProperty("ADAPTER_TOKEN_ERROR_CODE_VALUES");
|
||||
String tokenErrorHttpStatusCode = prop.getProperty("ADAPTER_TOKEN_ERROR_HTTP_STATUS_CODE"); // 200 or 400번대
|
||||
|
||||
// 레이아웃 메시지 타입 REST URL 추출 시 활용. Default JSON
|
||||
String messageType = prop.getProperty("MESSAGE_TYPE", MessageType.JSON);
|
||||
String inboundMethod = tempProp.getProperty(HttpAdapterServiceKey.INBOUND_METHOD, "POST");
|
||||
|
||||
/**
|
||||
* @formatter:off
|
||||
* TSEAIHE02.RESTOPTION 정보 => JSON 형태로 구성
|
||||
* - type : simpleRequest, variableUrlRequest
|
||||
* - extraPath : 어댑터 프로퍼티 URL에 추가될 HTTP REST URL
|
||||
* - method : get, delete, post, put
|
||||
* - contentType: application/json(default), application/x-www-form-urlencoded
|
||||
* - adapterTokenUseYn: Y, N(default)
|
||||
* ex)
|
||||
* {"type":"simpleRequest","extraPath":"v2.0/accout/balance","method":"post"}
|
||||
* @formatter:on
|
||||
*/
|
||||
|
||||
String restOptionData = tempProp.getProperty(REST_OPTION);
|
||||
|
||||
JSONObject restOptionObject = parseJson(restOptionData);
|
||||
if (restOptionObject == null) {
|
||||
throw new Exception("OptionData parsing result is NULL");
|
||||
}
|
||||
|
||||
String rmethod = (String) restOptionObject.getOrDefault("method", inboundMethod);
|
||||
String contentType = (String) restOptionObject.getOrDefault("contentType", "application/json");
|
||||
String adapterTokenUseYn = (String) restOptionObject.get("adapterTokenUseYn");
|
||||
if (StringUtils.isNotBlank(adapterTokenUseYn)) { // interface 에 설정된게 우선한다.
|
||||
useAdapterToken = StringUtils.equalsIgnoreCase(adapterTokenUseYn, "Y");
|
||||
}
|
||||
|
||||
HttpClient mclient = this.client;
|
||||
String sendData = "";
|
||||
if (data instanceof String) {
|
||||
sendData = (String) data;
|
||||
} else if (data instanceof byte[]) {
|
||||
sendData = new String((byte[]) data, vo.getEncode());
|
||||
}
|
||||
|
||||
////mclient.getParams().setContentCharset(vo.getEncode());
|
||||
|
||||
JSONObject dataObject = null;
|
||||
|
||||
Object httpHeader = null;
|
||||
Object dataContent = null;
|
||||
|
||||
if (MessageType.JSON.equals(messageType)) {
|
||||
|
||||
Object parsed = parseJsonGeneric(sendData);
|
||||
|
||||
if(parsed instanceof JSONObject) {
|
||||
dataObject = parseJson(sendData);
|
||||
if (dataObject != null && StringUtils.isNotBlank(headerGroupName)) {
|
||||
httpHeader = dataObject.get(headerGroupName);
|
||||
dataObject.remove(headerGroupName);
|
||||
}
|
||||
|
||||
dataContent = dataObject;
|
||||
if (dataObject.containsKey("innerList")) {
|
||||
JSONArray innerList = (JSONArray) dataObject.get("innerList");
|
||||
dataContent = innerList;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.debug("HttpClientAdapterServiceRest] dataObject1 = [" + dataObject + "]");
|
||||
logger.debug("HttpClientAdapterServiceRest] dataContent = [" + dataContent + "]");
|
||||
|
||||
// interface 에 설정된게 우선한다.
|
||||
String uri = null;
|
||||
if (dataObject == null) {
|
||||
uri = changeUrl(messageType, vo.getUrl(), restOptionData, sendData);
|
||||
} else {
|
||||
uri = changeUrl(messageType, vo.getUrl(), restOptionData, dataObject);
|
||||
}
|
||||
|
||||
// ////if (vo.getConnectionTimeout() != 0) {
|
||||
// mclient.getHttpConnectionManager().getParams().setConnectionTimeout(vo.getConnectionTimeout());
|
||||
// }
|
||||
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") URL=[" + vo.getUrl() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") PARAMETER_NAME=[" + vo.getParameterName() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") ENCODE=[" + vo.getEncode() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") RESPONSE_TYPE=[" + vo.getResponseType() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") URL_ENCODE_YN=[" + vo.getUrlEncodeYn() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") CONNECTION_TIMEOUT=[" + vo.getConnectionTimeout() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") REST_OPTION=[" + restOptionData + "] ");
|
||||
}
|
||||
|
||||
HttpUriRequestBase method = null;
|
||||
|
||||
// 메소드 타입에 따라 HttpRequestBase 인스턴스 생성
|
||||
switch (HttpMethodType.getValue(rmethod)) {
|
||||
case GET:
|
||||
method = new HttpGet(uri);
|
||||
break;
|
||||
case DELETE:
|
||||
method = new HttpDelete(uri);
|
||||
break;
|
||||
case POST:
|
||||
method = new HttpPost(uri);
|
||||
break;
|
||||
case PUT:
|
||||
method = new HttpPut(uri);
|
||||
break;
|
||||
default:
|
||||
method = new HttpGet(uri);
|
||||
break;
|
||||
}
|
||||
|
||||
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
|
||||
|
||||
if(useForwardProxy) {
|
||||
java.net.URL url = new java.net.URL(forwardProxyUrl);
|
||||
|
||||
// 프로토콜, 호스트, 포트 추출
|
||||
String protocol = url.getProtocol();
|
||||
String host = url.getHost();
|
||||
int port = url.getPort();
|
||||
HttpHost proxy = new HttpHost(protocol,host, port);
|
||||
requestConfigBuilder.setProxy(proxy);
|
||||
}
|
||||
|
||||
configureHttpClient(requestConfigBuilder, vo, method);
|
||||
|
||||
switch (HttpMethodType.getValue(rmethod)) {
|
||||
case GET:
|
||||
case DELETE:
|
||||
HashMap<String, String> h = getParameters(dataObject);
|
||||
URIBuilder uriBuilder = new URIBuilder(uri);
|
||||
for (Map.Entry<String, String> entry : h.entrySet()) {
|
||||
uriBuilder.addParameter(entry.getKey(), entry.getValue());
|
||||
}
|
||||
URI fullUri = uriBuilder.build();
|
||||
if (method instanceof HttpGet) {
|
||||
((HttpGet) method).setUri(fullUri);
|
||||
} else if (method instanceof HttpDelete) {
|
||||
((HttpDelete) method).setUri(fullUri);
|
||||
}
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClientAdapterServiceRest] (get Method) QueryString = [" + fullUri.getQuery() + "]");
|
||||
}
|
||||
break;
|
||||
case PUT:
|
||||
case POST:
|
||||
//assignPostBody(dataObject, contentType, vo.getEncode(), method);
|
||||
assignPostBody(dataContent, contentType, vo.getEncode(), method);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") method.getParams()=["
|
||||
+ method.getEntity() + "] ");
|
||||
}
|
||||
|
||||
OAuth2AccessTokenVO accessToken = null;
|
||||
if (useAdapterToken) {
|
||||
AccessTokenManagerByDB tokenManager = AccessTokenManagerByDB.getInstance();
|
||||
accessToken = (OAuth2AccessTokenVO) tokenManager.getAccessTokenVO(vo.getAdapterGroupName());
|
||||
|
||||
// 토큰이 없거나 만료 됐으면 재발급
|
||||
if (accessToken == null || accessToken.isExpired()) {
|
||||
String oldToken = accessToken == null ? null : accessToken.getAccessToken();
|
||||
accessToken = (OAuth2AccessTokenVO) tokenManager.retryAccessTokenVO(vo.getAdapterGroupName(), prop,
|
||||
oldToken);
|
||||
}
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") TOKEN = ["
|
||||
+ accessToken + "]");
|
||||
}
|
||||
|
||||
setAuthHeaders(method, accessToken);
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName()
|
||||
+ ") RequestHeader [Authorization=" + method.getHeader("Authorization") + "]");
|
||||
}
|
||||
}
|
||||
|
||||
// 2025.04.09 Authorization 헤더값을 프로퍼티(AUTH_TOKEN)에서 지정하여 설정할 수 있도록 수정
|
||||
if(!StringUtils.isBlank(authToken)) {
|
||||
setAuthHeaders(method, authToken);
|
||||
}
|
||||
|
||||
// 전달 header 셋팅
|
||||
// Adapter 레벨 header 보다 data로 넘어온 httpHeader를 우선 적용(header명이 같다면 덮어씀)
|
||||
assignRequestHeaders(method, httpHeader);
|
||||
|
||||
int status = -1;
|
||||
|
||||
try {
|
||||
byte[] responseMessage = null;
|
||||
Header[] responseHeaders;
|
||||
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
if (dataContent != null) { //dataObject
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = ["
|
||||
+ dataContent.toString() + "]"); //dataObject.toJSONString()
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = "
|
||||
+ CommonLib.getDumpMessage(dataContent.toString())); //dataObject.toJSONString()
|
||||
} else {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = [" + sendData
|
||||
+ "]");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = "
|
||||
+ CommonLib.getDumpMessage(sendData));
|
||||
}
|
||||
}
|
||||
StopWatch stopWatch = new StopWatch();
|
||||
stopWatch.start();
|
||||
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.txlog(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"SEND [" + sendData + "]" + CommonLib.getDumpMessage(sendData));
|
||||
}
|
||||
|
||||
String uuid = tempProp.getProperty(TransactionContextKeys.TRANSACTION_UUID);
|
||||
HttpContext context = new BasicHttpContext();
|
||||
context.setAttribute(TransactionContextKeys.TRANSACTION_UUID, uuid);
|
||||
context.setAttribute(HttpClientAdapterServiceKey.ADAPTER_GROUP_NAME, vo.getAdapterGroupName());
|
||||
context.setAttribute(HttpClientAdapterServiceKey.ADAPTER_NAME, vo.getAdapterName());
|
||||
Integer logProcessNo = (Integer) tempProp.get(HttpClientAdapterServiceKey.LOG_PROCESS_NO);
|
||||
if (logProcessNo != null && logProcessNo > 0) {
|
||||
context.setAttribute(HttpClientAdapterServiceKey.LOG_PROCESS_NO, logProcessNo);
|
||||
}
|
||||
|
||||
try {
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("[method getName]" + method.getMethod());
|
||||
logger.debug("[method getEntity]" + method.getEntity());
|
||||
logger.debug("[method getRequestHeaders]" + method.getHeaders().toString());
|
||||
logger.debug("[method getURI]" + method.getPath());
|
||||
}
|
||||
try (CloseableHttpResponse response = (CloseableHttpResponse) mclient.execute(method, context)) {
|
||||
status = response.getCode();
|
||||
|
||||
if (status >= 200 && status <= 207) {
|
||||
status = 200;
|
||||
}
|
||||
|
||||
// if (status == 404) {
|
||||
// status = 200;
|
||||
// }
|
||||
|
||||
// responseMessage = EntityUtils.toByteArray(response.getEntity());
|
||||
responseHeaders = response.getHeaders();
|
||||
// 2025/08/06 Response body를 Base64로 Encode 해서 Json으로 만들어서 전달하도록 수정
|
||||
HttpEntity entity = response.getEntity();
|
||||
if (entity != null) {
|
||||
byte[] entityBytes = EntityUtils.toByteArray(response.getEntity());
|
||||
String b64 = Base64.encodeBase64String(entityBytes);
|
||||
JSONObject resultJson = new JSONObject();
|
||||
resultJson.put("base64_file_data", b64);
|
||||
responseMessage = resultJson.toString().getBytes();
|
||||
} else {
|
||||
responseMessage = EntityUtils.toByteArray(response.getEntity());
|
||||
}
|
||||
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("[received status]" + status);
|
||||
logger.debug("HttpClientAdapterServiceRest] RECV (" + vo.getAdapterGroupName() + ") = [" + responseMessage + "]");
|
||||
}
|
||||
}
|
||||
} catch (ConnectException e) {
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] responseType =" + vo.getResponseType());
|
||||
}
|
||||
throw new Exception("excuteMethod java.net.ConnectException = " + e.getMessage());
|
||||
}
|
||||
|
||||
stopWatch.stop();
|
||||
|
||||
/**
|
||||
* @formatter:off
|
||||
* OAuth 토큰 응답 체크(Adapter properties로 설정)
|
||||
* 응답코드에 따라 유효한 토큰 확인(토큰 재발급 여부 확인)
|
||||
* API 서비스 마다 정책이 다름(보통 400대에서 체크하나 200에서도 체크할 수 있음)
|
||||
*
|
||||
* TOKEN_ERROR_CODE_KEY: 응답 json error code key
|
||||
* __ex) $.dataHeader.resultCode
|
||||
* TOKEN_ERROR_CODE_VALUES: 토큰 재발급이 필요한 응답 error codes(ex: O0001,O0002,O0003)
|
||||
* TOKEN_ERROR_HTTP_STATUS_CODE: 보통 400대에서 체크하나 API 제공자에 따라 200에서도 체클할수 있음
|
||||
* ex) TOKEN_ERROR_HTTP_STATUS_CODE = 200
|
||||
* @formatter:on
|
||||
*/
|
||||
boolean needReissue = false;
|
||||
|
||||
Properties responseHeaderProp = assignRelayDataToInbound(tempProp, responseHeaders);
|
||||
String responseString = new String(responseMessage, vo.getEncode());
|
||||
|
||||
Map<String, Object> map = new HashMap<String, Object>();
|
||||
tempProp.put(HttpAdapterServiceKey.OUTBOUND_PROPERTY_MAP, map);
|
||||
map.put(HttpAdapterServiceKey.OUTBOUND_RESPONSE_HEADERS, responseHeaderProp);
|
||||
map.put(HttpAdapterServiceKey.OUTBOUND_RESPONSE_MESSAGE, responseString);
|
||||
map.put(HttpAdapterServiceKey.OUTBOUND_RESPONSE_STATUS, status);
|
||||
|
||||
if (status >= 200 && status <= 207) {
|
||||
if (useAdapterToken && StringUtils.equals(tokenErrorHttpStatusCode, "200")) {
|
||||
needReissue = checkTokenRetry(responseMessage, tokenErrorCodeKey, tokenErrorCodeValues,
|
||||
vo.getEncode());
|
||||
}
|
||||
} else if (status == 302) {
|
||||
if (!StringUtils.contains(relayResponseHeaderKeys, "Location")) {
|
||||
relayResponseHeaderKeys += ",Location";
|
||||
}
|
||||
} else {
|
||||
String errMsg = String.format(
|
||||
"http receive status fail value=%d adapterName=%s.%s uri=%s method=%s response Data=%s",
|
||||
status, vo.getAdapterGroupName(), vo.getAdapterName(), uri, rmethod, responseString);
|
||||
// logger.error(errMsg);
|
||||
|
||||
if (status >= 400 && status < 500) {
|
||||
if (useAdapterToken) {
|
||||
needReissue = checkTokenRetry(responseMessage, tokenErrorCodeKey, tokenErrorCodeValues,
|
||||
vo.getEncode());
|
||||
}
|
||||
|
||||
// if (!needReissue) {
|
||||
// throw new Exception(errMsg);
|
||||
// }
|
||||
} else {
|
||||
|
||||
throw new Exception(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] responseType =" + vo.getResponseType());
|
||||
logger.debug("HttpClientAdapterServiceRest] RECV " + vo.getEncode() + "(" + vo.getAdapterGroupName() + ") = [" + new String(responseMessage, vo.getEncode()) + "]");
|
||||
// logger.debug("HttpClientAdapterServiceRest] RECV MS949 (" + vo.getAdapterGroupName() + ") = [" + new String(responseMessage, "MS949") + "]");
|
||||
// logger.debug("HttpClientAdapterServiceRest] RECV euc-kr (" + vo.getAdapterGroupName() + ") = [" + new String(responseMessage, "euc-kr") + "]");
|
||||
logger.debug("HttpClientAdapterServiceRest] RECV (" + vo.getAdapterGroupName() + ") = " + CommonLib.getDumpMessage(responseMessage));
|
||||
}
|
||||
|
||||
if (useAdapterToken) {
|
||||
if (responseMessage == null) {
|
||||
throw new Exception("responseMessage is NULL, HttpStatus=" + status);
|
||||
}
|
||||
|
||||
// OAuth 토큰 재요청 코드 확인
|
||||
if (needReissue) {
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] retry access token response code = ["
|
||||
+ vo.getResponseType() + "] message = [" + new String(responseMessage, vo.getEncode())
|
||||
+ "]");
|
||||
}
|
||||
|
||||
// 토큰 재발급
|
||||
AccessTokenManager tokenManager = AccessTokenManager.getInstance();
|
||||
String oldToken = accessToken == null ? null : accessToken.getAccessToken();
|
||||
OAuth2AccessTokenVO newaccessToken = (OAuth2AccessTokenVO) tokenManager
|
||||
.retryAccessTokenVO(vo.getAdapterGroupName(), prop, oldToken);
|
||||
method.setHeader("Authorization", newaccessToken.getAuthorization());
|
||||
|
||||
setAuthHeaders(method, newaccessToken);
|
||||
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName()
|
||||
+ ") RETRY TOKEN = [" + newaccessToken + "]");
|
||||
}
|
||||
|
||||
try (CloseableHttpResponse response = (CloseableHttpResponse) mclient.execute(method)) {
|
||||
status = response.getCode();
|
||||
responseMessage = EntityUtils.toByteArray(response.getEntity());
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("[received status]" + status);
|
||||
logger.debug("HttpClientAdapterServiceRest] RECV (" + vo.getAdapterGroupName() + ") = [" + new String(responseMessage, vo.getEncode()) + "]");
|
||||
}
|
||||
}catch (IOException e){
|
||||
throw new Exception("retry excuteMethod Exceptioin = " + e.getMessage());
|
||||
}
|
||||
|
||||
|
||||
if (status == 302) {
|
||||
if (!StringUtils.contains(relayResponseHeaderKeys, "Location")) {
|
||||
relayResponseHeaderKeys += ",Location";
|
||||
}
|
||||
} else {
|
||||
String errMsg = String.format(
|
||||
"http receive status fail value=%d adapterName=%s.%s uri=%s method=%s response Data=%s",
|
||||
status, vo.getAdapterGroupName(), vo.getAdapterName(), uri, rmethod, responseMessage);
|
||||
throw new Exception(errMsg);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] RETRY responseType =" + vo.getResponseType());
|
||||
logger.debug("HttpClientAdapterServiceRest] RETRY RECV " + vo.getEncode() + "("
|
||||
+ vo.getAdapterGroupName() + ") = [" + new String(responseMessage, vo.getEncode())
|
||||
+ "]");
|
||||
logger.debug("HttpClientAdapterServiceRest] RETRY RECV (" + vo.getAdapterGroupName() + ") = "
|
||||
+ CommonLib.getDumpMessage(responseMessage));
|
||||
}
|
||||
// ----------------------------------------------------------
|
||||
}
|
||||
}
|
||||
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.txlog(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"RECV [" + new String(responseMessage, vo.getEncode()) + "]"
|
||||
+ CommonLib.getDumpMessage(responseMessage));
|
||||
}
|
||||
|
||||
|
||||
return assignResponseHeaders(method, responseMessage, headerGroupName, vo.getEncode(), messageType,
|
||||
relayResponseHeaderKeys, status, responseHeaderProp);
|
||||
} catch (SocketTimeoutException ste) { // Read Timeout :: HttpClient 3.1일 경우
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"HttpClientAdapterServiceRest] SocketTimeoutException (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ste.toString(),
|
||||
ste);
|
||||
}
|
||||
logger.error("HttpClientAdapterServiceRest] SocketTimeoutException (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ste.toString(), ste);
|
||||
throw ste;
|
||||
} catch (ConnectException ce) {
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"HttpClientAdapterServiceRest] Connection Exception (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ce.toString(),
|
||||
ce);
|
||||
}
|
||||
logger.error("HttpClientAdapterServiceRest] Connection Exception (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ce.toString(), ce);
|
||||
throw ce;
|
||||
} catch (Exception e) {
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(), e.toString(), e);
|
||||
}
|
||||
logger.error("HttpClientAdapterServiceRest] Exception (" + vo.getAdapterGroupName() + ") : " + e.toString(),
|
||||
e);
|
||||
throw e;
|
||||
} finally {
|
||||
if (status != HttpStatus.SC_OK) {
|
||||
String[] msgArgs = new String[1];
|
||||
msgArgs[0] = String.valueOf(status);
|
||||
String resMsg = ExceptionUtil.make("RDCEAIAHA013", msgArgs);
|
||||
if (logger.isDebug()) {
|
||||
logger.debug(resMsg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Properties assignRelayDataToInbound(Properties prop, Header[] responseHeaders) {
|
||||
Properties headerProp = new Properties();
|
||||
if (responseHeaders == null || responseHeaders.length == 0) {
|
||||
return headerProp;
|
||||
}
|
||||
|
||||
for (Header header : responseHeaders) {
|
||||
headerProp.put(header.getName(), header.getValue());
|
||||
}
|
||||
|
||||
return headerProp;
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 1단계 레이아웃에만 적용되도록 구현됨.
|
||||
*
|
||||
* @param method
|
||||
* @param responseMessage
|
||||
* @param headerGroupName
|
||||
* @param encode
|
||||
* @param messageType
|
||||
* @param relayHeaderKeys
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private String assignResponseHeaders(HttpUriRequestBase method, byte[] responseMessage, String headerGroupName,
|
||||
String encode, String messageType, String relayHeaderKeys, int status, Properties responseHeaderProp) throws Exception {
|
||||
if (!MessageType.JSON.equals(messageType) || StringUtils.isBlank(headerGroupName)
|
||||
|| StringUtils.isBlank(relayHeaderKeys)) {
|
||||
return new String(responseMessage, encode);
|
||||
}
|
||||
|
||||
String[] relayKeyArr = org.springframework.util.StringUtils.tokenizeToStringArray(relayHeaderKeys, ",");
|
||||
JSONObject headerJson = new JSONObject();
|
||||
for (String key : relayKeyArr) {
|
||||
String value = responseHeaderProp.getProperty(key);
|
||||
if (StringUtils.isNotBlank(value)) {
|
||||
headerJson.put(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
headerJson.put(HTTP_STATUS, String.valueOf(status));
|
||||
|
||||
if (headerJson.size() <= 0) {
|
||||
return new String(responseMessage, encode);
|
||||
}
|
||||
|
||||
JSONObject message = null;
|
||||
if (responseMessage == null || responseMessage.length == 0) {
|
||||
message = new JSONObject();
|
||||
} else {
|
||||
message = parseJson(new String(responseMessage, encode));
|
||||
if (message == null) {
|
||||
message = new JSONObject();
|
||||
message.put("Malformed_Response_Message", new String(responseMessage, encode));
|
||||
}
|
||||
}
|
||||
|
||||
if (StringUtils.isNotBlank(headerGroupName) && message != null)
|
||||
message.put(headerGroupName, headerJson);
|
||||
|
||||
logger.info("------------- message --------------- : {} ", message);
|
||||
|
||||
return message.toJSONString();
|
||||
}
|
||||
|
||||
// 2025.04.09 Authorization 헤더값을 프로퍼티(AUTH_TOKEN)에서 지정하여 설정할 수 있도록 수정
|
||||
private void setAuthHeaders(HttpUriRequestBase method, String authorization) throws Exception {
|
||||
method.setHeader("Authorization",
|
||||
String.format("%s", authorization));
|
||||
}
|
||||
|
||||
private void setAuthHeaders(HttpUriRequestBase method, OAuth2AccessTokenVO accessToken) throws Exception {
|
||||
method.setHeader("Authorization",
|
||||
String.format("%s %s", AccessTokenVO.BEARER_TYPE, accessToken.getAccessToken()));
|
||||
}
|
||||
|
||||
private boolean checkTokenRetry(byte[] responseMessage, String tokenErrorCodeKey, String tokenErrorCodeValues,
|
||||
String encode) {
|
||||
if (responseMessage == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(tokenErrorCodeKey)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(tokenErrorCodeValues)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
DocumentContext jsonContext = JsonPath.parse(new String(responseMessage, encode));
|
||||
String responseCode = jsonContext.read(tokenErrorCodeKey);
|
||||
if (StringUtils.isBlank(responseCode)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String[] arr = org.springframework.util.StringUtils.tokenizeToStringArray(tokenErrorCodeValues, ",");
|
||||
return ArrayUtils.contains(arr, responseCode);
|
||||
} catch (Exception e) {
|
||||
logger.error("HttpClientAdapterServiceRest] checkTokenRetry error=" + e.getMessage());
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private void assignRequestHeaders(HttpUriRequestBase method, Object httpHeader) {
|
||||
if (httpHeader == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (httpHeader instanceof JSONObject) {
|
||||
JSONObject jsonObject = (JSONObject) httpHeader;
|
||||
for (Object key : jsonObject.keySet()) {
|
||||
Object obj = jsonObject.get(key);
|
||||
if ((obj instanceof JSONObject) || (obj instanceof JSONArray)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
method.setHeader((String) key, (String) obj);
|
||||
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("Request Header :" + (String) key + "=[" + (String) obj + "]");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private void assignPostBody(Object eaiBody, String contentType, String charset, HttpUriRequestBase method) {
|
||||
if (eaiBody == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (StringUtils.contains(contentType, "application/x-www-form-urlencoded")) {
|
||||
if (eaiBody instanceof JSONObject) {
|
||||
List<NameValuePair> params = new ArrayList<>();
|
||||
JSONObject jsonObject = (JSONObject) eaiBody;
|
||||
for (Object key : jsonObject.keySet()) {
|
||||
params.add(new BasicNameValuePair((String) key, (String) jsonObject.get(key)));
|
||||
}
|
||||
|
||||
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8);
|
||||
method.setEntity(entity);
|
||||
}
|
||||
|
||||
} else {
|
||||
ContentType contentTypeObj = ContentType.create(contentType, charset);
|
||||
|
||||
// 요청 본문을 StringEntity 객체로 생성
|
||||
StringEntity entity = new StringEntity(eaiBody.toString(), contentTypeObj);
|
||||
|
||||
// 요청에 본문 추가
|
||||
method.setEntity(entity);
|
||||
}
|
||||
}
|
||||
|
||||
private HashMap<String, String> getParameters(Object message) throws Exception {
|
||||
|
||||
HashMap<String, String> result = new HashMap<String, String>();
|
||||
|
||||
if (message != null) {
|
||||
if (message instanceof JSONObject) {
|
||||
JSONObject jsonObject = (JSONObject) message;
|
||||
for (Object key : jsonObject.keySet()) {
|
||||
Object obj = jsonObject.get(key);
|
||||
if ((obj instanceof JSONObject) || (obj instanceof JSONArray)) {
|
||||
continue;
|
||||
}
|
||||
result.put((String) key, getStringValue(obj));
|
||||
}
|
||||
} else {
|
||||
String[] messages = ((String) message).split("&");
|
||||
String[] data = null;
|
||||
|
||||
for (int i = 0; i < messages.length; i++) {
|
||||
data = messages[i].split("=", 2);
|
||||
if (data.length == 2) {
|
||||
result.put(data[0], data[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public String getStringValue(Object obj) {
|
||||
if (obj == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (obj instanceof String) {
|
||||
return (String) obj;
|
||||
} else if (obj instanceof Long) {
|
||||
return Long.toString((Long) obj);
|
||||
} else if (obj instanceof BigDecimal) {
|
||||
return ((BigDecimal) obj).toPlainString();
|
||||
} else {
|
||||
return (String) obj;
|
||||
}
|
||||
}
|
||||
|
||||
public static Object parseJsonGeneric(String jsonData) {
|
||||
if (StringUtils.isBlank(jsonData)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
JSONParser parser = new JSONParser();
|
||||
Object parsedObj = parser.parse(jsonData);
|
||||
return parsedObj;
|
||||
} catch (ParseException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private JSONObject parseJson(String message) throws Exception {
|
||||
if (message == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (JSONObject) JSONValue.parse(message);
|
||||
}
|
||||
|
||||
private Document convertXmlDocument(String message) throws Exception {
|
||||
SAXReader builder = new SAXReader();
|
||||
Document document = builder.read(new StringReader(message));
|
||||
return document;
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private String changeUrl(String messageType, String url, String restOption, Object sendData) {
|
||||
if ((MessageType.JSON.equals(messageType) || MessageType.XML.equals(messageType))) {
|
||||
try {
|
||||
if (StringUtils.isBlank(restOption)) {
|
||||
return url;
|
||||
}
|
||||
List<String> urlVariableList = new ArrayList<String>();
|
||||
JSONObject restOptionObject = parseJson(restOption);
|
||||
|
||||
if (restOptionObject == null)
|
||||
throw new Exception("restOption is NULL");
|
||||
|
||||
String type = (String) restOptionObject.get("type");
|
||||
String requestExtraPath = (String) restOptionObject.get("extraPath");
|
||||
url = getUrl(url, requestExtraPath);
|
||||
if (TYPE_VARIABLE_URL_REQUEST.equals(type)) {
|
||||
Pattern p = Pattern.compile("\\{(.*?)\\}");
|
||||
Matcher m = p.matcher(requestExtraPath);
|
||||
List<String> uriVariables = new ArrayList<>();
|
||||
while(m.find()) {
|
||||
String fieldName = m.group(1);
|
||||
uriVariables.add(fieldName);
|
||||
}
|
||||
if (MessageType.JSON.equals(messageType)) {
|
||||
JSONObject jsonObject;
|
||||
if (sendData instanceof JSONObject) {
|
||||
jsonObject = (JSONObject) sendData;
|
||||
} else {
|
||||
jsonObject = (JSONObject) JSONValue.parse((String) sendData);
|
||||
}
|
||||
for (Object tempObject : uriVariables) {
|
||||
String urlVaribleId = (String) tempObject;
|
||||
String uriVariable = (String) jsonObject.get(urlVaribleId);
|
||||
urlVariableList.add(uriVariable);
|
||||
jsonObject.remove(urlVaribleId);
|
||||
}
|
||||
} else if (MessageType.XML.equals(messageType)) {
|
||||
Document doc;
|
||||
if (sendData instanceof Document) {
|
||||
doc = (Document) sendData;
|
||||
} else {
|
||||
doc = convertXmlDocument((String) sendData);
|
||||
}
|
||||
for (Object tempObject : uriVariables) {
|
||||
String urlVaribleId = (String) tempObject;
|
||||
Element element = (Element) doc.selectSingleNode("//" + urlVaribleId);
|
||||
urlVariableList.add(element.getText());
|
||||
if (doc.getRootElement() == element) {
|
||||
doc = null;
|
||||
} else {
|
||||
element.getParent().remove(element);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (urlVariableList.size() > 0) {
|
||||
UriComponents uriComponents = UriComponentsBuilder.fromUriString(url).build();
|
||||
Object[] urls = urlVariableList.toArray();
|
||||
url = uriComponents.expand(urls).toUriString();
|
||||
logger.debug("HttpClientAdapterServiceRest] after extand url=[" + url + "] ");
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("Failed to change url", e);
|
||||
}
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
private String getUrl(String baseUrl, String extraPath) {
|
||||
if (StringUtils.isBlank(extraPath)) {
|
||||
return baseUrl;
|
||||
}
|
||||
|
||||
if (StringUtils.contains(extraPath, "http://") || StringUtils.contains(extraPath, "https://")) {
|
||||
return extraPath;
|
||||
}
|
||||
|
||||
String targetUrl = baseUrl;
|
||||
if (!targetUrl.endsWith("/")) {
|
||||
targetUrl += "/";
|
||||
}
|
||||
if (extraPath.startsWith("/")) {
|
||||
targetUrl += extraPath.substring(1);
|
||||
} else {
|
||||
targetUrl += extraPath;
|
||||
}
|
||||
|
||||
logger.debug("HttpClientAdapterServiceRest] after concatenate url=[" + targetUrl + "] ");
|
||||
return targetUrl;
|
||||
}
|
||||
|
||||
}
|
||||
+888
@@ -0,0 +1,888 @@
|
||||
package com.eactive.eai.adapter.http.client.impl.kjb;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
import java.math.BigDecimal;
|
||||
import java.net.ConnectException;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.time.StopWatch;
|
||||
import org.apache.hc.client5.http.classic.HttpClient;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpDelete;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpGet;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpPost;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpPut;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
|
||||
import org.apache.hc.client5.http.config.RequestConfig;
|
||||
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
|
||||
import org.apache.hc.core5.http.ContentType;
|
||||
import org.apache.hc.core5.http.Header;
|
||||
import org.apache.hc.core5.http.HttpHost;
|
||||
import org.apache.hc.core5.http.HttpStatus;
|
||||
import org.apache.hc.core5.http.NameValuePair;
|
||||
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
||||
import org.apache.hc.core5.http.io.entity.StringEntity;
|
||||
import org.apache.hc.core5.http.message.BasicNameValuePair;
|
||||
import org.apache.hc.core5.http.protocol.BasicHttpContext;
|
||||
import org.apache.hc.core5.http.protocol.HttpContext;
|
||||
import org.apache.hc.core5.net.URIBuilder;
|
||||
import org.dom4j.Document;
|
||||
import org.dom4j.Element;
|
||||
import org.dom4j.io.SAXReader;
|
||||
import org.json.simple.JSONArray;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.JSONValue;
|
||||
import org.json.simple.parser.JSONParser;
|
||||
import org.json.simple.parser.ParseException;
|
||||
import org.springframework.web.util.UriComponents;
|
||||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
|
||||
import com.eactive.eai.adapter.http.HttpMemoryLogger;
|
||||
import com.eactive.eai.adapter.http.HttpMethodType;
|
||||
import com.eactive.eai.adapter.http.client.HttpClient5AdapterServiceSupport;
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterVO;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
import com.eactive.eai.common.TransactionContextKeys;
|
||||
import com.eactive.eai.common.authoutbound.AccessTokenManagerByDB;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.message.MessageType;
|
||||
import com.eactive.eai.common.util.CommonLib;
|
||||
import com.jayway.jsonpath.DocumentContext;
|
||||
import com.jayway.jsonpath.JsonPath;
|
||||
import com.openbanking.eai.common.token.AccessTokenManager;
|
||||
import com.openbanking.eai.common.token.AccessTokenVO;
|
||||
import com.openbanking.eai.common.token.OAuth2AccessTokenVO;
|
||||
|
||||
import com.eactive.eai.common.property.PropManager;
|
||||
|
||||
public class HttpClient5AdapterServiceKbank extends HttpClient5AdapterServiceSupport
|
||||
implements HttpClientAdapterServiceKey {
|
||||
|
||||
public static final String TYPE_VARIABLE_URL_REQUEST = "variableUrlRequest";
|
||||
public static final String TYPE_SIMPLE_REQUEST = "simpleRequest";
|
||||
public static final String REST_OPTION = "REST_OPTION";
|
||||
//public static final String HEADER_CONTENT_TYPE = "Content-Type";
|
||||
public static final String HEADER_GROUP = "HEADER_GROUP";
|
||||
public static final String HTTP_STATUS = "HTTP_STATUS";
|
||||
public static final String HEADER_KEYS = "HEADER_KEYS";
|
||||
public static final String AUTH_TOKEN = "AUTH_TOKEN";
|
||||
|
||||
/**
|
||||
* 1. 기능 : REST API 통신에 사용 <br>
|
||||
* 2. 처리 개요 : - 속성 정보를 설정 하고 수동 시스템 서비스를 호출 한다. <br>
|
||||
* 3. 주의사항 <br>
|
||||
*
|
||||
* @param prop Http Adapter 속성 정보
|
||||
* @return 반환 된 Object
|
||||
* @exception Exception 수동 시스템 간 통신 중 발생
|
||||
**/
|
||||
@SuppressWarnings({ "unchecked" })
|
||||
public Object execute(Properties prop, Object data, Properties tempProp) throws Exception {
|
||||
HttpClientAdapterVO vo = super.setting(prop, tempProp);
|
||||
|
||||
// 2025.04.09 Authorization 헤더값을 프로퍼티(AUTH_TOKEN)에서 지정하여 설정할 수 있도록 수정
|
||||
String bizCode = "";
|
||||
String authToken = "";
|
||||
try {
|
||||
Properties authProp = PropManager.getInstance().getProperties(AUTH_TOKEN); //Authorization
|
||||
bizCode = vo.getAdapterGroupName().substring(1, 4);
|
||||
authToken = authProp.getProperty(bizCode, "");
|
||||
} catch (Exception e) {
|
||||
logger.debug("Property Group AUTH_TOKEN is not Exist !!");
|
||||
}
|
||||
|
||||
logger.debug("authToken :::::::::::::::::::::::::::::::::::" + authToken);
|
||||
|
||||
String headerGroupName = prop.getProperty(HEADER_GROUP);
|
||||
String relayResponseHeaderKeys = prop.getProperty(HEADER_KEYS, "");
|
||||
boolean useAdapterToken = StringUtils.equalsIgnoreCase(prop.getProperty("ADAPTER_TOKEN_USE_YN", "N"), "Y");
|
||||
|
||||
boolean useForwardProxy = StringUtils.equalsIgnoreCase(prop.getProperty("FORWARD_PROXY_USE_YN", "N"), "Y");
|
||||
String forwardProxyUrl = prop.getProperty("FORWARD_PROXY_URL");
|
||||
|
||||
// ex) $.dataHeader.GW_RSLT_CD
|
||||
String tokenErrorCodeKey = prop.getProperty("ADAPTER_TOKEN_ERROR_CODE_KEY");
|
||||
String tokenErrorCodeValues = prop.getProperty("ADAPTER_TOKEN_ERROR_CODE_VALUES");
|
||||
String tokenErrorHttpStatusCode = prop.getProperty("ADAPTER_TOKEN_ERROR_HTTP_STATUS_CODE"); // 200 or 400번대
|
||||
|
||||
// 레이아웃 메시지 타입 REST URL 추출 시 활용. Default JSON
|
||||
String messageType = prop.getProperty("MESSAGE_TYPE", MessageType.JSON);
|
||||
String inboundMethod = tempProp.getProperty(HttpAdapterServiceKey.INBOUND_METHOD, "POST");
|
||||
|
||||
/**
|
||||
* @formatter:off
|
||||
* TSEAIHE02.RESTOPTION 정보 => JSON 형태로 구성
|
||||
* - type : simpleRequest, variableUrlRequest
|
||||
* - extraPath : 어댑터 프로퍼티 URL에 추가될 HTTP REST URL
|
||||
* - method : get, delete, post, put
|
||||
* - contentType: application/json(default), application/x-www-form-urlencoded
|
||||
* - adapterTokenUseYn: Y, N(default)
|
||||
* ex)
|
||||
* {"type":"simpleRequest","extraPath":"v2.0/accout/balance","method":"post"}
|
||||
* @formatter:on
|
||||
*/
|
||||
|
||||
String restOptionData = tempProp.getProperty(REST_OPTION);
|
||||
|
||||
JSONObject restOptionObject = parseJson(restOptionData);
|
||||
if (restOptionObject == null) {
|
||||
throw new Exception("OptionData parsing result is NULL");
|
||||
}
|
||||
|
||||
String rmethod = (String) restOptionObject.getOrDefault("method", inboundMethod);
|
||||
String contentType = (String) restOptionObject.getOrDefault("contentType", "application/json");
|
||||
String adapterTokenUseYn = (String) restOptionObject.get("adapterTokenUseYn");
|
||||
if (StringUtils.isNotBlank(adapterTokenUseYn)) { // interface 에 설정된게 우선한다.
|
||||
useAdapterToken = StringUtils.equalsIgnoreCase(adapterTokenUseYn, "Y");
|
||||
}
|
||||
|
||||
HttpClient mclient = this.client;
|
||||
String sendData = "";
|
||||
if (data instanceof String) {
|
||||
sendData = (String) data;
|
||||
} else if (data instanceof byte[]) {
|
||||
sendData = new String((byte[]) data, vo.getEncode());
|
||||
}
|
||||
|
||||
////mclient.getParams().setContentCharset(vo.getEncode());
|
||||
|
||||
JSONObject dataObject = null;
|
||||
|
||||
Object httpHeader = null;
|
||||
Object dataContent = null;
|
||||
|
||||
if (MessageType.JSON.equals(messageType)) {
|
||||
|
||||
Object parsed = parseJsonGeneric(sendData);
|
||||
|
||||
if(parsed instanceof JSONObject) {
|
||||
dataObject = parseJson(sendData);
|
||||
if (dataObject != null && StringUtils.isNotBlank(headerGroupName)) {
|
||||
httpHeader = dataObject.get(headerGroupName);
|
||||
dataObject.remove(headerGroupName);
|
||||
}
|
||||
|
||||
dataContent = dataObject;
|
||||
if (dataObject.containsKey("innerList")) {
|
||||
JSONArray innerList = (JSONArray) dataObject.get("innerList");
|
||||
dataContent = innerList;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.debug("HttpClientAdapterServiceRest] dataObject1 = [" + dataObject + "]");
|
||||
logger.debug("HttpClientAdapterServiceRest] dataContent = [" + dataContent + "]");
|
||||
|
||||
// interface 에 설정된게 우선한다.
|
||||
String uri = null;
|
||||
if (dataObject == null) {
|
||||
uri = changeUrl(messageType, vo.getUrl(), restOptionData, sendData);
|
||||
} else {
|
||||
uri = changeUrl(messageType, vo.getUrl(), restOptionData, dataObject);
|
||||
}
|
||||
|
||||
// ////if (vo.getConnectionTimeout() != 0) {
|
||||
// mclient.getHttpConnectionManager().getParams().setConnectionTimeout(vo.getConnectionTimeout());
|
||||
// }
|
||||
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") URL=[" + vo.getUrl() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") PARAMETER_NAME=[" + vo.getParameterName() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") ENCODE=[" + vo.getEncode() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") RESPONSE_TYPE=[" + vo.getResponseType() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") URL_ENCODE_YN=[" + vo.getUrlEncodeYn() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") CONNECTION_TIMEOUT=[" + vo.getConnectionTimeout() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") REST_OPTION=[" + restOptionData + "] ");
|
||||
}
|
||||
|
||||
HttpUriRequestBase method = null;
|
||||
|
||||
// 메소드 타입에 따라 HttpRequestBase 인스턴스 생성
|
||||
switch (HttpMethodType.getValue(rmethod)) {
|
||||
case GET:
|
||||
method = new HttpGet(uri);
|
||||
break;
|
||||
case DELETE:
|
||||
method = new HttpDelete(uri);
|
||||
break;
|
||||
case POST:
|
||||
method = new HttpPost(uri);
|
||||
break;
|
||||
case PUT:
|
||||
method = new HttpPut(uri);
|
||||
break;
|
||||
default:
|
||||
method = new HttpGet(uri);
|
||||
break;
|
||||
}
|
||||
|
||||
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
|
||||
|
||||
if(useForwardProxy) {
|
||||
java.net.URL url = new java.net.URL(forwardProxyUrl);
|
||||
|
||||
// 프로토콜, 호스트, 포트 추출
|
||||
String protocol = url.getProtocol();
|
||||
String host = url.getHost();
|
||||
int port = url.getPort();
|
||||
HttpHost proxy = new HttpHost(protocol,host, port);
|
||||
requestConfigBuilder.setProxy(proxy);
|
||||
}
|
||||
|
||||
configureHttpClient(requestConfigBuilder, vo, method);
|
||||
|
||||
switch (HttpMethodType.getValue(rmethod)) {
|
||||
case GET:
|
||||
case DELETE:
|
||||
HashMap<String, String> h = getParameters(dataObject);
|
||||
URIBuilder uriBuilder = new URIBuilder(uri);
|
||||
for (Map.Entry<String, String> entry : h.entrySet()) {
|
||||
uriBuilder.addParameter(entry.getKey(), entry.getValue());
|
||||
}
|
||||
URI fullUri = uriBuilder.build();
|
||||
if (method instanceof HttpGet) {
|
||||
((HttpGet) method).setUri(fullUri);
|
||||
} else if (method instanceof HttpDelete) {
|
||||
((HttpDelete) method).setUri(fullUri);
|
||||
}
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClientAdapterServiceRest] (get Method) QueryString = [" + fullUri.getQuery() + "]");
|
||||
}
|
||||
break;
|
||||
case PUT:
|
||||
case POST:
|
||||
//assignPostBody(dataObject, contentType, vo.getEncode(), method);
|
||||
assignPostBody(dataContent, contentType, vo.getEncode(), method);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") method.getParams()=["
|
||||
+ method.getEntity() + "] ");
|
||||
}
|
||||
|
||||
OAuth2AccessTokenVO accessToken = null;
|
||||
if (useAdapterToken) {
|
||||
AccessTokenManagerByDB tokenManager = AccessTokenManagerByDB.getInstance();
|
||||
accessToken = (OAuth2AccessTokenVO) tokenManager.getAccessTokenVO(vo.getAdapterGroupName());
|
||||
|
||||
// 토큰이 없거나 만료 됐으면 재발급
|
||||
if (accessToken == null || accessToken.isExpired()) {
|
||||
String oldToken = accessToken == null ? null : accessToken.getAccessToken();
|
||||
accessToken = (OAuth2AccessTokenVO) tokenManager.retryAccessTokenVO(vo.getAdapterGroupName(), prop,
|
||||
oldToken);
|
||||
}
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") TOKEN = ["
|
||||
+ accessToken + "]");
|
||||
}
|
||||
|
||||
setAuthHeaders(method, accessToken);
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName()
|
||||
+ ") RequestHeader [Authorization=" + method.getHeader("Authorization") + "]");
|
||||
}
|
||||
}
|
||||
|
||||
// 2025.04.09 Authorization 헤더값을 프로퍼티(AUTH_TOKEN)에서 지정하여 설정할 수 있도록 수정
|
||||
if(!StringUtils.isBlank(authToken)) {
|
||||
setAuthHeaders(method, authToken);
|
||||
}
|
||||
|
||||
// 전달 header 셋팅
|
||||
// Adapter 레벨 header 보다 data로 넘어온 httpHeader를 우선 적용(header명이 같다면 덮어씀)
|
||||
assignRequestHeaders(method, httpHeader);
|
||||
|
||||
int status = -1;
|
||||
|
||||
try {
|
||||
byte[] responseMessage = null;
|
||||
Header[] responseHeaders;
|
||||
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
if (dataContent != null) { //dataObject
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = ["
|
||||
+ dataContent.toString() + "]"); //dataObject.toJSONString()
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = "
|
||||
+ CommonLib.getDumpMessage(dataContent.toString())); //dataObject.toJSONString()
|
||||
} else {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = [" + sendData
|
||||
+ "]");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = "
|
||||
+ CommonLib.getDumpMessage(sendData));
|
||||
}
|
||||
}
|
||||
StopWatch stopWatch = new StopWatch();
|
||||
stopWatch.start();
|
||||
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.txlog(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"SEND [" + sendData + "]" + CommonLib.getDumpMessage(sendData));
|
||||
}
|
||||
|
||||
String uuid = tempProp.getProperty(TransactionContextKeys.TRANSACTION_UUID);
|
||||
HttpContext context = new BasicHttpContext();
|
||||
context.setAttribute(TransactionContextKeys.TRANSACTION_UUID, uuid);
|
||||
context.setAttribute(HttpClientAdapterServiceKey.ADAPTER_GROUP_NAME, vo.getAdapterGroupName());
|
||||
context.setAttribute(HttpClientAdapterServiceKey.ADAPTER_NAME, vo.getAdapterName());
|
||||
Integer logProcessNo = (Integer) tempProp.get(HttpClientAdapterServiceKey.LOG_PROCESS_NO);
|
||||
if (logProcessNo != null && logProcessNo > 0) {
|
||||
context.setAttribute(HttpClientAdapterServiceKey.LOG_PROCESS_NO, logProcessNo);
|
||||
}
|
||||
|
||||
try {
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("[method getName]" + method.getMethod());
|
||||
logger.debug("[method getEntity]" + method.getEntity());
|
||||
logger.debug("[method getRequestHeaders]" + method.getHeaders().toString());
|
||||
logger.debug("[method getURI]" + method.getPath());
|
||||
}
|
||||
try (CloseableHttpResponse response = (CloseableHttpResponse) mclient.execute(method, context)) {
|
||||
status = response.getCode();
|
||||
|
||||
if (status >= 200 && status <= 207) {
|
||||
status = 200;
|
||||
}
|
||||
|
||||
// if (status == 404) {
|
||||
// status = 200;
|
||||
// }
|
||||
|
||||
responseMessage = EntityUtils.toByteArray(response.getEntity());
|
||||
responseHeaders = response.getHeaders();
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("[received status]" + status);
|
||||
logger.debug("HttpClientAdapterServiceRest] RECV (" + vo.getAdapterGroupName() + ") = [" + responseMessage + "]");
|
||||
}
|
||||
}
|
||||
} catch (ConnectException e) {
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] responseType =" + vo.getResponseType());
|
||||
}
|
||||
throw new Exception("excuteMethod java.net.ConnectException = " + e.getMessage());
|
||||
}
|
||||
|
||||
stopWatch.stop();
|
||||
|
||||
/**
|
||||
* @formatter:off
|
||||
* OAuth 토큰 응답 체크(Adapter properties로 설정)
|
||||
* 응답코드에 따라 유효한 토큰 확인(토큰 재발급 여부 확인)
|
||||
* API 서비스 마다 정책이 다름(보통 400대에서 체크하나 200에서도 체크할 수 있음)
|
||||
*
|
||||
* TOKEN_ERROR_CODE_KEY: 응답 json error code key
|
||||
* __ex) $.dataHeader.resultCode
|
||||
* TOKEN_ERROR_CODE_VALUES: 토큰 재발급이 필요한 응답 error codes(ex: O0001,O0002,O0003)
|
||||
* TOKEN_ERROR_HTTP_STATUS_CODE: 보통 400대에서 체크하나 API 제공자에 따라 200에서도 체클할수 있음
|
||||
* ex) TOKEN_ERROR_HTTP_STATUS_CODE = 200
|
||||
* @formatter:on
|
||||
*/
|
||||
boolean needReissue = false;
|
||||
|
||||
Properties responseHeaderProp = assignRelayDataToInbound(tempProp, responseHeaders);
|
||||
String responseString = new String(responseMessage, vo.getEncode());
|
||||
|
||||
Map<String, Object> map = new HashMap<String, Object>();
|
||||
tempProp.put(HttpAdapterServiceKey.OUTBOUND_PROPERTY_MAP, map);
|
||||
map.put(HttpAdapterServiceKey.OUTBOUND_RESPONSE_HEADERS, responseHeaderProp);
|
||||
map.put(HttpAdapterServiceKey.OUTBOUND_RESPONSE_MESSAGE, responseString);
|
||||
map.put(HttpAdapterServiceKey.OUTBOUND_RESPONSE_STATUS, status);
|
||||
|
||||
if (status >= 200 && status <= 207) {
|
||||
if (useAdapterToken && StringUtils.equals(tokenErrorHttpStatusCode, "200")) {
|
||||
needReissue = checkTokenRetry(responseMessage, tokenErrorCodeKey, tokenErrorCodeValues,
|
||||
vo.getEncode());
|
||||
}
|
||||
} else if (status == 302) {
|
||||
if (!StringUtils.contains(relayResponseHeaderKeys, "Location")) {
|
||||
relayResponseHeaderKeys += ",Location";
|
||||
}
|
||||
} else {
|
||||
String errMsg = String.format(
|
||||
"http receive status fail value=%d adapterName=%s.%s uri=%s method=%s response Data=%s",
|
||||
status, vo.getAdapterGroupName(), vo.getAdapterName(), uri, rmethod, responseString);
|
||||
// logger.error(errMsg);
|
||||
|
||||
if (status >= 400 && status < 500) {
|
||||
if (useAdapterToken) {
|
||||
needReissue = checkTokenRetry(responseMessage, tokenErrorCodeKey, tokenErrorCodeValues,
|
||||
vo.getEncode());
|
||||
}
|
||||
|
||||
// if (!needReissue) {
|
||||
// throw new Exception(errMsg);
|
||||
// }
|
||||
} else {
|
||||
|
||||
throw new Exception(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] responseType =" + vo.getResponseType());
|
||||
logger.debug("HttpClientAdapterServiceRest] RECV " + vo.getEncode() + "(" + vo.getAdapterGroupName() + ") = [" + new String(responseMessage, vo.getEncode()) + "]");
|
||||
// logger.debug("HttpClientAdapterServiceRest] RECV MS949 (" + vo.getAdapterGroupName() + ") = [" + new String(responseMessage, "MS949") + "]");
|
||||
// logger.debug("HttpClientAdapterServiceRest] RECV euc-kr (" + vo.getAdapterGroupName() + ") = [" + new String(responseMessage, "euc-kr") + "]");
|
||||
logger.debug("HttpClientAdapterServiceRest] RECV (" + vo.getAdapterGroupName() + ") = " + CommonLib.getDumpMessage(responseMessage));
|
||||
}
|
||||
|
||||
if (useAdapterToken) {
|
||||
if (responseMessage == null) {
|
||||
throw new Exception("responseMessage is NULL, HttpStatus=" + status);
|
||||
}
|
||||
|
||||
// OAuth 토큰 재요청 코드 확인
|
||||
if (needReissue) {
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] retry access token response code = ["
|
||||
+ vo.getResponseType() + "] message = [" + new String(responseMessage, vo.getEncode())
|
||||
+ "]");
|
||||
}
|
||||
|
||||
// 토큰 재발급
|
||||
AccessTokenManager tokenManager = AccessTokenManager.getInstance();
|
||||
String oldToken = accessToken == null ? null : accessToken.getAccessToken();
|
||||
OAuth2AccessTokenVO newaccessToken = (OAuth2AccessTokenVO) tokenManager
|
||||
.retryAccessTokenVO(vo.getAdapterGroupName(), prop, oldToken);
|
||||
method.setHeader("Authorization", newaccessToken.getAuthorization());
|
||||
|
||||
setAuthHeaders(method, newaccessToken);
|
||||
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName()
|
||||
+ ") RETRY TOKEN = [" + newaccessToken + "]");
|
||||
}
|
||||
|
||||
try (CloseableHttpResponse response = (CloseableHttpResponse) mclient.execute(method)) {
|
||||
status = response.getCode();
|
||||
responseMessage = EntityUtils.toByteArray(response.getEntity());
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("[received status]" + status);
|
||||
logger.debug("HttpClientAdapterServiceRest] RECV (" + vo.getAdapterGroupName() + ") = [" + new String(responseMessage, vo.getEncode()) + "]");
|
||||
}
|
||||
}catch (IOException e){
|
||||
throw new Exception("retry excuteMethod Exceptioin = " + e.getMessage());
|
||||
}
|
||||
|
||||
|
||||
if (status == 302) {
|
||||
if (!StringUtils.contains(relayResponseHeaderKeys, "Location")) {
|
||||
relayResponseHeaderKeys += ",Location";
|
||||
}
|
||||
} else {
|
||||
String errMsg = String.format(
|
||||
"http receive status fail value=%d adapterName=%s.%s uri=%s method=%s response Data=%s",
|
||||
status, vo.getAdapterGroupName(), vo.getAdapterName(), uri, rmethod, responseMessage);
|
||||
throw new Exception(errMsg);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] RETRY responseType =" + vo.getResponseType());
|
||||
logger.debug("HttpClientAdapterServiceRest] RETRY RECV " + vo.getEncode() + "("
|
||||
+ vo.getAdapterGroupName() + ") = [" + new String(responseMessage, vo.getEncode())
|
||||
+ "]");
|
||||
logger.debug("HttpClientAdapterServiceRest] RETRY RECV (" + vo.getAdapterGroupName() + ") = "
|
||||
+ CommonLib.getDumpMessage(responseMessage));
|
||||
}
|
||||
// ----------------------------------------------------------
|
||||
}
|
||||
}
|
||||
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.txlog(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"RECV [" + new String(responseMessage, vo.getEncode()) + "]"
|
||||
+ CommonLib.getDumpMessage(responseMessage));
|
||||
}
|
||||
|
||||
|
||||
return assignResponseHeaders(method, responseMessage, headerGroupName, vo.getEncode(), messageType,
|
||||
relayResponseHeaderKeys, status, responseHeaderProp);
|
||||
} catch (SocketTimeoutException ste) { // Read Timeout :: HttpClient 3.1일 경우
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"HttpClientAdapterServiceRest] SocketTimeoutException (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ste.toString(),
|
||||
ste);
|
||||
}
|
||||
logger.error("HttpClientAdapterServiceRest] SocketTimeoutException (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ste.toString(), ste);
|
||||
throw ste;
|
||||
} catch (ConnectException ce) {
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"HttpClientAdapterServiceRest] Connection Exception (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ce.toString(),
|
||||
ce);
|
||||
}
|
||||
logger.error("HttpClientAdapterServiceRest] Connection Exception (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ce.toString(), ce);
|
||||
throw ce;
|
||||
} catch (Exception e) {
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(), e.toString(), e);
|
||||
}
|
||||
logger.error("HttpClientAdapterServiceRest] Exception (" + vo.getAdapterGroupName() + ") : " + e.toString(),
|
||||
e);
|
||||
throw e;
|
||||
} finally {
|
||||
if (status != HttpStatus.SC_OK) {
|
||||
String[] msgArgs = new String[1];
|
||||
msgArgs[0] = String.valueOf(status);
|
||||
String resMsg = ExceptionUtil.make("RDCEAIAHA013", msgArgs);
|
||||
if (logger.isDebug()) {
|
||||
logger.debug(resMsg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Properties assignRelayDataToInbound(Properties prop, Header[] responseHeaders) {
|
||||
Properties headerProp = new Properties();
|
||||
if (responseHeaders == null || responseHeaders.length == 0) {
|
||||
return headerProp;
|
||||
}
|
||||
|
||||
for (Header header : responseHeaders) {
|
||||
headerProp.put(header.getName(), header.getValue());
|
||||
}
|
||||
|
||||
return headerProp;
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 1단계 레이아웃에만 적용되도록 구현됨.
|
||||
*
|
||||
* @param method
|
||||
* @param responseMessage
|
||||
* @param headerGroupName
|
||||
* @param encode
|
||||
* @param messageType
|
||||
* @param relayHeaderKeys
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private String assignResponseHeaders(HttpUriRequestBase method, byte[] responseMessage, String headerGroupName,
|
||||
String encode, String messageType, String relayHeaderKeys, int status, Properties responseHeaderProp) throws Exception {
|
||||
if (!MessageType.JSON.equals(messageType) || StringUtils.isBlank(headerGroupName)
|
||||
|| StringUtils.isBlank(relayHeaderKeys)) {
|
||||
return new String(responseMessage, encode);
|
||||
}
|
||||
|
||||
String[] relayKeyArr = org.springframework.util.StringUtils.tokenizeToStringArray(relayHeaderKeys, ",");
|
||||
JSONObject headerJson = new JSONObject();
|
||||
for (String key : relayKeyArr) {
|
||||
String value = responseHeaderProp.getProperty(key);
|
||||
if (StringUtils.isNotBlank(value)) {
|
||||
headerJson.put(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
headerJson.put(HTTP_STATUS, String.valueOf(status));
|
||||
|
||||
if (headerJson.size() <= 0) {
|
||||
return new String(responseMessage, encode);
|
||||
}
|
||||
|
||||
JSONObject message = null;
|
||||
if (responseMessage == null || responseMessage.length == 0) {
|
||||
message = new JSONObject();
|
||||
} else {
|
||||
message = parseJson(new String(responseMessage, encode));
|
||||
if (message == null) {
|
||||
message = new JSONObject();
|
||||
message.put("Malformed_Response_Message", new String(responseMessage, encode));
|
||||
}
|
||||
}
|
||||
|
||||
if (StringUtils.isNotBlank(headerGroupName) && message != null)
|
||||
message.put(headerGroupName, headerJson);
|
||||
|
||||
logger.info("------------- message --------------- : {} ", message);
|
||||
|
||||
return message.toJSONString();
|
||||
}
|
||||
|
||||
// 2025.04.09 Authorization 헤더값을 프로퍼티(AUTH_TOKEN)에서 지정하여 설정할 수 있도록 수정
|
||||
private void setAuthHeaders(HttpUriRequestBase method, String authorization) throws Exception {
|
||||
method.setHeader("Authorization",
|
||||
String.format("%s", authorization));
|
||||
}
|
||||
|
||||
private void setAuthHeaders(HttpUriRequestBase method, OAuth2AccessTokenVO accessToken) throws Exception {
|
||||
method.setHeader("Authorization",
|
||||
String.format("%s %s", AccessTokenVO.BEARER_TYPE, accessToken.getAccessToken()));
|
||||
}
|
||||
|
||||
private boolean checkTokenRetry(byte[] responseMessage, String tokenErrorCodeKey, String tokenErrorCodeValues,
|
||||
String encode) {
|
||||
if (responseMessage == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(tokenErrorCodeKey)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(tokenErrorCodeValues)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
DocumentContext jsonContext = JsonPath.parse(new String(responseMessage, encode));
|
||||
String responseCode = jsonContext.read(tokenErrorCodeKey);
|
||||
if (StringUtils.isBlank(responseCode)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String[] arr = org.springframework.util.StringUtils.tokenizeToStringArray(tokenErrorCodeValues, ",");
|
||||
return ArrayUtils.contains(arr, responseCode);
|
||||
} catch (Exception e) {
|
||||
logger.error("HttpClientAdapterServiceRest] checkTokenRetry error=" + e.getMessage());
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private void assignRequestHeaders(HttpUriRequestBase method, Object httpHeader) {
|
||||
if (httpHeader == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (httpHeader instanceof JSONObject) {
|
||||
JSONObject jsonObject = (JSONObject) httpHeader;
|
||||
for (Object key : jsonObject.keySet()) {
|
||||
Object obj = jsonObject.get(key);
|
||||
if ((obj instanceof JSONObject) || (obj instanceof JSONArray)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
method.setHeader((String) key, (String) obj);
|
||||
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("Request Header :" + (String) key + "=[" + (String) obj + "]");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private void assignPostBody(Object eaiBody, String contentType, String charset, HttpUriRequestBase method) {
|
||||
if (eaiBody == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (StringUtils.contains(contentType, "application/x-www-form-urlencoded")) {
|
||||
if (eaiBody instanceof JSONObject) {
|
||||
List<NameValuePair> params = new ArrayList<>();
|
||||
JSONObject jsonObject = (JSONObject) eaiBody;
|
||||
for (Object key : jsonObject.keySet()) {
|
||||
params.add(new BasicNameValuePair((String) key, (String) jsonObject.get(key)));
|
||||
}
|
||||
|
||||
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8);
|
||||
method.setEntity(entity);
|
||||
}
|
||||
|
||||
} else {
|
||||
ContentType contentTypeObj = ContentType.create(contentType, charset);
|
||||
|
||||
// 요청 본문을 StringEntity 객체로 생성
|
||||
StringEntity entity = new StringEntity(eaiBody.toString(), contentTypeObj);
|
||||
|
||||
// 요청에 본문 추가
|
||||
method.setEntity(entity);
|
||||
}
|
||||
}
|
||||
|
||||
private HashMap<String, String> getParameters(Object message) throws Exception {
|
||||
|
||||
HashMap<String, String> result = new HashMap<String, String>();
|
||||
|
||||
if (message != null) {
|
||||
if (message instanceof JSONObject) {
|
||||
JSONObject jsonObject = (JSONObject) message;
|
||||
for (Object key : jsonObject.keySet()) {
|
||||
Object obj = jsonObject.get(key);
|
||||
if ((obj instanceof JSONObject) || (obj instanceof JSONArray)) {
|
||||
continue;
|
||||
}
|
||||
result.put((String) key, getStringValue(obj));
|
||||
}
|
||||
} else {
|
||||
String[] messages = ((String) message).split("&");
|
||||
String[] data = null;
|
||||
|
||||
for (int i = 0; i < messages.length; i++) {
|
||||
data = messages[i].split("=", 2);
|
||||
if (data.length == 2) {
|
||||
result.put(data[0], data[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public String getStringValue(Object obj) {
|
||||
if (obj == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (obj instanceof String) {
|
||||
return (String) obj;
|
||||
} else if (obj instanceof Long) {
|
||||
return Long.toString((Long) obj);
|
||||
} else if (obj instanceof BigDecimal) {
|
||||
return ((BigDecimal) obj).toPlainString();
|
||||
} else {
|
||||
return (String) obj;
|
||||
}
|
||||
}
|
||||
|
||||
public static Object parseJsonGeneric(String jsonData) {
|
||||
if (StringUtils.isBlank(jsonData)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
JSONParser parser = new JSONParser();
|
||||
Object parsedObj = parser.parse(jsonData);
|
||||
return parsedObj;
|
||||
} catch (ParseException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private JSONObject parseJson(String message) throws Exception {
|
||||
if (message == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (JSONObject) JSONValue.parse(message);
|
||||
}
|
||||
|
||||
private Document convertXmlDocument(String message) throws Exception {
|
||||
SAXReader builder = new SAXReader();
|
||||
Document document = builder.read(new StringReader(message));
|
||||
return document;
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private String changeUrl(String messageType, String url, String restOption, Object sendData) {
|
||||
if ((MessageType.JSON.equals(messageType) || MessageType.XML.equals(messageType))) {
|
||||
try {
|
||||
if (StringUtils.isBlank(restOption)) {
|
||||
return url;
|
||||
}
|
||||
List<String> urlVariableList = new ArrayList<String>();
|
||||
JSONObject restOptionObject = parseJson(restOption);
|
||||
|
||||
if (restOptionObject == null)
|
||||
throw new Exception("restOption is NULL");
|
||||
|
||||
String type = (String) restOptionObject.get("type");
|
||||
String requestExtraPath = (String) restOptionObject.get("extraPath");
|
||||
url = getUrl(url, requestExtraPath);
|
||||
if (TYPE_VARIABLE_URL_REQUEST.equals(type)) {
|
||||
Pattern p = Pattern.compile("\\{(.*?)\\}");
|
||||
Matcher m = p.matcher(requestExtraPath);
|
||||
List<String> uriVariables = new ArrayList<>();
|
||||
while(m.find()) {
|
||||
String fieldName = m.group(1);
|
||||
uriVariables.add(fieldName);
|
||||
}
|
||||
if (MessageType.JSON.equals(messageType)) {
|
||||
JSONObject jsonObject;
|
||||
if (sendData instanceof JSONObject) {
|
||||
jsonObject = (JSONObject) sendData;
|
||||
} else {
|
||||
jsonObject = (JSONObject) JSONValue.parse((String) sendData);
|
||||
}
|
||||
for (Object tempObject : uriVariables) {
|
||||
String urlVaribleId = (String) tempObject;
|
||||
String uriVariable = (String) jsonObject.get(urlVaribleId);
|
||||
urlVariableList.add(uriVariable);
|
||||
jsonObject.remove(urlVaribleId);
|
||||
}
|
||||
} else if (MessageType.XML.equals(messageType)) {
|
||||
Document doc;
|
||||
if (sendData instanceof Document) {
|
||||
doc = (Document) sendData;
|
||||
} else {
|
||||
doc = convertXmlDocument((String) sendData);
|
||||
}
|
||||
for (Object tempObject : uriVariables) {
|
||||
String urlVaribleId = (String) tempObject;
|
||||
Element element = (Element) doc.selectSingleNode("//" + urlVaribleId);
|
||||
urlVariableList.add(element.getText());
|
||||
if (doc.getRootElement() == element) {
|
||||
doc = null;
|
||||
} else {
|
||||
element.getParent().remove(element);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (urlVariableList.size() > 0) {
|
||||
UriComponents uriComponents = UriComponentsBuilder.fromUriString(url).build();
|
||||
Object[] urls = urlVariableList.toArray();
|
||||
url = uriComponents.expand(urls).toUriString();
|
||||
logger.debug("HttpClientAdapterServiceRest] after extand url=[" + url + "] ");
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("Failed to change url", e);
|
||||
}
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
private String getUrl(String baseUrl, String extraPath) {
|
||||
if (StringUtils.isBlank(extraPath)) {
|
||||
return baseUrl;
|
||||
}
|
||||
|
||||
if (StringUtils.contains(extraPath, "http://") || StringUtils.contains(extraPath, "https://")) {
|
||||
return extraPath;
|
||||
}
|
||||
|
||||
String targetUrl = baseUrl;
|
||||
if (!targetUrl.endsWith("/")) {
|
||||
targetUrl += "/";
|
||||
}
|
||||
if (extraPath.startsWith("/")) {
|
||||
targetUrl += extraPath.substring(1);
|
||||
} else {
|
||||
targetUrl += extraPath;
|
||||
}
|
||||
|
||||
logger.debug("HttpClientAdapterServiceRest] after concatenate url=[" + targetUrl + "] ");
|
||||
return targetUrl;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.MDC;
|
||||
import org.json.simple.JSONObject;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterGroupVO;
|
||||
import com.eactive.eai.adapter.AdapterManager;
|
||||
@@ -21,6 +21,8 @@ import com.eactive.eai.common.TransactionContextKeys;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.common.util.TxSiftContext;
|
||||
import com.eactive.eai.common.util.UUIDGenerator;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public abstract class HttpAdapterServiceSupport implements HttpAdapterService, HttpAdapterServiceKey {
|
||||
private static final String LOG_PREFIX = "HttpAdapterServiceSupport] ";
|
||||
@@ -28,6 +30,7 @@ public abstract class HttpAdapterServiceSupport implements HttpAdapterService, H
|
||||
public static final String HEADER_NAME_CLIENT_ID = "x-elink-client-id";
|
||||
public static final String PROPERTIES_NAME_CLIENT_ID = "clientId";
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
private ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
public Object service(String adptGrpName, String adptName, Object message, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
@@ -63,6 +66,13 @@ public abstract class HttpAdapterServiceSupport implements HttpAdapterService, H
|
||||
Object obj = null;
|
||||
try {
|
||||
message = doPreFilters(adptGrpName, adptName, message, prop, request, response);
|
||||
|
||||
if (message instanceof JSONObject) {
|
||||
message = ((JSONObject) message).toJSONString();
|
||||
} else if (message instanceof JsonNode) {
|
||||
message = mapper.writeValueAsString((JsonNode) message);
|
||||
}
|
||||
|
||||
obj = RequestDispatcher.getRequestDispatcher(adptGrpName).handle(adptName, message, prop);
|
||||
obj = doPostFilters(adptGrpName, adptName, obj, prop, request, response);
|
||||
} catch (HttpStatusException e) { // inbound error
|
||||
@@ -70,13 +80,13 @@ public abstract class HttpAdapterServiceSupport implements HttpAdapterService, H
|
||||
throw e;
|
||||
} catch (JwtAuthException e) { // filter error
|
||||
logger.error(LOG_PREFIX + transactionId + "-" + adptGrpName + "-" + adptName + ">>" + e.getMessage(), e);
|
||||
UnkownMessageLogUtils.logUnkownMessage(adptGrpName, adptName, message, prop, request, response,
|
||||
"RECEAIIRP202", e);
|
||||
// UnkownMessageLogUtils.logUnkownMessage(adptGrpName, adptName, message, prop, request, response,
|
||||
// "RECEAIIRP202", e);
|
||||
throw e;
|
||||
} catch (Exception e) { // filter error
|
||||
logger.error(LOG_PREFIX + transactionId + "-" + adptGrpName + "-" + adptName + ">>" + e.getMessage(), e);
|
||||
UnkownMessageLogUtils.logUnkownMessage(adptGrpName, adptName, message, prop, request, response,
|
||||
"RECEAIIRP201", e);
|
||||
// UnkownMessageLogUtils.logUnkownMessage(adptGrpName, adptName, message, prop, request, response,
|
||||
// "RECEAIIRP201", e);
|
||||
throw e;
|
||||
}
|
||||
|
||||
@@ -86,6 +96,10 @@ public abstract class HttpAdapterServiceSupport implements HttpAdapterService, H
|
||||
return (byte[]) obj;
|
||||
} else if (obj instanceof String) {
|
||||
return (String) obj;
|
||||
} else if (obj instanceof JSONObject) {
|
||||
return ((JSONObject) obj).toJSONString();
|
||||
} else if (obj instanceof JsonNode) {
|
||||
return (JsonNode) obj;
|
||||
} else {
|
||||
throw new Exception("RECEAIAHA001");
|
||||
}
|
||||
|
||||
+10
-12
@@ -1,19 +1,17 @@
|
||||
package com.eactive.eai.adapter.http.dynamic.filter;
|
||||
|
||||
import com.eactive.eai.adapter.http.HttpStatusException;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.util.IpUtil;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.util.Properties;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.util.IpUtil;
|
||||
|
||||
public class AdapterAllowIPListFilter implements HttpAdapterFilter {
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
@@ -30,9 +28,9 @@ public class AdapterAllowIPListFilter implements HttpAdapterFilter {
|
||||
}
|
||||
|
||||
if (!IpUtil.isMatchIp(allowedIps, requestIp)) {
|
||||
throw new HttpStatusException("This IP was not allowed-" + requestIp, HttpStatus.FORBIDDEN.value());
|
||||
throw new FilterException("This IP was not allowed-" + requestIp, HttpStatus.FORBIDDEN.value());
|
||||
}
|
||||
} catch (HttpStatusException e) {
|
||||
} catch (FilterException e) {
|
||||
logger.debug(e.getMessage());
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
|
||||
+3
-5
@@ -8,11 +8,9 @@ import javax.servlet.http.HttpServletResponse;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
import com.eactive.eai.adapter.http.HttpStatusException;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.util.IpUtil;
|
||||
|
||||
|
||||
public class AdapterBlockIpListFilter implements HttpAdapterFilter {
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
@@ -28,9 +26,9 @@ public class AdapterBlockIpListFilter implements HttpAdapterFilter {
|
||||
}
|
||||
|
||||
if (IpUtil.isMatchIp(blockIps, requestIp)) {
|
||||
throw new HttpStatusException("This IP was not allowed-" + requestIp, HttpStatus.FORBIDDEN.value());
|
||||
throw new FilterException("This IP was not allowed-" + requestIp, HttpStatus.FORBIDDEN.value());
|
||||
}
|
||||
} catch (HttpStatusException e) {
|
||||
} catch (FilterException e) {
|
||||
logger.debug(e.getMessage());
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
@@ -46,7 +44,7 @@ public class AdapterBlockIpListFilter implements HttpAdapterFilter {
|
||||
if (ipAddress == null) {
|
||||
ipAddress = request.getRemoteAddr();
|
||||
}
|
||||
if(ipAddress.indexOf(",") >= 0) {
|
||||
if (ipAddress.indexOf(",") >= 0) {
|
||||
ipAddress = org.springframework.util.StringUtils.tokenizeToStringArray(ipAddress, ",")[0];
|
||||
}
|
||||
return ipAddress;
|
||||
|
||||
@@ -24,6 +24,8 @@ import com.nimbusds.jose.JWSVerifier;
|
||||
import com.nimbusds.jose.crypto.RSASSAVerifier;
|
||||
import com.nimbusds.jose.util.IOUtils;
|
||||
import com.nimbusds.jwt.SignedJWT;
|
||||
|
||||
import org.apache.commons.collections.CollectionUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
@@ -142,6 +144,11 @@ public class ApiAuthFilter implements HttpAdapterFilter {
|
||||
OAuth2Manager manager = OAuth2Manager.getInstance();
|
||||
HashSet<String> scopeSet = manager.getApiScopeMap().get(apiId);
|
||||
|
||||
// API에 scope 설정이 안되어 있는 경우, scope 체크를 pass하고 나중에 client API 맵을 체크한다.
|
||||
if(CollectionUtils.isEmpty(scopeSet))
|
||||
isPassScope = true;
|
||||
|
||||
if(!isPassScope) {
|
||||
String[] scopeArr = signedJWT.getJWTClaimsSet().getStringArrayClaim(PAYLOAD_PARAM_NAME_SCOPE);
|
||||
if (scopeArr == null || scopeArr.length == 0) {
|
||||
throw new JwtAuthException(ERROR_AUTHORIZATION_FAIL,
|
||||
@@ -160,6 +167,7 @@ public class ApiAuthFilter implements HttpAdapterFilter {
|
||||
String.format("Insufficient [Scope](Allowed Scope=%s)", scopeSet.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// header 값으로 전송된 clientId와 토큰 소유 clientId check
|
||||
if (!verifyClientId(prop, signedJWT)) {
|
||||
|
||||
@@ -6,6 +6,7 @@ import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||
@@ -48,7 +49,7 @@ public class ApiKeyExtractFilter implements HttpAdapterFilter {
|
||||
// PathVariable 지원 추가
|
||||
String ruledPath = getMatchedKey(requestPath);
|
||||
if(ruledPath == null)
|
||||
throw new IllegalAccessException("path not found - " + requestPath);
|
||||
throw new FilterException("path not found - " + requestPath, ERROR_PRE_FAIL, HttpStatus.FORBIDDEN.value());
|
||||
prop.setProperty(FINAL_STD_MESSAGE_KEY, ruledPath);// StandardMessageUtil.getMatchedKey(), url
|
||||
// pathvariable도 처리
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.eactive.eai.adapter.http.dynamic.filter;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public class FilterCryptoException extends FilterException {
|
||||
public FilterCryptoException(String msg) {
|
||||
super(msg);
|
||||
}
|
||||
public FilterCryptoException(String msg, int status) {
|
||||
super(msg, status);
|
||||
}
|
||||
public FilterCryptoException(String msg, String code, int status) {
|
||||
super(msg, code, status);
|
||||
}
|
||||
|
||||
public FilterCryptoException(String msg, String code, int status, Throwable cause) {
|
||||
super(msg, code, status, cause);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.eactive.eai.adapter.http.dynamic.filter;
|
||||
|
||||
import com.eactive.eai.adapter.http.HttpStatusException;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public class FilterException extends HttpStatusException {
|
||||
public FilterException(String msg) {
|
||||
super(msg);
|
||||
}
|
||||
public FilterException(String msg, int status) {
|
||||
super(msg, status);
|
||||
}
|
||||
public FilterException(String msg, String code, int status) {
|
||||
super(msg, code, status);
|
||||
}
|
||||
|
||||
public FilterException(String msg, String code, int status, Throwable cause) {
|
||||
super(msg, code, status, cause);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -7,6 +7,9 @@ import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
public interface HttpAdapterFilter {
|
||||
|
||||
public static final String ERROR_PRE_FAIL = "E.PREFILTER_FAIL";
|
||||
public static final String ERROR_POST_FAIL = "E.POSTFILTER_FAIL";
|
||||
|
||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception;
|
||||
|
||||
|
||||
@@ -25,13 +25,19 @@ import com.eactive.eai.adapter.http.filter.AbstractCryptoFilter;
|
||||
*/
|
||||
public class InCryptoFilter extends AbstractCryptoFilter implements HttpAdapterFilter {
|
||||
|
||||
public static final String ERROR_DEC_FAIL = "E.DECRYPT_FAIL";
|
||||
public static final String ERROR_ENC_FAIL = "E.ENCRYPT_FAIL";
|
||||
/**
|
||||
* DYNAMIC 키 도출용 컨텍스트를 구성한다.
|
||||
* STATIC 키 모듈이면 빈 Map({@code new HashMap<>()})을 반환한다.
|
||||
* 서브클래스에서 오버라이드하여 HttpServletRequest로부터 값을 추출할 수 있다.
|
||||
*/
|
||||
protected Map<String, String> buildRuntimeContext(Properties prop, HttpServletRequest request) {
|
||||
return new HashMap<>();
|
||||
Map<String, String> context = new HashMap<>();
|
||||
for (String key : prop.stringPropertyNames()) {
|
||||
context.put(key, prop.getProperty(key));
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -43,7 +49,9 @@ public class InCryptoFilter extends AbstractCryptoFilter implements HttpAdapterF
|
||||
if (StringUtils.isBlank(headerName) || request == null) {
|
||||
return null;
|
||||
}
|
||||
String headerValue = request.getHeader(headerName);
|
||||
Properties inboundHeaderProp = (Properties)prop.get("INBOUND_HEADER");
|
||||
String headerValue = inboundHeaderProp.getProperty(headerName);
|
||||
// String headerValue = request.getHeader(headerName);
|
||||
return StringUtils.isBlank(headerValue) ? null : headerValue.getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
|
||||
+39
-7
@@ -51,13 +51,6 @@ public class ReflectAllHeaderFilter implements HttpAdapterFilter {
|
||||
@Override
|
||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
return message;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
|
||||
logger.debug("doPreFilter ReflectAllHeaderFilter Start.");
|
||||
|
||||
String propValue = PropManager.getInstance().getProperty(PROPERTIES_GROUP_NAME, HEADER_KEY_NAMES, "").trim();
|
||||
@@ -90,6 +83,45 @@ public class ReflectAllHeaderFilter implements HttpAdapterFilter {
|
||||
|
||||
logger.debug("doPreFilter ReflectAllHeaderFilter End.");
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
|
||||
logger.debug("doPostFilter ReflectAllHeaderFilter Start.");
|
||||
|
||||
String propValue = PropManager.getInstance().getProperty(PROPERTIES_GROUP_NAME, HEADER_KEY_NAMES, "").trim();
|
||||
String[] userSettingBlackList = propValue.split(",");
|
||||
|
||||
if( userSettingBlackList.length > 0 ) {
|
||||
HttpHeaderRelayBlackList = Stream
|
||||
.concat(Arrays.stream(HttpHeaderRelayBlackList), Arrays.stream(userSettingBlackList))
|
||||
.toArray(String[]::new);
|
||||
}
|
||||
|
||||
try {
|
||||
Enumeration<String> headerNames = request.getHeaderNames();
|
||||
while (headerNames.hasMoreElements()) {
|
||||
|
||||
String headerName = headerNames.nextElement();
|
||||
String headerValue = request.getHeader(headerName);
|
||||
|
||||
if( StringUtils.equalsAnyIgnoreCase( headerName, HttpHeaderRelayBlackList ) ) {
|
||||
logger.debug("Skip Processing Key ["+headerName+"], value ["+headerValue+"] in HttpHeaderRelayBlackList");
|
||||
continue;
|
||||
}
|
||||
|
||||
response.setHeader(headerName, headerValue);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
}
|
||||
|
||||
logger.debug("doPostFilter ReflectAllHeaderFilter End.");
|
||||
|
||||
return resultMessage;
|
||||
}
|
||||
}
|
||||
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package com.eactive.eai.adapter.http.dynamic.filter.custom;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterManager;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public class JsonToSetStatusFilter implements HttpAdapterFilter {
|
||||
private ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@Override
|
||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
JsonNode rootNode = parseJson(adptGrpName, message);
|
||||
|
||||
int httpStatus = 200;
|
||||
|
||||
if (rootNode.has("apiRsltCd") && !rootNode.get("apiRsltCd").asText().isEmpty()) {
|
||||
try {
|
||||
String statusParam = rootNode.get("apiRsltCd").asText();
|
||||
httpStatus = Integer.parseInt(statusParam);
|
||||
} catch (NumberFormatException e) {
|
||||
httpStatus = 400; // 잘못된 입력일 경우 400 Bad Request 반환
|
||||
}
|
||||
// HTTP 상태 코드 설정
|
||||
response.setStatus(httpStatus);
|
||||
}
|
||||
return message;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
JsonNode rootNode = parseJson(adptGrpName, resultMessage);
|
||||
int httpStatus = 200;
|
||||
|
||||
if (rootNode.has("apiRsltCd") && !rootNode.get("apiRsltCd").asText().isEmpty()) {
|
||||
try {
|
||||
String statusParam = rootNode.get("apiRsltCd").asText();
|
||||
httpStatus = Integer.parseInt(statusParam);
|
||||
} catch (NumberFormatException e) {
|
||||
httpStatus = 400; // 잘못된 입력일 경우 400 Bad Request 반환
|
||||
}
|
||||
// HTTP 상태 코드 설정
|
||||
response.setStatus(httpStatus);
|
||||
}
|
||||
return resultMessage;
|
||||
}
|
||||
|
||||
public JsonNode parseJson(String adptGrpName, Object message) throws UnsupportedEncodingException, JsonMappingException, JsonProcessingException {
|
||||
String charset = StringUtils.defaultIfBlank(AdapterManager.getInstance().getAdapterGroupVO(adptGrpName).getMessageEncode(), "UTF-8");
|
||||
String orgMessageString;
|
||||
if(message instanceof byte[]) {
|
||||
orgMessageString = new String((byte[])message, charset);
|
||||
} else {
|
||||
orgMessageString = (String) message;
|
||||
}
|
||||
|
||||
return mapper.readTree(orgMessageString);
|
||||
}
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
package com.eactive.eai.adapter.http.dynamic.filter.custom;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterManager;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
public class JsonToStdConverterFilter implements HttpAdapterFilter {
|
||||
private ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@Override
|
||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
JsonNode rootNode = parseJson(adptGrpName, message);
|
||||
|
||||
if (rootNode.has("header_part")) {
|
||||
JsonNode headerPart = rootNode.path("header_part");
|
||||
if (!headerPart.has("eaiIntfId") || headerPart.get("eaiIntfId").asText().isEmpty()) {
|
||||
// /api/v1/public/getUserInfo.svc
|
||||
String inboundUri = prop.getProperty(HttpAdapterServiceKey.INBOUND_EXTURI);
|
||||
String apiPath = prop.getProperty(HttpAdapterServiceKey.API_PATH) + "/";
|
||||
|
||||
// getUserInfo.svc
|
||||
String eaiIntfId = org.apache.commons.lang.StringUtils.removeStart(inboundUri, apiPath);
|
||||
|
||||
// header_part 아래 eaiIntfId가 추가 또는 수정
|
||||
if (headerPart instanceof ObjectNode) {
|
||||
((ObjectNode) headerPart).put("eaiIntfId", eaiIntfId);
|
||||
// 요청 응답 구분코드 강제 설정 -> API명 찾아갈때 필요
|
||||
if (!headerPart.has("reqRspnsDscd")) {
|
||||
((ObjectNode) headerPart).put("reqRspnsDscd", "S");
|
||||
}
|
||||
|
||||
// GUID 강제 설정
|
||||
String orgnlTx = "";
|
||||
if (headerPart.has("orgnlTx") && !headerPart.get("orgnlTx").asText().isEmpty()) {
|
||||
orgnlTx = headerPart.get("orgnlTx").asText();
|
||||
}
|
||||
if (!headerPart.has("tlgrWrtnDt")) {
|
||||
((ObjectNode) headerPart).put("tlgrWrtnDt", orgnlTx);
|
||||
}
|
||||
if (!headerPart.has("tlgrCrtnSysNm")) {
|
||||
((ObjectNode) headerPart).put("tlgrCrtnSysNm", "");
|
||||
}
|
||||
if (!headerPart.has("tlgrSrlNo")) {
|
||||
((ObjectNode) headerPart).put("tlgrSrlNo", "");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
return message;
|
||||
}
|
||||
return rootNode.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
JsonNode rootNode = parseJson(adptGrpName, resultMessage);
|
||||
|
||||
if (rootNode.has("header_part")) {
|
||||
JsonNode headerPart = rootNode.path("header_part");
|
||||
if (!headerPart.has("eaiIntfId") || headerPart.get("eaiIntfId").asText().isEmpty()) {
|
||||
// /api/v1/public/getUserInfo.svc
|
||||
String inboundUri = prop.getProperty(HttpAdapterServiceKey.INBOUND_EXTURI);
|
||||
String apiPath = prop.getProperty(HttpAdapterServiceKey.API_PATH) + "/";
|
||||
|
||||
// getUserInfo.svc
|
||||
String eaiIntfId = org.apache.commons.lang.StringUtils.removeStart(inboundUri, apiPath);
|
||||
|
||||
// header_part 아래 eaiIntfId가 추가 또는 수정
|
||||
if (headerPart instanceof ObjectNode) {
|
||||
((ObjectNode) headerPart).put("eaiIntfId", eaiIntfId);
|
||||
// 요청 응답 구분코드 강제 설정 -> API명 찾아갈때 필요
|
||||
((ObjectNode) headerPart).put("reqRspnsDscd", "S");
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
return resultMessage;
|
||||
}
|
||||
return rootNode.toString();
|
||||
}
|
||||
|
||||
public JsonNode parseJson(String adptGrpName, Object message) throws UnsupportedEncodingException, JsonMappingException, JsonProcessingException {
|
||||
String charset = StringUtils.defaultIfBlank(AdapterManager.getInstance().getAdapterGroupVO(adptGrpName).getMessageEncode(), "UTF-8");
|
||||
String orgMessageString;
|
||||
if(message instanceof byte[]) {
|
||||
orgMessageString = new String((byte[])message, charset);
|
||||
} else {
|
||||
orgMessageString = (String) message;
|
||||
}
|
||||
|
||||
return mapper.readTree(orgMessageString);
|
||||
}
|
||||
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package com.eactive.eai.adapter.http.dynamic.filter.custom;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.Iterator;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterManager;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
public class KbankEaiJsonParseFilter implements HttpAdapterFilter {
|
||||
|
||||
private ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@Override
|
||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
JsonNode rootNode = parseJson(adptGrpName, message);
|
||||
|
||||
ObjectNode replacedJson = mapper.createObjectNode();
|
||||
for(Iterator<String> it = rootNode.fieldNames(); it.hasNext();) {
|
||||
String fieldName = it.next();
|
||||
String value = rootNode.get(fieldName).asText();
|
||||
JsonNode jsonNode = mapper.readTree(value);
|
||||
replacedJson.set(fieldName, jsonNode);
|
||||
}
|
||||
|
||||
return replacedJson.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
JsonNode rootNode = parseJson(adptGrpName, resultMessage);
|
||||
|
||||
ObjectNode replacedJson = mapper.createObjectNode();
|
||||
for(Iterator<String> it = rootNode.fieldNames(); it.hasNext();) {
|
||||
String fieldName = it.next();
|
||||
JsonNode childNode = rootNode.get(fieldName);
|
||||
String childString = mapper.writeValueAsString(childNode);
|
||||
replacedJson.put(fieldName, childString);
|
||||
}
|
||||
|
||||
return replacedJson.toString();
|
||||
}
|
||||
|
||||
public JsonNode parseJson(String adptGrpName, Object message) throws UnsupportedEncodingException, JsonMappingException, JsonProcessingException {
|
||||
String charset = StringUtils.defaultIfBlank(AdapterManager.getInstance().getAdapterGroupVO(adptGrpName).getMessageEncode(), "UTF-8");
|
||||
String orgMessageString;
|
||||
if(message instanceof byte[]) {
|
||||
orgMessageString = new String((byte[])message, charset);
|
||||
} else {
|
||||
orgMessageString = (String) message;
|
||||
}
|
||||
|
||||
return mapper.readTree(orgMessageString);
|
||||
}
|
||||
|
||||
}
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
package com.eactive.eai.adapter.http.dynamic.filter.custom;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.Properties;
|
||||
import java.util.Date;
|
||||
import java.util.Enumeration;
|
||||
import java.util.Iterator;
|
||||
import java.text.SimpleDateFormat;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.Mac;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterManager;
|
||||
import com.eactive.eai.common.property.PropManager;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import org.apache.commons.net.util.Base64;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||
import com.eactive.eai.common.server.Keys;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public class KbankHmacSha256VerifyFilter implements HttpAdapterFilter {
|
||||
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
private static final String SERVICE_CODE_UNKNOWN = "00";
|
||||
private static final int TIMESTAMP_EXPIRATION_SECONDS = 60*10*1000;
|
||||
private static final String GROUP_NAME = "HMAC_INFO";
|
||||
|
||||
private ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@Override
|
||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
|
||||
try {
|
||||
|
||||
String hmacSignature = getHeaderCaseInsensitive(request, "hmac_signature");
|
||||
String hmacTimestamp = getHeaderCaseInsensitive(request, "hmac_timestamp");
|
||||
|
||||
if(StringUtils.isBlank(hmacSignature) || StringUtils.isBlank(hmacTimestamp)) {
|
||||
throw new JwtAuthException(String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"), "Can not find hmac info");
|
||||
}
|
||||
|
||||
long inputTime = new SimpleDateFormat("yyyyMMddHHmmss").parse(hmacTimestamp).getTime();
|
||||
long currentTime = new Date().getTime();
|
||||
String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
|
||||
|
||||
logger.debug("### inputTime :"+inputTime);
|
||||
logger.debug("### currentTime :"+currentTime);
|
||||
logger.debug("### timeStamp :"+timeStamp);
|
||||
|
||||
String systemMode = System.getProperty(Keys.EAI_SYSTEMMODE);
|
||||
|
||||
if(currentTime - inputTime > TIMESTAMP_EXPIRATION_SECONDS) {
|
||||
|
||||
logger.debug("### systemMode:" + systemMode);
|
||||
logger.debug("### currentTime - inputTime:" + (currentTime - inputTime));
|
||||
|
||||
if("P".equals(systemMode)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN,"00"), "Signature verifying failed");
|
||||
}
|
||||
}
|
||||
|
||||
String sMessage = (String)message;
|
||||
|
||||
sMessage = sMessage.replace(" ","");
|
||||
sMessage = sMessage.replace("\n","");
|
||||
sMessage = sMessage.replace("\r","");
|
||||
|
||||
sMessage = sMessage + hmacTimestamp;
|
||||
|
||||
logger.info("### sMessage:"+sMessage);
|
||||
|
||||
String alCoId = "AL2021012901001";
|
||||
|
||||
JsonNode rootNode = parseJson(adptGrpName, message);
|
||||
|
||||
for(Iterator<String> it = rootNode.fieldNames(); it.hasNext();){
|
||||
String fieldName = it.next();
|
||||
if(fieldName.equals("ALCO_ID")) alCoId = rootNode.get(fieldName).asText();
|
||||
}
|
||||
|
||||
logger.info("### alCoId:"+alCoId);
|
||||
|
||||
Properties hmacProp = PropManager.getInstance().getProperties(GROUP_NAME);
|
||||
|
||||
String hmacKey = hmacProp.getProperty(alCoId+"-hmack-key","");
|
||||
String hmacKek = hmacProp.getProperty(alCoId+"-hmack-kek","");
|
||||
String hmacIvForKey = hmacProp.getProperty(alCoId+"-hmack-iv-for-key","");
|
||||
|
||||
logger.debug("### hmacKey:"+hmacKey);
|
||||
logger.debug("### hmacIvForKey:"+hmacIvForKey);
|
||||
logger.debug("### hmacKek:"+hmacKek);
|
||||
|
||||
//kbank.payment.hmac-key
|
||||
int hmacKeyLen = hmacKey.length();
|
||||
byte[] hmacKeyData = new byte[hmacKeyLen/2];
|
||||
for(int i=0;i<hmacKeyLen;i+=2){
|
||||
hmacKeyData[i/2] = (byte)((Character.digit(hmacKey.charAt(i), 16) << 4) + Character.digit(hmacKey.charAt(i+1), 16));
|
||||
}
|
||||
|
||||
//kbank.payment.hmac-kek
|
||||
int hmacKekLen = hmacKek.length();
|
||||
byte[] hmacKekData = new byte[hmacKekLen/2];
|
||||
for(int i=0;i<hmacKekLen;i+=2){
|
||||
hmacKekData[i/2] = (byte)((Character.digit(hmacKek.charAt(i),16) << 4) + Character.digit(hmacKek.charAt(i+1), 16));
|
||||
}
|
||||
|
||||
//kbank.payment.hmac-iv-for-key
|
||||
int hmacIvForKeyLen = hmacIvForKey.length();
|
||||
byte[] hmacIvForKeyData = new byte[hmacIvForKeyLen/2];
|
||||
for(int i=0;i<hmacIvForKeyLen;i+=2){
|
||||
hmacIvForKeyData[i/2] = (byte)((Character.digit(hmacIvForKey.charAt(i),16) << 4) + Character.digit(hmacIvForKey.charAt(i+1), 16));
|
||||
}
|
||||
|
||||
byte[] decrypedHmacKey = null;
|
||||
|
||||
try{
|
||||
Cipher cp = Cipher.getInstance("AES/CBC/PKCS5Padding");
|
||||
cp.init(Cipher.DECRYPT_MODE, new SecretKeySpec(hmacIvForKeyData,"AES"), new IvParameterSpec(hmacIvForKeyData));
|
||||
decrypedHmacKey = cp.doFinal(hmacKeyData);
|
||||
} catch (Exception e) {
|
||||
logger.debug(e.getMessage());
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"), "Signature verifying failed");
|
||||
}
|
||||
|
||||
SecretKeySpec secretKey = new SecretKeySpec(decrypedHmacKey, "HmacSHA256");
|
||||
String madeSignature = "";
|
||||
|
||||
logger.info("### secretKey:"+secretKey);
|
||||
|
||||
try{
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(secretKey);
|
||||
madeSignature= Base64.encodeBase64String(mac.doFinal(sMessage.getBytes()));
|
||||
} catch (Exception e) {
|
||||
logger.debug(e.getMessage());
|
||||
throw new JwtAuthException(String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"), "Signature verifying failed");
|
||||
}
|
||||
|
||||
logger.info("### madeSignature:"+madeSignature);
|
||||
|
||||
if(!StringUtils.equals(hmacSignature, madeSignature)){
|
||||
logger.info("### hmacSignature:"+hmacSignature);
|
||||
logger.info("### madeSignature:"+madeSignature);
|
||||
|
||||
throw new JwtAuthException(String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"), "Signature verifying failed" );
|
||||
}
|
||||
|
||||
} catch (JwtAuthException e) {
|
||||
logger.debug(e.getMessage());
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
logger.debug(e.getMessage());
|
||||
throw new JwtAuthException(String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"), "Signature verifying failed(Unknown)" );
|
||||
}
|
||||
|
||||
logger.info("### pass: "+"success");
|
||||
|
||||
return message;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 대소문자 구분 없이 HTTP 헤더 값을 가져오는 메소드
|
||||
* @param request HTTP 요청 객체
|
||||
* @param headerName 찾고자 하는 헤더 이름
|
||||
* @return 헤더 값 또는 null
|
||||
*/
|
||||
public static String getHeaderCaseInsensitive(HttpServletRequest request, String headerName) {
|
||||
Enumeration<String> headerNames = request.getHeaderNames();
|
||||
while (headerNames.hasMoreElements()) {
|
||||
String header = headerNames.nextElement();
|
||||
if (header != null && header.equalsIgnoreCase(headerName)) {
|
||||
return request.getHeader(header);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public JsonNode parseJson(String adptGrpName, Object message) throws UnsupportedEncodingException, JsonMappingException,JsonProcessingException {
|
||||
String charset = StringUtils.defaultIfBlank(AdapterManager.getInstance().getAdapterGroupVO(adptGrpName).getMessageEncode(), "UTF-8");
|
||||
String orgMessageString;
|
||||
|
||||
if(message instanceof byte[]) {
|
||||
orgMessageString = new String((byte[])message, charset);
|
||||
} else {
|
||||
orgMessageString = (String) message;
|
||||
}
|
||||
|
||||
return mapper.readTree(orgMessageString);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
return resultMessage;
|
||||
}
|
||||
|
||||
}
|
||||
+205
@@ -0,0 +1,205 @@
|
||||
package com.eactive.eai.adapter.http.dynamic.filter.custom;
|
||||
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.codec.digest.DigestUtils;
|
||||
import org.apache.commons.codec.digest.HmacAlgorithms;
|
||||
import org.apache.commons.codec.digest.HmacUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||
import com.eactive.eai.authserver.service.OAuth2Manager;
|
||||
import com.eactive.eai.authserver.vo.ClientVO;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public class SnapHmacSha512VerifyFilter implements HttpAdapterFilter {
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
private static final String SERVICE_CODE_UNKNOWN = "00";
|
||||
private static final int X_TIMESTAMP_EXPIRATION_SECONDS = 60 * 5;
|
||||
|
||||
@Override
|
||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
// @formatter:off
|
||||
/*
|
||||
* HMAC_SHA512 (clientSecret, stringToSign)
|
||||
*
|
||||
* stringToSign = HTTPMethod:EndpointUrl:AccessToken
|
||||
* :Lowercase(HexEncode(SHA-256(minify(RequestBody)))):TimeStamp
|
||||
*/
|
||||
try {
|
||||
String xSignature = request.getHeader("X-SIGNATURE");
|
||||
if (StringUtils.isBlank(xSignature)) {
|
||||
throw new JwtAuthException(String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"), "Can not find X-SIGNATURE");
|
||||
}
|
||||
|
||||
String clientSecret = assignClientSecret(prop, request);
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(request.getMethod())
|
||||
.append(":")
|
||||
.append(getEndpointUrl(request))
|
||||
.append(":")
|
||||
.append(SnapSimpleOauth2Filter.extractToken(request))
|
||||
.append(":")
|
||||
.append(getRequestBody((String)message))
|
||||
.append(":")
|
||||
.append(getTimeStamp(request));
|
||||
// @formatter:on
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug(sb.toString());
|
||||
}
|
||||
|
||||
String hmac = new HmacUtils(HmacAlgorithms.HMAC_SHA_512, clientSecret).hmacHex(sb.toString());
|
||||
|
||||
if (!StringUtils.equals(xSignature, hmac)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"Signature verifying failed");
|
||||
}
|
||||
} catch (JwtAuthException e) {
|
||||
logger.debug(e.getMessage());
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"Signature verifying failed(unkown)");
|
||||
}
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
private String assignClientSecret(Properties prop, HttpServletRequest request) throws Exception {
|
||||
String clientId = assignClientId(prop, request);
|
||||
if (StringUtils.isBlank(clientId)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"Can not find clientId info");
|
||||
}
|
||||
|
||||
ClientVO client = (ClientVO) OAuth2Manager.getInstance().getClientDeatilsStore().get(clientId);
|
||||
if (client == null) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"Can not find client info");
|
||||
}
|
||||
|
||||
return client.getClientSecret();
|
||||
}
|
||||
|
||||
private String assignClientId(Properties prop, HttpServletRequest request) {
|
||||
String clientId = null;
|
||||
try {
|
||||
// 이전 filter에서 셋팅한 clientId 확보
|
||||
clientId = prop.getProperty(HttpAdapterServiceSupport.PROPERTIES_NAME_CLIENT_ID);
|
||||
|
||||
// 이전 filter에서 셋팅한 값이 없다면 header 정보에서 확보
|
||||
if (StringUtils.isBlank(clientId)) {
|
||||
clientId = request.getHeader(HttpAdapterServiceSupport.HEADER_NAME_CLIENT_ID);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
}
|
||||
|
||||
return clientId;
|
||||
}
|
||||
|
||||
private String getEndpointUrl(HttpServletRequest request) {
|
||||
String servletPath = request.getServletPath();
|
||||
String pathInfo = request.getPathInfo();
|
||||
String queryString = request.getQueryString();
|
||||
|
||||
StringBuilder url = new StringBuilder();
|
||||
url.append(servletPath);
|
||||
|
||||
if (pathInfo != null) {
|
||||
url.append(pathInfo);
|
||||
}
|
||||
|
||||
if (queryString != null) {
|
||||
url.append("?").append(queryString);
|
||||
}
|
||||
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
private String getRequestBody(String message) throws Exception {
|
||||
if (StringUtils.isEmpty(message)) {
|
||||
return "";
|
||||
}
|
||||
|
||||
// Lowercase(HexEncode(SHA-256(minify(RequestBody))))
|
||||
String body = minifyJson(message);
|
||||
try {
|
||||
body = DigestUtils.sha256Hex(body);
|
||||
} catch (Exception e) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"SHA-256 digest error");
|
||||
}
|
||||
return body.toLowerCase();
|
||||
}
|
||||
|
||||
private String minifyJson(String json) {
|
||||
try {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
JsonNode jsonNode = objectMapper.readValue(json, JsonNode.class);
|
||||
return jsonNode.toString();
|
||||
} catch (Exception e) {
|
||||
// json이 아닐경우
|
||||
return json;
|
||||
}
|
||||
}
|
||||
|
||||
private String getTimeStamp(HttpServletRequest request) throws Exception {
|
||||
String timeStamp = request.getHeader("X-TIMESTAMP");
|
||||
if (StringUtils.isBlank(timeStamp)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"Can not find X-TIMESTAMP");
|
||||
}
|
||||
|
||||
// 2020-12-23T09:10:11+07:00(현재시간이랑 비교로직 추가-보안)
|
||||
ZonedDateTime xTimeStamp = ZonedDateTime.parse(timeStamp, DateTimeFormatter.ISO_DATE_TIME);
|
||||
xTimeStamp = xTimeStamp.plusSeconds(X_TIMESTAMP_EXPIRATION_SECONDS);
|
||||
ZonedDateTime now = ZonedDateTime.now();
|
||||
if (xTimeStamp.isBefore(now.withZoneSameInstant(xTimeStamp.getZone()))) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"Too old X-TIMESTAMP");
|
||||
}
|
||||
|
||||
return timeStamp;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
return resultMessage;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
String str = "POST:/api/test/aaa/type02/555:"
|
||||
+ "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJzbmFwIl0sImV4cCI6MTY3NjUyNDI1MSwianRpIjoiNzI0MWMyZGUtZjJhNi00NTFmLWExMjQtZGM3NmI0ZGY1OThjIiwiY2xpZW50X2lkIjoic1NHSkR3bEpzZWw1V2VYb2R6ZDNKM01RMjBLWUNacEwifQ.Obe8t8IwuQ3P7i4yCSASYze-9DLmVwXe0g_gBYlwv_Jzc7V8-ooTwp6SVnaNsM6pp1GV-9lxMpAzQO_CRHQq_hdMeiPI_CXHh3gETvjQThn57QGEGdCNp_lUEVYtMPUxi5u3X6Of07o0_OB83WI7rA1zD0DaP8V67pgfq-jMRe_3IXztOYu_nwMgREbGvs9tqcsjxppRKkEHcK1S8Eq4HzaLwjwyHJAhIlTba27yd4T8ELC7IpFphJBfEPF_t0ZpYW15lOrg5pHPjy1xpTV0Kgipog5wycTZlFUeCWWjfxTrpVmt_1XlEOlZH9X6xAefWrH93_fpbt3OcxwP4u9KhA"
|
||||
+ ":424058b889b9d860d13b79d90df52ddcbefba2fc9d27607e999c7c3c4d61d9c8:" + "2023-02-16T09:47:07+07:00";
|
||||
|
||||
String hmac = new HmacUtils(HmacAlgorithms.HMAC_SHA_512,
|
||||
"o3Hre3voTrHbLueDrHC0LYM5effHQZILI8t23htbD12TKD5QJUMONqFqv4494iQS46bzHS0xW1fBC5LHo3D0SzhZvQcPUaJZw0iQ79NnzYFUCTrEsoFJRL300dp3Ql4y")
|
||||
.hmacHex(str);
|
||||
|
||||
// System.out.println(hmac);
|
||||
}
|
||||
}
|
||||
+237
@@ -0,0 +1,237 @@
|
||||
package com.eactive.eai.adapter.http.dynamic.filter.custom;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.interfaces.RSAPublicKey;
|
||||
import java.security.spec.InvalidKeySpecException;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.text.ParseException;
|
||||
import java.util.Base64;
|
||||
import java.util.Date;
|
||||
import java.util.HashSet;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthFilter;
|
||||
import com.eactive.eai.authserver.service.OAuth2Manager;
|
||||
import com.eactive.eai.common.property.PropGroupVO;
|
||||
import com.eactive.eai.common.property.PropManager;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.inbound.action.ActionFactory;
|
||||
import com.eactive.eai.inbound.action.RequestAction;
|
||||
import com.eactive.eai.inbound.processor.Processor;
|
||||
import com.eactive.eai.message.StandardMessageUtil;
|
||||
import com.nimbusds.jose.JWSVerifier;
|
||||
import com.nimbusds.jose.crypto.RSASSAVerifier;
|
||||
import com.nimbusds.jose.util.IOUtils;
|
||||
import com.nimbusds.jwt.SignedJWT;
|
||||
|
||||
public class SnapJwtAuthFilter implements HttpAdapterFilter {
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
public static final String PROP_GROUP_AUTH_SERVER = "OAuthServer";
|
||||
public static final String PROP_KEYSTORE_PATH = "certification.publicKeyPath";
|
||||
|
||||
private static final String SERVICE_CODE_UNKNOWN = "00";
|
||||
|
||||
public static final String PAYLOAD_PARAM_NAME_SCOPE = "scope";
|
||||
public static final String PAYLOAD_PARAM_NAME_CLIENT_ID = "client_id";
|
||||
|
||||
private JWSVerifier jwsVerifier;
|
||||
|
||||
public SnapJwtAuthFilter() {
|
||||
super();
|
||||
|
||||
PropGroupVO vo = PropManager.getInstance().getPropGroupVO(PROP_GROUP_AUTH_SERVER);
|
||||
String publicKeyPath = "/certificate/elink-oauth-dev.pub";
|
||||
if (vo != null) {
|
||||
publicKeyPath = vo.getProperty(PROP_KEYSTORE_PATH);
|
||||
} else {
|
||||
logger.warn("The properties has not been set.[" + PROP_GROUP_AUTH_SERVER + "]");
|
||||
}
|
||||
|
||||
Resource resource = new ClassPathResource(publicKeyPath);
|
||||
String publicKey = null;
|
||||
try {
|
||||
publicKey = IOUtils.readInputStreamToString(resource.getInputStream());
|
||||
publicKey = StringUtils.replace(publicKey, "-----BEGIN PUBLIC KEY-----", "");
|
||||
publicKey = StringUtils.replace(publicKey, "-----END PUBLIC KEY-----", "");
|
||||
publicKey = StringUtils.remove(publicKey, "\r");
|
||||
publicKey = StringUtils.remove(publicKey, "\n");
|
||||
|
||||
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey));
|
||||
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||
jwsVerifier = new RSASSAVerifier((RSAPublicKey) keyFactory.generatePublic(keySpec));
|
||||
} catch (final IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
String apiId = assignApiId(adptGrpName, adptName, message, prop, request);
|
||||
if (StringUtils.isBlank(apiId)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"Can not find apiId(apiCode) info");
|
||||
}
|
||||
|
||||
try {
|
||||
String token = JwtAuthFilter.extractJWTToken(request);
|
||||
SignedJWT signedJWT = SignedJWT.parse(token);
|
||||
|
||||
if (new Date().after(signedJWT.getJWTClaimsSet().getExpirationTime())) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "01"),
|
||||
"Invalid Token - expired (B2B)");
|
||||
}
|
||||
|
||||
if (!signedJWT.verify(jwsVerifier)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "01"),
|
||||
"Invalid Token (B2B)");
|
||||
}
|
||||
|
||||
OAuth2Manager manager = OAuth2Manager.getInstance();
|
||||
HashSet<String> scopeSet = manager.getApiScopeMap().get(apiId);
|
||||
if (!verifyScope(scopeSet, signedJWT)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "01"),
|
||||
String.format("Insufficient [Scope](Allowed Scope=%s)", scopeSet.toString()));
|
||||
}
|
||||
|
||||
// header 값으로 전송된 clientId와 토큰 소유 clientId check
|
||||
if (!verifyClientId(prop, signedJWT)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"client_id not matched(header/token)");
|
||||
}
|
||||
} catch (JwtAuthException e) {
|
||||
logger.debug(e.getMessage());
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "01"),
|
||||
"Invalid Token (B2B)");
|
||||
}
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
private boolean verifyClientId(Properties prop, SignedJWT signedJWT) {
|
||||
try {
|
||||
// 이전 filter에서 셋팅한 clientId 확보
|
||||
String headerClientId = prop.getProperty(HttpAdapterServiceSupport.PROPERTIES_NAME_CLIENT_ID);
|
||||
String tokenClientId = (String) signedJWT.getJWTClaimsSet().getClaim(PAYLOAD_PARAM_NAME_CLIENT_ID);
|
||||
|
||||
// 이전 filter에서 셋팅한 값이 없다면 token 정보에서 확보
|
||||
if (StringUtils.isBlank(headerClientId)) {
|
||||
if (StringUtils.isNotBlank(tokenClientId)) {
|
||||
prop.put(HttpAdapterServiceSupport.PROPERTIES_NAME_CLIENT_ID, tokenClientId);
|
||||
}
|
||||
} else { // header로 전달된 clientId가 있을때만 비교
|
||||
if (!headerClientId.equals(tokenClientId)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private String assignApiId(String adptGrpName, String adptName, Object message, Properties prop,
|
||||
HttpServletRequest request) {
|
||||
String apiId = null;
|
||||
try {
|
||||
String actionName = prop.getProperty(Processor.REQUEST_ACTION);
|
||||
RequestAction action = ActionFactory.createAction(actionName);
|
||||
action.setAdapterInfo(adptGrpName, adptName, prop);
|
||||
String[] keys = action.perform(message);
|
||||
apiId = keys[0];
|
||||
|
||||
// PathVariable 지원 추가
|
||||
apiId = StandardMessageUtil.getMatchedKey(apiId, actionName);
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
}
|
||||
|
||||
// // header 에서 확보
|
||||
// String apiId = request.getHeader(HEADER_NAME_API_CODE);
|
||||
// if (StringUtils.isBlank(apiId)) {
|
||||
// // url에서 확보
|
||||
// // /ONLWeb/api/v1/public/getUserInfo.svc/
|
||||
// apiId = request.getRequestURI();
|
||||
// // /ONLWeb/api/v1/public/getUserInfo.svc
|
||||
// apiId = StringUtils.removeEnd(apiId, "/");
|
||||
// // getUserInfo.svc
|
||||
// apiId = StringUtils.substringAfterLast(apiId, "/");
|
||||
// }
|
||||
|
||||
return apiId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
return resultMessage;
|
||||
}
|
||||
|
||||
private boolean verifyScope(HashSet<String> scopeSet, SignedJWT signedJWT) throws ParseException {
|
||||
if (scopeSet == null || scopeSet.isEmpty()) {
|
||||
return true; // If no scope is specified in the api, all are allowed
|
||||
}
|
||||
|
||||
String[] scopeArr = signedJWT.getJWTClaimsSet().getStringArrayClaim(PAYLOAD_PARAM_NAME_SCOPE);
|
||||
if (scopeArr == null || scopeArr.length == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (String scope : scopeArr) {
|
||||
if (scopeSet.contains(scope)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static String extractJWTToken(HttpServletRequest request) throws JwtAuthException {
|
||||
String authorization = request.getHeader("Authorization");
|
||||
if (StringUtils.isBlank(authorization)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"No have header info: Authorization");
|
||||
}
|
||||
|
||||
String[] components = authorization.split("\\s");
|
||||
|
||||
if (components.length != 2) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"Malformat [Authorization] content");
|
||||
}
|
||||
|
||||
if (!StringUtils.equalsIgnoreCase(components[0], "Bearer")) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"[Bearer] is needed");
|
||||
}
|
||||
|
||||
return components[1].trim();
|
||||
}
|
||||
}
|
||||
+205
@@ -0,0 +1,205 @@
|
||||
package com.eactive.eai.adapter.http.dynamic.filter.custom;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.oauth2.common.OAuth2AccessToken;
|
||||
import org.springframework.security.oauth2.provider.OAuth2Authentication;
|
||||
import org.springframework.security.oauth2.provider.token.TokenStore;
|
||||
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||
import com.eactive.eai.authserver.service.OAuth2Manager;
|
||||
import com.eactive.eai.authserver.util.BeanUtils;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.inbound.action.ActionFactory;
|
||||
import com.eactive.eai.inbound.action.RequestAction;
|
||||
import com.eactive.eai.inbound.processor.Processor;
|
||||
import com.eactive.eai.message.StandardMessageUtil;
|
||||
|
||||
public class SnapSimpleOauth2Filter implements HttpAdapterFilter {
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
private static final String SERVICE_CODE_UNKNOWN = "00";
|
||||
|
||||
private TokenStore tokenStore;
|
||||
|
||||
public SnapSimpleOauth2Filter() {
|
||||
super();
|
||||
tokenStore = BeanUtils.getBean("tokenStore", TokenStore.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
try {
|
||||
String apiId = assignApiId(adptGrpName, adptName, message, prop, request);
|
||||
if (StringUtils.isBlank(apiId)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"Can not find apiId(apiCode) info");
|
||||
}
|
||||
|
||||
String tokenStr = extractToken(request);
|
||||
|
||||
OAuth2AccessToken token = tokenStore.readAccessToken(tokenStr);
|
||||
if (token == null) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "03"),
|
||||
"Token Not Found (B2B)");
|
||||
}
|
||||
|
||||
if (token.isExpired()) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "01"),
|
||||
"Invalid Token - expired (B2B)");
|
||||
}
|
||||
|
||||
OAuth2Authentication authentication = tokenStore.readAuthentication(token);
|
||||
if (!authentication.isAuthenticated()) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "01"),
|
||||
"Invalid Token (B2B)");
|
||||
}
|
||||
|
||||
// check scope
|
||||
OAuth2Manager manager = OAuth2Manager.getInstance();
|
||||
HashSet<String> scopeSet = manager.getApiScopeMap().get(apiId);
|
||||
if (!verifyScope(scopeSet, authentication)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "01"),
|
||||
String.format("Insufficient [Scope](Allowed Scope=%s)", scopeSet.toString()));
|
||||
}
|
||||
|
||||
// header 값으로 전송된 clientId와 토큰 소유 clientId check
|
||||
if (!verifyClientId(prop, authentication)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"client_id not matched(header/token)");
|
||||
}
|
||||
} catch (JwtAuthException e) {
|
||||
logger.debug(e.getMessage());
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "01"),
|
||||
"Invalid Token (B2B)");
|
||||
}
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
private boolean verifyScope(HashSet<String> scopeSet, OAuth2Authentication auth) {
|
||||
if (scopeSet == null || scopeSet.isEmpty()) {
|
||||
return true; // If no scope is specified in the api, all are allowed
|
||||
}
|
||||
|
||||
Set<String> scopesInToken = auth.getOAuth2Request().getScope();
|
||||
|
||||
if (scopesInToken == null || scopesInToken.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (String scope : scopesInToken) {
|
||||
if (scopeSet.contains(scope)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean verifyClientId(Properties prop, Authentication authentication) {
|
||||
try {
|
||||
// 이전 filter에서 셋팅한 clientId 확보
|
||||
String headerClientId = prop.getProperty(HttpAdapterServiceSupport.PROPERTIES_NAME_CLIENT_ID);
|
||||
String tokenClientId = ((OAuth2Authentication) authentication).getOAuth2Request().getClientId();
|
||||
|
||||
// 이전 filter에서 셋팅한 값이 없다면 token 정보에서 확보
|
||||
if (StringUtils.isBlank(headerClientId)) {
|
||||
if (StringUtils.isNotBlank(tokenClientId)) {
|
||||
prop.put(HttpAdapterServiceSupport.PROPERTIES_NAME_CLIENT_ID, tokenClientId);
|
||||
}
|
||||
} else { // header로 전달된 clientId가 있을때만 비교
|
||||
if (!headerClientId.equals(tokenClientId)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private String assignApiId(String adptGrpName, String adptName, Object message, Properties prop,
|
||||
HttpServletRequest request) {
|
||||
String apiId = null;
|
||||
try {
|
||||
String actionName = prop.getProperty(Processor.REQUEST_ACTION);
|
||||
RequestAction action = ActionFactory.createAction(actionName);
|
||||
action.setAdapterInfo(adptGrpName, adptName, prop);
|
||||
String[] keys = action.perform(message);
|
||||
apiId = keys[0];
|
||||
|
||||
// PathVariable 지원 추가
|
||||
apiId = StandardMessageUtil.getMatchedKey(apiId, actionName);
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
}
|
||||
|
||||
// // header 에서 확보
|
||||
// String apiId = request.getHeader(HEADER_NAME_API_CODE);
|
||||
// if (StringUtils.isBlank(apiId)) {
|
||||
// // url에서 확보
|
||||
// // /ONLWeb/api/v1/public/getUserInfo.svc/
|
||||
// apiId = request.getRequestURI();
|
||||
// // /ONLWeb/api/v1/public/getUserInfo.svc
|
||||
// apiId = StringUtils.removeEnd(apiId, "/");
|
||||
// // getUserInfo.svc
|
||||
// apiId = StringUtils.substringAfterLast(apiId, "/");
|
||||
// }
|
||||
|
||||
return apiId;
|
||||
}
|
||||
|
||||
public static String extractToken(HttpServletRequest request) throws JwtAuthException {
|
||||
String authorization = request.getHeader("Authorization");
|
||||
if (StringUtils.isBlank(authorization)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"No have header info: Authorization");
|
||||
}
|
||||
|
||||
String[] components = authorization.split("\\s");
|
||||
|
||||
if (components.length != 2) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"Malformat [Authorization] content");
|
||||
}
|
||||
|
||||
if (!StringUtils.equalsIgnoreCase(components[0], "Bearer")) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"[Bearer] is needed");
|
||||
}
|
||||
|
||||
return components[1].trim();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
return resultMessage;
|
||||
}
|
||||
}
|
||||
+92
-65
@@ -1,5 +1,27 @@
|
||||
package com.eactive.eai.adapter.http.dynamic.impl;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLDecoder;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletInputStream;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.time.StopWatch;
|
||||
import org.apache.mina.common.ByteBuffer;
|
||||
import org.json.simple.JSONArray;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.JSONValue;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterGroupVO;
|
||||
import com.eactive.eai.adapter.AdapterManager;
|
||||
import com.eactive.eai.adapter.AdapterPropManager;
|
||||
@@ -8,8 +30,8 @@ import com.eactive.eai.adapter.Keys;
|
||||
import com.eactive.eai.adapter.http.HttpMemoryLogger;
|
||||
import com.eactive.eai.adapter.http.HttpStatusException;
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
|
||||
import com.eactive.eai.adapter.http.dynamic.UnkownMessageLogUtils;
|
||||
import com.eactive.eai.common.TransactionContextKeys;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.util.CommonLib;
|
||||
@@ -19,27 +41,6 @@ import com.eactive.eai.common.util.MessageUtil;
|
||||
import com.eactive.eai.env.ElinkConfig;
|
||||
import com.eactive.eai.inbound.processor.Processor;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.time.StopWatch;
|
||||
import org.apache.mina.common.ByteBuffer;
|
||||
import org.json.simple.JSONArray;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.JSONValue;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletInputStream;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.net.URLDecoder;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.TreeMap;
|
||||
|
||||
public class HttpAdapterServiceStandard extends HttpAdapterServiceSupport
|
||||
{
|
||||
public static final String PROPERTIES_NAME_HTTP_REQUEST_METHOD = "httpRequestMethod";
|
||||
@@ -63,7 +64,8 @@ public class HttpAdapterServiceStandard extends HttpAdapterServiceSupport
|
||||
|
||||
AdapterGroupVO adapterGroupVo = null;
|
||||
Properties prop = null;
|
||||
|
||||
byte[] requestBytes = null;
|
||||
String encode = "MS949";
|
||||
try {
|
||||
AdapterManager adapterManager = AdapterManager.getInstance();
|
||||
AdapterVO adptVO = adapterManager.getAdapterVO(adptGrpName,adptName);
|
||||
@@ -75,9 +77,9 @@ public class HttpAdapterServiceStandard extends HttpAdapterServiceSupport
|
||||
}
|
||||
|
||||
Properties httpProp = manager.getProperties(adptVO.getPropGroupName());
|
||||
encode = StringUtils.defaultIfBlank(adapterManager.getAdapterGroupVO(adptGrpName).getMessageEncode(), "MS949");
|
||||
String responseType = httpProp.getProperty(RESPONSE_TYPE,"SYNC");
|
||||
String urlDecodeYn = httpProp.getProperty(URL_DECODE_YN,"N");
|
||||
String encode = StringUtils.defaultIfBlank(adapterManager.getAdapterGroupVO(adptGrpName).getMessageEncode(), "MS949");
|
||||
String messageType = adapterManager.getAdapterGroupVO(adptGrpName).getMessageType();
|
||||
String requestBodyYn = httpProp.getProperty(REQUEST_BODY_YN,"N");
|
||||
String parameterName = httpProp.getProperty(PARAMETER_NAME,PARAMETER_MESSAGE);
|
||||
@@ -104,7 +106,6 @@ public class HttpAdapterServiceStandard extends HttpAdapterServiceSupport
|
||||
|
||||
logger.info("시작 >> encode = [" + encode + "]");
|
||||
|
||||
byte[] requestBytes = null;
|
||||
|
||||
if ("Y".equals(requestBodyYn)){
|
||||
ServletInputStream sis = request.getInputStream();
|
||||
@@ -188,19 +189,19 @@ public class HttpAdapterServiceStandard extends HttpAdapterServiceSupport
|
||||
prop.put(PROPERTIES_NAME_HTTP_REQUEST_METHOD, request.getMethod());
|
||||
prop.put(ALLOW_IP, httpProp.getProperty(ALLOW_IP, ""));
|
||||
|
||||
String body = new String ( requestBytes,encode);
|
||||
|
||||
try {
|
||||
Object root = JSONValue.parse(body);
|
||||
if( root instanceof JSONArray ) {
|
||||
JSONObject wrappedObject = new JSONObject();
|
||||
wrappedObject.put("DJB_ROOTLESS_ARRAY", root);
|
||||
requestBytes = wrappedObject.toJSONString().getBytes(encode);
|
||||
}
|
||||
|
||||
}catch (Exception e) {
|
||||
// ignore json이 아니기에 해줄것이 없음.
|
||||
}
|
||||
// String body = new String ( requestBytes,encode);
|
||||
//
|
||||
// try {
|
||||
// Object root = JSONValue.parse(body);
|
||||
// if( root instanceof JSONArray ) {
|
||||
// JSONObject wrappedObject = new JSONObject();
|
||||
// wrappedObject.put("DJB_ROOTLESS_ARRAY", root);
|
||||
// requestBytes = wrappedObject.toJSONString().getBytes(encode);
|
||||
// }
|
||||
//
|
||||
// }catch (Exception e) {
|
||||
// // ignore json이 아니기에 해줄것이 없음.
|
||||
// }
|
||||
|
||||
// 로컬 서비스 호출
|
||||
Object result = null;
|
||||
@@ -212,6 +213,7 @@ public class HttpAdapterServiceStandard extends HttpAdapterServiceSupport
|
||||
|
||||
stopWatch.stop();
|
||||
|
||||
byte[] responseBytes = null;
|
||||
String responseData = "";
|
||||
if (RESPONSE_TYPE_ASYNC.equals(responseType)){
|
||||
if (stopWatch.getTime() > slowTranTime){
|
||||
@@ -222,17 +224,22 @@ public class HttpAdapterServiceStandard extends HttpAdapterServiceSupport
|
||||
|
||||
if ( result == null) {
|
||||
responseData = ElinkConfig.getAsyncDummyDataForAdapterGroup(adptGrpName);
|
||||
responseBytes = responseData.getBytes();
|
||||
} else if (result instanceof byte[]) {
|
||||
responseData = new String((byte[]) result, encode);
|
||||
responseBytes = (byte[]) result;
|
||||
} else if (result instanceof String) {
|
||||
responseData = (String) result;
|
||||
if ( StringUtils.isBlank( responseData ) ) {
|
||||
responseBytes = ((String)result).getBytes();
|
||||
if ( StringUtils.isBlank((String)result ) ) {
|
||||
responseData = ElinkConfig.getAsyncDummyDataForAdapterGroup(adptGrpName, adptName);
|
||||
responseBytes = responseData.getBytes();
|
||||
}
|
||||
}
|
||||
|
||||
response.setCharacterEncoding(encode);
|
||||
response.getWriter().print(responseData);
|
||||
// response.getWriter().print(responseData);
|
||||
response.getOutputStream().write(responseBytes);
|
||||
|
||||
if (traceLevel >= 3){
|
||||
HttpMemoryLogger.txlog(adptGrpName+adptName, "SEND "+"["+responseData+"]"+
|
||||
((responseData == null)?"":CommonLib.getDumpMessage(responseData))
|
||||
@@ -240,45 +247,58 @@ public class HttpAdapterServiceStandard extends HttpAdapterServiceSupport
|
||||
}
|
||||
} else {
|
||||
if(requestBytes != null) {
|
||||
if (result instanceof byte[]) {
|
||||
if ( result == null) {
|
||||
responseData = ElinkConfig.getAsyncDummyDataForAdapterGroup(adptGrpName);
|
||||
responseBytes = responseData.getBytes();
|
||||
} else if (result instanceof byte[]) {
|
||||
responseData = new String((byte[]) result, encode);
|
||||
responseBytes = (byte[]) result;
|
||||
} else if (result instanceof String) {
|
||||
responseData = (String) result;
|
||||
responseBytes = ((String)result).getBytes(encode);
|
||||
if ( StringUtils.isBlank((String)result ) ) {
|
||||
responseData = ElinkConfig.getAsyncDummyDataForAdapterGroup(adptGrpName, adptName);
|
||||
responseBytes = responseData.getBytes(encode);
|
||||
}
|
||||
}
|
||||
|
||||
logger.info("종료 >> encode = [" + encode + "]");
|
||||
|
||||
if (addData.length() > 0){
|
||||
responseData = addData + responseData;
|
||||
responseBytes = responseData.getBytes();
|
||||
}
|
||||
|
||||
try {
|
||||
Object root = JSONValue.parse(responseData);
|
||||
if( root instanceof JSONObject ) {
|
||||
JSONObject wrappedObject = (JSONObject) root;
|
||||
responseData = wrappedObject.get("DJB_ROOTLESS_ARRAY").toString();
|
||||
}
|
||||
|
||||
}catch (Exception e) {
|
||||
// ignore json이 아니기에 해줄것이 없음.
|
||||
}
|
||||
// try {
|
||||
// Object root = JSONValue.parse(responseData);
|
||||
// if( root instanceof JSONObject ) {
|
||||
// JSONObject wrappedObject = (JSONObject) root;
|
||||
// responseData = wrappedObject.get("DJB_ROOTLESS_ARRAY").toString();
|
||||
// }
|
||||
//
|
||||
// }catch (Exception e) {
|
||||
// // ignore json이 아니기에 해줄것이 없음.
|
||||
// }
|
||||
|
||||
// 300응답에서 받은 Header정보 사용하기 위해 읽어옴.
|
||||
Map<String, Object> responsePropertyMap = (Map<String, Object>) prop.get(OUTBOUND_PROPERTY_MAP);
|
||||
if(responsePropertyMap != null){
|
||||
Properties responseHeaders = (Properties)responsePropertyMap.get(OUTBOUND_RESPONSE_HEADERS);
|
||||
Map<String, String> responseHeaderMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
|
||||
// Properties 내용을 모두 복사
|
||||
for (String name : responseHeaders.stringPropertyNames()) {
|
||||
responseHeaderMap.put(name, responseHeaders.getProperty(name));
|
||||
}
|
||||
String contentTytpe = responseHeaderMap.get("Content-Type");
|
||||
response.setContentType(contentTytpe); // 300응답에서 받은 Content-Type을 그대로 적용.
|
||||
}
|
||||
// Map<String, Object> responsePropertyMap = (Map<String, Object>) prop.get(OUTBOUND_PROPERTY_MAP);
|
||||
// if(responsePropertyMap != null){
|
||||
// Properties responseHeaders = (Properties)responsePropertyMap.get(OUTBOUND_RESPONSE_HEADERS);
|
||||
// Map<String, String> responseHeaderMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
|
||||
// // Properties 내용을 모두 복사
|
||||
// for (String name : responseHeaders.stringPropertyNames()) {
|
||||
// responseHeaderMap.put(name, responseHeaders.getProperty(name));
|
||||
// }
|
||||
// String contentTytpe = responseHeaderMap.get("Content-Type");
|
||||
// response.setContentType(contentTytpe); // 300응답에서 받은 Content-Type을 그대로 적용.
|
||||
// }
|
||||
|
||||
// UI와 통신시(UTF-8) 변환오류로 ENCODE 제거
|
||||
response.setCharacterEncoding(encode);
|
||||
response.getWriter().print(responseData);
|
||||
// response.getWriter().print(responseData);
|
||||
String resContentType = request.getContentType();
|
||||
response.setContentType(resContentType);
|
||||
response.getOutputStream().write(responseBytes);
|
||||
|
||||
if (logger.isDebug()){
|
||||
logger.debug("HttpAdapter] SEND ("+adptGrpName+") = [" + responseData + "]");
|
||||
logger.debug("HttpAdapter] SEND ("+adptGrpName+") = " +
|
||||
@@ -316,6 +336,13 @@ public class HttpAdapterServiceStandard extends HttpAdapterServiceSupport
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
UnkownMessageLogUtils.logUnkownMessage(adptGrpName, adptName, requestBytes != null ? new String(requestBytes, encode) : null, prop, request, response,
|
||||
"RECEAIIRP202", e);
|
||||
} catch (UnsupportedEncodingException e1) {
|
||||
UnkownMessageLogUtils.logUnkownMessage(adptGrpName, adptName, requestBytes != null ? new String(requestBytes) : null, prop, request, response,
|
||||
"RECEAIIRP202", e);
|
||||
}
|
||||
if (traceLevel >= 3){
|
||||
HttpMemoryLogger.error(adptGrpName+adptName, e.toString(),e);
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@ public abstract class AbstractCryptoFilter {
|
||||
* fromPath의 Base64 값을 복호화하여 toPath에 반영. JSON 파싱 1회.
|
||||
* toPath = "/" → fromPath 필드를 제거하고 복호화된 JSON을 body에 병합.
|
||||
*/
|
||||
protected String decryptField(String body, String moduleName, Map<String, String> runtimeCtx,
|
||||
protected Object decryptField(String body, String moduleName, Map<String, String> runtimeCtx,
|
||||
byte[] aad, String fromPath, String toPath) throws Exception {
|
||||
JsonNode root = JsonPathUtil.toTree(body);
|
||||
String encBase64 = JsonPathUtil.getAt(root, fromPath);
|
||||
@@ -81,7 +81,7 @@ public abstract class AbstractCryptoFilter {
|
||||
return JsonPathUtil.mergeAtRoot(root, fromPath, plainText);
|
||||
}
|
||||
JsonPathUtil.setAt(root, toPath, plainText);
|
||||
return JsonPathUtil.fromTree(root);
|
||||
return root;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
@@ -99,7 +99,7 @@ public abstract class AbstractCryptoFilter {
|
||||
* fromPath 값을 암호화하여 toPath(Base64)에 반영. JSON 파싱 1회.
|
||||
* fromPath = "/" → body 전체를 암호화하여 toPath 필드명으로 래핑 (파싱 불필요).
|
||||
*/
|
||||
protected String encryptField(String body, String moduleName, Map<String, String> runtimeCtx,
|
||||
protected Object encryptField(String body, String moduleName, Map<String, String> runtimeCtx,
|
||||
byte[] aad, String fromPath, String toPath) throws Exception {
|
||||
if (PATH_ROOT.equals(fromPath)) {
|
||||
byte[] cipherBytes = CryptoModuleService.getInstance().encrypt(moduleName, runtimeCtx, aad,
|
||||
@@ -112,13 +112,13 @@ public abstract class AbstractCryptoFilter {
|
||||
String plainText = JsonPathUtil.getAt(root, fromPath);
|
||||
if (StringUtils.isBlank(plainText)) {
|
||||
logger.warn("CryptoFilter] 암호화 대상 필드 없음: path=" + fromPath);
|
||||
return body;
|
||||
return root;
|
||||
}
|
||||
byte[] cipherBytes = CryptoModuleService.getInstance().encrypt(moduleName, runtimeCtx, aad,
|
||||
plainText.getBytes(StandardCharsets.UTF_8));
|
||||
String encBase64 = Base64.getEncoder().encodeToString(cipherBytes);
|
||||
JsonPathUtil.setAt(root, toPath, encBase64);
|
||||
return JsonPathUtil.fromTree(root);
|
||||
return root;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
@@ -12,8 +12,8 @@ import com.eactive.eai.common.property.PropManager;
|
||||
import com.eactive.eai.common.server.Keys;
|
||||
import com.eactive.eai.common.util.ApplicationContextProvider;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.ext.djb.DamoManager;
|
||||
import com.eactive.ext.kjb.safedb.KjbSafedbWrapper;
|
||||
import com.eactive.ext.kjb.safedb.Utils;
|
||||
|
||||
@Component
|
||||
public class EncryptionManager implements Lifecycle {
|
||||
@@ -161,6 +161,10 @@ public class EncryptionManager implements Lifecycle {
|
||||
public String decryptDBData(String dbData) {
|
||||
if (StringUtils.isNotEmpty(dbData)) {
|
||||
if (this.isEncrypted(dbData)) {
|
||||
if ("DAMO".equals(dbEncryptSolutionName)) {
|
||||
com.eactive.ext.djb.DamoManager damoManager = new com.eactive.ext.djb.DamoManager();
|
||||
return damoManager.decrypt(dbData);
|
||||
} else if ("SAFEDB".equals(dbEncryptSolutionName)) {
|
||||
KjbSafedbWrapper safeDBWrapper = KjbSafedbWrapper.getInstance();
|
||||
try {
|
||||
dbData = safeDBWrapper.decryptNotRnno(dbData);
|
||||
@@ -170,6 +174,7 @@ public class EncryptionManager implements Lifecycle {
|
||||
logger.warn("DB 복호화 실패: 복호화하지 않고 원본 반환. dbData={} (Length : {})", logData, dbData.length());
|
||||
return dbData;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
logger.debug("DB 복호화 경고: Base64 형식이 아님. 복호화하지 않고 원본 반환. dbData={}", dbData);
|
||||
}
|
||||
@@ -197,7 +202,7 @@ public class EncryptionManager implements Lifecycle {
|
||||
data = data.trim();
|
||||
|
||||
// Base64 형식 체크
|
||||
if (!Utils.isBase64(data)) {
|
||||
if (!isBase64(data)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -208,4 +213,13 @@ public class EncryptionManager implements Lifecycle {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean isBase64(String str) {
|
||||
if (str == null || str.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
String base64Pattern = "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$";
|
||||
return str.matches(base64Pattern);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -327,7 +327,7 @@ public class AccessTokenManagerByDB implements Lifecycle {
|
||||
logger.warn("No valid adapter configuration found for adapter group: {}", adapterGroupName);
|
||||
}
|
||||
|
||||
}catch (Exception e) {
|
||||
} catch (Exception e) {
|
||||
logger.error("Task execution failed for adapter group: {}", adapterGroupName, e);
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import javax.annotation.PostConstruct;
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -44,9 +45,26 @@ public class HsmCryptoService implements PropertyChangeListener {
|
||||
private static final String PROP_GROUP = "HSM";
|
||||
private static final String PROP_CACHE_RELOAD_YN = "CACHE_RELOAD_YN";
|
||||
|
||||
private static final String PROP_CACHE_TTL_SEC = "CACHE_TTL_SEC";
|
||||
private static long CACHE_TTL_MS = 10 * 60 * 1000; // 10분, 필요시 PropManager로 외부화
|
||||
|
||||
private static class CachedKey<T> {
|
||||
final T key;
|
||||
final long cachedAt;
|
||||
|
||||
CachedKey(T key) {
|
||||
this.key = key;
|
||||
this.cachedAt = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
boolean isExpired() {
|
||||
return System.currentTimeMillis() - cachedAt > CACHE_TTL_MS;
|
||||
}
|
||||
}
|
||||
|
||||
// HSM 통신 최소화: 최초 1회 조회 후 JVM 메모리에 캐싱
|
||||
private final ConcurrentHashMap<String, SecretKey> secretKeyCache = new ConcurrentHashMap<String, SecretKey>();
|
||||
private final ConcurrentHashMap<String, PublicKey> publicKeyCache = new ConcurrentHashMap<String, PublicKey>();
|
||||
private final ConcurrentHashMap<String, CachedKey<SecretKey>> secretKeyCache = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, CachedKey<PublicKey>> publicKeyCache = new ConcurrentHashMap<>();
|
||||
|
||||
@Autowired
|
||||
private PropManager propManager;
|
||||
@@ -70,6 +88,9 @@ public class HsmCryptoService implements PropertyChangeListener {
|
||||
if ("Y".equalsIgnoreCase(reloadYn)) {
|
||||
clearKeyCache();
|
||||
}
|
||||
|
||||
String propCacheTtlSec = propManager.getProperty(PROP_GROUP, PROP_CACHE_TTL_SEC, "600");
|
||||
CACHE_TTL_MS = (Integer.parseInt(propCacheTtlSec.trim())) * 1000; // 10분, 필요시 PropManager로 외부화
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
@@ -78,56 +99,99 @@ public class HsmCryptoService implements PropertyChangeListener {
|
||||
|
||||
/**
|
||||
* HSM KeyStore 에서 공개키를 반환합니다. 최초 1회만 HSM 통신하고 이후 캐시를 반환합니다.
|
||||
* HSM 장애 시 만료된 캐시가 있으면 그것을 반환하여 서비스 연속성을 유지합니다.
|
||||
*/
|
||||
public PublicKey getPublicKey(String keyAlias) throws HsmException {
|
||||
checkReady();
|
||||
PublicKey cached = publicKeyCache.get(keyAlias);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
// 1. 유효한 캐시 즉시 반환 (HSM 상태 무관)
|
||||
CachedKey<PublicKey> cached = publicKeyCache.get(keyAlias);
|
||||
if (cached != null && !cached.isExpired()) {
|
||||
return cached.key;
|
||||
}
|
||||
|
||||
// 2. 캐시 미스 또는 만료 → HSM 갱신 시도
|
||||
if (HsmManager.getInstance().isReady()) {
|
||||
try {
|
||||
Certificate cert = HsmManager.getInstance().getKeyStore().getCertificate(keyAlias);
|
||||
if (cert == null) {
|
||||
throw new HsmException("인증서를 찾을 수 없습니다. alias=" + keyAlias);
|
||||
}
|
||||
PublicKey key = cert.getPublicKey();
|
||||
publicKeyCache.put(keyAlias, key);
|
||||
publicKeyCache.put(keyAlias, new CachedKey<>(key));
|
||||
logger.warn("HsmCryptoService] 공개키 캐시 등록: alias=" + keyAlias);
|
||||
return key;
|
||||
} catch (HsmException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new HsmException("공개키 조회 실패: " + e.getMessage(), e);
|
||||
logger.warn("HsmCryptoService] 공개키 HSM 조회 실패: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// 3. HSM 조회 불가 → 만료 캐시 fallback
|
||||
if (cached != null) {
|
||||
logger.warn("HsmCryptoService] HSM 장애, 만료 공개키 캐시 fallback: alias=" + keyAlias);
|
||||
return cached.key;
|
||||
}
|
||||
|
||||
throw new HsmException("공개키 조회 불가: HSM 장애이며 캐시도 없습니다. alias=" + keyAlias);
|
||||
}
|
||||
|
||||
/**
|
||||
* HSM KeyStore 에서 AES 대칭키를 반환합니다. 최초 1회만 HSM 통신하고 이후 캐시를 반환합니다.
|
||||
* HSM 키 생성 시 CKA_EXTRACTABLE=true (ctkmu -x 플래그) 로 생성된 키만 반환됩니다.
|
||||
*
|
||||
* [캐싱 전략]
|
||||
* HSM 에서 가져온 P11SecretKey(PKCS11 핸들 래퍼)를 그대로 캐싱하면, HSM Provider 가
|
||||
* 재초기화될 때 세션 무효화로 인해 캐시된 키를 사용한 Cipher 연산이 실패한다.
|
||||
* 따라서 getEncoded() 로 키 바이트를 추출하여 SecretKeySpec(JVM 메모리 키) 으로 변환 후
|
||||
* 캐싱한다. encryptAes/decryptAes 는 이미 JVM 소프트웨어 Cipher 를 사용하므로,
|
||||
* HSM Provider 상태와 완전히 독립적으로 동작한다.
|
||||
*
|
||||
* HSM 장애 시 만료된 캐시가 있으면 그것을 반환하여 서비스 연속성을 유지합니다.
|
||||
*/
|
||||
public SecretKey getSecretKey(String keyAlias) throws HsmException {
|
||||
checkReady();
|
||||
SecretKey cached = secretKeyCache.get(keyAlias);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
// 1. 유효한 캐시 즉시 반환 (HSM 상태 무관)
|
||||
CachedKey<SecretKey> cached = secretKeyCache.get(keyAlias);
|
||||
if (cached != null && !cached.isExpired()) {
|
||||
return cached.key;
|
||||
}
|
||||
|
||||
// 2. 캐시 미스 또는 만료 → HSM 갱신 시도
|
||||
if (HsmManager.getInstance().isReady()) {
|
||||
try {
|
||||
KeyStore keyStore = HsmManager.getInstance().getKeyStore();
|
||||
java.security.Key key = keyStore.getKey(keyAlias, null);
|
||||
if (!(key instanceof SecretKey)) {
|
||||
throw new HsmException("AES 키를 찾을 수 없습니다 (CKA_EXTRACTABLE=true 확인 필요). alias=" + keyAlias);
|
||||
if (key == null) {
|
||||
throw new HsmException("키를 찾을 수 없습니다. alias=" + keyAlias);
|
||||
}
|
||||
SecretKey secretKey = (SecretKey) key;
|
||||
secretKeyCache.put(keyAlias, secretKey);
|
||||
logger.warn("HsmCryptoService] 대칭키 캐시 등록: alias=" + keyAlias);
|
||||
|
||||
// P11SecretKey → SecretKeySpec 변환: HSM Provider 의존성 제거
|
||||
// getEncoded() 가 null 이면 non-extractable 키이므로 원본 유지
|
||||
byte[] keyBytes = secretKey.getEncoded();
|
||||
if (keyBytes != null) {
|
||||
secretKey = new SecretKeySpec(keyBytes, secretKey.getAlgorithm());
|
||||
}
|
||||
|
||||
secretKeyCache.put(keyAlias, new CachedKey<>(secretKey));
|
||||
logger.warn("HsmCryptoService] 대칭키 캐시 등록(갱신): alias=" + keyAlias);
|
||||
return secretKey;
|
||||
|
||||
} catch (HsmException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new HsmException("AES 키 조회 실패: " + e.getMessage(), e);
|
||||
logger.warn("HsmCryptoService] 대칭키 HSM 조회 실패: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// 3. HSM 조회 불가 → 만료 캐시 fallback
|
||||
if (cached != null) {
|
||||
logger.warn("HsmCryptoService] HSM 장애, 만료 대칭키 캐시 fallback: alias=" + keyAlias);
|
||||
return cached.key;
|
||||
}
|
||||
|
||||
throw new HsmException("키 조회 불가: HSM 장애이며 캐시도 없습니다. alias=" + keyAlias);
|
||||
}
|
||||
|
||||
/** 캐시를 비웁니다. HSM 키 교체 후 재로드가 필요할 때 호출합니다. */
|
||||
public void clearKeyCache() {
|
||||
secretKeyCache.clear();
|
||||
@@ -254,13 +318,4 @@ public class HsmCryptoService implements PropertyChangeListener {
|
||||
return decryptAes(secretKey, iv, ciphertext, null);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Private helpers
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
private void checkReady() throws HsmException {
|
||||
if (!HsmManager.getInstance().isReady()) {
|
||||
throw new HsmException("HsmManager 가 초기화되지 않았습니다.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,12 +5,23 @@ import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.lang.reflect.Method;
|
||||
import java.nio.file.Files;
|
||||
import java.security.AuthProvider;
|
||||
import java.security.KeyStore;
|
||||
import java.security.KeyStoreException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.Provider;
|
||||
import java.security.Security;
|
||||
import java.security.UnrecoverableKeyException;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.eactive.eai.agent.encryption.EncryptionManager;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.lifecycle.Lifecycle;
|
||||
import com.eactive.eai.common.lifecycle.LifecycleException;
|
||||
@@ -35,6 +46,18 @@ import com.eactive.eai.common.util.Logger;
|
||||
* name = SoftHSM
|
||||
* library = C:/SoftHSM2/lib/softhsm2-x64.dll
|
||||
* slotListIndex = 0
|
||||
*
|
||||
* ---------------------------------------------------------------------
|
||||
* [세션 누적 방지 / 회로차단 로직 추가]
|
||||
* 기존 구현은 재로드마다 KeyStore.getInstance(...).load(null, pin) 을 새로
|
||||
* 호출하여 PKCS11 세션(C_OpenSession)이 계속 누적되고, 결국 HSM 파티션의
|
||||
* 최대 세션 수를 초과하면서 reload 가 영구적으로 실패하는 문제가 있었다.
|
||||
* 이를 방지하기 위해:
|
||||
* 1) 정상 상황에서는 "기존 keyStore 인스턴스"에 다시 load() 하여 세션 재사용
|
||||
* 2) 실제 키 조회(probe)로 세션이 살아있는지 검증
|
||||
* 3) 연속 실패가 임계치를 넘으면 Provider 자체를 logout 후 완전히 재생성
|
||||
* 4) 재생성마저 실패하면 마지막으로 성공한 keyStore 를 유지 (서비스 연속성 우선)
|
||||
* ---------------------------------------------------------------------
|
||||
*/
|
||||
@Component
|
||||
public class HsmManager implements Lifecycle {
|
||||
@@ -44,13 +67,21 @@ public class HsmManager implements Lifecycle {
|
||||
private static final String GROUP_NAME = "HSM";
|
||||
private static final String PROP_CONFIG = "PKCS11_CONFIG";
|
||||
private static final String PROP_PIN = "PIN";
|
||||
private static final String PROP_RELOAD_INTERVAL_MINUTES = "RELOAD_INTERVAL_MINUTES";
|
||||
|
||||
private Provider pkcs11Provider;
|
||||
private KeyStore keyStore;
|
||||
private volatile KeyStore keyStore;
|
||||
private boolean started;
|
||||
|
||||
private final LifecycleSupport lifecycle = new LifecycleSupport(this);
|
||||
|
||||
private volatile char[] pin;
|
||||
|
||||
// 재로드 주기 (분 단위). 필요시 PropManager로 외부화 가능.
|
||||
private static long RELOAD_INTERVAL_MINUTES = 1;
|
||||
private ScheduledExecutorService scheduler;
|
||||
private ScheduledFuture<?> reloadFuture;
|
||||
|
||||
private HsmManager() {
|
||||
}
|
||||
|
||||
@@ -67,6 +98,7 @@ public class HsmManager implements Lifecycle {
|
||||
|
||||
try {
|
||||
init();
|
||||
startReloadScheduler();
|
||||
} catch (Exception e) {
|
||||
throw new LifecycleException(ExceptionUtil.getErrorCode(e, "RECEAIHSM002"));
|
||||
}
|
||||
@@ -76,8 +108,13 @@ public class HsmManager implements Lifecycle {
|
||||
}
|
||||
|
||||
private void init() throws Exception {
|
||||
String configContent = PropManager.getInstance().getProperty(GROUP_NAME, PROP_CONFIG);
|
||||
String pin = PropManager.getInstance().getProperty(GROUP_NAME, PROP_PIN);
|
||||
|
||||
String reloadIntervalStr = PropManager.getInstance().getProperty(GROUP_NAME, PROP_RELOAD_INTERVAL_MINUTES, "10");
|
||||
RELOAD_INTERVAL_MINUTES = Long.parseLong(reloadIntervalStr);
|
||||
EncryptionManager encManager = EncryptionManager.getInstance();
|
||||
|
||||
String configContent = encManager.decryptDBData(PropManager.getInstance().getProperty(GROUP_NAME, PROP_CONFIG));
|
||||
String pinStr = encManager.decryptDBData(PropManager.getInstance().getProperty(GROUP_NAME, PROP_PIN));
|
||||
|
||||
if (configContent == null || configContent.trim().isEmpty()) {
|
||||
logger.warn("HsmManager] PKCS11_CONFIG 가 설정되지 않았습니다. HSM 초기화를 건너뜁니다.");
|
||||
@@ -94,20 +131,144 @@ public class HsmManager implements Lifecycle {
|
||||
Security.addProvider(pkcs11Provider);
|
||||
|
||||
keyStore = KeyStore.getInstance("PKCS11", pkcs11Provider);
|
||||
char[] pinChars = (pin != null) ? pin.toCharArray() : null;
|
||||
keyStore.load(null, pinChars);
|
||||
this.pin = (pinStr != null) ? pinStr.toCharArray() : null;
|
||||
keyStore.load(null, pin);
|
||||
|
||||
logger.warn("HsmManager] 초기화 완료. Provider=" + pkcs11Provider.getName());
|
||||
|
||||
logKeyStore(this.keyStore);
|
||||
}
|
||||
|
||||
private void logKeyStore(KeyStore keyStore) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
|
||||
java.util.Enumeration<String> aliases = keyStore.aliases();
|
||||
StringBuilder aliasList = new StringBuilder();
|
||||
while (aliases.hasMoreElements()) {
|
||||
if (aliasList.length() > 0) aliasList.append(", ");
|
||||
aliasList.append(aliases.nextElement());
|
||||
|
||||
String alias = aliases.nextElement();
|
||||
aliasList.append(alias);
|
||||
|
||||
java.security.Key key = keyStore.getKey(alias, null);
|
||||
if (key instanceof SecretKey) {
|
||||
SecretKey secretKey = (SecretKey) key;
|
||||
if (secretKey.getEncoded() == null) {
|
||||
logger.warn("HsmManager] HSM - secretKey null {} : [{}]", alias, secretKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
logger.warn("HsmManager] HSM 키 목록: [" + aliasList + "]");
|
||||
}
|
||||
|
||||
/**
|
||||
* 별도 스레드에서 주기적으로 KeyStore 를 다시 로드하여
|
||||
* HSM 에 새로 생성/추가된 키를 인식하도록 한다.
|
||||
*/
|
||||
private void startReloadScheduler() {
|
||||
scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
|
||||
Thread t = new Thread(r, "hsm-keystore-reloader");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
|
||||
reloadFuture = scheduler.scheduleWithFixedDelay(
|
||||
this::reloadKeyStoreSafely,
|
||||
RELOAD_INTERVAL_MINUTES,
|
||||
RELOAD_INTERVAL_MINUTES,
|
||||
TimeUnit.MINUTES
|
||||
);
|
||||
|
||||
logger.warn("HsmManager] KeyStore 주기적 재로드 스케줄러 시작. interval=" + RELOAD_INTERVAL_MINUTES + "분");
|
||||
}
|
||||
|
||||
/**
|
||||
* 스케줄러에서 호출되는 래퍼. 예외가 스케줄러 스레드를 죽이지 않도록 반드시 catch 한다.
|
||||
* (ScheduledExecutorService 는 task 에서 예외가 던져지면 이후 스케줄을 자동으로 중단시킨다)
|
||||
*/
|
||||
private void reloadKeyStoreSafely() {
|
||||
try {
|
||||
reloadKeyStoreIfNeeded();
|
||||
} catch (Throwable t) {
|
||||
logger.warn("HsmManager] KeyStore 주기적 재로드 실패: " + t.getMessage(), t);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* KeyStore 를 다시 로드한다. 외부(getSecretKey 등)에서 키 미스 발생 시
|
||||
* 즉시 재시도용으로 직접 호출할 수도 있다.
|
||||
*
|
||||
* 세션 누적 방지를 위해 새 KeyStore 인스턴스를 만들지 않고,
|
||||
* 기존 keyStore 객체에 다시 load() 하여 기존 PKCS11 세션을 재사용한다.
|
||||
* 연속 실패가 임계치를 넘으면 Provider 자체를 재생성한다.
|
||||
*/
|
||||
public synchronized void reloadKeyStoreIfNeeded() throws Exception {
|
||||
if (pkcs11Provider == null) {
|
||||
return; // HSM 비활성화 상태
|
||||
}
|
||||
|
||||
try {
|
||||
if (keyStore != null) {
|
||||
keyStore.load(null, pin);
|
||||
logger.warn("HsmManager] KeyStore 재로드 완료 (기존 세션 재사용).");
|
||||
} else {
|
||||
KeyStore ks = KeyStore.getInstance("PKCS11", pkcs11Provider);
|
||||
ks.load(null, pin);
|
||||
this.keyStore = ks;
|
||||
logger.warn("HsmManager] KeyStore 신규 생성 완료.");
|
||||
}
|
||||
|
||||
logKeyStore(keyStore);
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.warn("HsmManager] KeyStore 재로드 실패:" + e.getMessage(), e);
|
||||
logger.warn("HsmManager] Provider 전체 재초기화를 시도합니다.");
|
||||
fullReinitialize();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 세션 누적, 네트워크 단절 등으로 일반 재로드가 더 이상 복구되지 않을 때
|
||||
* 기존 세션을 정리하고 Provider 를 완전히 새로 생성한다.
|
||||
*
|
||||
* 신규 Provider/KeyStore 준비가 완전히 성공한 후에만 기존 Provider 를 제거하고 교체한다.
|
||||
* 재초기화 중 예외가 발생하면 기존 Provider 와 keyStore 를 그대로 유지한다
|
||||
* (서비스 중단보다 마지막 정상 상태 보존을 우선).
|
||||
*/
|
||||
private void fullReinitialize() throws Exception {
|
||||
Provider oldProvider = this.pkcs11Provider;
|
||||
try {
|
||||
// 1. 신규 Provider 인스턴스 생성 (Security 미등록 상태)
|
||||
String configContent = EncryptionManager.getInstance()
|
||||
.decryptDBData(PropManager.getInstance().getProperty(GROUP_NAME, PROP_CONFIG));
|
||||
Provider newProvider = createProvider(configContent.trim().replace("\\n", "\n"));
|
||||
|
||||
// 2. 신규 Provider 로 KeyStore 로드 테스트
|
||||
// KeyStore.getInstance(type, providerInstance) 는 Security 등록 없이도 동작하므로
|
||||
// 여기서 실패해도 oldProvider/keyStore 는 변경되지 않은 상태를 유지함
|
||||
KeyStore ks = KeyStore.getInstance("PKCS11", newProvider);
|
||||
ks.load(null, pin);
|
||||
|
||||
// 3. 신규 연결 성공 → 기존 Provider 정리 후 교체
|
||||
if (oldProvider instanceof AuthProvider) {
|
||||
try {
|
||||
((AuthProvider) oldProvider).logout();
|
||||
} catch (Exception logoutEx) {
|
||||
logger.warn("HsmManager] 기존 세션 logout 실패(무시하고 진행): " + logoutEx.getMessage());
|
||||
}
|
||||
}
|
||||
Security.removeProvider(oldProvider.getName());
|
||||
Security.addProvider(newProvider);
|
||||
|
||||
this.pkcs11Provider = newProvider;
|
||||
this.keyStore = ks;
|
||||
|
||||
logger.warn("HsmManager] Provider 전체 재초기화 성공.");
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.warn("HsmManager] Provider 전체 재초기화 실패. 이전 keyStore 를 그대로 유지합니다: " + e.getMessage(), e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* JDK 버전에 따라 SunPKCS11 Provider 를 생성한다.
|
||||
*
|
||||
@@ -143,7 +304,21 @@ public class HsmManager implements Lifecycle {
|
||||
}
|
||||
lifecycle.fireLifecycleEvent(STOPING_EVENT, this);
|
||||
|
||||
if (reloadFuture != null) {
|
||||
reloadFuture.cancel(false);
|
||||
}
|
||||
if (scheduler != null) {
|
||||
scheduler.shutdown();
|
||||
}
|
||||
|
||||
if (pkcs11Provider != null) {
|
||||
if (pkcs11Provider instanceof AuthProvider) {
|
||||
try {
|
||||
((AuthProvider) pkcs11Provider).logout();
|
||||
} catch (Exception e) {
|
||||
logger.warn("HsmManager] 종료 시 logout 실패(무시): " + e.getMessage());
|
||||
}
|
||||
}
|
||||
Security.removeProvider(pkcs11Provider.getName());
|
||||
}
|
||||
pkcs11Provider = null;
|
||||
@@ -184,4 +359,20 @@ public class HsmManager implements Lifecycle {
|
||||
public boolean isReady() {
|
||||
return started && pkcs11Provider != null && keyStore != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* isReady() 와 달리 실제 HSM 호출로 세션 생존 여부까지 확인하는 헬스체크.
|
||||
* 모니터링/헬스체크 엔드포인트에서 사용을 권장한다.
|
||||
*/
|
||||
public boolean isHealthy() {
|
||||
if (!isReady()) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
logKeyStore(keyStore);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
package com.eactive.eai.common.message;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import com.eactive.eai.message.StandardMessage;
|
||||
import com.eactive.eai.message.manager.StandardMessageManager;
|
||||
@@ -110,6 +110,7 @@ public class EAIMessage implements EAIMessageKeys, Serializable, Comparable<EAIM
|
||||
|
||||
private String authCheckdYn;
|
||||
|
||||
private Properties callProp;
|
||||
|
||||
public EAIMessage() {
|
||||
this.svcMsgs = new ArrayList<>();
|
||||
@@ -665,6 +666,14 @@ public class EAIMessage implements EAIMessageKeys, Serializable, Comparable<EAIM
|
||||
return transactionContextTransfer;
|
||||
}
|
||||
|
||||
public Properties getCallProp() {
|
||||
return callProp;
|
||||
}
|
||||
|
||||
public void setCallProp(Properties callProp) {
|
||||
this.callProp = callProp;
|
||||
}
|
||||
|
||||
/**
|
||||
* [비동기 전달 전용] 컨텍스트 전달용 Map 설정
|
||||
* @see #transactionContextTransfer
|
||||
|
||||
@@ -177,7 +177,7 @@ public class CryptoModuleManager implements Lifecycle {
|
||||
private KeyDerivationStrategy resolveStrategy(String fqcn) {
|
||||
return strategyCache.computeIfAbsent(fqcn, key -> {
|
||||
try {
|
||||
Class<?> clazz = Class.forName(key);
|
||||
Class<?> clazz = Class.forName(key.trim());
|
||||
return (KeyDerivationStrategy) clazz.getDeclaredConstructor().newInstance();
|
||||
} catch (Exception e) {
|
||||
throw new IllegalArgumentException("전략 클래스 로드 실패: " + key, e);
|
||||
|
||||
-62
@@ -1,62 +0,0 @@
|
||||
package com.eactive.eai.common.security.keyderiv.strategy;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
|
||||
import com.eactive.eai.common.hsm.HsmCryptoService;
|
||||
import com.eactive.eai.common.security.keyderiv.DerivedKey;
|
||||
import com.eactive.eai.common.security.keyderiv.KeyDerivationStrategy;
|
||||
import com.eactive.eai.common.util.ApplicationContextProvider;
|
||||
|
||||
/**
|
||||
* HSM 마스터키 + 런타임 컨텍스트값을 연결(concatenate)한 뒤 SHA-256 해싱으로 키를 도출하는 전략.
|
||||
* SHA-256 출력은 항상 32바이트(AES-256)이므로 별도 keyLength 파라미터가 불필요하다.
|
||||
*
|
||||
* key_deriv_params (JSON) 예시:
|
||||
* {
|
||||
* "hsmKeyAlias" : "MASTER_KEY_AES",
|
||||
* "contextKey" : "X-Api-Group-Seq" -- runtimeContext에서 꺼낼 키 이름
|
||||
* }
|
||||
*/
|
||||
public class HsmContextSha256KeyDerivationStrategy implements KeyDerivationStrategy {
|
||||
|
||||
@Override
|
||||
public DerivedKey deriveKey(Map<String, String> params, Map<String, String> runtimeContext) throws Exception {
|
||||
String hsmKeyAlias = required(params, PARAM_HSM_KEY_ALIAS);
|
||||
String contextKey = required(params, PARAM_CONTEXT_KEY);
|
||||
|
||||
SecretKey masterKey = hsmCryptoService().getSecretKey(hsmKeyAlias);
|
||||
byte[] masterKeyBytes = masterKey.getEncoded();
|
||||
byte[] contextBytes = runtimeContext.getOrDefault(contextKey, "")
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
byte[] combined = new byte[masterKeyBytes.length + contextBytes.length];
|
||||
System.arraycopy(masterKeyBytes, 0, combined, 0, masterKeyBytes.length);
|
||||
System.arraycopy(contextBytes, 0, combined, masterKeyBytes.length, contextBytes.length);
|
||||
|
||||
byte[] derived = MessageDigest.getInstance("SHA-256").digest(combined);
|
||||
return new DerivedKey(derived, derived);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String buildCacheKey(String cryptoName, Map<String, String> params, Map<String, String> runtimeContext) {
|
||||
String contextKey = params.getOrDefault(PARAM_CONTEXT_KEY, "");
|
||||
String contextValue = runtimeContext.getOrDefault(contextKey, "");
|
||||
return cryptoName + ":" + contextValue;
|
||||
}
|
||||
|
||||
private String required(Map<String, String> params, String key) {
|
||||
String value = params.get(key);
|
||||
if (value == null || value.trim().isEmpty()) {
|
||||
throw new IllegalArgumentException("key_deriv_params 필수값 누락: " + key);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private HsmCryptoService hsmCryptoService() {
|
||||
return ApplicationContextProvider.getContext().getBean(HsmCryptoService.class);
|
||||
}
|
||||
}
|
||||
@@ -49,9 +49,10 @@ public class STDMessageDAO extends BaseDAO {
|
||||
for (StandardMessageInfo info : list) {
|
||||
vo = standardManager.getStandardMessage();
|
||||
vo.setServiceKey(info.getBzwksvckeyname());
|
||||
vo.setEaiSvcCd(info.getEaisvcname());
|
||||
// TODO
|
||||
// to be defined...
|
||||
mapper.setInterfaceId(vo, info.getEaitranname());
|
||||
// mapper.setInterfaceId(vo, info.getEaitranname());
|
||||
mapper.setSendRecvDivision(vo, info.getEaisendrecv()); // S | R
|
||||
mapper.setInExDivision(vo, info.getEaidirection()); // 1 | 2
|
||||
List<StandardMessageItem> items = info.getStandardMessageItems();
|
||||
|
||||
@@ -12,6 +12,7 @@ import org.apache.commons.lang3.math.NumberUtils;
|
||||
import org.json.simple.JSONArray;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.JSONValue;
|
||||
import org.json.simple.parser.JSONParser;
|
||||
import org.json.simple.parser.ParseException;
|
||||
|
||||
public class JSONUtils {
|
||||
@@ -20,6 +21,30 @@ public class JSONUtils {
|
||||
throw new IllegalStateException("Utility class");
|
||||
}
|
||||
|
||||
public static Object parseJsonGeneric(Object jsonData) {
|
||||
if (jsonData == null) {
|
||||
return new JSONObject();
|
||||
}
|
||||
if (jsonData instanceof JSONObject) {
|
||||
return (JSONObject) jsonData;
|
||||
} else if (jsonData instanceof String) {
|
||||
if (StringUtils.isBlank((String) jsonData)) {
|
||||
return new JSONObject();
|
||||
}
|
||||
try {
|
||||
JSONParser parser = new JSONParser();
|
||||
Object parsedObj = parser.parse((String) jsonData);
|
||||
return parsedObj;
|
||||
} catch (ParseException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
} else
|
||||
throw new IllegalArgumentException("not support json type. " + jsonData.getClass());
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static JSONObject parseJson(Object message) {
|
||||
if (message == null) {
|
||||
return new JSONObject();
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
package com.eactive.eai.common.util;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
import org.json.simple.JSONObject;
|
||||
|
||||
/**
|
||||
* Jackson JsonNode 범용 접근 유틸리티
|
||||
*
|
||||
* "." 구분자로 필드 단계를 이동하고, "[n]" 으로 배열 인덱스에 접근하는
|
||||
* path 표현식을 지원한다.
|
||||
*
|
||||
* 사용 예:
|
||||
* JacksonUtil.getText(root, "term_agreements[0].is_agreed")
|
||||
* JacksonUtil.getBoolean(root, "term_agreements[0].is_agreed", false)
|
||||
* JacksonUtil.getNode(root, "data.list[2].child[0].name")
|
||||
*
|
||||
* 경로 중간에 필드가 없거나, 배열 인덱스가 범위를 벗어나거나,
|
||||
* 배열이 아닌 노드에 인덱스 접근을 시도하는 경우 모두
|
||||
* 예외를 던지지 않고 null / 기본값을 반환한다.
|
||||
*/
|
||||
public final class JacksonUtil {
|
||||
|
||||
/** "fieldName" 또는 "fieldName[0]" 형태의 토큰을 분해하는 패턴 */
|
||||
private static final Pattern TOKEN_PATTERN = Pattern.compile("([^\\[\\]]*)((?:\\[\\d+\\])*)");
|
||||
private static final Pattern INDEX_PATTERN = Pattern.compile("\\[(\\d+)\\]");
|
||||
|
||||
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
||||
|
||||
|
||||
|
||||
private JacksonUtil() {
|
||||
// 인스턴스화 방지
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 기본 트리 탐색
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Object(JSONObject/String/JsonNode 등)를 JsonNode로 변환한다.
|
||||
* KakaopayFilter.readTree()를 일반화한 버전.
|
||||
*/
|
||||
public static JsonNode readTree(Object jsonData, ObjectMapper objectMapper)
|
||||
throws JsonMappingException, JsonProcessingException {
|
||||
|
||||
if (jsonData == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (jsonData instanceof JsonNode) {
|
||||
return (JsonNode) jsonData;
|
||||
}
|
||||
|
||||
String jsonStr = null;
|
||||
|
||||
if (jsonData instanceof JSONObject) {
|
||||
jsonStr = ((JSONObject) jsonData).toJSONString();
|
||||
} else if (jsonData instanceof String) {
|
||||
jsonStr = (String) jsonData;
|
||||
} else {
|
||||
// 그 외 POJO 등은 writeValueAsString을 통해 변환
|
||||
jsonStr = objectMapper.writeValueAsString(jsonData);
|
||||
}
|
||||
|
||||
if (jsonStr == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return objectMapper.readTree(jsonStr);
|
||||
}
|
||||
|
||||
public static JsonNode readTree(Object jsonData) throws JsonMappingException, JsonProcessingException {
|
||||
return readTree(jsonData, OBJECT_MAPPER);
|
||||
}
|
||||
|
||||
public static String writeAsString(JsonNode node) throws JsonProcessingException {
|
||||
return OBJECT_MAPPER.writeValueAsString(node);
|
||||
}
|
||||
|
||||
public static ObjectNode createObjectNode() {
|
||||
return OBJECT_MAPPER.createObjectNode();
|
||||
}
|
||||
|
||||
/**
|
||||
* path 표현식으로 JsonNode를 탐색한다.
|
||||
* 경로가 존재하지 않으면 null을 반환한다 (MissingNode가 아닌 진짜 null).
|
||||
*
|
||||
* @param root 탐색을 시작할 JsonNode
|
||||
* @param path 예: "term_agreements[0].is_agreed", "data.list[2].name"
|
||||
*/
|
||||
public static JsonNode getNode(JsonNode root, String path) {
|
||||
if (root == null || path == null || path.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
JsonNode current = root;
|
||||
|
||||
for (String rawToken : path.split("\\.")) {
|
||||
if (current == null || current.isMissingNode() || current.isNull()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String fieldName = extractFieldName(rawToken);
|
||||
List<Integer> indices = extractIndices(rawToken);
|
||||
|
||||
// 필드명이 있으면 먼저 필드로 이동 (빈 문자열이면 현재 노드 유지 - 최상위 배열 접근용)
|
||||
if (!fieldName.isEmpty()) {
|
||||
if (!current.has(fieldName)) {
|
||||
return null;
|
||||
}
|
||||
current = current.get(fieldName);
|
||||
}
|
||||
|
||||
// 이어지는 [n][m]... 인덱스를 순서대로 적용
|
||||
for (Integer idx : indices) {
|
||||
if (current == null || !current.isArray() || idx < 0 || idx >= current.size()) {
|
||||
return null;
|
||||
}
|
||||
current = current.get(idx);
|
||||
}
|
||||
}
|
||||
|
||||
return current;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 타입별 getter (전부 null-safe, 기본값 지원)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
public static String getText(JsonNode root, String path) {
|
||||
return getText(root, path, null);
|
||||
}
|
||||
|
||||
public static String getText(JsonNode root, String path, String defaultValue) {
|
||||
JsonNode node = getNode(root, path);
|
||||
return (node == null || node.isMissingNode() || node.isNull()) ? defaultValue : node.asText(defaultValue);
|
||||
}
|
||||
|
||||
public static boolean getBoolean(JsonNode root, String path, boolean defaultValue) {
|
||||
JsonNode node = getNode(root, path);
|
||||
return (node == null || node.isMissingNode() || node.isNull()) ? defaultValue : node.asBoolean(defaultValue);
|
||||
}
|
||||
|
||||
public static int getInt(JsonNode root, String path, int defaultValue) {
|
||||
JsonNode node = getNode(root, path);
|
||||
return (node == null || node.isMissingNode() || node.isNull()) ? defaultValue : node.asInt(defaultValue);
|
||||
}
|
||||
|
||||
public static long getLong(JsonNode root, String path, long defaultValue) {
|
||||
JsonNode node = getNode(root, path);
|
||||
return (node == null || node.isMissingNode() || node.isNull()) ? defaultValue : node.asLong(defaultValue);
|
||||
}
|
||||
|
||||
public static double getDouble(JsonNode root, String path, double defaultValue) {
|
||||
JsonNode node = getNode(root, path);
|
||||
return (node == null || node.isMissingNode() || node.isNull()) ? defaultValue : node.asDouble(defaultValue);
|
||||
}
|
||||
|
||||
/** path가 가리키는 노드가 실제로 존재하는지 (null/missing이 아닌지) */
|
||||
public static boolean exists(JsonNode root, String path) {
|
||||
JsonNode node = getNode(root, path);
|
||||
return node != null && !node.isMissingNode() && !node.isNull();
|
||||
}
|
||||
|
||||
/** path가 가리키는 노드가 배열일 때 그 크기를 반환, 배열이 아니거나 없으면 -1 */
|
||||
public static int size(JsonNode root, String path) {
|
||||
JsonNode node = getNode(root, path);
|
||||
return (node != null && node.isArray()) ? node.size() : -1;
|
||||
}
|
||||
|
||||
/** path가 가리키는 ArrayNode를 List<JsonNode>로 반환, 없으면 빈 리스트 */
|
||||
public static List<JsonNode> getList(JsonNode root, String path) {
|
||||
List<JsonNode> result = new ArrayList<>();
|
||||
JsonNode node = getNode(root, path);
|
||||
if (node != null && node.isArray()) {
|
||||
for (JsonNode item : node) {
|
||||
result.add(item);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 값 설정 (필요 시 사용 - 존재하는 경로에 대해서만 동작)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* path가 가리키는 위치의 텍스트 값을 변경한다.
|
||||
* 부모 컨테이너(ObjectNode/ArrayNode)가 존재해야 하며, 중간 경로가 없으면 false를 반환한다.
|
||||
* (자동으로 중간 경로를 생성하지는 않음)
|
||||
*/
|
||||
public static boolean setText(JsonNode root, String path, String value) {
|
||||
return setValue(root, path, value);
|
||||
}
|
||||
|
||||
private static boolean setValue(JsonNode root, String path, String value) {
|
||||
int lastDot = path.lastIndexOf('.');
|
||||
String parentPath = (lastDot == -1) ? "" : path.substring(0, lastDot);
|
||||
String lastToken = (lastDot == -1) ? path : path.substring(lastDot + 1);
|
||||
|
||||
JsonNode parent = parentPath.isEmpty() ? root : getNode(root, parentPath);
|
||||
if (parent == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String fieldName = extractFieldName(lastToken);
|
||||
List<Integer> indices = extractIndices(lastToken);
|
||||
|
||||
JsonNode target = parent;
|
||||
if (!fieldName.isEmpty()) {
|
||||
if (!target.has(fieldName)) {
|
||||
return false;
|
||||
}
|
||||
target = target.get(fieldName);
|
||||
}
|
||||
|
||||
// 마지막 인덱스 전까지 이동
|
||||
for (int i = 0; i < indices.size() - 1; i++) {
|
||||
int idx = indices.get(i);
|
||||
if (target == null || !target.isArray() || idx < 0 || idx >= target.size()) {
|
||||
return false;
|
||||
}
|
||||
target = target.get(idx);
|
||||
}
|
||||
|
||||
if (!indices.isEmpty()) {
|
||||
// 배열의 특정 인덱스 값 교체
|
||||
int lastIdx = indices.get(indices.size() - 1);
|
||||
if (target == null || !target.isArray() || lastIdx < 0 || lastIdx >= target.size()) {
|
||||
return false;
|
||||
}
|
||||
((ArrayNode) target).set(lastIdx, value);
|
||||
return true;
|
||||
} else {
|
||||
// 객체 필드 값 교체 (target은 fieldName으로 이미 이동된 상태이므로, parent 기준 재설정 필요)
|
||||
if (parent.isObject() && fieldName != null && !fieldName.isEmpty()) {
|
||||
((ObjectNode) parent).put(fieldName, value);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 내부 파싱 헬퍼
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/** "term_agreements[0]" -> "term_agreements" / "[0]" -> "" */
|
||||
private static String extractFieldName(String token) {
|
||||
Matcher m = TOKEN_PATTERN.matcher(token);
|
||||
if (m.matches()) {
|
||||
return m.group(1) == null ? "" : m.group(1);
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
/** "term_agreements[0][1]" -> [0, 1] / "term_agreements" -> [] */
|
||||
private static List<Integer> extractIndices(String token) {
|
||||
List<Integer> indices = new ArrayList<>();
|
||||
Matcher m = INDEX_PATTERN.matcher(token);
|
||||
while (m.find()) {
|
||||
indices.add(Integer.parseInt(m.group(1)));
|
||||
}
|
||||
return indices;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -412,9 +412,16 @@ public final class MessageUtil {
|
||||
if ("RECEAIAHA022".equals(oldErrCode)) { // UUID가 같지 않은 에러
|
||||
return STDMessageErrorKeys.UUID_MISMATCH_ERROR_CODE_VALUE;
|
||||
}
|
||||
if ("RECEAIIRP070".equals(oldErrCode)) { // 거래제한
|
||||
return STDMessageErrorKeys.RESTRICT_ERROR_CODE_VALUE;
|
||||
}
|
||||
if ("RECEAIIRP072".equals(oldErrCode)) { // 유량제어 초과 에러
|
||||
return STDMessageErrorKeys.RATELIMIT_ERROR_CODE_VALUE;
|
||||
}
|
||||
if ("RECEAIOHP201".equals(oldErrCode)) { // CIRCUITBREAKER 초과 에러
|
||||
return STDMessageErrorKeys.RATELIMIT_ERROR_CODE_VALUE;
|
||||
}
|
||||
|
||||
if (EAIServiceMonitor.getInstance().isTimeOutCodes(oldErrCode)){ //TIMEOUT일경우
|
||||
return STDMessageErrorKeys.TIMEOUT_ERROR_CODE_VALUE;
|
||||
}else if (EAIServiceMonitor.getInstance().isBizErrorCodes(oldErrCode)){ //업무오류일경우
|
||||
@@ -445,9 +452,15 @@ public final class MessageUtil {
|
||||
if ("RECEAIAHA022".equals(oldErrCode)) { // UUID가 같지 않은 에러
|
||||
return STDMessageErrorKeys.UUID_MISMATCH_ERROR_MSG_VALUE;
|
||||
}
|
||||
if ("RECEAIIRP070".equals(oldErrCode)) { // 거래제한
|
||||
return STDMessageErrorKeys.RESTRICT_ERROR_MSG_VALUE;
|
||||
}
|
||||
if ("RECEAIIRP072".equals(oldErrCode)) { // 유량제어 초과 에러
|
||||
return STDMessageErrorKeys.RATELIMIT_ERROR_MSG_VALUE;
|
||||
}
|
||||
if ("RECEAIOHP201".equals(oldErrCode)) { // CIRCUITBREAKER 초과 에러
|
||||
return STDMessageErrorKeys.RATELIMIT_ERROR_MSG_VALUE;
|
||||
}
|
||||
if (EAIServiceMonitor.getInstance().isTimeOutCodes(oldErrCode) ){ //TIMEOUT일경우
|
||||
return STDMessageErrorKeys.TIMEOUT_ERROR_MSG_VALUE;
|
||||
}else if (EAIServiceMonitor.getInstance().isBizErrorCodes(oldErrCode)){ //업무오류일경우
|
||||
@@ -457,6 +470,31 @@ public final class MessageUtil {
|
||||
}
|
||||
}
|
||||
|
||||
public static String getTobeDesc(String oldErrCode){
|
||||
if ("".equals(oldErrCode)){
|
||||
return STDMessageErrorKeys.SYSTEM_ERROR_DESC_VALUE;
|
||||
}
|
||||
if ("RECEAIIRP020,RECEAIIRP120,RECEAIIRP110".indexOf(oldErrCode) >= 0 ){//유효값 오류
|
||||
return STDMessageErrorKeys.VALID_VALUE_ERROR_DESC_VALUE;
|
||||
}
|
||||
if ("RECEAIIRP070".equals(oldErrCode)) { // 거래제한
|
||||
return STDMessageErrorKeys.RESTRICT_ERROR_DESC_VALUE;
|
||||
}
|
||||
if ("RECEAIIRP072".equals(oldErrCode)) { // 유량제어 초과 에러
|
||||
return STDMessageErrorKeys.RATELIMIT_ERROR_DESC_VALUE;
|
||||
}
|
||||
if ("RECEAIOHP201".equals(oldErrCode)) { // CIRCUITBREAKER 초과 에러
|
||||
return STDMessageErrorKeys.RATELIMIT_ERROR_DESC_VALUE;
|
||||
}
|
||||
if (EAIServiceMonitor.getInstance().isTimeOutCodes(oldErrCode) ){ //TIMEOUT일경우
|
||||
return STDMessageErrorKeys.TIMEOUT_ERROR_DESC_VALUE;
|
||||
}else if (EAIServiceMonitor.getInstance().isBizErrorCodes(oldErrCode)){ //업무오류일경우
|
||||
return STDMessageErrorKeys.BIZ_ERROR_DESC_VALUE;
|
||||
}else{
|
||||
return STDMessageErrorKeys.SYSTEM_ERROR_DESC_VALUE;
|
||||
}
|
||||
}
|
||||
|
||||
// TODO json tunning 요소 다시 확인해봐야됨(불필요한 파싱)
|
||||
public static String addJsonRootItem(String jsonString, String rootItemName) {
|
||||
JSONObject value = (JSONObject) JSONValue.parse(jsonString);
|
||||
|
||||
@@ -4,7 +4,7 @@ import java.util.Properties;
|
||||
|
||||
public class TxFileLogger {
|
||||
|
||||
public static void logTxFile(Properties transactionProp, String message, String prefix) {
|
||||
public static void logTxFile(Properties transactionProp, Object message, String prefix) {
|
||||
Logger siftLogger = Logger.getLogger(Logger.LOGGER_SIFT);
|
||||
if (siftLogger.isInfoEnabled()) {
|
||||
siftLogger.info(prefix + message);
|
||||
|
||||
@@ -6,6 +6,9 @@ import java.lang.reflect.Method;
|
||||
import java.net.InetAddress;
|
||||
import java.nio.charset.Charset;
|
||||
import java.rmi.RemoteException;
|
||||
import java.rmi.registry.LocateRegistry;
|
||||
import java.rmi.registry.Registry;
|
||||
import java.rmi.server.ExportException;
|
||||
import java.security.Security;
|
||||
import java.util.Arrays;
|
||||
|
||||
@@ -24,6 +27,7 @@ import com.eactive.eai.common.dao.Keys;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.lifecycle.LifecycleException;
|
||||
import com.eactive.eai.common.lifecycle.LifecycleManager;
|
||||
import com.eactive.eai.common.logger.async.AsyncHttpLoggingPoolManager;
|
||||
import com.eactive.eai.common.logger.async.AsyncLoggingPoolManager;
|
||||
import com.eactive.eai.common.property.PropManager;
|
||||
import com.eactive.eai.common.routing.rmi.RemoteProxy;
|
||||
@@ -36,7 +40,6 @@ import com.eactive.eai.common.util.ServiceLocator;
|
||||
import com.eactive.eai.common.util.ServiceLocatorException;
|
||||
import com.eactive.eai.env.ConfigKeys;
|
||||
import com.eactive.eai.env.ElinkConfig;
|
||||
import com.eactive.eai.common.logger.async.AsyncHttpLoggingPoolManager;
|
||||
|
||||
/**
|
||||
* eLink FrameWork이 초기화(Deploy)될 때 실행되어야 할 작업을 정의
|
||||
@@ -180,14 +183,25 @@ public class AppInitializer implements InitializingBean, DisposableBean {
|
||||
this.shutdownWaitIntervalMs = shutdownWaitIntervalMs;
|
||||
}
|
||||
|
||||
private Registry rmiRegistry;
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private void initRmiServer(int registryPort, int servicePort) throws RemoteException {
|
||||
try {
|
||||
rmiRegistry = LocateRegistry.createRegistry(registryPort);
|
||||
} catch (ExportException e) {
|
||||
// 혹시 이전 정리 실패로 이미 떠있다면 재사용 시도
|
||||
Logger.getLogger(Logger.LOGGER_DEFAULT)
|
||||
.warn("Registry already exists on port " + registryPort + ", reusing", e);
|
||||
rmiRegistry = LocateRegistry.getRegistry(registryPort);
|
||||
}
|
||||
|
||||
rmiServiceExporter.setServiceName("RemoteProxy");
|
||||
rmiServiceExporter.setService(remoteProxy);
|
||||
rmiServiceExporter.setServiceInterface(serviceInterface);
|
||||
rmiServiceExporter.setRegistryPort(registryPort);
|
||||
rmiServiceExporter.setServicePort(servicePort);
|
||||
rmiServiceExporter.setAlwaysCreateRegistry(true);
|
||||
rmiServiceExporter.setAlwaysCreateRegistry(false);
|
||||
rmiServiceExporter.afterPropertiesSet();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.eactive.eai.inbound.error;
|
||||
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
@@ -54,9 +55,12 @@ public class InboundErrorInfoDAO extends BaseDAO {
|
||||
return;
|
||||
}
|
||||
|
||||
String errCode = StringUtils.substring(vo.getErrCd(), 0, 12);
|
||||
vo.setErrCd(errCode);
|
||||
|
||||
InboundErrorInfo entity = inboundErrorInfoMapper.toEntity(vo);
|
||||
inboundErrorInfoLoader.save(entity);
|
||||
} catch (Exception e) {
|
||||
} catch (Throwable e) {
|
||||
logger.error(e);
|
||||
throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAIIEI001"), e);
|
||||
}
|
||||
|
||||
@@ -4,9 +4,6 @@ import java.util.Calendar;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import com.eactive.eai.common.TransactionContextKeys;
|
||||
import com.eactive.eai.common.context.ElinkTransactionContext;
|
||||
import com.eactive.eai.common.util.*;
|
||||
@@ -25,7 +22,6 @@ import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
|
||||
import com.eactive.eai.common.bizkey.BizKeyManager;
|
||||
import com.eactive.eai.common.bizkey.BizKeyVO;
|
||||
import com.eactive.eai.common.dao.DAOFactory;
|
||||
import com.eactive.eai.common.errorcode.ErrorCodeHandler;
|
||||
import com.eactive.eai.common.exception.ExceptionHandler;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.inflow.Bucket;
|
||||
@@ -59,9 +55,6 @@ import com.eactive.eai.message.service.InterfaceMapper;
|
||||
import com.eactive.eai.util.SimHeaderUtil;
|
||||
import com.ext.eai.common.stdmessage.STDMessageKeys;
|
||||
|
||||
import org.json.simple.JSONObject;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
//import org.apache.commons.lang3.StringUtils;
|
||||
//import org.springframework.http.HttpStatus;
|
||||
|
||||
@@ -465,6 +458,8 @@ public class RequestProcessor extends RequestProcessorSupport {
|
||||
return getInboundErrorResponse(prop, standardMessage, mapper, vo.getRspErrorCode(), vo.getRspErrorMsg(), inboundCharset);
|
||||
}
|
||||
|
||||
eaiMsg.setCallProp(prop);
|
||||
|
||||
// set standardMessage & mapper to EAIMessage
|
||||
eaiMsg.setStandardMessage(standardMessage);
|
||||
eaiMsg.setMapper(mapper);
|
||||
@@ -476,6 +471,8 @@ public class RequestProcessor extends RequestProcessorSupport {
|
||||
if (esbLogger.isInfo()) esbLogger.info("RequestProcessor] started... - EAI Server Log Level is INFO");
|
||||
}
|
||||
|
||||
afterFoundEaiMessage(eaiMsg, vo, prop);
|
||||
|
||||
// 3-1. 수신메시지와 초기값을 EAIMessage에 설정한다.
|
||||
// 메시지 수신시각 설정
|
||||
eaiMsg.setMsgRcvTm(vo.getErrTm());
|
||||
@@ -1010,8 +1007,15 @@ public class RequestProcessor extends RequestProcessorSupport {
|
||||
if (logger.isError()) logger.error(guidLogPrefix + " : 거래통제 Log 실패 - " + vo.getRspErrorMsg());
|
||||
}
|
||||
|
||||
AdapterGroupVO adptGrpVO = AdapterManager.getInstance().getAdapterGroupVO(vo.getAdapterGroupName());
|
||||
if (!Keys.IF_STANDARD.equals(vo.getStdMsgTypeCode()) && StringUtils.equalsAny(adptGrpVO.getType(),
|
||||
Keys.TYPE_REST, Keys.TYPE_HTTP, Keys.TYPE_HTTP_CUSTOM)) {
|
||||
throw new HttpStatusException(eaiMsg.getRspErrMsg(), eaiMsg.getRspErrCd(),
|
||||
HttpStatus.SERVICE_UNAVAILABLE.value());
|
||||
} else {
|
||||
return restrictResponse;
|
||||
}
|
||||
}
|
||||
else {
|
||||
// ExceptionHandler에 의해 에러 응답송신
|
||||
try {
|
||||
@@ -1256,7 +1260,7 @@ public class RequestProcessor extends RequestProcessorSupport {
|
||||
|
||||
beforeRoute(eaiMsg, prop);
|
||||
retEaiMsg = FlowRouter.process(eaiMsg, prop);
|
||||
|
||||
retEaiMsg.setCallProp(prop);
|
||||
// 응답메시지에 Error Code기 설정되어 있을 경우
|
||||
// ExceptionHandler를 통해 응답메시지를 생성한다.
|
||||
if(retEaiMsg != null && !MessageUtil.checkRspErrCd(retEaiMsg.getRspErrCd())) {
|
||||
@@ -1396,6 +1400,10 @@ public class RequestProcessor extends RequestProcessorSupport {
|
||||
}
|
||||
}
|
||||
|
||||
protected void afterFoundEaiMessage(EAIMessage eaiMsg, ProcessVO vo, Properties prop) {
|
||||
}
|
||||
|
||||
|
||||
protected String checkCustomInflow(Bucket bucket, EAIMessage eaiMsg, Properties prop) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import org.springframework.http.HttpStatus;
|
||||
import com.eactive.eai.adapter.AdapterGroupVO;
|
||||
import com.eactive.eai.adapter.AdapterManager;
|
||||
import com.eactive.eai.adapter.http.HttpStatusException;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||
import com.eactive.eai.common.exception.ExceptionHandler;
|
||||
import com.eactive.eai.common.message.EAIMessage;
|
||||
@@ -111,7 +112,13 @@ public abstract class RequestProcessorSupport implements Processor
|
||||
**/
|
||||
public Object execute(Object message, Properties prop) throws HttpStatusException
|
||||
{
|
||||
long msgRcvTm = System.currentTimeMillis();
|
||||
String receivedTimestamp = prop.getProperty(HttpAdapterServiceKey.INBOUND_REQUESTED_TIME);
|
||||
long msgRcvTm = 0L;
|
||||
if(receivedTimestamp == null)
|
||||
msgRcvTm = System.currentTimeMillis();
|
||||
else
|
||||
msgRcvTm = Long.parseLong(receivedTimestamp);
|
||||
|
||||
increaseRcvCount();
|
||||
local.set(new Long(msgRcvTm));
|
||||
|
||||
|
||||
@@ -18,6 +18,9 @@ import com.eactive.eai.message.filter.MessageFilter;
|
||||
public class StandardMessage extends StandardItem {
|
||||
private static final long serialVersionUID = 8250470942348479859L;
|
||||
static Logger logger = LoggerFactory.getLogger(StandardMessage.class);
|
||||
|
||||
String eaiSvcCd = null;
|
||||
|
||||
int readPosition = 0;
|
||||
|
||||
private String serviceKey = null;
|
||||
@@ -30,6 +33,14 @@ public class StandardMessage extends StandardItem {
|
||||
|
||||
private MessageFilter flatFilter = null;
|
||||
|
||||
public String getEaiSvcCd() {
|
||||
return eaiSvcCd;
|
||||
}
|
||||
|
||||
public void setEaiSvcCd(String eaiSvcCd) {
|
||||
this.eaiSvcCd = eaiSvcCd;
|
||||
}
|
||||
|
||||
public String getBizDataCharset() {
|
||||
return bizDataCharset;
|
||||
}
|
||||
|
||||
@@ -284,7 +284,7 @@ public class StandardMessageUtil {
|
||||
if (item.getLevel() == curItem.getLevel() + 1) {
|
||||
if (curItem.getType() == StandardType.GRID) {
|
||||
curItem.addArrayItem(0,
|
||||
setRecursiveItems(message, itemList, i, getFullPath(parentPath, curItem.getName())));
|
||||
setRecursiveItems(message, itemList, i, getFullPath(parentPath, curItem.getName() + "[0]")));
|
||||
} else {
|
||||
curItem.addItem(
|
||||
setRecursiveItems(message, itemList, i, getFullPath(parentPath, curItem.getName())));
|
||||
|
||||
@@ -140,7 +140,7 @@ reader.FLAT=com.eactive.eai.message.parser.FlatReader
|
||||
|
||||
lifecycle.fireLifecycleEvent(STOPING_EVENT, this);
|
||||
readerMap.clear();
|
||||
readerMap = null;
|
||||
// readerMap = null;
|
||||
started = false;
|
||||
lifecycle.fireLifecycleEvent(STOPPED_EVENT, this);
|
||||
}
|
||||
@@ -208,6 +208,10 @@ reader.FLAT=com.eactive.eai.message.parser.FlatReader
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
private void initReaderFactory(Properties config) {
|
||||
if (readerMap == null) {
|
||||
readerMap = new ConcurrentHashMap<>();
|
||||
}
|
||||
|
||||
Class cl = null;
|
||||
StandardReader reader = null;
|
||||
|
||||
@@ -334,6 +338,8 @@ reader.FLAT=com.eactive.eai.message.parser.FlatReader
|
||||
}
|
||||
if(logger.isDebug()) logger.debug("mapperClass : {}", mapper.getClass().getCanonicalName());
|
||||
|
||||
standardMessage.setBizDataPath(mapper.getPath(InterfaceMapper.BIZ_DATA));
|
||||
|
||||
String versionMapperClass = config.getProperty(VERSION_MAPPER);
|
||||
if(StringUtils.isEmpty(versionMapperClass)) {
|
||||
versionMapperClass = "com.eactive.eai.message.mapper.DefaultMessageMapper";
|
||||
|
||||
@@ -18,7 +18,7 @@ public class DefaultInterfaceMapper implements InterfaceMapper {
|
||||
itemPathMap = map;
|
||||
}
|
||||
|
||||
protected String getPath(String key) {
|
||||
public String getPath(String key) {
|
||||
String path = itemPathMap.get(key);
|
||||
if(StringUtils.isBlank(path)) {
|
||||
logger.debug("message-mapping not defined key = {}", key);
|
||||
|
||||
@@ -34,7 +34,11 @@ public interface InterfaceMapper extends Serializable {
|
||||
String RESPONSE_TYPE = "RESPONSE_TYPE";
|
||||
String SYNC_ASYNC_TYPE = "SYNC_ASYNC_TYPE";
|
||||
|
||||
String BIZ_DATA = "BIZ_DATA";
|
||||
|
||||
public void initPathMap(HashMap<String, String> map);
|
||||
|
||||
public String getPath(String key);
|
||||
//------------------------------------------------------------
|
||||
// 표준전문과 Mapping 되는 항목을 모두 정의해야 함.
|
||||
//------------------------------------------------------------
|
||||
|
||||
@@ -684,11 +684,17 @@ public abstract class DefaultProcess extends Process {
|
||||
AdapterVO inboundAdapterVO = AdapterManager.getInstance().getAdapterVO(inboudnAdapterGroupName, inboudnAdapterName);
|
||||
String errorResponseHandlerClass = AdapterPropManager.getInstance().getProperty(inboundAdapterVO.getPropGroupName(), "ERR_MSG_HANDLER");
|
||||
if(StringUtils.isBlank(errorResponseHandlerClass)) {
|
||||
if ((com.eactive.eai.adapter.Keys.IF_STANDARD.equals(this.adptrMsgPtrnCd)
|
||||
||com.eactive.eai.adapter.Keys.IF_SUBSTANDARD.equals(this.adptrMsgPtrnCd))) {
|
||||
String errorCode = mapper.getErrorCode(resStandardMessage);
|
||||
String errorMsg = StringUtils.trim(mapper.getErrorMsg(resStandardMessage));
|
||||
String errorDesc = StringUtils.trim(resStandardMessage.findItemValue("MSG.MAIN_MSG.outp_msg_desc"));
|
||||
this.resEaiMsg.setRspErr("RECEAIINA001", String.format("[%s] %s (%s)", errorCode, errorMsg, errorDesc));
|
||||
return;
|
||||
} else {
|
||||
this.resEaiMsg.setRspErr("RECEAIINA001", "비표준 오류 응답 수신");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
logger.info(inboudnAdapterName+", Handle Error Message Class-"+errorResponseHandlerClass);
|
||||
@@ -776,6 +782,7 @@ public abstract class DefaultProcess extends Process {
|
||||
if(this.tempProp.get(HttpAdapterServiceKey.OUTBOUND_PROPERTY_MAP) instanceof Map) {
|
||||
Map<String, Object> map = (Map<String, Object>) this.tempProp.get(HttpAdapterServiceKey.OUTBOUND_PROPERTY_MAP);
|
||||
this.resObject = map.get(HttpAdapterServiceKey.OUTBOUND_RESPONSE_MESSAGE);
|
||||
this.callProp.put(HttpAdapterServiceKey.OUTBOUND_PROPERTY_MAP, map);
|
||||
}
|
||||
standardMessage.setBizData(this.resObject, this.inboundCharset);
|
||||
try {
|
||||
|
||||
@@ -1,29 +1,25 @@
|
||||
package com.eactive.eai.outbound;
|
||||
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import com.eactive.eai.common.TransactionContextKeys;
|
||||
import com.eactive.eai.common.circuitBreaker.CircuitBreakerManager;
|
||||
import com.eactive.eai.common.circuitBreaker.type.TypedCircuitBreakerManager;
|
||||
import com.eactive.eai.message.StandardMessage;
|
||||
import com.eactive.eai.util.PropertiesUtil;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.initech.core.util.PropertiesManager;
|
||||
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterGroupVO;
|
||||
import com.eactive.eai.adapter.AdapterManager;
|
||||
import com.eactive.eai.adapter.AdapterPropManager;
|
||||
import com.eactive.eai.adapter.AdapterVO;
|
||||
import com.eactive.eai.adapter.handler.AdapterErrorMessageHandler;
|
||||
import com.eactive.eai.adapter.handler.AdapterErrorMessageHandlerFactory;
|
||||
import com.eactive.eai.adapter.http.HttpStatusException;
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
|
||||
import com.eactive.eai.common.EAIKeys;
|
||||
import com.eactive.eai.common.TransactionContextKeys;
|
||||
import com.eactive.eai.common.circuitBreaker.CircuitBreakerManager;
|
||||
import com.eactive.eai.common.circuitBreaker.type.TypedCircuitBreakerManager;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.header.HeaderAction;
|
||||
import com.eactive.eai.common.header.HeaderActionFactory;
|
||||
@@ -43,14 +39,16 @@ import com.eactive.eai.common.worker.ResponseMap;
|
||||
import com.eactive.eai.control.HttpSender;
|
||||
import com.eactive.eai.control.LogSender;
|
||||
import com.eactive.eai.control.Transform;
|
||||
import com.eactive.eai.custom.alarm.AlarmStateManager;
|
||||
import com.eactive.eai.custom.alarm.condition.AlarmCondition;
|
||||
import com.eactive.eai.custom.alarm.event.AlarmEvent;
|
||||
import com.eactive.eai.custom.alarm.key.AlarmKey;
|
||||
import com.eactive.eai.custom.alarm.key.CoreAlarmKey;
|
||||
import com.eactive.eai.env.ElinkConfig;
|
||||
import com.eactive.eai.inbound.processor.Processor;
|
||||
import com.eactive.eai.message.StandardMessage;
|
||||
import com.eactive.eai.util.PropertiesUtil;
|
||||
import com.ext.eai.common.stdmessage.STDMessageKeys;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
import io.github.resilience4j.circuitbreaker.CallNotPermittedException;
|
||||
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
|
||||
|
||||
public class RESTProcess extends HTTPProcess {
|
||||
static final long serialVersionUID = 1L;
|
||||
@@ -148,6 +146,16 @@ public class RESTProcess extends HTTPProcess {
|
||||
logger.error(guidLogPrefix + rspErrorMsg, hse);
|
||||
this.resEaiMsg.setRspErr(rspErrorCode,rspErrorMsg);
|
||||
throw new RuntimeException(rspErrorCode);
|
||||
|
||||
} catch (CallNotPermittedException e) {
|
||||
String[] msgArgs = new String[1];
|
||||
msgArgs[0] = this.reqEaiMsg.getEAISvcCd();
|
||||
String rspErrorCode = "RECEAIOHP201";
|
||||
String rspErrorMsg = ExceptionUtil.make(e, rspErrorCode, msgArgs);
|
||||
if (logger.isError())
|
||||
logger.error(guidLogPrefix + rspErrorMsg, e);
|
||||
this.resEaiMsg.setRspErr(rspErrorCode,rspErrorMsg);
|
||||
throw new RuntimeException(rspErrorCode);
|
||||
} catch (Exception e) {
|
||||
String[] msgArgs = new String[1];
|
||||
msgArgs[0] = this.reqEaiMsg.getEAISvcCd();
|
||||
@@ -683,4 +691,46 @@ public class RESTProcess extends HTTPProcess {
|
||||
|
||||
}
|
||||
|
||||
public void setOutboundErrorMessage() throws Exception {
|
||||
this.logPssSno = TranLogUtil.getResLogSeq(this.svcPssTp, this.svcPssSeq, this.isComp);
|
||||
|
||||
boolean setResObject = false;
|
||||
// 에러에 대한 응답메시지
|
||||
if(this.tempProp.get(HttpAdapterServiceKey.OUTBOUND_PROPERTY_MAP) instanceof Map) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> map = (Map<String, Object>) this.tempProp.get(HttpAdapterServiceKey.OUTBOUND_PROPERTY_MAP);
|
||||
this.callProp.put(HttpAdapterServiceKey.OUTBOUND_PROPERTY_MAP, map);
|
||||
|
||||
// OUTBOUND_PROPERTY_MAP 이 있는 경우, 즉 타겟서버와 통신은 정상적으로 이루진 경우 처리한다.
|
||||
AdapterGroupVO outboundAdapterGroupVO = AdapterManager.getInstance().getAdapterGroupVO(adapterGroupName);
|
||||
if (outboundAdapterGroupVO != null) {
|
||||
AdapterVO outboundAdapterVo = null;
|
||||
if(adapterName != null)
|
||||
outboundAdapterVo = outboundAdapterGroupVO.getAdapterVO(adapterName);
|
||||
else
|
||||
outboundAdapterVo = outboundAdapterGroupVO.nextAdapterVO();
|
||||
|
||||
if (outboundAdapterVo != null) {
|
||||
String errorHandlerClass = AdapterPropManager.getInstance().getProperty(
|
||||
outboundAdapterVo.getPropGroupName(), "ERR_MSG_HANDLER");
|
||||
if (StringUtils.isNotBlank(errorHandlerClass)) {
|
||||
if (logger.isInfo())
|
||||
logger.info("ExceptionHandler] errorSyncSend ERR_MSG_HANDLER=" + errorHandlerClass);
|
||||
AdapterErrorMessageHandler handler = AdapterErrorMessageHandlerFactory.createHandler(errorHandlerClass);
|
||||
this.resObject = handler.generateOutboundErrorResponseMessage(adapterGroupName, adapterGroupName,
|
||||
callProp, this.reqObject, this.resEaiMsg);
|
||||
setResObject = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!setResObject) {
|
||||
this.resObject = "";
|
||||
}
|
||||
StandardMessage standardMessage = this.resEaiMsg.getStandardMessage();
|
||||
standardMessage.setBizData(this.resObject, this.inboundCharset);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -25,6 +25,33 @@ public class HexaConverter {
|
||||
return bytes;
|
||||
}
|
||||
|
||||
public static String binToHex(byte[] bytes) {
|
||||
StringBuilder sb = new StringBuilder(bytes.length * 2);
|
||||
for (byte b : bytes) {
|
||||
sb.append(String.format("%02X", b));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static byte[] hexToBin(String hexStr) {
|
||||
String lookup = "0123456789ABCDEF";
|
||||
|
||||
int len = hexStr.length();
|
||||
byte[] bArray = new byte[len / 2];
|
||||
|
||||
for (int i = 0; i < bArray.length; i++) {
|
||||
char highChar = Character.toUpperCase(hexStr.charAt(i * 2));
|
||||
char lowChar = Character.toUpperCase(hexStr.charAt(i * 2 + 1));
|
||||
|
||||
int high = lookup.indexOf(highChar);
|
||||
int low = lookup.indexOf(lowChar);
|
||||
|
||||
bArray[i] = (byte) ((high << 4) | low);
|
||||
}
|
||||
|
||||
return bArray;
|
||||
}
|
||||
|
||||
// public static void main(String[] argv) {
|
||||
// String str = "TEST\nÇѱÛ";
|
||||
// String hexStr = HexaConverter.bytesToHexa(str.getBytes());
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.eactive.eai.util;
|
||||
|
||||
import org.json.simple.JSONObject;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
@@ -20,13 +22,28 @@ public class JsonPathUtil {
|
||||
// ---------------------------------------------------------------
|
||||
|
||||
/** JSON 문자열을 JsonNode 트리로 파싱. */
|
||||
public static JsonNode toTree(String json) throws Exception {
|
||||
return objectMapper.readTree(json);
|
||||
public static JsonNode toTree(Object json) throws Exception {
|
||||
if(json == null)
|
||||
return null;
|
||||
else if(json instanceof JsonNode)
|
||||
return (JsonNode)json;
|
||||
else if(json instanceof String)
|
||||
return objectMapper.readTree((String)json);
|
||||
else if(json instanceof JSONObject)
|
||||
return objectMapper.readTree(((JSONObject)json).toJSONString());
|
||||
else
|
||||
return objectMapper.readTree(json.toString());
|
||||
}
|
||||
|
||||
/** 이미 파싱된 트리에서 경로의 값을 추출. */
|
||||
public static String getAt(JsonNode root, String path) {
|
||||
JsonNode node = getNodeAtPath(root, path);
|
||||
JsonNode node = getNodeAtPath(root, path, "/");
|
||||
return node != null ? node.asText() : null;
|
||||
}
|
||||
|
||||
/** 이미 파싱된 트리에서 경로의 값을 추출. */
|
||||
public static String getAt(JsonNode root, String path, String delimeter) {
|
||||
JsonNode node = getNodeAtPath(root, path, delimeter);
|
||||
return node != null ? node.asText() : null;
|
||||
}
|
||||
|
||||
@@ -90,12 +107,12 @@ public class JsonPathUtil {
|
||||
|
||||
// 특정 경로에 해당하는 부모 노드를 가져오는 유틸리티 함수
|
||||
private static JsonNode getParentNode(JsonNode rootNode, String parentPath) {
|
||||
return getNodeAtPath(rootNode, parentPath);
|
||||
return getNodeAtPath(rootNode, parentPath, "/");
|
||||
}
|
||||
|
||||
// 특정 경로에 해당하는 노드를 가져오는 유틸리티 함수
|
||||
private static JsonNode getNodeAtPath(JsonNode rootNode, String path) {
|
||||
String[] tokens = path.split("/");
|
||||
private static JsonNode getNodeAtPath(JsonNode rootNode, String path, String delimeter) {
|
||||
String[] tokens = path.split(delimeter);
|
||||
JsonNode currentNode = rootNode;
|
||||
|
||||
for (String token : tokens) {
|
||||
@@ -128,12 +145,12 @@ public class JsonPathUtil {
|
||||
* @param mergeJson 병합할 JSON 문자열
|
||||
* @return 병합된 JSON 문자열, 병합 불가 시 mergeJson 그대로 반환
|
||||
*/
|
||||
public static String mergeAtRoot(JsonNode bodyNode, String removeFromPath, String mergeJson) {
|
||||
public static JsonNode mergeAtRoot(JsonNode bodyNode, String removeFromPath, String mergeJson) {
|
||||
try {
|
||||
JsonNode mergeNode = objectMapper.readTree(mergeJson);
|
||||
|
||||
if (!bodyNode.isObject() || !mergeNode.isObject()) {
|
||||
return mergeJson;
|
||||
return bodyNode;
|
||||
}
|
||||
|
||||
ObjectNode result = (ObjectNode) bodyNode.deepCopy();
|
||||
@@ -144,7 +161,7 @@ public class JsonPathUtil {
|
||||
if (lastSlash == 0) {
|
||||
result.remove(fieldName);
|
||||
} else {
|
||||
JsonNode parent = getNodeAtPath(result, removeFromPath.substring(0, lastSlash));
|
||||
JsonNode parent = getNodeAtPath(result, removeFromPath.substring(0, lastSlash), "/");
|
||||
if (parent instanceof ObjectNode) {
|
||||
((ObjectNode) parent).remove(fieldName);
|
||||
}
|
||||
@@ -152,9 +169,10 @@ public class JsonPathUtil {
|
||||
|
||||
// mergeJson 필드를 body에 병합 (기존 필드 덮어쓰기)
|
||||
result.setAll((ObjectNode) mergeNode);
|
||||
return objectMapper.writeValueAsString(result);
|
||||
// return objectMapper.writeValueAsString(result);
|
||||
return result;
|
||||
} catch (Exception e) {
|
||||
return mergeJson;
|
||||
return bodyNode;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,7 +193,7 @@ public class JsonPathUtil {
|
||||
*/
|
||||
public static String mergeAtRoot(String body, String removeFromPath, String mergeJson) {
|
||||
try {
|
||||
return mergeAtRoot(objectMapper.readTree(body), removeFromPath, mergeJson);
|
||||
return objectMapper.writeValueAsString(mergeAtRoot(objectMapper.readTree(body), removeFromPath, mergeJson));
|
||||
} catch (Exception e) {
|
||||
return mergeJson;
|
||||
}
|
||||
|
||||
+549
@@ -0,0 +1,549 @@
|
||||
package com.eactive.eai.adapter.handler;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
|
||||
import com.eactive.eai.common.message.EAIMessage;
|
||||
import com.eactive.eai.common.property.PropManager;
|
||||
import com.eactive.eai.common.util.ApplicationContextProvider;
|
||||
import com.eactive.eai.message.StandardItem;
|
||||
import com.eactive.eai.message.StandardMessage;
|
||||
import com.eactive.eai.message.StandardType;
|
||||
|
||||
/**
|
||||
* TemplateCodeConvertAdapterErrorMsgHandler 단위테스트
|
||||
*
|
||||
* 검증 대상: generateNonStandardErrorResponseMessage
|
||||
* - 부모 클래스(TemplateAdapterErrorMsgHandler)가 반환한 JSON 문자열에서
|
||||
* PropManager(AdapterErrorMessageHandler{CODE_CONVERT} 그룹)에 등록된
|
||||
* 매핑 정보로 지정 필드 값을 변환한다.
|
||||
*/
|
||||
class TemplateCodeConvertAdapterErrorMsgHandlerTest {
|
||||
|
||||
private TemplateCodeConvertAdapterErrorMsgHandler handler;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
handler = new TemplateCodeConvertAdapterErrorMsgHandler();
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// 공통 헬퍼
|
||||
// ================================================================
|
||||
|
||||
private static StandardItem field(String name, String value) {
|
||||
return new StandardItem(name, 3, StandardType.FIELD, 1, 0, 300, 1, "", "", value, name);
|
||||
}
|
||||
|
||||
private static StandardItem group(String name) {
|
||||
return new StandardItem(name, 2, StandardType.GROUP, 1, 0, 0, 1, "", "", null, name);
|
||||
}
|
||||
|
||||
private StandardMessage buildMsg(String errCode, String errMsg) {
|
||||
StandardMessage msg = new StandardMessage();
|
||||
StandardItem msgGroup = group("MSG");
|
||||
StandardItem mainMsg = group("MAIN_MSG");
|
||||
mainMsg.addItem(field("outp_msg_cd", errCode));
|
||||
mainMsg.addItem(field("outp_msg_ctnt", errMsg));
|
||||
msgGroup.addItem(mainMsg);
|
||||
|
||||
StandardItem msgList = new StandardItem(
|
||||
"MSG_LIST", 2, StandardType.GRID, 0, 0, 0, 1, "", "", null, "MSG_LIST");
|
||||
msgList.addItem(field("outp_msg_cd", ""));
|
||||
msgList.addItem(field("outp_msg_ctnt", ""));
|
||||
msgGroup.addItem(msgList);
|
||||
msg.addItem(msgGroup);
|
||||
return msg;
|
||||
}
|
||||
|
||||
private EAIMessage toEaiMessage(StandardMessage msg) {
|
||||
EAIMessage eaiMessage = new EAIMessage();
|
||||
eaiMessage.setStandardMessage(msg);
|
||||
return eaiMessage;
|
||||
}
|
||||
|
||||
/**
|
||||
* ApplicationContextProvider 에 mock PropManager 를 주입한다.
|
||||
* 부모 클래스의 getProperty(group, key) 와
|
||||
* 자식 클래스의 getProperties(group) 을 동일한 mock 으로 처리한다.
|
||||
*/
|
||||
private void injectMockPropManager(PropManager mockPropManager) throws Exception {
|
||||
ApplicationContext mockCtx = Mockito.mock(ApplicationContext.class);
|
||||
Mockito.when(mockCtx.getBean(PropManager.class)).thenReturn(mockPropManager);
|
||||
Field ctxField = ApplicationContextProvider.class.getDeclaredField("context");
|
||||
ctxField.setAccessible(true);
|
||||
ctxField.set(null, mockCtx);
|
||||
}
|
||||
|
||||
/**
|
||||
* 부모 템플릿 결과가 될 JSON 과 코드 변환 설정을 함께 세팅하는 헬퍼.
|
||||
*
|
||||
* @param adapterGroupName 어댑터 그룹명
|
||||
* @param template 부모 핸들러에서 사용할 JSON 템플릿 문자열
|
||||
* @param convertProps PROP_GROUP(CODE_CONVERT) 에서 반환될 Properties (null 가능)
|
||||
*/
|
||||
private PropManager setupMock(String adapterGroupName, String template,
|
||||
Properties convertProps) throws Exception {
|
||||
PropManager mockProp = Mockito.mock(PropManager.class);
|
||||
// 부모 클래스: getProperty("AdapterErrorMessageHandler", "GROUP.template")
|
||||
Mockito.when(mockProp.getProperty(
|
||||
eq(TemplateAdapterErrorMsgHandler.PROP_GROUP),
|
||||
eq(adapterGroupName + ".template"))).thenReturn(template);
|
||||
// 자식 클래스: getProperties("AdapterErrorMessageHandler{CODE_CONVERT}")
|
||||
Mockito.when(mockProp.getProperties(
|
||||
eq(TemplateCodeConvertAdapterErrorMsgHandler.PROP_GROUP))).thenReturn(convertProps);
|
||||
injectMockPropManager(mockProp);
|
||||
return mockProp;
|
||||
}
|
||||
|
||||
/** convert.fields 와 매핑 항목들로 Properties 를 생성하는 헬퍼 */
|
||||
private static Properties convertProps(String adapterGroupName,
|
||||
String fields,
|
||||
String... mappings) {
|
||||
Properties p = new Properties();
|
||||
p.setProperty(adapterGroupName + ".convert.fields", fields);
|
||||
for (int i = 0; i < mappings.length - 1; i += 2) {
|
||||
p.setProperty(adapterGroupName + "." + mappings[i], mappings[i + 1]);
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// 사전 조건 및 조기 반환
|
||||
// ================================================================
|
||||
|
||||
@Nested
|
||||
@DisplayName("사전 조건 – 조기 반환")
|
||||
class EarlyReturn {
|
||||
|
||||
@Test
|
||||
@DisplayName("부모 핸들러가 null 반환 시 null 그대로 반환")
|
||||
void 부모_null_반환시_null() throws Exception {
|
||||
PropManager mockProp = Mockito.mock(PropManager.class);
|
||||
// 템플릿 없음 → 부모 핸들러가 null 반환
|
||||
Mockito.when(mockProp.getProperty(anyString(), anyString())).thenReturn(null);
|
||||
injectMockPropManager(mockProp);
|
||||
|
||||
Object result = handler.generateNonStandardErrorResponseMessage(
|
||||
"MY_GROUP", "MY_ADAPTER", new Properties(), null,
|
||||
toEaiMessage(buildMsg("40000", "오류")));
|
||||
|
||||
assertNull(result);
|
||||
// getProperties 는 호출되지 않아야 함
|
||||
Mockito.verify(mockProp, Mockito.never())
|
||||
.getProperties(TemplateCodeConvertAdapterErrorMsgHandler.PROP_GROUP);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("부모 핸들러가 빈 문자열 반환 시 그대로 반환 (변환 미수행)")
|
||||
void 부모_빈문자열_그대로_반환() throws Exception {
|
||||
setupMock("MY_GROUP", " ", null); // blank → 부모도 null 반환
|
||||
|
||||
Object result = handler.generateNonStandardErrorResponseMessage(
|
||||
"MY_GROUP", "MY_ADAPTER", new Properties(), null,
|
||||
toEaiMessage(buildMsg("40000", "오류")));
|
||||
|
||||
assertNull(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("CODE_CONVERT 그룹의 Properties 가 null 이면 템플릿 결과 그대로 반환")
|
||||
void convert_props_null_시_원본_반환() throws Exception {
|
||||
String template = "{\"resCode\":\"${MSG.MAIN_MSG.outp_msg_cd}\"}";
|
||||
setupMock("MY_GROUP", template, null); // getProperties → null
|
||||
|
||||
Object result = handler.generateNonStandardErrorResponseMessage(
|
||||
"MY_GROUP", "MY_ADAPTER", new Properties(), null,
|
||||
toEaiMessage(buildMsg("40000", "오류")));
|
||||
|
||||
assertEquals("{\"resCode\":\"40000\"}", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("convert.fields 키가 없으면 템플릿 결과 그대로 반환")
|
||||
void convert_fields_없으면_원본_반환() throws Exception {
|
||||
String template = "{\"resCode\":\"${MSG.MAIN_MSG.outp_msg_cd}\"}";
|
||||
// convert.fields 를 설정하지 않은 빈 Properties
|
||||
setupMock("MY_GROUP", template, new Properties());
|
||||
|
||||
Object result = handler.generateNonStandardErrorResponseMessage(
|
||||
"MY_GROUP", "MY_ADAPTER", new Properties(), null,
|
||||
toEaiMessage(buildMsg("40000", "오류")));
|
||||
|
||||
assertEquals("{\"resCode\":\"40000\"}", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("convert.fields 가 공백이면 템플릿 결과 그대로 반환")
|
||||
void convert_fields_공백이면_원본_반환() throws Exception {
|
||||
String template = "{\"resCode\":\"${MSG.MAIN_MSG.outp_msg_cd}\"}";
|
||||
Properties cp = new Properties();
|
||||
cp.setProperty("MY_GROUP.convert.fields", " ");
|
||||
setupMock("MY_GROUP", template, cp);
|
||||
|
||||
Object result = handler.generateNonStandardErrorResponseMessage(
|
||||
"MY_GROUP", "MY_ADAPTER", new Properties(), null,
|
||||
toEaiMessage(buildMsg("40000", "오류")));
|
||||
|
||||
// 필드가 공백이므로 split 후 trim → blank → skip → 변환 없음
|
||||
assertEquals("{\"resCode\":\"40000\"}", result);
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// 단순 필드 코드 변환
|
||||
// ================================================================
|
||||
|
||||
@Nested
|
||||
@DisplayName("단순 필드 코드 변환")
|
||||
class SimpleFieldConvert {
|
||||
|
||||
@Test
|
||||
@DisplayName("단일 필드 값 변환")
|
||||
void 단일_필드_변환() throws Exception {
|
||||
String template = "{\"resCode\":\"${MSG.MAIN_MSG.outp_msg_cd}\",\"resMessage\":\"${MSG.MAIN_MSG.outp_msg_ctnt}\"}";
|
||||
Properties cp = convertProps("GRP",
|
||||
"resCode",
|
||||
"resCode.40000", "TB_ERR_999");
|
||||
setupMock("GRP", template, cp);
|
||||
|
||||
Object result = handler.generateNonStandardErrorResponseMessage(
|
||||
"GRP", "ADP", new Properties(), null,
|
||||
toEaiMessage(buildMsg("40000", "Bad Request")));
|
||||
|
||||
assertEquals("{\"resCode\":\"TB_ERR_999\",\"resMessage\":\"Bad Request\"}", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("여러 필드 동시 변환")
|
||||
void 여러_필드_변환() throws Exception {
|
||||
String template = "{\"resCode\":\"${MSG.MAIN_MSG.outp_msg_cd}\",\"resMessage\":\"${MSG.MAIN_MSG.outp_msg_ctnt}\"}";
|
||||
Properties cp = convertProps("GRP",
|
||||
"resCode,resMessage",
|
||||
"resCode.40000", "TB_ERR_999",
|
||||
"resMessage.40000", "요청파라미터에 문제가 있습니다.(필수값 입력오류)");
|
||||
setupMock("GRP", template, cp);
|
||||
|
||||
Object result = handler.generateNonStandardErrorResponseMessage(
|
||||
"GRP", "ADP", new Properties(), null,
|
||||
toEaiMessage(buildMsg("40000", "40000")));
|
||||
|
||||
assertEquals(
|
||||
"{\"resCode\":\"TB_ERR_999\",\"resMessage\":\"요청파라미터에 문제가 있습니다.(필수값 입력오류)\"}",
|
||||
result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("매핑에 없는 값은 원본 그대로 유지")
|
||||
void 매핑_없는_값_원본_유지() throws Exception {
|
||||
String template = "{\"resCode\":\"${MSG.MAIN_MSG.outp_msg_cd}\"}";
|
||||
Properties cp = convertProps("GRP",
|
||||
"resCode",
|
||||
"resCode.40000", "TB_ERR_999"); // 99999 에 대한 매핑 없음
|
||||
setupMock("GRP", template, cp);
|
||||
|
||||
Object result = handler.generateNonStandardErrorResponseMessage(
|
||||
"GRP", "ADP", new Properties(), null,
|
||||
toEaiMessage(buildMsg("99999", "기타오류")));
|
||||
|
||||
assertEquals("{\"resCode\":\"99999\"}", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("convert.fields 쉼표 구분 중 공백 포함해도 정상 처리")
|
||||
void fields_공백_포함_정상처리() throws Exception {
|
||||
String template = "{\"resCode\":\"${MSG.MAIN_MSG.outp_msg_cd}\",\"resMessage\":\"${MSG.MAIN_MSG.outp_msg_ctnt}\"}";
|
||||
Properties cp = convertProps("GRP",
|
||||
" resCode , resMessage ", // 공백 포함
|
||||
"resCode.40000", "TB_ERR_999",
|
||||
"resMessage.40000", "필수값 오류");
|
||||
setupMock("GRP", template, cp);
|
||||
|
||||
Object result = handler.generateNonStandardErrorResponseMessage(
|
||||
"GRP", "ADP", new Properties(), null,
|
||||
toEaiMessage(buildMsg("40000", "40000")));
|
||||
|
||||
assertEquals("{\"resCode\":\"TB_ERR_999\",\"resMessage\":\"필수값 오류\"}", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("매핑에 없는 값은 default 키로 폴백 변환")
|
||||
void 매핑_없는_값_default_폴백() throws Exception {
|
||||
String template = "{\"resCode\":\"${MSG.MAIN_MSG.outp_msg_cd}\"}";
|
||||
Properties cp = convertProps("GRP",
|
||||
"resCode",
|
||||
"resCode.40000", "TB_ERR_999",
|
||||
"resCode.default", "TB_ERR_DEFAULT"); // 폴백
|
||||
setupMock("GRP", template, cp);
|
||||
|
||||
Object result = handler.generateNonStandardErrorResponseMessage(
|
||||
"GRP", "ADP", new Properties(), null,
|
||||
toEaiMessage(buildMsg("99999", ""))); // 99999 매핑 없음
|
||||
|
||||
assertEquals("{\"resCode\":\"TB_ERR_DEFAULT\"}", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("매핑이 있으면 default 보다 우선 적용")
|
||||
void 매핑_존재시_default_미사용() throws Exception {
|
||||
String template = "{\"resCode\":\"${MSG.MAIN_MSG.outp_msg_cd}\"}";
|
||||
Properties cp = convertProps("GRP",
|
||||
"resCode",
|
||||
"resCode.40000", "TB_ERR_999",
|
||||
"resCode.default", "TB_ERR_DEFAULT");
|
||||
setupMock("GRP", template, cp);
|
||||
|
||||
Object result = handler.generateNonStandardErrorResponseMessage(
|
||||
"GRP", "ADP", new Properties(), null,
|
||||
toEaiMessage(buildMsg("40000", ""))); // 40000 매핑 존재
|
||||
|
||||
assertEquals("{\"resCode\":\"TB_ERR_999\"}", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("매핑도 default 도 없으면 원본 유지")
|
||||
void 매핑_default_모두없으면_원본_유지() throws Exception {
|
||||
String template = "{\"resCode\":\"${MSG.MAIN_MSG.outp_msg_cd}\"}";
|
||||
Properties cp = convertProps("GRP",
|
||||
"resCode",
|
||||
"resCode.40000", "TB_ERR_999" // 99999 매핑 없음, default 도 없음
|
||||
);
|
||||
setupMock("GRP", template, cp);
|
||||
|
||||
Object result = handler.generateNonStandardErrorResponseMessage(
|
||||
"GRP", "ADP", new Properties(), null,
|
||||
toEaiMessage(buildMsg("99999", "")));
|
||||
|
||||
assertEquals("{\"resCode\":\"99999\"}", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("여러 필드에서 일부는 매핑, 일부는 default 로 변환")
|
||||
void 여러_필드_매핑과_default_혼합() throws Exception {
|
||||
String template = "{\"resCode\":\"${MSG.MAIN_MSG.outp_msg_cd}\",\"resMessage\":\"${MSG.MAIN_MSG.outp_msg_ctnt}\"}";
|
||||
Properties cp = new Properties();
|
||||
cp.setProperty("GRP.convert.fields", "resCode,resMessage");
|
||||
cp.setProperty("GRP.resCode.40000", "TB_ERR_999"); // 정확 매핑
|
||||
cp.setProperty("GRP.resMessage.default", "기타 오류입니다."); // resMessage 는 default 만
|
||||
setupMock("GRP", template, cp);
|
||||
|
||||
Object result = handler.generateNonStandardErrorResponseMessage(
|
||||
"GRP", "ADP", new Properties(), null,
|
||||
toEaiMessage(buildMsg("40000", "Bad Request")));
|
||||
|
||||
assertEquals("{\"resCode\":\"TB_ERR_999\",\"resMessage\":\"기타 오류입니다.\"}", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("여러 에러코드에 대한 각각 다른 매핑 적용")
|
||||
void 다른_에러코드_다른_매핑() throws Exception {
|
||||
String template = "{\"resCode\":\"${MSG.MAIN_MSG.outp_msg_cd}\"}";
|
||||
Properties cp = new Properties();
|
||||
cp.setProperty("GRP.convert.fields", "resCode");
|
||||
cp.setProperty("GRP.resCode.40000", "TB_ERR_999");
|
||||
cp.setProperty("GRP.resCode.50000", "TB_ERR_500");
|
||||
setupMock("GRP", template, cp);
|
||||
|
||||
// 40000 → TB_ERR_999
|
||||
Object result1 = handler.generateNonStandardErrorResponseMessage(
|
||||
"GRP", "ADP", new Properties(), null,
|
||||
toEaiMessage(buildMsg("40000", "")));
|
||||
assertEquals("{\"resCode\":\"TB_ERR_999\"}", result1);
|
||||
|
||||
// 50000 → TB_ERR_500
|
||||
Object result2 = handler.generateNonStandardErrorResponseMessage(
|
||||
"GRP", "ADP", new Properties(), null,
|
||||
toEaiMessage(buildMsg("50000", "")));
|
||||
assertEquals("{\"resCode\":\"TB_ERR_500\"}", result2);
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// 중첩 경로(dot path) 필드 코드 변환
|
||||
// ================================================================
|
||||
|
||||
@Nested
|
||||
@DisplayName("중첩 경로(dot path) 필드 코드 변환")
|
||||
class NestedPathConvert {
|
||||
|
||||
@Test
|
||||
@DisplayName("1단계 중첩 경로 필드 변환 – result.code")
|
||||
void 한단계_중첩_경로_변환() throws Exception {
|
||||
// 템플릿이 중첩 JSON 을 생성하는 경우 → 변환 전 JSON 을 직접 구성
|
||||
// 부모 render 결과를 미리 알고 있으므로, 간단한 템플릿 + 고정값 활용
|
||||
String template = "{\"result\":{\"code\":\"${MSG.MAIN_MSG.outp_msg_cd}\"}}";
|
||||
Properties cp = convertProps("GRP",
|
||||
"result.code",
|
||||
"result.code.40000", "TB_ERR_999");
|
||||
setupMock("GRP", template, cp);
|
||||
|
||||
Object result = handler.generateNonStandardErrorResponseMessage(
|
||||
"GRP", "ADP", new Properties(), null,
|
||||
toEaiMessage(buildMsg("40000", "")));
|
||||
|
||||
assertEquals("{\"result\":{\"code\":\"TB_ERR_999\"}}", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("2단계 중첩 경로 필드 변환 – a.b.code")
|
||||
void 두단계_중첩_경로_변환() throws Exception {
|
||||
// 부모가 반환할 JSON: 고정 문자열 + stdmsg 치환 없이 직접 지정
|
||||
// 어댑터 그룹명 키 + template 이 fixed JSON 을 반환하도록 설정
|
||||
String fixedJson = "{\"a\":{\"b\":{\"code\":\"ERR_001\"}}}";
|
||||
PropManager mockProp = Mockito.mock(PropManager.class);
|
||||
Mockito.when(mockProp.getProperty(
|
||||
eq(TemplateAdapterErrorMsgHandler.PROP_GROUP),
|
||||
eq("GRP.template"))).thenReturn(fixedJson); // 변수 없는 고정 JSON
|
||||
Properties cp = convertProps("GRP",
|
||||
"a.b.code",
|
||||
"a.b.code.ERR_001", "MAPPED_CODE");
|
||||
Mockito.when(mockProp.getProperties(
|
||||
eq(TemplateCodeConvertAdapterErrorMsgHandler.PROP_GROUP))).thenReturn(cp);
|
||||
injectMockPropManager(mockProp);
|
||||
|
||||
Object result = handler.generateNonStandardErrorResponseMessage(
|
||||
"GRP", "ADP", new Properties(), null,
|
||||
toEaiMessage(buildMsg("", "")));
|
||||
|
||||
assertEquals("{\"a\":{\"b\":{\"code\":\"MAPPED_CODE\"}}}", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("중첩 경로가 존재하지 않으면 해당 필드 변환 건너뜀")
|
||||
void 없는_중첩_경로_건너뜀() throws Exception {
|
||||
String template = "{\"resCode\":\"${MSG.MAIN_MSG.outp_msg_cd}\"}";
|
||||
Properties cp = convertProps("GRP",
|
||||
"nonExist.code", // JSON 에 없는 경로
|
||||
"nonExist.code.40000", "MAPPED");
|
||||
setupMock("GRP", template, cp);
|
||||
|
||||
Object result = handler.generateNonStandardErrorResponseMessage(
|
||||
"GRP", "ADP", new Properties(), null,
|
||||
toEaiMessage(buildMsg("40000", "")));
|
||||
|
||||
// 변환 대상 필드가 없으므로 원본 그대로
|
||||
assertEquals("{\"resCode\":\"40000\"}", result);
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// 복합 시나리오
|
||||
// ================================================================
|
||||
|
||||
@Nested
|
||||
@DisplayName("복합 시나리오")
|
||||
class Combined {
|
||||
|
||||
@Test
|
||||
@DisplayName("일부 필드만 매핑 존재 – 나머지는 원본 유지")
|
||||
void 일부_필드_매핑_나머지_원본() throws Exception {
|
||||
String template = "{\"resCode\":\"${MSG.MAIN_MSG.outp_msg_cd}\",\"resMessage\":\"${MSG.MAIN_MSG.outp_msg_ctnt}\"}";
|
||||
Properties cp = convertProps("GRP",
|
||||
"resCode,resMessage",
|
||||
"resCode.40000", "TB_ERR_999"
|
||||
// resMessage 매핑 없음
|
||||
);
|
||||
setupMock("GRP", template, cp);
|
||||
|
||||
Object result = handler.generateNonStandardErrorResponseMessage(
|
||||
"GRP", "ADP", new Properties(), null,
|
||||
toEaiMessage(buildMsg("40000", "Bad Request")));
|
||||
|
||||
// resCode 는 변환, resMessage 는 원본 유지
|
||||
assertEquals("{\"resCode\":\"TB_ERR_999\",\"resMessage\":\"Bad Request\"}", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("프로퍼티 그룹명 검증 – PROP_GROUP 상수 값")
|
||||
void PROP_GROUP_상수_검증() {
|
||||
assertEquals("AdapterErrorMessageHandler{CODE_CONVERT}",
|
||||
TemplateCodeConvertAdapterErrorMsgHandler.PROP_GROUP);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("부모 PROP_GROUP 과 자식 PROP_GROUP 이 다른 그룹을 사용")
|
||||
void 부모_자식_PROP_GROUP_다름() {
|
||||
// 부모: "AdapterErrorMessageHandler"
|
||||
// 자식: "AdapterErrorMessageHandler{CODE_CONVERT}"
|
||||
assertNotEquals(
|
||||
TemplateAdapterErrorMsgHandler.PROP_GROUP,
|
||||
TemplateCodeConvertAdapterErrorMsgHandler.PROP_GROUP);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("변환 후에도 JSON 에 변환 대상 외 필드는 그대로 유지")
|
||||
void 변환_후_비대상_필드_유지() throws Exception {
|
||||
String template = "{\"resCode\":\"${MSG.MAIN_MSG.outp_msg_cd}\",\"extra\":\"value\",\"resMessage\":\"${MSG.MAIN_MSG.outp_msg_ctnt}\"}";
|
||||
Properties cp = convertProps("GRP",
|
||||
"resCode",
|
||||
"resCode.40000", "TB_ERR_999");
|
||||
setupMock("GRP", template, cp);
|
||||
|
||||
Object result = handler.generateNonStandardErrorResponseMessage(
|
||||
"GRP", "ADP", new Properties(), null,
|
||||
toEaiMessage(buildMsg("40000", "오류")));
|
||||
|
||||
assertEquals("{\"resCode\":\"TB_ERR_999\",\"extra\":\"value\",\"resMessage\":\"오류\"}", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("convert.fields 에 등록된 필드가 JSON 루트에 없어도 예외 없이 처리")
|
||||
void JSON에_없는_필드_등록시_예외_없음() throws Exception {
|
||||
String template = "{\"resCode\":\"${MSG.MAIN_MSG.outp_msg_cd}\"}";
|
||||
Properties cp = convertProps("GRP",
|
||||
"resCode,nonExistField",
|
||||
"resCode.40000", "TB_ERR_999",
|
||||
"nonExistField.40000", "MAPPED");
|
||||
setupMock("GRP", template, cp);
|
||||
|
||||
Object result = handler.generateNonStandardErrorResponseMessage(
|
||||
"GRP", "ADP", new Properties(), null,
|
||||
toEaiMessage(buildMsg("40000", "")));
|
||||
|
||||
// nonExistField 는 getJsonValue 가 null 반환 → 건너뜀, 예외 없음
|
||||
assertEquals("{\"resCode\":\"TB_ERR_999\"}", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("inboundAdapterGroupName 이 달라지면 다른 convert.fields 키를 사용")
|
||||
void 다른_어댑터그룹_다른_키_사용() throws Exception {
|
||||
String template = "{\"resCode\":\"${MSG.MAIN_MSG.outp_msg_cd}\"}";
|
||||
Properties cp = new Properties();
|
||||
cp.setProperty("GROUP_A.convert.fields", "resCode");
|
||||
cp.setProperty("GROUP_A.resCode.40000", "A_MAPPED");
|
||||
cp.setProperty("GROUP_B.convert.fields", "resCode");
|
||||
cp.setProperty("GROUP_B.resCode.40000", "B_MAPPED");
|
||||
PropManager mockProp = Mockito.mock(PropManager.class);
|
||||
Mockito.when(mockProp.getProperty(
|
||||
eq(TemplateAdapterErrorMsgHandler.PROP_GROUP),
|
||||
anyString())).thenReturn(template);
|
||||
Mockito.when(mockProp.getProperties(
|
||||
eq(TemplateCodeConvertAdapterErrorMsgHandler.PROP_GROUP))).thenReturn(cp);
|
||||
injectMockPropManager(mockProp);
|
||||
|
||||
EAIMessage msg = toEaiMessage(buildMsg("40000", ""));
|
||||
|
||||
Object resultA = handler.generateNonStandardErrorResponseMessage(
|
||||
"GROUP_A", "ADP", new Properties(), null, msg);
|
||||
Object resultB = handler.generateNonStandardErrorResponseMessage(
|
||||
"GROUP_B", "ADP", new Properties(), null, msg);
|
||||
|
||||
assertEquals("{\"resCode\":\"A_MAPPED\"}", resultA);
|
||||
assertEquals("{\"resCode\":\"B_MAPPED\"}", resultB);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
-466
@@ -1,466 +0,0 @@
|
||||
package com.eactive.eai.adapter.http.dynamic.filter;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import javax.crypto.KeyGenerator;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
|
||||
import org.springframework.context.support.GenericApplicationContext;
|
||||
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.InCryptoFilter;
|
||||
import com.eactive.eai.adapter.http.filter.AbstractCryptoFilter;
|
||||
import com.eactive.eai.common.hsm.HsmCryptoService;
|
||||
import com.eactive.eai.common.hsm.HsmManager;
|
||||
import com.eactive.eai.common.property.PropManager;
|
||||
import com.eactive.eai.common.security.CryptoModuleConfigVO;
|
||||
import com.eactive.eai.common.security.CryptoModuleManager;
|
||||
import com.eactive.eai.common.security.CryptoModuleService;
|
||||
import com.eactive.eai.common.security.keyderiv.strategy.HsmContextSha256KeyDerivationStrategy;
|
||||
import com.eactive.eai.common.security.keyderiv.strategy.HsmKeyDerivationStrategy;
|
||||
import com.eactive.eai.common.security.loader.CryptoModuleConfigLoader;
|
||||
import com.eactive.eai.common.security.mapper.CryptoModuleConfigMapper;
|
||||
import com.eactive.eai.common.util.ApplicationContextProvider;
|
||||
import com.eactive.eai.data.entity.onl.security.CryptoModuleConfig;
|
||||
|
||||
/**
|
||||
* CryptoFilter HSM 연동 통합 테스트 (SoftHSM2 / SunPKCS11)
|
||||
*
|
||||
* SoftHSM2에서 MASTER_KEY를 조회하여 키를 도출한 뒤
|
||||
* InCryptoFilter 의 암복호화 전체 흐름을 검증한다.
|
||||
*
|
||||
* 사전 조건:
|
||||
* C:\SoftHSM2 에 SoftHSM2 설치 (미설치 시 자동 건너뜀)
|
||||
* MASTER_KEY alias는 없으면 자동 생성됨
|
||||
*
|
||||
* 검증 전략:
|
||||
* HSM → 키 도출 → CryptoModuleExtension → InCryptoFilter doPostFilter(암호화) → doPreFilter(복호화) → 원문 일치
|
||||
*/
|
||||
@TestMethodOrder(MethodOrderer.DisplayName.class)
|
||||
public class CryptoFilterHsmIntegrationTest {
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 상수
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
private static final String SOFTHSM2_DLL = "C:/SoftHSM2/lib/softhsm2-x64.dll";
|
||||
private static final String SOFTHSM2_UTIL = "C:/SoftHSM2/bin/softhsm2-util.exe";
|
||||
private static final String TOKEN_LABEL = "eapim-test";
|
||||
private static final String PIN = "1234";
|
||||
private static final String MASTER_KEY_ALIAS = "MASTER_KEY";
|
||||
|
||||
/** HsmKeyDerivationStrategy: HSM 마스터키를 파생 없이 직접 사용 */
|
||||
private static final String MOD_HSM_GCM = "HSM_GCM";
|
||||
/** HsmContextSha256KeyDerivationStrategy: HSM 마스터키 + 컨텍스트값 SHA-256 파생 */
|
||||
private static final String MOD_CTX_SHA_GCM = "CTX_SHA256_GCM";
|
||||
|
||||
private static final String CTX_KEY = "X-Api-Group-Seq";
|
||||
private static final String CTX_VAL_A = "GROUP-A";
|
||||
private static final String CTX_VAL_B = "GROUP-B";
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 정적 필드
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
private static GenericApplicationContext springCtx;
|
||||
private static HsmManager hsmManager;
|
||||
private static File tempCfgFile;
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 내부 클래스: runtimeContext를 고정값으로 반환하는 필터
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
static class ContextAwareCryptoFilter extends InCryptoFilter {
|
||||
private final String key;
|
||||
private final String value;
|
||||
|
||||
ContextAwareCryptoFilter(String key, String value) {
|
||||
this.key = key;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Map<String, String> buildRuntimeContext(Properties prop, HttpServletRequest request) {
|
||||
Map<String, String> ctx = new HashMap<>();
|
||||
ctx.put(key, value);
|
||||
return ctx;
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 인스턴스 필드
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
private HttpServletRequest mockReq;
|
||||
private HttpServletResponse mockRes;
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 전체 설정 / 해제
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
@BeforeAll
|
||||
static void setUpAll() throws Exception {
|
||||
assumeTrue(new File(SOFTHSM2_DLL).exists(),
|
||||
"SoftHSM2 미설치 (C:/SoftHSM2) - 테스트 건너뜀");
|
||||
System.setProperty("SOFTHSM2_CONF", "C:\\SoftHSM2\\etc\\softhsm2.conf");
|
||||
|
||||
// 1. 토큰 초기화
|
||||
ensureTokenInitialized();
|
||||
|
||||
// 2. PKCS11 설정 문자열
|
||||
// attributes(*,...): generate/import 모두 CKA_SENSITIVE=false → getEncoded() 사용 가능
|
||||
String cfgContent = "name = SoftHSM\n"
|
||||
+ "library = " + SOFTHSM2_DLL + "\n"
|
||||
+ "slotListIndex = 0\n"
|
||||
+ "attributes(*, CKO_SECRET_KEY, CKK_AES) = {\n"
|
||||
+ " CKA_SENSITIVE = false\n"
|
||||
+ " CKA_EXTRACTABLE = true\n"
|
||||
+ "}\n";
|
||||
tempCfgFile = File.createTempFile("pkcs11-filter-it-", ".cfg");
|
||||
Files.write(tempCfgFile.toPath(), cfgContent.getBytes("UTF-8"));
|
||||
|
||||
// 3. Mock PropManager (DB 없이 HSM 설정값 제공)
|
||||
PropManager mockPropManager = mock(PropManager.class);
|
||||
when(mockPropManager.getProperty("HSM", "PKCS11_CONFIG")).thenReturn(cfgContent);
|
||||
when(mockPropManager.getProperty("HSM", "PIN")).thenReturn(PIN);
|
||||
when(mockPropManager.getProperty(eq("HSM"), eq("CACHE_RELOAD_YN"), anyString())).thenReturn("N");
|
||||
|
||||
// 4. HsmManager (private 생성자 → 리플렉션)
|
||||
Constructor<HsmManager> hsmCtor = HsmManager.class.getDeclaredConstructor();
|
||||
hsmCtor.setAccessible(true);
|
||||
hsmManager = hsmCtor.newInstance();
|
||||
|
||||
// 5. CryptoModuleManager (private 생성자 → 리플렉션)
|
||||
CryptoModuleConfigLoader mockLoader = mock(CryptoModuleConfigLoader.class);
|
||||
when(mockLoader.findAll()).thenReturn(buildModuleConfigs());
|
||||
|
||||
Constructor<CryptoModuleManager> managerCtor = CryptoModuleManager.class.getDeclaredConstructor();
|
||||
managerCtor.setAccessible(true);
|
||||
CryptoModuleManager manager = managerCtor.newInstance();
|
||||
|
||||
CryptoModuleService cryptoService = new CryptoModuleService();
|
||||
HsmCryptoService hsmCryptoService = new HsmCryptoService();
|
||||
|
||||
// 6. Spring ApplicationContext 구성
|
||||
springCtx = new GenericApplicationContext();
|
||||
springCtx.getBeanFactory().registerSingleton("propManager", mockPropManager);
|
||||
springCtx.getBeanFactory().registerSingleton("hsmManager", hsmManager);
|
||||
springCtx.getBeanFactory().registerSingleton("hsmCryptoService", hsmCryptoService);
|
||||
springCtx.getBeanFactory().registerSingleton("cryptoModuleConfigLoader", mockLoader);
|
||||
springCtx.getBeanFactory().registerSingleton("cryptoModuleManager", manager);
|
||||
springCtx.getBeanFactory().registerSingleton("cryptoModuleService", cryptoService);
|
||||
springCtx.getBeanFactory().registerSingleton("cryptoModuleConfigMapper", testMapper());
|
||||
springCtx.registerBeanDefinition("applicationContextProvider",
|
||||
BeanDefinitionBuilder.genericBeanDefinition(ApplicationContextProvider.class)
|
||||
.getBeanDefinition());
|
||||
springCtx.refresh();
|
||||
|
||||
// 7. HsmManager 시작 (SunPKCS11 Provider 초기화 + KeyStore 오픈)
|
||||
hsmManager.start();
|
||||
assertTrue(hsmManager.isReady(), "HsmManager 초기화 실패");
|
||||
System.out.println("[HSM] Provider: " + hsmManager.getPkcs11Provider().getName());
|
||||
|
||||
// 8. MASTER_KEY 등록 (없으면 자동 생성)
|
||||
ensureMasterKey();
|
||||
|
||||
// 9. CryptoModuleManager 시작 (모듈 설정 로드)
|
||||
manager.start();
|
||||
System.out.println("[Crypto] 모듈 로드 완료");
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void tearDownAll() throws Exception {
|
||||
if (hsmManager != null && hsmManager.isStarted()) hsmManager.stop();
|
||||
if (springCtx != null) springCtx.close();
|
||||
if (tempCfgFile != null) tempCfgFile.delete();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
mockReq = mock(HttpServletRequest.class);
|
||||
mockRes = mock(HttpServletResponse.class);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 1. HsmKeyDerivationStrategy — HSM 마스터키 직접 사용 (InCryptoFilter)
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
@DisplayName("1-1. FIELD/GCM HsmKey — doPostFilter 암호화 → doPreFilter 복호화 라운드트립")
|
||||
void testHsmGcm_field_roundTrip() throws Exception {
|
||||
InCryptoFilter filter = new InCryptoFilter();
|
||||
String original = "{\"acno\":\"1234567890\",\"amount\":\"100000\"}";
|
||||
|
||||
Properties prop = new Properties();
|
||||
prop.setProperty(AbstractCryptoFilter.PROP_MODULE_NAME, MOD_HSM_GCM);
|
||||
// SCOPE 기본값 FIELD, 경로 기본값 사용
|
||||
|
||||
// 암호화: body 전체 → /encrypted_data 필드
|
||||
String encrypted = (String) filter.doPostFilter("G", "A", original, prop, mockReq, mockRes);
|
||||
System.out.println("[1-1] encrypted: " + encrypted);
|
||||
assertTrue(encrypted.contains("encrypted_data"), "/encrypted_data 필드가 있어야 한다");
|
||||
|
||||
// 복호화: /encrypted_data 필드 → body 전체 교체
|
||||
String decrypted = (String) filter.doPreFilter("G", "A", encrypted, prop, mockReq, mockRes);
|
||||
System.out.println("[1-1] decrypted: " + decrypted);
|
||||
assertEquals(original, decrypted);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("1-2. BODY/GCM HsmKey — doPostFilter 암호화 → doPreFilter 복호화 라운드트립")
|
||||
void testHsmGcm_body_roundTrip() throws Exception {
|
||||
InCryptoFilter filter = new InCryptoFilter();
|
||||
String original = "{\"acno\":\"1234567890\",\"amount\":\"100000\"}";
|
||||
|
||||
Properties prop = new Properties();
|
||||
prop.setProperty(AbstractCryptoFilter.PROP_MODULE_NAME, MOD_HSM_GCM);
|
||||
prop.setProperty(AbstractCryptoFilter.PROP_SCOPE, "BODY");
|
||||
|
||||
// 암호화: body 전체 → Base64 암호문
|
||||
String encrypted = (String) filter.doPostFilter("G", "A", original, prop, mockReq, mockRes);
|
||||
System.out.println("[1-2] encrypted(Base64): " + encrypted);
|
||||
assertNotEquals(original, encrypted, "암호문은 평문과 달라야 한다");
|
||||
|
||||
// 복호화: Base64 암호문 → 원문
|
||||
String decrypted = (String) filter.doPreFilter("G", "A", encrypted, prop, mockReq, mockRes);
|
||||
System.out.println("[1-2] decrypted: " + decrypted);
|
||||
assertEquals(original, decrypted);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("1-3. FIELD/GCM HsmKey + AAD 헤더 — 동일 요청 ID로 암복호화 성공")
|
||||
void testHsmGcm_field_withAad_success() throws Exception {
|
||||
InCryptoFilter filter = new InCryptoFilter();
|
||||
String original = "{\"amount\":\"500000\"}";
|
||||
String requestId = "REQ-20240101-001";
|
||||
|
||||
when(mockReq.getHeader("X-Request-Id")).thenReturn(requestId);
|
||||
|
||||
Properties prop = new Properties();
|
||||
prop.setProperty(AbstractCryptoFilter.PROP_MODULE_NAME, MOD_HSM_GCM);
|
||||
prop.setProperty(AbstractCryptoFilter.PROP_AAD_HEADER, "X-Request-Id");
|
||||
|
||||
String encrypted = (String) filter.doPostFilter("G", "A", original, prop, mockReq, mockRes);
|
||||
String decrypted = (String) filter.doPreFilter( "G", "A", encrypted, prop, mockReq, mockRes);
|
||||
System.out.println("[1-3] decrypted: " + decrypted);
|
||||
assertEquals(original, decrypted);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("1-4. FIELD/GCM HsmKey + AAD 헤더 — 다른 요청 ID로 복호화 시 GCM 인증 실패")
|
||||
void testHsmGcm_field_withAad_wrongAad_fails() throws Exception {
|
||||
InCryptoFilter filter = new InCryptoFilter();
|
||||
String original = "{\"amount\":\"500000\"}";
|
||||
|
||||
// 암호화 시 요청 ID
|
||||
HttpServletRequest encReq = mock(HttpServletRequest.class);
|
||||
when(encReq.getHeader("X-Request-Id")).thenReturn("REQ-CORRECT");
|
||||
|
||||
// 복호화 시 다른 요청 ID
|
||||
HttpServletRequest decReq = mock(HttpServletRequest.class);
|
||||
when(decReq.getHeader("X-Request-Id")).thenReturn("REQ-WRONG");
|
||||
|
||||
Properties prop = new Properties();
|
||||
prop.setProperty(AbstractCryptoFilter.PROP_MODULE_NAME, MOD_HSM_GCM);
|
||||
prop.setProperty(AbstractCryptoFilter.PROP_AAD_HEADER, "X-Request-Id");
|
||||
|
||||
String encrypted = (String) filter.doPostFilter("G", "A", original, prop, encReq, mockRes);
|
||||
|
||||
assertThrows(Exception.class,
|
||||
() -> filter.doPreFilter("G", "A", encrypted, prop, decReq, mockRes),
|
||||
"잘못된 AAD로 GCM 복호화 시 예외가 발생해야 한다");
|
||||
System.out.println("[1-4] 다른 AAD 복호화 예외 확인 완료");
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 2. HsmContextSha256KeyDerivationStrategy — 컨텍스트 기반 SHA-256 파생 키
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
@DisplayName("2-1. FIELD/GCM ContextSha256 — 동일 컨텍스트로 암복호화 라운드트립")
|
||||
void testCtxSha256Gcm_field_roundTrip() throws Exception {
|
||||
InCryptoFilter filter = new ContextAwareCryptoFilter(CTX_KEY, CTX_VAL_A);
|
||||
String original = "{\"accNo\":\"0011234567890\",\"amount\":\"50000\"}";
|
||||
|
||||
Properties prop = new Properties();
|
||||
prop.setProperty(AbstractCryptoFilter.PROP_MODULE_NAME, MOD_CTX_SHA_GCM);
|
||||
|
||||
String encrypted = (String) filter.doPostFilter("G", "A", original, prop, mockReq, mockRes);
|
||||
System.out.println("[2-1] encrypted: " + encrypted);
|
||||
assertTrue(encrypted.contains("encrypted_data"));
|
||||
|
||||
String decrypted = (String) filter.doPreFilter("G", "A", encrypted, prop, mockReq, mockRes);
|
||||
System.out.println("[2-1] decrypted: " + decrypted);
|
||||
assertEquals(original, decrypted);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("2-2. FIELD/GCM ContextSha256 — 암호화와 다른 컨텍스트로 복호화 시 GCM 인증 실패")
|
||||
void testCtxSha256Gcm_differentContext_throwsException() throws Exception {
|
||||
InCryptoFilter encFilter = new ContextAwareCryptoFilter(CTX_KEY, CTX_VAL_A);
|
||||
InCryptoFilter decFilter = new ContextAwareCryptoFilter(CTX_KEY, CTX_VAL_B);
|
||||
String original = "{\"data\":\"sensitive\"}";
|
||||
|
||||
Properties prop = new Properties();
|
||||
prop.setProperty(AbstractCryptoFilter.PROP_MODULE_NAME, MOD_CTX_SHA_GCM);
|
||||
|
||||
String encrypted = (String) encFilter.doPostFilter("G", "A", original, prop, mockReq, mockRes);
|
||||
|
||||
assertThrows(Exception.class,
|
||||
() -> decFilter.doPreFilter("G", "A", encrypted, prop, mockReq, mockRes),
|
||||
"다른 컨텍스트 키로 파생된 키는 복호화에 실패해야 한다");
|
||||
System.out.println("[2-2] 다른 컨텍스트 복호화 예외 확인 완료");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("2-3. FIELD/GCM ContextSha256 — 컨텍스트별 독립 암복호화 (GROUP-A, GROUP-B 각각 성공)")
|
||||
void testCtxSha256Gcm_perGroupRoundTrip() throws Exception {
|
||||
InCryptoFilter filterA = new ContextAwareCryptoFilter(CTX_KEY, CTX_VAL_A);
|
||||
InCryptoFilter filterB = new ContextAwareCryptoFilter(CTX_KEY, CTX_VAL_B);
|
||||
String plainA = "{\"group\":\"A\",\"amount\":\"1000\"}";
|
||||
String plainB = "{\"group\":\"B\",\"amount\":\"2000\"}";
|
||||
|
||||
Properties prop = new Properties();
|
||||
prop.setProperty(AbstractCryptoFilter.PROP_MODULE_NAME, MOD_CTX_SHA_GCM);
|
||||
|
||||
String encA = (String) filterA.doPostFilter("G", "A", plainA, prop, mockReq, mockRes);
|
||||
String encB = (String) filterB.doPostFilter("G", "B", plainB, prop, mockReq, mockRes);
|
||||
|
||||
assertEquals(plainA, (String) filterA.doPreFilter("G", "A", encA, prop, mockReq, mockRes));
|
||||
assertEquals(plainB, (String) filterB.doPreFilter("G", "B", encB, prop, mockReq, mockRes));
|
||||
System.out.println("[2-3] GROUP-A, GROUP-B 각각 독립 암복호화 성공");
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 헬퍼
|
||||
// =========================================================================
|
||||
|
||||
private static List<CryptoModuleConfig> buildModuleConfigs() {
|
||||
return Arrays.asList(
|
||||
buildDynamic(MOD_HSM_GCM, "AES", "GCM", "NoPadding",
|
||||
HsmKeyDerivationStrategy.class.getName(),
|
||||
"{\"hsmKeyAlias\":\"" + MASTER_KEY_ALIAS + "\"}"),
|
||||
buildDynamic(MOD_CTX_SHA_GCM, "AES", "GCM", "NoPadding",
|
||||
HsmContextSha256KeyDerivationStrategy.class.getName(),
|
||||
"{\"hsmKeyAlias\":\"" + MASTER_KEY_ALIAS + "\",\"contextKey\":\"" + CTX_KEY + "\"}")
|
||||
);
|
||||
}
|
||||
|
||||
private static CryptoModuleConfig buildDynamic(String name, String alg, String mode, String padding,
|
||||
String strategy, String params) {
|
||||
CryptoModuleConfig c = new CryptoModuleConfig();
|
||||
c.setCryptoId(UUID.randomUUID().toString());
|
||||
c.setCryptoName(name);
|
||||
c.setAlgType(alg);
|
||||
c.setCipherMode(mode);
|
||||
c.setPadding(padding);
|
||||
c.setKeySourceType("DYNAMIC");
|
||||
c.setKeyDerivStrategy(strategy);
|
||||
c.setKeyDerivParams(params);
|
||||
c.setCacheYn("Y");
|
||||
c.setCacheTtlSec(60);
|
||||
c.setUseYn("Y");
|
||||
// ivHex = null: GCM에서 IV를 AAD 대체값으로 사용하지 않도록 의도적으로 미설정
|
||||
return c;
|
||||
}
|
||||
|
||||
private static void ensureMasterKey() throws Exception {
|
||||
java.security.KeyStore ks = hsmManager.getKeyStore();
|
||||
|
||||
// 이전 실행 키 삭제 (sensitive 여부 무관하게 항상 고정키로 재등록)
|
||||
if (ks.containsAlias(MASTER_KEY_ALIAS)) {
|
||||
ks.deleteEntry(MASTER_KEY_ALIAS);
|
||||
System.out.println("[HSM] 기존 MASTER_KEY 삭제");
|
||||
}
|
||||
|
||||
// CryptoModuleServiceTest.KEY_128 과 동일한 고정 키 → 두 테스트 간 암호문 비교 가능
|
||||
// attributes(*, CKO_SECRET_KEY, CKK_AES) 지시어로 임포트 시 CKA_SENSITIVE=false 적용
|
||||
byte[] keyBytes = "0123456789abcdef".getBytes(StandardCharsets.UTF_8);
|
||||
SecretKey fixedKey = new SecretKeySpec(keyBytes, "AES");
|
||||
ks.setKeyEntry(MASTER_KEY_ALIAS, fixedKey, null, null);
|
||||
|
||||
// 임포트 후 getEncoded() 검증
|
||||
SecretKey stored = (SecretKey) ks.getKey(MASTER_KEY_ALIAS, null);
|
||||
byte[] encoded = stored.getEncoded();
|
||||
System.out.println("[HSM] MASTER_KEY 등록 완료: alias=" + MASTER_KEY_ALIAS
|
||||
+ " / getEncoded()=" + (encoded != null ? encoded.length + "bytes, " + new String(encoded) : "null (추출 불가!)"));
|
||||
}
|
||||
|
||||
private static void ensureTokenInitialized() throws Exception {
|
||||
ProcessBuilder pb = new ProcessBuilder(
|
||||
SOFTHSM2_UTIL, "--init-token", "--free",
|
||||
"--label", TOKEN_LABEL, "--pin", PIN, "--so-pin", PIN);
|
||||
pb.redirectErrorStream(true);
|
||||
Process p = pb.start();
|
||||
String out = readOutput(p);
|
||||
p.waitFor(10, TimeUnit.SECONDS);
|
||||
System.out.println("[SoftHSM2] init-token: " + out.trim());
|
||||
}
|
||||
|
||||
private static CryptoModuleConfigMapper testMapper() {
|
||||
return new CryptoModuleConfigMapper() {
|
||||
@Override
|
||||
public CryptoModuleConfigVO toVo(CryptoModuleConfig e) {
|
||||
CryptoModuleConfigVO vo = new CryptoModuleConfigVO();
|
||||
vo.setCryptoId(e.getCryptoId());
|
||||
vo.setCryptoName(e.getCryptoName());
|
||||
vo.setCryptoDesc(e.getCryptoDesc());
|
||||
vo.setAlgType(e.getAlgType());
|
||||
vo.setCipherMode(e.getCipherMode());
|
||||
vo.setPadding(e.getPadding());
|
||||
vo.setIvHex(e.getIvHex());
|
||||
vo.setKeySourceType(e.getKeySourceType());
|
||||
vo.setEncKeyHex(e.getEncKeyHex());
|
||||
vo.setDecKeyHex(e.getDecKeyHex());
|
||||
vo.setKeyDerivStrategy(e.getKeyDerivStrategy());
|
||||
vo.setKeyDerivParams(e.getKeyDerivParams());
|
||||
vo.setCacheYn(e.getCacheYn());
|
||||
vo.setCacheTtlSec(e.getCacheTtlSec());
|
||||
vo.setUseYn(e.getUseYn());
|
||||
return vo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CryptoModuleConfig toEntity(CryptoModuleConfigVO vo) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static String readOutput(Process p) throws Exception {
|
||||
InputStream is = p.getInputStream();
|
||||
byte[] buf = new byte[4096];
|
||||
StringBuilder sb = new StringBuilder();
|
||||
int len;
|
||||
while ((len = is.read(buf)) != -1) {
|
||||
sb.append(new String(buf, 0, len, "UTF-8"));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package com.eactive.eai.agent.encryption;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* EncryptionManager 단위 테스트 — DAMO 솔루션 모드.
|
||||
*
|
||||
* damo-manager.jar 가 DAMO 라이브러리(com.penta.scpdb.ScpDbAgent) 없이 로드되면
|
||||
* 자동으로 FAKE MODE 로 동작한다:
|
||||
* encrypt(plain) → Base64 인코딩
|
||||
* decrypt(b64) → Base64 디코딩
|
||||
* 따라서 encrypt → decrypt 라운드트립이 완전히 검증 가능하다.
|
||||
*
|
||||
* EncryptionManager 생성자가 private 이므로 리플렉션으로 인스턴스를 생성하고
|
||||
* 필드를 직접 주입한다.
|
||||
*/
|
||||
class EncryptionManagerTest {
|
||||
|
||||
private EncryptionManager manager;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
Constructor<EncryptionManager> ctor = EncryptionManager.class.getDeclaredConstructor();
|
||||
ctor.setAccessible(true);
|
||||
manager = ctor.newInstance();
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 헬퍼
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
private void setField(String name, Object value) throws Exception {
|
||||
Field f = EncryptionManager.class.getDeclaredField(name);
|
||||
f.setAccessible(true);
|
||||
f.set(manager, value);
|
||||
}
|
||||
|
||||
private void enableDamo() throws Exception {
|
||||
setField("encryptYN", "Y");
|
||||
setField("dbEncryptSolutionName", "DAMO");
|
||||
}
|
||||
|
||||
private void disableEncrypt() throws Exception {
|
||||
setField("encryptYN", "N");
|
||||
setField("dbEncryptSolutionName", "DAMO");
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 1. DAMO 모드 — encrypt + decrypt 라운드트립
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
@DisplayName("1-1. DAMO 암호화 후 복호화 시 원문 복원 — 한글")
|
||||
void testRoundTrip_korean() throws Exception {
|
||||
enableDamo();
|
||||
String plain = "홍길동";
|
||||
String encrypted = manager.encryptDBData(plain);
|
||||
assertNotEquals(plain, encrypted, "암호화 결과가 원문과 달라야 한다");
|
||||
assertEquals(plain, manager.decryptDBData(encrypted));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("1-2. DAMO 암호화 후 복호화 시 원문 복원 — 영문/숫자 혼합")
|
||||
void testRoundTrip_alphanumeric() throws Exception {
|
||||
enableDamo();
|
||||
String plain = "test@example.com";
|
||||
String encrypted = manager.encryptDBData(plain);
|
||||
assertNotEquals(plain, encrypted);
|
||||
assertEquals(plain, manager.decryptDBData(encrypted));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("1-3. DAMO 암호화 후 복호화 시 원문 복원 — 주민등록번호 형식")
|
||||
void testRoundTrip_idNumber() throws Exception {
|
||||
enableDamo();
|
||||
String plain = "900101-1234567";
|
||||
String encrypted = manager.encryptDBData(plain);
|
||||
// 숫자와 '-' 만으로 이루어진 원문은 암호화되어 Base64 형식으로 변환된다
|
||||
assertNotEquals(plain, encrypted);
|
||||
assertEquals(plain, manager.decryptDBData(encrypted));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("1-4. DAMO 암호화 후 복호화 시 원문 복원 — 다양한 입력 일괄 검증")
|
||||
void testRoundTrip_multipleValues() throws Exception {
|
||||
enableDamo();
|
||||
String[] inputs = {
|
||||
"홍길동",
|
||||
"test@example.com",
|
||||
"900101-1234567",
|
||||
"ABC테스트123",
|
||||
"special chars: !@#$%",
|
||||
"긴문자열긴문자열긴문자열긴문자열긴문자열긴문자열긴문자열긴문자열긴문자열긴문자열"
|
||||
};
|
||||
for (String input : inputs) {
|
||||
String encrypted = manager.encryptDBData(input);
|
||||
String decrypted = manager.decryptDBData(encrypted);
|
||||
assertEquals(input, decrypted, "라운드트립 불일치: [" + input + "]");
|
||||
}
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 2. 암호화 비활성(encryptYN=N)
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
@DisplayName("2-1. encryptYN=N 이면 encryptDBData 가 원문 그대로 반환")
|
||||
void testEncrypt_disabled_returnsPlain() throws Exception {
|
||||
disableEncrypt();
|
||||
String plain = "홍길동";
|
||||
assertEquals(plain, manager.encryptDBData(plain));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("2-2. encryptYN=N 상태의 원문은 isEncrypted=false 이므로 decryptDBData 도 원문 반환")
|
||||
void testDecrypt_plainTextNotBase64_returnsOriginal() throws Exception {
|
||||
disableEncrypt();
|
||||
String plain = "홍길동";
|
||||
assertEquals(plain, manager.decryptDBData(plain));
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 3. 특수 입력 처리
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
@DisplayName("3-1. decryptDBData — null 입력 시 null 반환")
|
||||
void testDecrypt_null() throws Exception {
|
||||
enableDamo();
|
||||
assertNull(manager.decryptDBData(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("3-2. decryptDBData — 빈 문자열 입력 시 빈 문자열 반환")
|
||||
void testDecrypt_empty() throws Exception {
|
||||
enableDamo();
|
||||
assertEquals("", manager.decryptDBData(""));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("3-3. decryptDBData — 숫자로만 구성된 값은 복호화하지 않고 원문 반환 (연락처)")
|
||||
void testDecrypt_numericOnly_returnsOriginal() throws Exception {
|
||||
enableDamo();
|
||||
assertEquals("01012345678", manager.decryptDBData("01012345678"));
|
||||
assertEquals("0101234-5678", manager.decryptDBData("0101234-5678"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("3-4. decryptDBData — Base64 형식이 아닌 문자열은 원문 반환")
|
||||
void testDecrypt_nonBase64_returnsOriginal() throws Exception {
|
||||
enableDamo();
|
||||
String plain = "이름: 홍길동"; // 공백 포함, Base64 문자셋 아님
|
||||
assertEquals(plain, manager.decryptDBData(plain));
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 4. isEncrypt() / getEncryptYN() 상태 확인
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
@DisplayName("4-1. encryptYN=Y 이면 isEncrypt()=true")
|
||||
void testIsEncrypt_true() throws Exception {
|
||||
setField("encryptYN", "Y");
|
||||
assertTrue(manager.isEncrypt());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("4-2. encryptYN=N 이면 isEncrypt()=false")
|
||||
void testIsEncrypt_false() throws Exception {
|
||||
setField("encryptYN", "N");
|
||||
assertFalse(manager.isEncrypt());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("4-3. getDBEncryptSolutionName() 반환값 확인")
|
||||
void testGetDBEncryptSolutionName() throws Exception {
|
||||
setField("dbEncryptSolutionName", "DAMO");
|
||||
assertEquals("DAMO", manager.getDBEncryptSolutionName());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
package com.eactive.eai.common.hsm;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.lang.reflect.Method;
|
||||
import java.nio.file.Files;
|
||||
import java.security.KeyStore;
|
||||
import java.security.KeyStoreException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.Provider;
|
||||
import java.security.Security;
|
||||
import java.security.UnrecoverableKeyException;
|
||||
import java.security.spec.InvalidKeySpecException;
|
||||
import java.util.Base64;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.SecretKeyFactory;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
public class HsmAddKeyTest {
|
||||
|
||||
/**
|
||||
* JDK 버전에 따라 SunPKCS11 Provider 를 생성한다.
|
||||
*
|
||||
* JDK 8 : SunPKCS11(InputStream) 생성자를 리플렉션으로 호출 JDK 9+:
|
||||
* Provider.configure(configFilePath) 를 리플렉션으로 호출
|
||||
*
|
||||
* 두 경로 모두 리플렉션을 사용하므로 컴파일 타임에 JDK 버전 의존성이 없다.
|
||||
*/
|
||||
static Provider createProvider(String cfgContent) throws Exception {
|
||||
String javaVersion = System.getProperty("java.version");
|
||||
if (javaVersion.startsWith("1.")) {
|
||||
// JDK 8: new SunPKCS11(InputStream)
|
||||
InputStream is = new ByteArrayInputStream(cfgContent.getBytes("UTF-8"));
|
||||
return (Provider) Class.forName("sun.security.pkcs11.SunPKCS11").getConstructor(InputStream.class)
|
||||
.newInstance(is);
|
||||
} else {
|
||||
// JDK 9+: Security.getProvider("SunPKCS11").configure(configFilePath)
|
||||
// configure() 는 JDK 9 에서 추가된 메서드이므로 리플렉션으로 호출
|
||||
File tmp = File.createTempFile("pkcs11-hsm-", ".cfg");
|
||||
tmp.deleteOnExit();
|
||||
Files.write(tmp.toPath(), cfgContent.getBytes("UTF-8"));
|
||||
Provider base = Security.getProvider("SunPKCS11");
|
||||
Method configure = Provider.class.getMethod("configure", String.class);
|
||||
return (Provider) configure.invoke(base, tmp.getAbsolutePath());
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
// String config = "name = ProtectServer\r\n"
|
||||
// + "library = /usr/safenet/protecttoolkit5/ptk/lib/libcryptoki.so\r\n"
|
||||
// + "slot = 0";
|
||||
|
||||
// String config = "name = SoftHSM\r\nlibrary = C:/SoftHSM2/lib/softhsm2-x64.dll\r\nslotListIndex = 0\r\n";
|
||||
|
||||
String config = "name = SoftHSM\r\n"
|
||||
+ "library = C:/SoftHSM2/lib/softhsm2-x64.dll\r\n"
|
||||
+ "slotListIndex = 0\r\n"
|
||||
+ "attributes(*, CKO_SECRET_KEY, CKK_AES) = {\r\n"
|
||||
+ " CKA_TOKEN = true\r\n"
|
||||
+ " CKA_SENSITIVE = false\r\n"
|
||||
+ " CKA_EXTRACTABLE = true\r\n"
|
||||
+ " CKA_ENCRYPT = true\r\n"
|
||||
+ " CKA_DECRYPT = true\r\n"
|
||||
+ "}\r\n";
|
||||
|
||||
KeyStore keyStore;
|
||||
// Provider pkcs11Provider = HsmManagerSingleTest.createProvider(config);
|
||||
InputStream is = new ByteArrayInputStream(config.getBytes("UTF-8"));
|
||||
Provider pkcs11Provider = (Provider) Class.forName("sun.security.pkcs11.SunPKCS11")
|
||||
.getConstructor(InputStream.class).newInstance(is);
|
||||
Security.addProvider(pkcs11Provider);
|
||||
String pin = "1234";
|
||||
keyStore = KeyStore.getInstance("PKCS11", pkcs11Provider);
|
||||
|
||||
char[] pinChars = (pin != null) ? pin.toCharArray() : null;
|
||||
keyStore.load(null, pinChars);
|
||||
|
||||
// addKey("20250916_openapi_erpbank_t", "55187afc5d36a2e3b71f3bf992947389964ac5ea0bc8ebe2297265134fa34cb9",
|
||||
// keyStore, pkcs11Provider);
|
||||
// addKey("20240401_openapi_kakaobank_t", "f009328cb94f5c866ff730735ce8031b43ca84f9266ced641b4046c6a5c21038",
|
||||
// keyStore, pkcs11Provider);
|
||||
// addKey("20250620_openapi_coocon_t", "3e7a7673392c424e58265c7b6f2e596f7a59542b277472704c3d5d6c70226673",
|
||||
// keyStore, pkcs11Provider);
|
||||
// addKey("20211221_openapi_kakaopay_t", "23667b665037785c3c312a414b6c566d2f3832476b254646727c4d703d484534",
|
||||
// keyStore, pkcs11Provider);
|
||||
//
|
||||
// addKey("20250916_openapi_erpbank_t_0", "55187afc5d36a2e3b71f3bf992947389964ac5ea0bc8ebe2297265134fa34cb9",
|
||||
// keyStore, pkcs11Provider);
|
||||
// addKey("20240401_openapi_kakaobank_t_0", "f009328cb94f5c866ff730735ce8031b43ca84f9266ced641b4046c6a5c21038",
|
||||
// keyStore, pkcs11Provider);
|
||||
// addKey("20250620_openapi_coocon_t_0", "3e7a7673392c424e58265c7b6f2e596f7a59542b277472704c3d5d6c70226673",
|
||||
// keyStore, pkcs11Provider);
|
||||
// addKey("20211221_openapi_kakaopay_t_0", "23667b665037785c3c312a414b6c566d2f3832476b254646727c4d703d484534",
|
||||
// keyStore, pkcs11Provider);
|
||||
|
||||
addKey("20260518_openapi_npayloan_t", "7f7f6608a0c2f28d9a7e53f81b265f12b46f893ffcecc253bdc0561338e10208",
|
||||
keyStore, pkcs11Provider);
|
||||
addKey("20260518_openapi_npayloan_iv_t", "b797008af20f0e1eda6c71d14bec5bb7",
|
||||
keyStore, pkcs11Provider);
|
||||
addKey("20241022_openapi_toss_t", "3051557a6c786475536c4f532f4c6b6b436a4c312f42434947764d336b66306e",
|
||||
keyStore, pkcs11Provider);
|
||||
addKey("20250307_openapi_tossbank_t", "48b8465313d6fc529a9f16c3347cde55a663efaf9ade41429c1cb484398bcf93",
|
||||
keyStore, pkcs11Provider);
|
||||
addKey("20250307_openapi_tossbank_iv_t", "2bdf93b1f872962d2aa2f890e179e3e0",
|
||||
keyStore, pkcs11Provider);
|
||||
addKey("20240524_openapi_banksalad_t", "466166733957513862616a646e55686a353759554c784e4a6463783279767035",
|
||||
keyStore, pkcs11Provider);
|
||||
|
||||
System.out.println("HsmManager] 초기화 완료. Provider=" + pkcs11Provider.getName());
|
||||
|
||||
java.util.Enumeration<String> aliases = keyStore.aliases();
|
||||
StringBuilder aliasList = new StringBuilder();
|
||||
while (aliases.hasMoreElements()) {
|
||||
if (aliasList.length() > 0)
|
||||
aliasList.append(", ");
|
||||
|
||||
String alias = aliases.nextElement();
|
||||
aliasList.append(alias);
|
||||
|
||||
java.security.Key key = keyStore.getKey(alias, null);
|
||||
if (key instanceof SecretKey) {
|
||||
SecretKey secretKey = (SecretKey) key;
|
||||
if (secretKey.getEncoded() != null) {
|
||||
String encBase64 = Base64.getEncoder().encodeToString(secretKey.getEncoded());
|
||||
System.out.println("HsmManager] HSM - alias:" + alias + ", base64:" + encBase64 + ", secretKey:" + secretKey);
|
||||
} else {
|
||||
System.out
|
||||
.println("HsmManager] HSM - secretKey null - alias:" + alias + ", secretKey:" + secretKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
System.out.println("HsmManager] HSM 키 목록: [" + aliasList + "]");
|
||||
}
|
||||
|
||||
private static void addKey(String keyAlias, String keyValue, KeyStore keyStore, Provider pkcs11Provider)
|
||||
throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, InvalidKeySpecException {
|
||||
byte[] keyBytes = hexToBytes(keyValue);
|
||||
|
||||
SecretKeySpec spec = new SecretKeySpec(keyBytes, "AES");
|
||||
SecretKeyFactory factory = SecretKeyFactory.getInstance("AES", pkcs11Provider);
|
||||
SecretKey fixedKey = (SecretKey) factory.generateSecret(spec);
|
||||
|
||||
// SecretKey fixedKey = new SecretKeySpec(keyBytes, "AES");
|
||||
|
||||
keyStore.setKeyEntry(keyAlias, fixedKey, null, null);
|
||||
|
||||
// // 2. wrapping key 생성 (최초 1회만 — 이후엔 재사용)
|
||||
// KeyGenerator wrapKeyGen = KeyGenerator.getInstance("AES", pkcs11Provider);
|
||||
// wrapKeyGen.init(256);
|
||||
// SecretKey wrappingKey = wrapKeyGen.generateKey();
|
||||
//
|
||||
// // 3. 테스트 환경 key 값 지정
|
||||
// byte[] testKeyBytes = hexToBytes(keyValue);
|
||||
// SecretKey targetKeySpec = new SecretKeySpec(testKeyBytes, "AES");
|
||||
//
|
||||
// // 4. wrap
|
||||
// Cipher wrapCipher = Cipher.getInstance("AESWRAP", pkcs11Provider);
|
||||
// wrapCipher.init(Cipher.WRAP_MODE, wrappingKey);
|
||||
// byte[] wrapped = wrapCipher.wrap(targetKeySpec);
|
||||
//
|
||||
// // 5. unwrap → SoftHSM2 내부에 실제 등록
|
||||
// Cipher unwrapCipher = Cipher.getInstance("AESWRAP", pkcs11Provider);
|
||||
// unwrapCipher.init(Cipher.UNWRAP_MODE, wrappingKey);
|
||||
// SecretKey hsmKey = (SecretKey) unwrapCipher.unwrap(wrapped, "AES", Cipher.SECRET_KEY
|
||||
//
|
||||
// );
|
||||
//
|
||||
// // 6. 평문 byte 배열 즉시 제거
|
||||
// Arrays.fill(testKeyBytes, (byte) 0);
|
||||
//
|
||||
// System.out.println("Key 등록 완료: " + hsmKey.getAlgorithm() + " / " + hsmKey.getFormat());
|
||||
//
|
||||
// // 7. 등록 확인 — alias 지정해서 KeyStore에 올리고 싶으면:
|
||||
// keyStore.setKeyEntry(keyAlias, hsmKey, null, null);
|
||||
}
|
||||
|
||||
private static byte[] hexToBytes(String hex) {
|
||||
int len = hex.length();
|
||||
byte[] data = new byte[len / 2];
|
||||
for (int i = 0; i < len; i += 2) {
|
||||
data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + Character.digit(hex.charAt(i + 1), 16));
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
public static String bytesToHex(byte[] bytes) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (byte b : bytes) {
|
||||
sb.append(String.format("%02X", b));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.eactive.eai.common.hsm;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.lang.reflect.Method;
|
||||
import java.nio.file.Files;
|
||||
import java.security.KeyStore;
|
||||
import java.security.Provider;
|
||||
import java.security.Security;
|
||||
import java.util.Base64;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
|
||||
public class HsmManagerSingleTest {
|
||||
|
||||
/**
|
||||
* JDK 버전에 따라 SunPKCS11 Provider 를 생성한다.
|
||||
*
|
||||
* JDK 8 : SunPKCS11(InputStream) 생성자를 리플렉션으로 호출
|
||||
* JDK 9+: Provider.configure(configFilePath) 를 리플렉션으로 호출
|
||||
*
|
||||
* 두 경로 모두 리플렉션을 사용하므로 컴파일 타임에 JDK 버전 의존성이 없다.
|
||||
*/
|
||||
static Provider createProvider(String cfgContent) throws Exception {
|
||||
String javaVersion = System.getProperty("java.version");
|
||||
if (javaVersion.startsWith("1.")) {
|
||||
// JDK 8: new SunPKCS11(InputStream)
|
||||
InputStream is = new ByteArrayInputStream(cfgContent.getBytes("UTF-8"));
|
||||
return (Provider) Class.forName("sun.security.pkcs11.SunPKCS11")
|
||||
.getConstructor(InputStream.class)
|
||||
.newInstance(is);
|
||||
} else {
|
||||
// JDK 9+: Security.getProvider("SunPKCS11").configure(configFilePath)
|
||||
// configure() 는 JDK 9 에서 추가된 메서드이므로 리플렉션으로 호출
|
||||
File tmp = File.createTempFile("pkcs11-hsm-", ".cfg");
|
||||
tmp.deleteOnExit();
|
||||
Files.write(tmp.toPath(), cfgContent.getBytes("UTF-8"));
|
||||
Provider base = Security.getProvider("SunPKCS11");
|
||||
Method configure = Provider.class.getMethod("configure", String.class);
|
||||
return (Provider) configure.invoke(base, tmp.getAbsolutePath());
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
// String config = "name = ProtectServer\r\n"
|
||||
// + "library = /usr/safenet/protecttoolkit5/ptk/lib/libcryptoki.so\r\n"
|
||||
// + "slot = 0";
|
||||
|
||||
String config = "name = SoftHSM\r\nlibrary = C:/SoftHSM2/lib/softhsm2-x64.dll\r\nslotListIndex = 0\r\n";
|
||||
|
||||
KeyStore keyStore;
|
||||
// Provider pkcs11Provider = HsmManagerSingleTest.createProvider(config);
|
||||
InputStream is = new ByteArrayInputStream(config.getBytes("UTF-8"));
|
||||
Provider pkcs11Provider = (Provider) Class.forName("sun.security.pkcs11.SunPKCS11")
|
||||
.getConstructor(InputStream.class)
|
||||
.newInstance(is);
|
||||
Provider existing = Security.getProvider(pkcs11Provider.getName());
|
||||
Security.addProvider(pkcs11Provider);
|
||||
String pin = "1234";
|
||||
keyStore = KeyStore.getInstance("PKCS11", pkcs11Provider);
|
||||
char[] pinChars = (pin != null) ? pin.toCharArray() : null;
|
||||
keyStore.load(null, pinChars);
|
||||
|
||||
System.out.println("HsmManager] 초기화 완료. Provider=" + pkcs11Provider.getName());
|
||||
|
||||
java.util.Enumeration<String> aliases = keyStore.aliases();
|
||||
StringBuilder aliasList = new StringBuilder();
|
||||
while (aliases.hasMoreElements()) {
|
||||
if (aliasList.length() > 0) aliasList.append(", ");
|
||||
|
||||
String alias = aliases.nextElement();
|
||||
aliasList.append(alias);
|
||||
|
||||
java.security.Key key = keyStore.getKey(alias, null);
|
||||
if (key instanceof SecretKey) {
|
||||
SecretKey secretKey = (SecretKey) key;
|
||||
if(secretKey.getEncoded() != null) {
|
||||
String encBase64 = Base64.getEncoder().encodeToString(secretKey.getEncoded());
|
||||
System.out.println("HsmManager] HSM - alias:" + alias +", base64:"+ encBase64);
|
||||
} else {
|
||||
System.out.println("HsmManager] HSM - secretKey null - alias:" + alias + ", secretKey:" + secretKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
System.out.println("HsmManager] HSM 키 목록: [" + aliasList + "]");
|
||||
}
|
||||
}
|
||||
+179
-179
@@ -1,179 +1,179 @@
|
||||
package com.eactive.eai.common.security.keyderiv;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
|
||||
import org.springframework.context.support.GenericApplicationContext;
|
||||
|
||||
import com.eactive.eai.common.hsm.HsmCryptoService;
|
||||
import com.eactive.eai.common.security.keyderiv.DerivedKey;
|
||||
import com.eactive.eai.common.security.keyderiv.strategy.HsmContextSha256KeyDerivationStrategy;
|
||||
import com.eactive.eai.common.util.ApplicationContextProvider;
|
||||
|
||||
/**
|
||||
* HsmContextSha256KeyDerivationStrategy 단위 테스트
|
||||
*/
|
||||
@TestMethodOrder(MethodOrderer.DisplayName.class)
|
||||
class HsmContextSha256KeyDerivationStrategyTest {
|
||||
|
||||
private static final String HSM_KEY_ALIAS = "MASTER_KEY_AES";
|
||||
private static final byte[] MASTER_KEY = "0123456789abcdef".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
private static GenericApplicationContext ctx;
|
||||
private static HsmCryptoService mockHsmCryptoService;
|
||||
private static HsmContextSha256KeyDerivationStrategy strategy;
|
||||
|
||||
private Map<String, String> params;
|
||||
private Map<String, String> runtimeContext;
|
||||
|
||||
@BeforeAll
|
||||
static void setUpClass() throws Exception {
|
||||
mockHsmCryptoService = mock(HsmCryptoService.class);
|
||||
SecretKey mockSecretKey = new SecretKeySpec(MASTER_KEY, "AES");
|
||||
when(mockHsmCryptoService.getSecretKey(HSM_KEY_ALIAS)).thenReturn(mockSecretKey);
|
||||
|
||||
ctx = new GenericApplicationContext();
|
||||
ctx.getBeanFactory().registerSingleton("hsmCryptoService", mockHsmCryptoService);
|
||||
ctx.registerBeanDefinition("applicationContextProvider",
|
||||
BeanDefinitionBuilder.genericBeanDefinition(ApplicationContextProvider.class)
|
||||
.getBeanDefinition());
|
||||
ctx.refresh();
|
||||
|
||||
strategy = new HsmContextSha256KeyDerivationStrategy();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUpParams() {
|
||||
params = new HashMap<>();
|
||||
params.put("hsmKeyAlias", HSM_KEY_ALIAS);
|
||||
params.put("contextKey", "X-Api-Group-Seq");
|
||||
|
||||
runtimeContext = new HashMap<>();
|
||||
runtimeContext.put("X-Api-Group-Seq", "GROUP_001");
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 1. deriveKey
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
@DisplayName("1-1. 정상 파라미터 — DerivedKey 반환, 길이 32바이트(SHA-256 고정 출력)")
|
||||
void testDeriveKey_validParams_returns32ByteKey() throws Exception {
|
||||
DerivedKey dk = strategy.deriveKey(params, runtimeContext);
|
||||
|
||||
assertNotNull(dk);
|
||||
assertNotNull(dk.getEncKey());
|
||||
assertNotNull(dk.getDecKey());
|
||||
assertEquals(32, dk.getEncKey().length, "SHA-256 출력은 항상 32바이트여야 한다");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("1-2. SHA-256(masterKey || contextValue) 계산 결과 검증")
|
||||
void testDeriveKey_sha256ResultIsCorrect() throws Exception {
|
||||
DerivedKey dk = strategy.deriveKey(params, runtimeContext);
|
||||
|
||||
byte[] contextBytes = "GROUP_001".getBytes(StandardCharsets.UTF_8);
|
||||
byte[] combined = new byte[MASTER_KEY.length + contextBytes.length];
|
||||
System.arraycopy(MASTER_KEY, 0, combined, 0, MASTER_KEY.length);
|
||||
System.arraycopy(contextBytes, 0, combined, MASTER_KEY.length, contextBytes.length);
|
||||
byte[] expected = MessageDigest.getInstance("SHA-256").digest(combined);
|
||||
|
||||
assertArrayEquals(expected, dk.getEncKey(), "SHA-256 해싱 결과가 일치해야 한다");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("1-3. 대칭 알고리즘 — encKey == decKey")
|
||||
void testDeriveKey_encKeyEqualsDecKey() throws Exception {
|
||||
DerivedKey dk = strategy.deriveKey(params, runtimeContext);
|
||||
|
||||
assertArrayEquals(dk.getEncKey(), dk.getDecKey(), "대칭 방식이므로 encKey와 decKey가 동일해야 한다");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("1-4. runtimeContext 값 없음 — 빈 문자열로 처리")
|
||||
void testDeriveKey_missingContextValue_emptyStringUsed() throws Exception {
|
||||
runtimeContext.remove("X-Api-Group-Seq");
|
||||
DerivedKey dk = strategy.deriveKey(params, runtimeContext);
|
||||
|
||||
byte[] expected = MessageDigest.getInstance("SHA-256").digest(MASTER_KEY);
|
||||
|
||||
assertArrayEquals(expected, dk.getEncKey(), "컨텍스트 값 없으면 masterKey만 해싱해야 한다");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("1-5. 다른 runtimeContext 값 — 다른 DerivedKey 생성")
|
||||
void testDeriveKey_differentContextValue_differentKey() throws Exception {
|
||||
DerivedKey dk1 = strategy.deriveKey(params, runtimeContext);
|
||||
|
||||
runtimeContext.put("X-Api-Group-Seq", "GROUP_002");
|
||||
DerivedKey dk2 = strategy.deriveKey(params, runtimeContext);
|
||||
|
||||
assertFalse(java.util.Arrays.equals(dk1.getEncKey(), dk2.getEncKey()),
|
||||
"컨텍스트 값이 다르면 도출된 키도 달라야 한다");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("1-6. 필수 파라미터 누락(hsmKeyAlias) — IllegalArgumentException")
|
||||
void testDeriveKey_missingHsmKeyAlias_throwsException() {
|
||||
params.remove("hsmKeyAlias");
|
||||
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> strategy.deriveKey(params, runtimeContext),
|
||||
"hsmKeyAlias 누락 시 IllegalArgumentException이 발생해야 한다");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("1-7. 필수 파라미터 누락(contextKey) — IllegalArgumentException")
|
||||
void testDeriveKey_missingContextKey_throwsException() {
|
||||
params.remove("contextKey");
|
||||
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> strategy.deriveKey(params, runtimeContext),
|
||||
"contextKey 누락 시 IllegalArgumentException이 발생해야 한다");
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 2. buildCacheKey
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
@DisplayName("2-1. buildCacheKey — cryptoName:contextValue 형식")
|
||||
void testBuildCacheKey_format() {
|
||||
String cacheKey = strategy.buildCacheKey("CRYPTO_A", params, runtimeContext);
|
||||
|
||||
assertEquals("CRYPTO_A:GROUP_001", cacheKey);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("2-2. buildCacheKey — contextKey 값 없으면 빈 문자열")
|
||||
void testBuildCacheKey_missingContextValue_emptyString() {
|
||||
runtimeContext.remove("X-Api-Group-Seq");
|
||||
String cacheKey = strategy.buildCacheKey("CRYPTO_A", params, runtimeContext);
|
||||
|
||||
assertEquals("CRYPTO_A:", cacheKey);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("2-3. buildCacheKey — 다른 cryptoName은 다른 캐시 키")
|
||||
void testBuildCacheKey_differentCryptoName_differentKey() {
|
||||
String key1 = strategy.buildCacheKey("CRYPTO_A", params, runtimeContext);
|
||||
String key2 = strategy.buildCacheKey("CRYPTO_B", params, runtimeContext);
|
||||
|
||||
assertNotEquals(key1, key2);
|
||||
}
|
||||
}
|
||||
//package com.eactive.eai.common.security.keyderiv;
|
||||
//
|
||||
//import static org.junit.jupiter.api.Assertions.*;
|
||||
//import static org.mockito.Mockito.*;
|
||||
//
|
||||
//import java.nio.charset.StandardCharsets;
|
||||
//import java.security.MessageDigest;
|
||||
//import java.util.HashMap;
|
||||
//import java.util.Map;
|
||||
//
|
||||
//import javax.crypto.SecretKey;
|
||||
//import javax.crypto.spec.SecretKeySpec;
|
||||
//
|
||||
//import org.junit.jupiter.api.BeforeAll;
|
||||
//import org.junit.jupiter.api.BeforeEach;
|
||||
//import org.junit.jupiter.api.DisplayName;
|
||||
//import org.junit.jupiter.api.MethodOrderer;
|
||||
//import org.junit.jupiter.api.Test;
|
||||
//import org.junit.jupiter.api.TestMethodOrder;
|
||||
//import org.springframework.beans.factory.support.BeanDefinitionBuilder;
|
||||
//import org.springframework.context.support.GenericApplicationContext;
|
||||
//
|
||||
//import com.eactive.eai.common.hsm.HsmCryptoService;
|
||||
//import com.eactive.eai.common.security.keyderiv.DerivedKey;
|
||||
//import com.eactive.eai.common.security.keyderiv.strategy.HsmContextSha256KeyDerivationStrategy;
|
||||
//import com.eactive.eai.common.util.ApplicationContextProvider;
|
||||
//
|
||||
///**
|
||||
// * HsmContextSha256KeyDerivationStrategy 단위 테스트
|
||||
// */
|
||||
//@TestMethodOrder(MethodOrderer.DisplayName.class)
|
||||
//class HsmContextSha256KeyDerivationStrategyTest {
|
||||
//
|
||||
// private static final String HSM_KEY_ALIAS = "MASTER_KEY_AES";
|
||||
// private static final byte[] MASTER_KEY = "0123456789abcdef".getBytes(StandardCharsets.UTF_8);
|
||||
//
|
||||
// private static GenericApplicationContext ctx;
|
||||
// private static HsmCryptoService mockHsmCryptoService;
|
||||
// private static HsmContextSha256KeyDerivationStrategy strategy;
|
||||
//
|
||||
// private Map<String, String> params;
|
||||
// private Map<String, String> runtimeContext;
|
||||
//
|
||||
// @BeforeAll
|
||||
// static void setUpClass() throws Exception {
|
||||
// mockHsmCryptoService = mock(HsmCryptoService.class);
|
||||
// SecretKey mockSecretKey = new SecretKeySpec(MASTER_KEY, "AES");
|
||||
// when(mockHsmCryptoService.getSecretKey(HSM_KEY_ALIAS)).thenReturn(mockSecretKey);
|
||||
//
|
||||
// ctx = new GenericApplicationContext();
|
||||
// ctx.getBeanFactory().registerSingleton("hsmCryptoService", mockHsmCryptoService);
|
||||
// ctx.registerBeanDefinition("applicationContextProvider",
|
||||
// BeanDefinitionBuilder.genericBeanDefinition(ApplicationContextProvider.class)
|
||||
// .getBeanDefinition());
|
||||
// ctx.refresh();
|
||||
//
|
||||
// strategy = new HsmContextSha256KeyDerivationStrategy();
|
||||
// }
|
||||
//
|
||||
// @BeforeEach
|
||||
// void setUpParams() {
|
||||
// params = new HashMap<>();
|
||||
// params.put("hsmKeyAlias", HSM_KEY_ALIAS);
|
||||
// params.put("contextKey", "X-Api-Group-Seq");
|
||||
//
|
||||
// runtimeContext = new HashMap<>();
|
||||
// runtimeContext.put("X-Api-Group-Seq", "GROUP_001");
|
||||
// }
|
||||
//
|
||||
// // =========================================================================
|
||||
// // 1. deriveKey
|
||||
// // =========================================================================
|
||||
//
|
||||
// @Test
|
||||
// @DisplayName("1-1. 정상 파라미터 — DerivedKey 반환, 길이 32바이트(SHA-256 고정 출력)")
|
||||
// void testDeriveKey_validParams_returns32ByteKey() throws Exception {
|
||||
// DerivedKey dk = strategy.deriveKey(params, runtimeContext);
|
||||
//
|
||||
// assertNotNull(dk);
|
||||
// assertNotNull(dk.getEncKey());
|
||||
// assertNotNull(dk.getDecKey());
|
||||
// assertEquals(32, dk.getEncKey().length, "SHA-256 출력은 항상 32바이트여야 한다");
|
||||
// }
|
||||
//
|
||||
// @Test
|
||||
// @DisplayName("1-2. SHA-256(masterKey || contextValue) 계산 결과 검증")
|
||||
// void testDeriveKey_sha256ResultIsCorrect() throws Exception {
|
||||
// DerivedKey dk = strategy.deriveKey(params, runtimeContext);
|
||||
//
|
||||
// byte[] contextBytes = "GROUP_001".getBytes(StandardCharsets.UTF_8);
|
||||
// byte[] combined = new byte[MASTER_KEY.length + contextBytes.length];
|
||||
// System.arraycopy(MASTER_KEY, 0, combined, 0, MASTER_KEY.length);
|
||||
// System.arraycopy(contextBytes, 0, combined, MASTER_KEY.length, contextBytes.length);
|
||||
// byte[] expected = MessageDigest.getInstance("SHA-256").digest(combined);
|
||||
//
|
||||
// assertArrayEquals(expected, dk.getEncKey(), "SHA-256 해싱 결과가 일치해야 한다");
|
||||
// }
|
||||
//
|
||||
// @Test
|
||||
// @DisplayName("1-3. 대칭 알고리즘 — encKey == decKey")
|
||||
// void testDeriveKey_encKeyEqualsDecKey() throws Exception {
|
||||
// DerivedKey dk = strategy.deriveKey(params, runtimeContext);
|
||||
//
|
||||
// assertArrayEquals(dk.getEncKey(), dk.getDecKey(), "대칭 방식이므로 encKey와 decKey가 동일해야 한다");
|
||||
// }
|
||||
//
|
||||
// @Test
|
||||
// @DisplayName("1-4. runtimeContext 값 없음 — 빈 문자열로 처리")
|
||||
// void testDeriveKey_missingContextValue_emptyStringUsed() throws Exception {
|
||||
// runtimeContext.remove("X-Api-Group-Seq");
|
||||
// DerivedKey dk = strategy.deriveKey(params, runtimeContext);
|
||||
//
|
||||
// byte[] expected = MessageDigest.getInstance("SHA-256").digest(MASTER_KEY);
|
||||
//
|
||||
// assertArrayEquals(expected, dk.getEncKey(), "컨텍스트 값 없으면 masterKey만 해싱해야 한다");
|
||||
// }
|
||||
//
|
||||
// @Test
|
||||
// @DisplayName("1-5. 다른 runtimeContext 값 — 다른 DerivedKey 생성")
|
||||
// void testDeriveKey_differentContextValue_differentKey() throws Exception {
|
||||
// DerivedKey dk1 = strategy.deriveKey(params, runtimeContext);
|
||||
//
|
||||
// runtimeContext.put("X-Api-Group-Seq", "GROUP_002");
|
||||
// DerivedKey dk2 = strategy.deriveKey(params, runtimeContext);
|
||||
//
|
||||
// assertFalse(java.util.Arrays.equals(dk1.getEncKey(), dk2.getEncKey()),
|
||||
// "컨텍스트 값이 다르면 도출된 키도 달라야 한다");
|
||||
// }
|
||||
//
|
||||
// @Test
|
||||
// @DisplayName("1-6. 필수 파라미터 누락(hsmKeyAlias) — IllegalArgumentException")
|
||||
// void testDeriveKey_missingHsmKeyAlias_throwsException() {
|
||||
// params.remove("hsmKeyAlias");
|
||||
//
|
||||
// assertThrows(IllegalArgumentException.class,
|
||||
// () -> strategy.deriveKey(params, runtimeContext),
|
||||
// "hsmKeyAlias 누락 시 IllegalArgumentException이 발생해야 한다");
|
||||
// }
|
||||
//
|
||||
// @Test
|
||||
// @DisplayName("1-7. 필수 파라미터 누락(contextKey) — IllegalArgumentException")
|
||||
// void testDeriveKey_missingContextKey_throwsException() {
|
||||
// params.remove("contextKey");
|
||||
//
|
||||
// assertThrows(IllegalArgumentException.class,
|
||||
// () -> strategy.deriveKey(params, runtimeContext),
|
||||
// "contextKey 누락 시 IllegalArgumentException이 발생해야 한다");
|
||||
// }
|
||||
//
|
||||
// // =========================================================================
|
||||
// // 2. buildCacheKey
|
||||
// // =========================================================================
|
||||
//
|
||||
// @Test
|
||||
// @DisplayName("2-1. buildCacheKey — cryptoName:contextValue 형식")
|
||||
// void testBuildCacheKey_format() {
|
||||
// String cacheKey = strategy.buildCacheKey("CRYPTO_A", params, runtimeContext);
|
||||
//
|
||||
// assertEquals("CRYPTO_A:GROUP_001", cacheKey);
|
||||
// }
|
||||
//
|
||||
// @Test
|
||||
// @DisplayName("2-2. buildCacheKey — contextKey 값 없으면 빈 문자열")
|
||||
// void testBuildCacheKey_missingContextValue_emptyString() {
|
||||
// runtimeContext.remove("X-Api-Group-Seq");
|
||||
// String cacheKey = strategy.buildCacheKey("CRYPTO_A", params, runtimeContext);
|
||||
//
|
||||
// assertEquals("CRYPTO_A:", cacheKey);
|
||||
// }
|
||||
//
|
||||
// @Test
|
||||
// @DisplayName("2-3. buildCacheKey — 다른 cryptoName은 다른 캐시 키")
|
||||
// void testBuildCacheKey_differentCryptoName_differentKey() {
|
||||
// String key1 = strategy.buildCacheKey("CRYPTO_A", params, runtimeContext);
|
||||
// String key2 = strategy.buildCacheKey("CRYPTO_B", params, runtimeContext);
|
||||
//
|
||||
// assertNotEquals(key1, key2);
|
||||
// }
|
||||
//}
|
||||
|
||||
Reference in New Issue
Block a user