7 Commits

Author SHA1 Message Date
curry772 c2ad6d2423 Merge branch 'feature/inflow-control-improvement' into master 2026-05-08 10:51:48 +09:00
curry772 b6954139fe fix: custom.inflow 컴포넌트 스캔 추가 및 /manage/* FrontFilter 등록
- authserver-servlet.xml: com.eactive.eai.custom.inflow 패키지 component-scan 추가
  (ClientInflowTargetBucketController/MetricController 빈 등록)
- web.xml: FrontFilter url-pattern에 /manage/* 추가

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-08 10:50:14 +09:00
curry772 d46fa8bd1a refactor: 클라이언트 버킷 상태 모니터링 custom.inflow 패키지로 분리
- InflowTargetBucketService/Controller에서 클라이언트 관련 메서드/엔드포인트 제거
- ClientInflowTargetBucketService/Controller를 custom.inflow 패키지에 신규 생성
  (ClientInflowTargetMetricService/Controller 패턴과 일치)
- 관련 단위 테스트 추가 및 기존 테스트에서 클라이언트 케이스 제거

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-08 10:22:15 +09:00
curry772 31171d0187 feat: 클라이언트 유량제어/RequestProcessor custom 패키지로 분리
- DJBRequestProcessor: inbound.processor → custom.inbound.processor 이동
- ClientInflowTargetMetricService/Controller: custom.inflow 패키지 신규 생성
  클라이언트 메트릭 API(/manage/inflow/client/**)를 InflowTargetMetric*에서 분리
- InflowTargetMetricService/Controller: 클라이언트 관련 메서드/엔드포인트 제거
- InflowTargetBucketService: getClientDualManager() 분리 반영
- standard-message-config.properties: requestProcessor.class 경로 업데이트
- 단위 테스트: ClientInflowTargetMetric{Service,Controller}Test 추가,
  기존 테스트에서 클라이언트 케이스 분리

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 18:02:51 +09:00
curry772 45ad9d8b6f Merge branch 'feature/crypto-module' into master 2026-05-07 15:39:00 +09:00
curry772 dd02c5902e feat: DJB ERP 연동 암복호화 필터 추가 및 단위테스트 작성
- DJBErpCryptoFilter: CryptoFilter 상속, httpHeaderGroup 헤더 JSON에서
  x-emp-nm(groupSeq|empNo) 파싱 → groupSeq를 runtimeContext로 전달
- DJBErpCryptoFilterTest: 17개 단위테스트 (buildRuntimeContext/doPreFilter/doPostFilter)
- elink-online-common 서브모듈 업데이트 (CryptoFilter 기반 클래스 포함)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 15:04:01 +09:00
curry772 c225104711 feat: 암호화모듈 프레임워크 적용 및 사이트 특화 전략 추가
- 서브모듈 포인터 업데이트 (elink-online-common, elink-online-core-jpa)
- HsmContextSha256KeyDerivationStrategy: SHA-256(masterKey || contextValue) 키 도출 전략
  elink-online-common에서 eapim-online custom 패키지로 분리 (사이트 의존성)
  FQCN: com.eactive.eai.custom.security.keyderiv.strategy.HsmContextSha256KeyDerivationStrategy
- HsmContextSha256KeyDerivationStrategyTest 추가

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-06 16:50:17 +09:00
34 changed files with 2515 additions and 617 deletions
@@ -20,12 +20,7 @@
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
">
<context:component-scan base-package="com.eactive.eai">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
<context:exclude-filter type="annotation"
expression="org.springframework.web.bind.annotation.RestController"/>
</context:component-scan>
<context:component-scan base-package="com.eactive.eai" />
<bean id="entityManagerFactory" primary="true"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
+3 -8
View File
@@ -17,10 +17,6 @@
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:property-placeholder
location="/WEB-INF/properties/*.${eai.systemmode}.properties"
ignore-unresolvable="true" />
<context:component-scan
base-package="com.eactive.eai.authserver" />
<context:component-scan
@@ -29,14 +25,13 @@
base-package="com.eactive.eai.adapter" />
<context:component-scan
base-package="com.eactive.eai.manage" />
<context:component-scan
base-package="com.eactive.eai.custom.inflow" />
<context:annotation-config />
<mvc:annotation-driven />
<mvc:default-servlet-handler />
<mvc:interceptors>
<bean class="com.eactive.eai.adapter.interceptor.HttpResponseLoggingInterceptor"/>
</mvc:interceptors>
<bean class="com.eactive.eai.adapter.controller.DJErpAdapterMappingRegistrar">
<property name="paths" value="${dj.erp.adapter.paths}" />
</bean>
</beans>
@@ -20,6 +20,3 @@ eai.systemmode=D
eai.systemtype=API
eai.tableowner=AGWADM
eai.server.extractor=[0,2],[0,2],[-2]
# DJErp API Adapter request mapping paths (comma-separated)
dj.erp.adapter.paths=/dj/{path:^(?!oauth).*$},/dj/{path:^(?!oauth).*$}/**
@@ -12,6 +12,3 @@ hibernate.dialect=org.hibernate.dialect.Oracle12cDialect
eai.systemtype=API
eai.server.extractor=[0,2],[0,2],[-2]
# DJErp API Adapter request mapping paths (comma-separated)
dj.erp.adapter.paths=/dj/{path:^(?!oauth).*$},/dj/{path:^(?!oauth).*$}/**
@@ -18,6 +18,3 @@ eai.systemmode=D
eai.systemtype=API
eai.tableowner=dapigw
eai.server.extractor=[0,2],[0,2],[-2]
# DJErp API Adapter request mapping paths (comma-separated)
dj.erp.adapter.paths=/dj/{path:^(?!oauth).*$},/dj/{path:^(?!oauth).*$}/**
+1
View File
@@ -19,6 +19,7 @@
<url-pattern>/agent/*</url-pattern>
<url-pattern>/common/*</url-pattern>
<url-pattern>/management/*</url-pattern>
<url-pattern>/manage/*</url-pattern>
<url-pattern>/mgr/*</url-pattern>
</filter-mapping>
@@ -1,91 +0,0 @@
package com.eactive.eai.adapter.controller;
import java.lang.reflect.Method;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import com.eactive.eai.common.util.Logger;
/**
* properties 파일의 dj.erp.adapter.paths 값을 읽어
* DJErpApiAdapterController 의 callApi 메서드를 동적으로 URL에 등록한다.
*
* 경로는 쉼표로 구분하여 여러 개를 지정할 수 있다.
* 예) /dj/{path:^(?!oauth).*$},/dj/{path:^(?!oauth).*$}/**
*/
public class DJErpAdapterMappingRegistrar implements ApplicationListener<ContextRefreshedEvent> {
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
@Autowired
private DJErpApiAdapterController djErpApiAdapterController;
private String paths;
private boolean registered = false;
public void setPaths(String paths) {
this.paths = paths;
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if (registered) {
return;
}
if (StringUtils.isBlank(paths)) {
logger.warn("DJErpAdapterMappingRegistrar] dj.erp.adapter.paths 가 설정되지 않았습니다.");
return;
}
// OAuth2의 FrameworkEndpointHandlerMapping 을 제외하고 MVC 기본 매핑만 선택
Map<String, RequestMappingHandlerMapping> candidates =
event.getApplicationContext().getBeansOfType(RequestMappingHandlerMapping.class);
RequestMappingHandlerMapping requestMappingHandlerMapping = candidates.values().stream()
.filter(m -> m.getClass() == RequestMappingHandlerMapping.class)
.findFirst()
.orElse(null);
if (requestMappingHandlerMapping == null) {
logger.warn("DJErpAdapterMappingRegistrar] RequestMappingHandlerMapping 을 찾을 수 없습니다.");
return;
}
try {
Method callApi = DJErpApiAdapterController.class.getDeclaredMethod(
"callApi", HttpServletRequest.class, HttpServletResponse.class);
RequestMappingInfo.BuilderConfiguration options = new RequestMappingInfo.BuilderConfiguration();
options.setPatternParser(requestMappingHandlerMapping.getPatternParser());
for (String path : paths.split(",")) {
path = path.trim();
if (path.isEmpty()) {
continue;
}
RequestMappingInfo mappingInfo = RequestMappingInfo
.paths(path)
.options(options)
.build();
requestMappingHandlerMapping.registerMapping(mappingInfo, djErpApiAdapterController, callApi);
logger.warn("DJErpAdapterMappingRegistrar] 등록 완료: " + path);
}
registered = true;
} catch (NoSuchMethodException e) {
logger.error("DJErpAdapterMappingRegistrar] callApi 메서드를 찾을 수 없습니다.", e);
}
}
}
@@ -16,6 +16,7 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.eactive.eai.adapter.AdapterGroupVO;
@@ -56,6 +57,7 @@ public class DJErpApiAdapterController implements HttpAdapterServiceKey {
* @See com.eactive.eai.authserver.config.AuthorizationServerConfig.configure(AuthorizationServerEndpointsConfigurer
* endpoints)
*/
@RequestMapping(value = { "/dj/{path:^(?!oauth).*$}", "/dj/{path:^(?!oauth).*$}/**" })
public ResponseEntity<String> callApi(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
throws Exception {
// /ONLWeb/api/v1/public/getUserInfo.svc
@@ -142,14 +144,50 @@ public class DJErpApiAdapterController implements HttpAdapterServiceKey {
try {
String responseData = service.callApi(servletRequest, servletResponse, httpProp, adapterGroupVO, adapterVO,
transactionProp);
servletResponse.addHeader("traceId",
transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID)); // uuid를 response header에
int httpStatus = servletResponse.getStatus();
if (httpStatus != 200) {
responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseData);
// if (RESPONSE_TYPE_ASYNC.equals(responseType)) { // table의 값이 ASYNC 로 들어가 있는데
// response_type_async는 ASYN 로 되어 있어 아래처럼 비교함 jwhong 2025
if ("ASYNC".equals(responseType)) {
// responseEntity = ResponseEntity.ok("dummy"); // comment by jwhong
// servletResponse.addHeader("traceId", responseData); // uuid를 response header에
servletResponse.addHeader("traceId",
transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID)); // uuid를 response header에
int httpStatus = servletResponse.getStatus();
if (httpStatus == 200) {
// 업체별 aync response message 가 다르다.
String asyncMsgStyle = httpProp.getProperty("ASYNC_RTNMSG_TYPE", "");
String responseBody = "";
boolean encryptAsyncAckApply = StringUtils
.equalsIgnoreCase(httpProp.getProperty("ASYNC_ENCRYPT_ACK", "N"), "Y");
if (asyncMsgStyle == null || asyncMsgStyle.trim().isEmpty()) {
responseBody = makeResponseBodyMsg();
} else {
responseBody = asyncMsgStyle;
}
if (encryptAsyncAckApply) {
responseBody = service.doPostEncryption(responseBody, transactionProp, servletRequest);
}
responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseBody);
// jwhong
} else {
responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseData);
}
} else {
responseEntity = ResponseEntity.ok().contentType(mediaType).body(responseData);
// responseEntity = ResponseEntity.ok().contentType(mediaType).body(responseData);
// 버즈빌 포인트 적립 처리하기 위하여 정상응답이더라도 응답코드(apiRsltCd) 값이 200이 아닌 경우 처리를 위하여 수정
// Filter에서 설정한 response status값을 responseEntity 생성시 적용 modify by lwk 2025.03.24
servletResponse.addHeader("traceId",
transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID)); // uuid를 response header에
int httpStatus = servletResponse.getStatus();
if (httpStatus != 200) {
responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseData);
} else {
responseEntity = ResponseEntity.ok().contentType(mediaType).body(responseData);
}
}
} catch (Exception e) {
@@ -1,38 +1,13 @@
package com.eactive.eai.adapter.service;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
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.JSONObject;
import org.json.simple.JSONValue;
import org.springframework.context.annotation.Primary;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
import com.eactive.eai.adapter.AdapterGroupVO;
import com.eactive.eai.adapter.AdapterPropManager;
import com.eactive.eai.adapter.AdapterVO;
import com.eactive.eai.adapter.Keys;
import com.eactive.eai.adapter.http.HttpMemoryLogger;
import com.eactive.eai.adapter.http.HttpMethodType;
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
import com.eactive.eai.common.context.ElinkTransactionContext;
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthFilter;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.message.MessageType;
import com.eactive.eai.common.util.CommonLib;
@@ -45,19 +20,61 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
@Primary
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.mina.common.ByteBuffer;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.JSONParser;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.util.*;
//for encrypt/decrypt jwhong
import com.eactive.eai.authserver.service.OAuth2Manager;
import com.kjbank.encrypt.exchange.crypto.AES256Cipher;
import com.kjbank.encrypt.exchange.crypto.AESCipher;
import com.kjbank.encrypt.exchange.crypto.AES256GCMCipher;
import java.nio.charset.StandardCharsets;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import org.springframework.security.oauth2.provider.ClientDetails;
import com.nimbusds.jwt.SignedJWT;
import com.eactive.eai.common.context.ElinkTransactionContext;
@Service
public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
public static final String HEADER_GROUP = "HEADER_GROUP";
public static final String HTTP_STATUS = "HTTP_STATUS";
public static final String HTTP_STATUS = "HTTP_STATUS"; // jwhong
// HEADER_GROUP JSON에 추가할 항목 정의, 없으면 전체 header 추가
public static final String HEADER_KEYS = "HEADER_KEYS";
public static final String PROPERTIES_NAME_HTTP_REQUEST_METHOD = "httpRequestMethod";
private static final String JSON_CONTENT_TYPE = "application/json";
private static final String JSON_FIELD_NAME = "json-body";
private static final String FILE_GROUP_NAME = "image-file";
private static final String UPLOAD_ROOT_PATH = "UPLOAD_ROOT_PATH";
public static final String PAYLOAD_PARAM_NAME_CLIENT_ID = "client_id"; // jwhong
private boolean encryptResponseApply; // inbound에 대한 응답 암호화 여부 flag
public String callApi(HttpServletRequest request, HttpServletResponse response, Properties httpProp, AdapterGroupVO adapterGroupVO, AdapterVO adapterVO, Properties transactionProp) throws Exception {
int traceLevel = 0;
AdapterPropManager manager = null;
String adptGrpName = adapterGroupVO.getName();
String adptName = adapterVO.getName();
@@ -73,56 +90,61 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
String paramValue = null;
String adptMsgType = null;
transactionProp.put(INBOUND_METHOD, request.getMethod());
transactionProp.put(INBOUND_URI, request.getRequestURI());
transactionProp.put(INBOUND_QUERY_STRING, StringUtils.defaultString(request.getQueryString()));
transactionProp.put(INBOUND_HEADER, getHeaders(request));
transactionProp.put(INBOUND_EXTPARAMS, StringUtils.defaultString(request.getQueryString()));
transactionProp.put(INBOUND_EXTPARAMS, StringUtils.defaultString(request.getQueryString()));
if (StringUtils.equals(adapterVO.getAdapterGroupVO().getType(), Keys.TYPE_REST)
|| StringUtils.equals(adapterVO.getAdapterGroupVO().getType(), Keys.TYPE_HTTP_CUSTOM)) {
// /api/v1/public/getUserInfo.svc
String extUrl = StringUtils.removeStart(request.getRequestURI(), request.getContextPath());
transactionProp.put(INBOUND_EXTURI, extUrl);
} else {
transactionProp.put(INBOUND_EXTURI, getExtUri(request));
transactionProp.put(INBOUND_EXTURI, getExtUri(request));
}
transactionProp.put(INBOUND_CLIENT_IP, getClientIp(request));
transactionProp.put(INBOUND_CLIENT_IP, getClientIp(request)); // Client IP 추가
transactionProp.put(Processor.REQUEST_ACTION, adapterVO.getAdapterGroupVO().getRefClass());
transactionProp.put(API_PATH, httpProp.getProperty(API_PATH, ""));
//djerp bypass
transactionProp.put(INBOUND_REWRITE_PATH,
getRewritePath(transactionProp.getProperty(INBOUND_EXTURI), transactionProp.getProperty(API_PATH)));
transactionProp.put(INBOUND_REMOTE_ADDR, request.getRemoteAddr());
transactionProp.put(INBOUND_SCHEME, request.getScheme());
transactionProp.put(PRE_FILTERS, httpProp.getProperty(PRE_FILTERS, ""));
transactionProp.put(POST_FILTERS, httpProp.getProperty(POST_FILTERS, ""));
transactionProp.put(PROPERTIES_NAME_HTTP_REQUEST_METHOD, request.getMethod());
transactionProp.put(ALLOW_IP, httpProp.getProperty(ALLOW_IP, ""));
transactionProp.put("BLOCK_IP", httpProp.getProperty("BLOCK_IP", ""));
//djerp bypass
Map<String, String> pathVariables = assignPathVariables(request, adptGrpName, adptName, null, transactionProp);
if (pathVariables != null) {
transactionProp.put(INBOUND_PATH_VARIABLES, pathVariables);
}
transactionProp.put(ENC_PATHS, httpProp.getProperty(ENC_PATHS, ""));
transactionProp.put(ENCRYPT_ALGORITHM, httpProp.getProperty(ENCRYPT_ALGORITHM, ""));
if (getHeaders(request).get(HEADER_NAME_CLIENT_ID) != null) {
transactionProp.put(HEADER_NAME_CLIENT_ID, getHeaders(request).get(HEADER_NAME_CLIENT_ID));
transactionProp.put(ENCRYPT_ALGORITHM, httpProp.getProperty(ENCRYPT_ALGORITHM, "")); //jwhong
if (getHeaders(request).get(HEADER_NAME_CLIENT_ID) != null) { // jwhong
transactionProp.put(HEADER_NAME_CLIENT_ID, getHeaders(request).get(HEADER_NAME_CLIENT_ID));
}
transactionProp.put(ENCRYPT_BASE_TYPE, httpProp.getProperty(ENCRYPT_BASE_TYPE, ""));
transactionProp.put(ENCRYPT_BASE_TYPE, httpProp.getProperty(ENCRYPT_BASE_TYPE, "")); //jwhong
// //transactionProp.put(INBOUND_TOKEN, getHeaders(request).get(INBOUND_TOKEN)); // jwhong
// transactionProp.put(INBOUND_TOKEN, getHeaders(request).get(INBOUND_TOKEN) != null ? getHeaders(request).get(INBOUND_TOKEN) : ""); //jwhong , null 이면 default로 "" put
String inboundToken = getHeaders(request).getOrDefault(INBOUND_TOKEN, "").toString();
if (StringUtils.isNotBlank(inboundToken) && StringUtils.startsWith(inboundToken, "Bearer ")) {
inboundToken = inboundToken.substring(7);
}
transactionProp.put(INBOUND_TOKEN, inboundToken);
transactionProp.put(ENCRYPT_AES256_IV, httpProp.getProperty(ENCRYPT_AES256_IV, ""));
transactionProp.put(ENCRYPT_AES256_KEY, httpProp.getProperty(ENCRYPT_AES256_KEY, ""));
// SEED 컬럼암호화 시 Key로 사용함
transactionProp.put(ENCRYPT_AES256_IV, httpProp.getProperty(ENCRYPT_AES256_IV, "")); //jwhong
transactionProp.put(ENCRYPT_AES256_KEY, httpProp.getProperty(ENCRYPT_AES256_KEY, "")); //jwhong
// SEED 컬럼암호하 시 Key로 사용함
String seedkey = getHeaders(request).getOrDefault("x-obp-partnercode", "").toString();
ElinkTransactionContext.setSeedKey(seedkey);
@@ -146,7 +168,7 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
case PUT:
if (StringUtils.contains(request.getContentType(), "application/x-www-form-urlencoded")) {
isParameterType = true;
} else if (StringUtils.isNoneBlank(request.getQueryString())) {
} else if ( StringUtils.isNoneBlank(request.getQueryString()) ) { // jwhong
isParameterType = true;
} else {
isParameterType = false;
@@ -158,7 +180,7 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
if (isParameterType) {
paramValue = request.getQueryString();
transactionProp.put(INBOUND_QUERY_STRING, StringUtils.defaultString(paramValue));
transactionProp.put(INBOUND_QUERY_STRING, StringUtils.defaultString(paramValue)); // Filter에서 QueryString 검증을 위해 저장
if (paramValue == null)
paramValue = "";
if (traceLevel >= 3) {
@@ -197,7 +219,7 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
sb.append("}");
paramValue = sb.toString();
if (logger.isDebug()) {
logger.debug("HttpAdapterServiceRest] RECV (" + adptGrpName + ") = [" + paramValue + "]\n"
+ CommonLib.getDumpMessage(paramValue.getBytes(encode)));
@@ -244,11 +266,17 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
}
}
if (paramValue == null) {
if (paramValue == null) { // parameter가 없는 경우때문에 처리
paramValue = "";
}
// 순수한 Body값을 저장을 위해 위치 변경.
transactionProp.put(INBOUND_REQUEST_MESSAGE, paramValue);
// paramValue가 null이 아닌 빈문자열(""," ")인 경우에 대비하여 조건 수정.
// if (StringUtils.isNotBlank(paramValue)) { // jwhong decrypt
// paramValue = doPreDecryption(paramValue, transactionProp, request);
// }
if ("Y".equals(urlDecodeYn) && isParameterType) {
message = URLDecoder.decode(paramValue);
} else {
@@ -263,7 +291,11 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
logger.debug(resMsg);
}
adptMsgType = adapterVO.getAdapterGroupVO().getMessageType();
// HttpHeaders responseHeaders = new HttpHeaders();
// responseHeaders.setContentType(MediaType.valueOf("application/json;charset=" + encode));
// HEADER_GROUP 셋팅
if (MessageType.JSON.equals(adptMsgType) && StringUtils.isNotBlank(headerGroupName)
@@ -286,7 +318,7 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
}
}
}
if (headerJson.size() > 0) {
jsonMessage.put(headerGroupName, headerJson);
message = jsonMessage.toJSONString();
@@ -297,6 +329,9 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
message = "";
}
// 위치변경 : 가공되지 않은 Body값을 저장하기 위하여 위쪽으로 이동.
// transactionProp.put(INBOUND_REQUEST_MESSAGE, message);
// 로컬 서비스 호출 ,encoding 처리 추가
String result = (String) service(adptGrpName, adptName, message, transactionProp, request, response);
applyOutboundResponseHeaders(transactionProp, response);
@@ -323,11 +358,17 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
result = mapper.writeValueAsString(rootNode);
}
}
// KJBank는 요청에 대한 응답 (Sync응답, Aync 에 대한 Ack응답) 에 대하여 암호화 하지 않는다. 무조건 안한다. 따라서 아래부분은 구현은 했지만 사용하지 않는다.
// 위 2가지 경우 암호화 하는걸로 요청 변경되어 아래 암호화 수행하도록 수정함
// encryptResponseApply = StringUtils.equalsIgnoreCase(httpProp.getProperty("ENCRYPT_RESPONSE_APPLY", "N"), "Y");
// if ( encryptResponseApply) {
// result = doPostEncryption(result, transactionProp, request); // jwhong Encrypt
// }
return result;
}
/**
* HttpClientAdapterServiceBypass.assignRelayDataToInbound() 에서
* transactionProp에 저장한 OUTBOUND_RESPONSE_HEADERS를 response에 적용한다.
@@ -370,6 +411,411 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
}
}
// jwhong decrypt
private String doPreDecryption(String eaiBody, Properties transactionProp, HttpServletRequest request) throws Exception {
String decryptAlgorithm = transactionProp.getProperty(ENCRYPT_ALGORITHM, "");
String xElinkClientId = transactionProp.getProperty(HEADER_NAME_CLIENT_ID, ""); // 이 값이 OAuth의 client id 값이다 . http header 에 포함되어 온다. jwhong
String encryptBaseKeyType = transactionProp.getProperty(ENCRYPT_BASE_TYPE);
//String inboundToken2 = transactionProp.getProperty(INBOUND_TOKEN, ""); // 이건 token 값이 아니고 authorization 값이다
String inboundToken = "";
String secretAES256Iv = transactionProp.getProperty("ENCRYPT_AES256_IV");
String secretAES256Key = transactionProp.getProperty("ENCRYPT_AES256_KEY");
if ( decryptAlgorithm == "" ) { // 복호화 대상이 아님
return eaiBody;
}
inboundToken = JwtTokenExtractor(request);
xElinkClientId = JwtClientIdExtractor(inboundToken); // token에서 client id를 추출함
// 암호화 key를 token 내용으로 할지 client secret 내용으로 할지 결정함. adapter property에 정의함
// ENCRYPT_ALGORITHM 을 설정했는데 ENCRYPT_BASE_TYPE을 설정안하면 Decrypt 수행시 Exception 발생함
String clientSecret = "";
if ("TOKEN".equalsIgnoreCase(encryptBaseKeyType)) {
clientSecret = inboundToken;
} else if ( "SECRETKEY".equalsIgnoreCase(encryptBaseKeyType)) {
OAuth2Manager manager = OAuth2Manager.getInstance();
ClientDetails clientDetail = manager.getClientDeatilsStore().get(xElinkClientId);
if ( clientDetail != null ) { // 여기서 not null 이라는 것은 apim oauth server에서 발급된 token 임.
// 즉 KJBank 에서 요청이 들어온 것이다.
clientSecret = clientDetail.getClientSecret();
} // 그럼 업체에서 요청이 들어오면?? 업체도 apim oauth server에서 발급된 token을 사용하는것이다.
}
byte[] decryptedMessage = null;
decryptedMessage = doInboundPreDecrypt(eaiBody, decryptAlgorithm,clientSecret,secretAES256Iv, secretAES256Key );
if (decryptedMessage == null) {
throw new Exception("[ApiAdapterService] Decrypt Error : Invalid encrypted message");
}
String resultMessage = new String(decryptedMessage, StandardCharsets.UTF_8 );
return resultMessage;
//return new String(decryptedMessage, StandardCharsets.UTF_8 );
}
// jwhong encrypt
public String doPostEncryption(String eaiBody, Properties transactionProp, HttpServletRequest request) throws Exception {
String decryptAlgorithm = transactionProp.getProperty(ENCRYPT_ALGORITHM, "");
String xElinkClientId = transactionProp.getProperty(HEADER_NAME_CLIENT_ID, ""); // 이 값이 OAuth의 client id 값이다 . http header 에 포함되어 온다. jwhong
String encryptBaseKeyType = transactionProp.getProperty(ENCRYPT_BASE_TYPE);
String inboundToken = "";
String secretAES256Iv = transactionProp.getProperty("ENCRYPT_AES256_IV");
String secretAES256Key = transactionProp.getProperty("ENCRYPT_AES256_KEY");
if ( decryptAlgorithm == "" ) { // 복호화 대상이 아님
return eaiBody;
}
inboundToken = JwtTokenExtractor(request);
xElinkClientId = JwtClientIdExtractor(inboundToken); // token에서 client id를 추출함
// 암호화 key를 token 내용으로 할지 client secret 내용으로 할지 결정함. adapter property에 정의함
// ENCRYPT_ALGORITHM 을 설정했는데 ENCRYPT_BASE_TYPE을 설정안하면 Decrypt 수행시 Exception 발생함
String clientSecret = "";
if ("TOKEN".equalsIgnoreCase(encryptBaseKeyType)) {
clientSecret = inboundToken;
} else if ( "SECRETKEY".equalsIgnoreCase(encryptBaseKeyType)) {
OAuth2Manager manager = OAuth2Manager.getInstance();
ClientDetails clientDetail = manager.getClientDeatilsStore().get(xElinkClientId);
if ( clientDetail != null ) {
clientSecret = clientDetail.getClientSecret();
}
}
String encryptedMessage = null;
encryptedMessage = doInboundPostEncrypt(eaiBody, decryptAlgorithm,clientSecret,secretAES256Iv, secretAES256Key );
if (encryptedMessage == null) {
throw new Exception("[ApiAdapterService] Encrypt Error : Invalid PlainText message");
}
return encryptedMessage;
//String resultMessage = new String(encryptedMessage, StandardCharsets.UTF_8 );
//return resultMessage;
}
private byte[] convertObjectToBytes(Object obj) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
return bos.toByteArray();
}
private byte[] convertObjectToBase64Bytes(Object obj) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
oos.close();
// 직렬화된 byte[] → Base64 문자열 → 다시 byte[]로 변환
String base64String = Base64.getEncoder().encodeToString(bos.toByteArray());
return base64String.getBytes(StandardCharsets.UTF_8);
}
public static Object convertBytesToObject(byte[] bytes) throws IOException, ClassNotFoundException {
try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bis)) {
return ois.readObject();
}
}
private byte[] doInboundPreDecrypt(String eaiStringBody, String decryptAlgorithm, String clientSecretKey, String secretAES256Iv, String secretAES256Key) throws Exception {
byte[] decryptedMessage = null;
//String eaiStringBody = new String(eaiBody, StandardCharsets.UTF_8);
eaiStringBody = extractBodyMsg(decryptAlgorithm, eaiStringBody);
if (eaiStringBody == null) {
throw new Exception("[ApiAdapterService] Cannot decrypt Error : input is plain text");
}
//test source
logger.debug("Base64 문자열: " + eaiStringBody);
logger.debug("Base64 문자열 길이: " + eaiStringBody.length());
logger.debug("Base64 문자열 끝: " + eaiStringBody.substring(eaiStringBody.length() - 10));
// Base64 디코딩 테스트
try {
byte[] decoded = Base64.getDecoder().decode(eaiStringBody);
logger.debug("디코딩 성공, 길이: " + decoded.length);
} catch (IllegalArgumentException e) {
logger.debug("Base64 디코딩 실패: " + e.getMessage());
}
// end test source
switch (decryptAlgorithm) {
case "AES128":
case "AES128-TOSS":
try {
String key128 = clientSecretKey.substring(22,38); //togetherEncoder 경우는 substring(44,60) 이네??
//String decryptedStrMessage = AESCipher.decrypt(eaiStringBody, key128);
String decryptedStrMessage = AESCipher.decryptExistException(eaiStringBody, key128);
decryptedMessage = decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
logger.error("HttpClientAdapterServiceRest] AES128 Decryption error=" + e.getMessage());
}
break;
case "AES128-TOGETHER":
try {
String key128 = clientSecretKey.substring(44,60); //togetherEncoder 경우는 substring(44,60) 이네??
//String decryptedStrMessage = AESCipher.decrypt(eaiStringBody, key128);
String decryptedStrMessage = AESCipher.decryptExistException(eaiStringBody, key128);
decryptedMessage = decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
logger.error("HttpClientAdapterServiceRest] AES128 Decryption error=" + e.getMessage());
}
break;
case "AES256":
try {
String key = clientSecretKey.substring(10,42);
String decryptedStrMessage = AES256Cipher.decrypt(eaiStringBody, key);
decryptedMessage = decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
logger.error("HttpClientAdapterServiceRest] AES256 Decryption error=" + e.getMessage());
}
break;
case "AES256-KAKAO":
try {
String decryptedStrMessage = AES256Cipher.decrypt(eaiStringBody, secretAES256Iv, secretAES256Key);
decryptedMessage = decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
logger.error("HttpClientAdapterServiceRest] AES256 Decryption error=" + e.getMessage());
}
break;
case "AES256-TOSS":
try {
String decryptedStrMessage = AES256Cipher.decrypt(eaiStringBody, secretAES256Iv, secretAES256Key);
decryptedMessage = decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
logger.error("HttpClientAdapterServiceRest] AES256 Decryption error=" + e.getMessage());
}
break;
case "AES256GCM":
try {
byte[] key = AES256GCMCipher.generateKey();
AES256GCMCipher cipher = new AES256GCMCipher(key);
byte[] aad = "metadata".getBytes();
String decryptedStrMessage = cipher.decrypt(eaiStringBody , aad);
decryptedMessage = decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
logger.error("HttpClientAdapterServiceRest] AES256GCM Encryption error=" + e.getMessage());
}
break;
default:
try {
decryptedMessage = eaiStringBody.getBytes();
} catch (Exception e) {
e.printStackTrace();
logger.error("HttpClientAdapterServiceRest] doOutboundPostFilter Array copy error=" + e.getMessage());
}
break;
}
return decryptedMessage;
}
private String extractBodyMsg(String decryptAlgorithm, String eaiStringBody) {
String decryptedJsonKey = "";
String decryptedBodyMessage = "";
decryptedJsonKey = getJsonKey(decryptAlgorithm);
try {
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(eaiStringBody);
decryptedBodyMessage = (String) jsonObject.get(decryptedJsonKey);
} catch (Exception e) {
e.printStackTrace();
logger.error("HttpClient5AdapterServiceRest] extractBodyMsg error : " + e.getMessage());
}
return decryptedBodyMessage;
}
private String getJsonKey(String Algorithm) {
String jsonKey = "";
switch (Algorithm) {
case "AES128":
case "AES128-TOSS":
jsonKey = "preScreeningRequest";
break;
case "AES128-TOGETHER":
jsonKey = "obpTxData";
break;
case "AES256":
jsonKey = "preScreeningRequest";
break;
case "AES256-KAKAO":
jsonKey = "encrypted_data";
break;
case "AES256-TOSS":
jsonKey = "encryptedData";
break;
case "AES256-NICEON":
jsonKey = "enc_data";
break;
case "AES256GCM":
break;
default:
break;
}
return jsonKey;
}
private String doInboundPostEncrypt(String eaiStringBody, String encryptAlgorithm, String clientSecretKey, String secretAES256Iv, String secretAES256Key) {
//byte[] encryptedMessage = null;
String encryptedStrMessage = null;
String encryptedJsonKey = "";
encryptedJsonKey = getJsonKey(encryptAlgorithm);
switch (encryptAlgorithm) {
case "AES128":
case "AES128-TOSS":
try {
String key128 = clientSecretKey.substring(22,38); //togetherEncoder 경우는 substring(44,60) 이네??
encryptedStrMessage = AESCipher.encrypt(eaiStringBody, key128);
//encryptedMessage = encryptedStrMessage.getBytes(StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
logger.error("HttpClientAdapterServiceRest] AES128 Encryption error=" + e.getMessage());
}
break;
case "AES128-TOGETHER":
try {
String key128 = clientSecretKey.substring(44,60); //togetherEncoder 경우는 substring(44,60) 이네??
encryptedStrMessage = AESCipher.encrypt(eaiStringBody, key128);
//encryptedMessage = encryptedStrMessage.getBytes(StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
logger.error("HttpClientAdapterServiceRest] AES128 Encryption error=" + e.getMessage());
}
break;
case "AES256":
try {
String key = clientSecretKey.substring(10,42);
encryptedStrMessage = AES256Cipher.encrypt(eaiStringBody, key);
//encryptedMessage = encryptedStrMessage.getBytes(StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
logger.error("HttpClientAdapterServiceRest] AES256 Encryption error=" + e.getMessage());
}
break;
case "AES256-KAKAO":
try {
encryptedStrMessage = AES256Cipher.encrypt(eaiStringBody, secretAES256Iv, secretAES256Key);
//encryptedMessage = encryptedStrMessage.getBytes(StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
logger.error("HttpClientAdapterServiceRest] AES256 Encryption error=" + e.getMessage());
}
break;
case "AES256-TOSS":
try {
encryptedStrMessage = AES256Cipher.encrypt(eaiStringBody, secretAES256Iv, secretAES256Key);
//encryptedMessage = encryptedStrMessage.getBytes(StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
logger.error("HttpClientAdapterServiceRest] AES256 Encryption error=" + e.getMessage());
}
break;
case "AES256GCM":
try {
byte[] key = AES256GCMCipher.generateKey();
AES256GCMCipher cipher = new AES256GCMCipher(key);
byte[] aad = "metadata".getBytes();
encryptedStrMessage = cipher.encrypt(eaiStringBody , aad);
//encryptedMessage = encryptedStrMessage.getBytes(StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
logger.error("HttpClientAdapterServiceRest] AES256GCM Encryption error=" + e.getMessage());
}
break;
default:
try {
encryptedStrMessage = eaiStringBody;
//encryptedMessage = eaiStringBody.getBytes();
} catch (Exception e) {
e.printStackTrace();
logger.error("HttpClientAdapterServiceRest] doOutboundPostFilter Array copy error=" + e.getMessage());
}
break;
}
Map<String, Object> map = new HashMap<>();
map.put(encryptedJsonKey, encryptedStrMessage);
JSONObject json = new JSONObject();
json.putAll(map);
return json.toJSONString();
//return encryptedMessage;
}
private String JwtTokenExtractor(HttpServletRequest request) {
String Token = "";
try {
Token = JwtAuthFilter.extractJWTToken(request);
} catch (Exception e) {
logger.error(e.getMessage());
}
logger.debug("Token is: " + Token);
return Token;
}
private String JwtClientIdExtractor(String inboundToken) {
String tokenClientId ="";
try {
SignedJWT signedJWT = SignedJWT.parse(inboundToken);
tokenClientId = (String) signedJWT.getJWTClaimsSet().getClaim(PAYLOAD_PARAM_NAME_CLIENT_ID);
} catch (Exception e) {
logger.error(e.getMessage());
tokenClientId = "";
}
logger.debug("Token Client ID: " + tokenClientId);
return tokenClientId;
}
// jwhong until here
private Map<String, String[]> assignParameterMap(HttpServletRequest request, String adptGrpName, String adptName,
Object requestBytes, Properties prop) {
// PathVariable 체크
@@ -406,11 +852,11 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
return request.getParameterMap();
}
private String getRewritePath(String extUri, String basePath) {
return StringUtils.removeStart(extUri, StringUtils.removeEnd(basePath, "/"));
}
private Map<String, String> assignPathVariables(HttpServletRequest request, String adptGrpName, String adptName,
Object requestBytes, Properties prop) {
Map<String, String> variablesMap = null;
@@ -435,7 +881,7 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
return variablesMap;
}
private Properties getHeaders(HttpServletRequest request) {
Properties prop = new Properties();
@@ -478,6 +924,11 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
}
/**
* HTTP 요청에서 클라이언트 IP를 추출합니다.
* X-Forwarded-For 헤더가 있는 경우 이를 우선적으로 사용하고,
* 없는 경우 remoteAddr을 사용합니다.
*/
private String getClientIp(HttpServletRequest request) {
String ipAddress = request.getHeader("X-Forwarded-For");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
@@ -497,4 +948,35 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
}
return ipAddress;
}
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;
}
}
@@ -0,0 +1,82 @@
package com.eactive.eai.custom.adapter.http.dynamic.filter;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import com.eactive.eai.adapter.http.dynamic.filter.CryptoFilter;
import com.eactive.eai.util.JsonPathUtil;
/**
* DJB ERP 연동용 암복호화 필터.
*
* DYNAMIC 키 컨텍스트 추출 규칙:
* HTTP 헤더 {@code httpHeaderGroup}의 값은 JSON 객체이며,
* 그 중 {@code x-emp-nm} 필드 값을 {@code groupSeq}로
* runtimeContext에 담아 키 도출 전략에 전달한다.
*
* 어댑터 프로퍼티 (부모 클래스 공통 설정 외 추가 키):
* crypto.context.key runtimeContext에 넣을 키 이름 (기본: groupSeq)
* crypto.context.header 컨텍스트 JSON이 담긴 HTTP 헤더명 (기본: httpHeaderGroup)
* crypto.context.header.field 헤더 JSON에서 추출할 필드명 (기본: x-emp-nm)
*
* 어댑터 프로퍼티 설정 예:
* crypto.module.name = AES_GCM_NoPadding_DYNAMIC_sample
* crypto.scope = FIELD
* crypto.dec.enabled = Y
* crypto.enc.enabled = N
* crypto.dec.from.path = /encryptedData
* crypto.dec.to.path = /
* crypto.context.key = groupSeq
* crypto.context.header = httpHeaderGroup
* crypto.context.header.field = x-emp-nm
*
* 필터 타입 등록 (FQCN):
* com.eactive.eai.custom.adapter.http.dynamic.filter.DJBErpCryptoFilter
*/
public class DJBErpCryptoFilter extends CryptoFilter {
public static final String PROP_CONTEXT_KEY = "crypto.context.key";
public static final String PROP_CONTEXT_HEADER = "crypto.context.header";
public static final String PROP_CONTEXT_HEADER_FIELD = "crypto.context.header.field";
private static final String DEFAULT_CONTEXT_KEY = "groupSeq";
private static final String DEFAULT_CONTEXT_HEADER = "httpHeaderGroup";
private static final String DEFAULT_CONTEXT_HEADER_FIELD = "x-emp-nm";
/**
* httpHeaderGroup 헤더(JSON)에서 x-emp-nm 값을 추출하여 groupSeq로 매핑한다.
* 헤더가 없거나 필드를 찾을 수 없으면 빈 Map을 반환한다.
*/
@Override
protected Map<String, String> buildRuntimeContext(Properties prop, HttpServletRequest request) {
Map<String, String> ctx = new HashMap<>();
String contextKey = prop.getProperty(PROP_CONTEXT_KEY, DEFAULT_CONTEXT_KEY);
String contextHeaderName = prop.getProperty(PROP_CONTEXT_HEADER, DEFAULT_CONTEXT_HEADER);
String contextHeaderField = prop.getProperty(PROP_CONTEXT_HEADER_FIELD, DEFAULT_CONTEXT_HEADER_FIELD);
String headerJson = request.getHeader(contextHeaderName);
if (StringUtils.isBlank(headerJson)) {
logger.warn("DJBErpCryptoFilter] 컨텍스트 헤더 없음: " + contextHeaderName);
return ctx;
}
String value = JsonPathUtil.getValueAtPath(headerJson, "/" + contextHeaderField);
if (value == null) {
logger.warn("DJBErpCryptoFilter] 헤더 JSON에서 필드 추출 실패: header="
+ contextHeaderName + ", field=" + contextHeaderField);
return ctx;
}
// x-emp-nm 값은 "groupSeq|empNo" 형태 — '|' 앞부분만 groupSeq로 사용
String groupSeq = value.contains("|") ? value.substring(0, value.indexOf('|')) : value;
ctx.put(contextKey, groupSeq);
return ctx;
}
}
@@ -0,0 +1,81 @@
package com.eactive.eai.custom.inbound.processor;
import org.apache.commons.lang3.StringUtils;
import com.eactive.eai.common.inflow.Bucket;
import com.eactive.eai.common.inflow.InflowTargetVO;
import com.eactive.eai.common.inflow.dual.ClientDualBucket;
import com.eactive.eai.common.inflow.dual.DualBucket;
import com.eactive.eai.common.inflow.dual.DualCustomBucket;
import com.eactive.eai.inbound.processor.RequestProcessor;
/**
* 어댑터/인터페이스/클라이언트 유량제어 차단 시 어느 버킷(PER_SECOND/THRESHOLD)에서
* 차단됐는지 에러 메시지에 포함하는 RequestProcessor 확장.
*
* <p>ClientDualInflowControlManager와 함께 사용:
* <pre>
* inflow.control.bucket.className=com.eactive.eai.common.inflow.dual.ClientDualInflowControlManager
* </pre>
*
* <p>Spring Bean 등록 후 기존 RequestProcessor 대신 이 클래스를 어댑터에 설정한다.
*/
public class DJBRequestProcessor extends RequestProcessor {
@Override
protected String checkClientInflow(Bucket bucket, String clientId) {
if (StringUtils.isBlank(clientId)) return null;
if (bucket instanceof ClientDualBucket) {
return ((ClientDualBucket) bucket).isClientPassDetail(clientId);
}
return null;
}
@Override
protected InflowTargetVO resolveClientInflowThreshold(Bucket bucket, String clientId) {
if (bucket instanceof ClientDualBucket) {
return ((ClientDualBucket) bucket).getClientInflowThreshold(clientId);
}
return null;
}
@Override
protected String checkAdapterInflow(Bucket bucket, String adapterGroupName) {
if (bucket instanceof DualBucket) {
return ((DualBucket) bucket).isAdapterPassDetail(adapterGroupName);
}
return super.checkAdapterInflow(bucket, adapterGroupName);
}
@Override
protected String checkInterfaceInflow(Bucket bucket, String eaiSvcCd) {
if (bucket instanceof DualBucket) {
return ((DualBucket) bucket).isInterfacePassDetail(eaiSvcCd);
}
return super.checkInterfaceInflow(bucket, eaiSvcCd);
}
/**
* 차단 원인에 따라 에러 메시지에 한도 정보를 포함.
* <ul>
* <li>PER_SECOND: "API 호출 한도 초과 [name: Nreq/sec]"</li>
* <li>THRESHOLD: "API 호출 한도 초과 [name: Nreq/UNIT]"</li>
* <li>그 외: "API 호출 한도 초과 [name]" (기존 동작)</li>
* </ul>
*/
@Override
protected String buildInflowTargetErrorMsg(InflowTargetVO inflowTargetVO, String blockedType) {
if (DualCustomBucket.RESULT_BLOCKED_PER_SECOND.equals(blockedType)) {
return String.format("API 호출 한도 초과 [%s: %dreq/sec]",
inflowTargetVO.getName(),
inflowTargetVO.getThresholdPerSecond());
}
if (DualCustomBucket.RESULT_BLOCKED_THRESHOLD.equals(blockedType)) {
return String.format("API 호출 한도 초과 [%s: %dreq/%s]",
inflowTargetVO.getName(),
inflowTargetVO.getThreshold(),
inflowTargetVO.getThresholdTimeUnit());
}
return super.buildInflowTargetErrorMsg(inflowTargetVO, blockedType);
}
}
@@ -0,0 +1,63 @@
package com.eactive.eai.custom.inflow;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.eactive.eai.manage.inflow.TargetBucketStatusDTO;
/**
* 클라이언트 버킷 상태 모니터링 API.
*
* ClientDualInflowControlManager 가 활성화된 환경에서만 정상 응답한다.
*
* GET /manage/inflow/client/bucket-status → 전체 클라이언트 버킷 상태
* GET /manage/inflow/client/{clientId}/bucket-status → 특정 클라이언트 버킷 상태
*/
@RestController
@RequestMapping("/manage/inflow")
public class ClientInflowTargetBucketController {
@Autowired
private ClientInflowTargetBucketService bucketService;
@GetMapping("/client/bucket-status")
public ResponseEntity<?> getAllClientBucketStatus() {
List<TargetBucketStatusDTO> list = bucketService.getAllClientBucketStatus();
return ok(list);
}
@GetMapping("/client/{clientId}/bucket-status")
public ResponseEntity<?> getClientBucketStatus(@PathVariable String clientId) {
TargetBucketStatusDTO dto = bucketService.getClientBucketStatus(clientId);
return single(dto, "클라이언트를 찾을 수 없습니다: " + clientId);
}
private ResponseEntity<?> ok(List<TargetBucketStatusDTO> list) {
Map<String, Object> result = new HashMap<>();
result.put("success", true);
result.put("data", list);
result.put("count", list.size());
return ResponseEntity.ok(result);
}
private ResponseEntity<?> single(TargetBucketStatusDTO dto, String notFoundMsg) {
if (dto == null) {
Map<String, Object> error = new HashMap<>();
error.put("success", false);
error.put("message", notFoundMsg);
return ResponseEntity.ok(error);
}
Map<String, Object> result = new HashMap<>();
result.put("success", true);
result.put("data", dto);
return ResponseEntity.ok(result);
}
}
@@ -0,0 +1,79 @@
package com.eactive.eai.custom.inflow;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
import com.eactive.eai.common.inflow.AbstractInflowControlManager;
import com.eactive.eai.common.inflow.InflowControlUtil;
import com.eactive.eai.common.inflow.InflowTargetVO;
import com.eactive.eai.common.inflow.dual.ClientDualInflowControlManager;
import com.eactive.eai.common.inflow.dual.DualCustomBucket;
import com.eactive.eai.manage.inflow.GroupBucketStatusDTO;
import com.eactive.eai.manage.inflow.TargetBucketStatusDTO;
/**
* 클라이언트 버킷 상태 조회 서비스.
*
* ClientDualInflowControlManager 가 활성화된 경우에만 동작한다.
*/
@Service
public class ClientInflowTargetBucketService {
public TargetBucketStatusDTO getClientBucketStatus(String clientId) {
ClientDualInflowControlManager manager = getClientDualManager();
if (manager == null) return null;
DualCustomBucket bucket = manager.getClientBucket(clientId);
if (bucket == null) return null;
return toDto(clientId, "CLIENT", bucket);
}
public List<TargetBucketStatusDTO> getAllClientBucketStatus() {
ClientDualInflowControlManager manager = getClientDualManager();
if (manager == null) return new ArrayList<>();
return toDtoList("CLIENT", manager.getClientBucketMap());
}
protected ClientDualInflowControlManager getClientDualManager() {
AbstractInflowControlManager base = InflowControlUtil.getInflowControlManager();
return (base instanceof ClientDualInflowControlManager) ? (ClientDualInflowControlManager) base : null;
}
private TargetBucketStatusDTO toDto(String targetId, String targetType, DualCustomBucket bucket) {
InflowTargetVO vo = bucket.getInflowTargetVo();
List<GroupBucketStatusDTO.BucketInfo> buckets = new ArrayList<>();
if (vo.getThresholdPerSecond() > 0) {
long capacity = vo.getThresholdPerSecond();
long available = bucket.getPerSecondAvailableTokens();
if (available < 0) available = capacity;
buckets.add(new GroupBucketStatusDTO.BucketInfo(
"perSecond", capacity, Math.min(available, capacity), "SEC"));
}
if (vo.getThreshold() > 0) {
long capacity = vo.getThreshold();
long available = bucket.getThresholdAvailableTokens();
if (available < 0) available = capacity;
buckets.add(new GroupBucketStatusDTO.BucketInfo(
"threshold", capacity, Math.min(available, capacity), vo.getThresholdTimeUnit()));
}
TargetBucketStatusDTO dto = new TargetBucketStatusDTO();
dto.setTargetId(targetId);
dto.setTargetType(targetType);
dto.setActivate(vo.isActivate());
dto.setBuckets(buckets);
return dto;
}
private List<TargetBucketStatusDTO> toDtoList(String targetType, Map<String, DualCustomBucket> bucketMap) {
List<TargetBucketStatusDTO> result = new ArrayList<>();
for (Map.Entry<String, DualCustomBucket> entry : bucketMap.entrySet()) {
result.add(toDto(entry.getKey(), targetType, entry.getValue()));
}
return result;
}
}
@@ -0,0 +1,94 @@
package com.eactive.eai.custom.inflow;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.eactive.eai.manage.inflow.TargetMetricDTO;
/**
* 클라이언트 유량제어 메트릭 API.
*
* ClientDualInflowControlManager 가 활성화된 환경에서만 정상 응답한다.
*
* GET /manage/inflow/client/metric → 전체 클라이언트 메트릭
* GET /manage/inflow/client/{clientId}/metric → 특정 클라이언트 메트릭
* POST /manage/inflow/client/metric/reset → 전체 클라이언트 메트릭 초기화
* POST /manage/inflow/client/{clientId}/metric/reset → 특정 클라이언트 메트릭 초기화
*/
@RestController
@RequestMapping("/manage/inflow")
public class ClientInflowTargetMetricController {
@Autowired
private ClientInflowTargetMetricService metricService;
@GetMapping("/client/metric")
public ResponseEntity<?> getAllClientMetrics() {
List<TargetMetricDTO> list = metricService.getAllClientMetrics();
return okList(list);
}
@GetMapping("/client/{clientId}/metric")
public ResponseEntity<?> getClientMetric(@PathVariable String clientId) {
TargetMetricDTO dto = metricService.getClientMetric(clientId);
return okSingle(dto, "클라이언트를 찾을 수 없습니다: " + clientId);
}
@PostMapping("/client/metric/reset")
public ResponseEntity<?> resetAllClientMetrics() {
metricService.resetAllClientMetrics();
return okReset("전체 클라이언트 메트릭 초기화 완료");
}
@PostMapping("/client/{clientId}/metric/reset")
public ResponseEntity<?> resetClientMetric(@PathVariable String clientId) {
boolean ok = metricService.resetClientMetric(clientId);
return okResetSingle(ok, clientId, "클라이언트");
}
private ResponseEntity<?> okList(List<TargetMetricDTO> list) {
Map<String, Object> result = new HashMap<>();
result.put("success", true);
result.put("data", list);
result.put("count", list.size());
return ResponseEntity.ok(result);
}
private ResponseEntity<?> okSingle(TargetMetricDTO dto, String notFoundMsg) {
if (dto == null) {
Map<String, Object> error = new HashMap<>();
error.put("success", false);
error.put("message", notFoundMsg);
return ResponseEntity.ok(error);
}
Map<String, Object> result = new HashMap<>();
result.put("success", true);
result.put("data", dto);
return ResponseEntity.ok(result);
}
private ResponseEntity<?> okReset(String message) {
Map<String, Object> result = new HashMap<>();
result.put("success", true);
result.put("message", message);
return ResponseEntity.ok(result);
}
private ResponseEntity<?> okResetSingle(boolean ok, String targetId, String targetLabel) {
Map<String, Object> result = new HashMap<>();
result.put("success", ok);
result.put("message", ok
? "초기화 완료: " + targetId
: targetLabel + "를 찾을 수 없습니다: " + targetId);
return ResponseEntity.ok(result);
}
}
@@ -0,0 +1,79 @@
package com.eactive.eai.custom.inflow;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;
import com.eactive.eai.common.inflow.AbstractInflowControlManager;
import com.eactive.eai.common.inflow.InflowControlUtil;
import com.eactive.eai.common.inflow.InflowTargetVO;
import com.eactive.eai.common.inflow.dual.ClientDualInflowControlManager;
import com.eactive.eai.common.inflow.dual.DualInflowControlManager;
import com.eactive.eai.manage.inflow.TargetMetricDTO;
@Service
public class ClientInflowTargetMetricService {
public TargetMetricDTO getClientMetric(String clientId) {
ClientDualInflowControlManager manager = getClientDualManager();
if (manager == null) return null;
InflowTargetVO vo = manager.getClientInflowThreshold(clientId);
if (vo == null) return null;
return buildDTO(clientId, "CLIENT", vo, manager.getClientMetrics(clientId));
}
public List<TargetMetricDTO> getAllClientMetrics() {
ClientDualInflowControlManager manager = getClientDualManager();
if (manager == null) return new ArrayList<>();
List<TargetMetricDTO> result = new ArrayList<>();
for (String id : manager.getClientBucketMap().keySet()) {
TargetMetricDTO dto = getClientMetric(id);
if (dto != null) result.add(dto);
}
return result;
}
public boolean resetClientMetric(String clientId) {
ClientDualInflowControlManager manager = getClientDualManager();
if (manager == null) return false;
if (manager.getClientInflowThreshold(clientId) == null) return false;
manager.resetClientMetrics(clientId);
return true;
}
public void resetAllClientMetrics() {
ClientDualInflowControlManager manager = getClientDualManager();
if (manager != null) manager.resetAllClientMetrics();
}
protected ClientDualInflowControlManager getClientDualManager() {
AbstractInflowControlManager base = InflowControlUtil.getInflowControlManager();
return (base instanceof ClientDualInflowControlManager) ? (ClientDualInflowControlManager) base : null;
}
private TargetMetricDTO buildDTO(String targetId, String targetType,
InflowTargetVO vo,
DualInflowControlManager.TargetMetrics m) {
TargetMetricDTO dto = new TargetMetricDTO();
dto.setTargetId(targetId);
dto.setTargetType(targetType);
dto.setActivate(vo.isActivate());
if (m != null) {
long allowed = m.allowed.get();
long rejPs = m.rejectedPerSecond.get();
long rejTh = m.rejectedThreshold.get();
long total = allowed + rejPs + rejTh;
dto.setAllowed(allowed);
dto.setRejectedPerSecond(rejPs);
dto.setRejectedThreshold(rejTh);
dto.setTotalRequests(total);
dto.setRejectRatio(total > 0
? Math.round((double)(rejPs + rejTh) / total * 10000) / 100.0
: 0.0);
dto.setLastResetTime(m.lastResetTime);
}
return dto;
}
}
@@ -0,0 +1,68 @@
package com.eactive.eai.custom.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 {
/** DB key_deriv_strategy 컬럼에 사용하는 FQCN 참조용 상수. */
public static final String STRATEGY_CLASS = HsmContextSha256KeyDerivationStrategy.class.getName();
private static final String PARAM_HSM_KEY_ALIAS = "hsmKeyAlias";
private static final String PARAM_CONTEXT_KEY = "contextKey";
@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);
}
}
@@ -21,8 +21,6 @@ import org.springframework.web.bind.annotation.RestController;
* GET /manage/inflow/adapter/{adapterId}/bucket-status → 특정 어댑터 버킷 상태
* GET /manage/inflow/interface/bucket-status → 전체 인터페이스 버킷 상태
* GET /manage/inflow/interface/{interfaceId}/bucket-status → 특정 인터페이스 버킷 상태
* GET /manage/inflow/client/bucket-status → 전체 클라이언트 버킷 상태
* GET /manage/inflow/client/{clientId}/bucket-status → 특정 클라이언트 버킷 상태
*/
@RestController
@RequestMapping("/manage/inflow")
@@ -63,22 +61,6 @@ public class InflowTargetBucketController {
return single(dto, "인터페이스를 찾을 수 없습니다: " + interfaceId);
}
// =========================================================================
// 클라이언트
// =========================================================================
@GetMapping("/client/bucket-status")
public ResponseEntity<?> getAllClientBucketStatus() {
List<TargetBucketStatusDTO> list = bucketService.getAllClientBucketStatus();
return ok(list);
}
@GetMapping("/client/{clientId}/bucket-status")
public ResponseEntity<?> getClientBucketStatus(@PathVariable String clientId) {
TargetBucketStatusDTO dto = bucketService.getClientBucketStatus(clientId);
return single(dto, "클라이언트를 찾을 수 없습니다: " + clientId);
}
// =========================================================================
// Helpers
// =========================================================================
@@ -57,24 +57,6 @@ public class InflowTargetBucketService {
return toDtoList("INTERFACE", manager.getInterfaceBucketMap());
}
// -------------------------------------------------------------------------
// 클라이언트
// -------------------------------------------------------------------------
public TargetBucketStatusDTO getClientBucketStatus(String clientId) {
DualInflowControlManager manager = getDualManager();
if (manager == null) return null;
DualCustomBucket bucket = manager.getClientBucket(clientId);
if (bucket == null) return null;
return toDto(clientId, "CLIENT", bucket);
}
public List<TargetBucketStatusDTO> getAllClientBucketStatus() {
DualInflowControlManager manager = getDualManager();
if (manager == null) return new ArrayList<>();
return toDtoList("CLIENT", manager.getClientBucketMap());
}
// -------------------------------------------------------------------------
// Private helpers
// -------------------------------------------------------------------------
@@ -13,7 +13,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 어댑터/인터페이스/클라이언트 유량제어 메트릭 API.
* 어댑터/인터페이스 유량제어 메트릭 API.
*
* DualInflowControlManager 가 활성화된 환경에서만 정상 응답한다.
*
@@ -26,11 +26,6 @@ import org.springframework.web.bind.annotation.RestController;
* GET /manage/inflow/interface/{interfaceId}/metric → 특정 인터페이스 메트릭
* POST /manage/inflow/interface/metric/reset → 전체 인터페이스 메트릭 초기화
* POST /manage/inflow/interface/{interfaceId}/metric/reset → 특정 인터페이스 메트릭 초기화
*
* GET /manage/inflow/client/metric → 전체 클라이언트 메트릭
* GET /manage/inflow/client/{clientId}/metric → 특정 클라이언트 메트릭
* POST /manage/inflow/client/metric/reset → 전체 클라이언트 메트릭 초기화
* POST /manage/inflow/client/{clientId}/metric/reset → 특정 클라이언트 메트릭 초기화
*/
@RestController
@RequestMapping("/manage/inflow")
@@ -95,34 +90,6 @@ public class InflowTargetMetricController {
return okResetSingle(ok, interfaceId, "인터페이스");
}
// =========================================================================
// 클라이언트
// =========================================================================
@GetMapping("/client/metric")
public ResponseEntity<?> getAllClientMetrics() {
List<TargetMetricDTO> list = metricService.getAllClientMetrics();
return okList(list);
}
@GetMapping("/client/{clientId}/metric")
public ResponseEntity<?> getClientMetric(@PathVariable String clientId) {
TargetMetricDTO dto = metricService.getClientMetric(clientId);
return okSingle(dto, "클라이언트를 찾을 수 없습니다: " + clientId);
}
@PostMapping("/client/metric/reset")
public ResponseEntity<?> resetAllClientMetrics() {
metricService.resetAllClientMetrics();
return okReset("전체 클라이언트 메트릭 초기화 완료");
}
@PostMapping("/client/{clientId}/metric/reset")
public ResponseEntity<?> resetClientMetric(@PathVariable String clientId) {
boolean ok = metricService.resetClientMetric(clientId);
return okResetSingle(ok, clientId, "클라이언트");
}
// =========================================================================
// Helpers
// =========================================================================
@@ -85,42 +85,6 @@ public class InflowTargetMetricService {
if (manager != null) manager.resetAllInterfaceMetrics();
}
// -------------------------------------------------------------------------
// 클라이언트
// -------------------------------------------------------------------------
public TargetMetricDTO getClientMetric(String clientId) {
DualInflowControlManager manager = getDualManager();
if (manager == null) return null;
InflowTargetVO vo = manager.getClientInflowThreshold(clientId);
if (vo == null) return null;
return buildDTO(clientId, "CLIENT", vo, manager.getClientMetrics(clientId));
}
public List<TargetMetricDTO> getAllClientMetrics() {
DualInflowControlManager manager = getDualManager();
if (manager == null) return new ArrayList<>();
List<TargetMetricDTO> result = new ArrayList<>();
for (String id : manager.getClientBucketMap().keySet()) {
TargetMetricDTO dto = getClientMetric(id);
if (dto != null) result.add(dto);
}
return result;
}
public boolean resetClientMetric(String clientId) {
DualInflowControlManager manager = getDualManager();
if (manager == null) return false;
if (manager.getClientInflowThreshold(clientId) == null) return false;
manager.resetClientMetrics(clientId);
return true;
}
public void resetAllClientMetrics() {
DualInflowControlManager manager = getDualManager();
if (manager != null) manager.resetAllClientMetrics();
}
// -------------------------------------------------------------------------
// Private helpers
// -------------------------------------------------------------------------
@@ -8,7 +8,7 @@ mapper.definition=standard-message-mapping-config-djb.properties
# StandardMessage Coordinator implementation
message.coordinator.class=com.eactive.eai.custom.message.StandardMessageCoordinatorDJB
# RequestProcessor implementation
requestProcessor.class=com.eactive.eai.inbound.processor.DualRequestProcessor
requestProcessor.class=com.eactive.eai.custom.inbound.processor.DJBRequestProcessor
# reader : parsing input data to StandardMessage
reader.JSON=com.eactive.eai.message.parser.JsonReader
reader.JSN=com.eactive.eai.message.parser.JsonReader
@@ -0,0 +1,317 @@
package com.eactive.eai.custom.adapter.http.dynamic.filter;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
import java.util.Properties;
import org.mockito.ArgumentCaptor;
import javax.servlet.http.HttpServletRequest;
import org.json.simple.JSONObject;
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.common.security.CryptoModuleService;
import com.eactive.eai.common.util.ApplicationContextProvider;
@TestMethodOrder(MethodOrderer.DisplayName.class)
class DJBErpCryptoFilterTest {
private static final String MODULE_NAME = "TEST_MODULE";
// 복호화 평문 (JSON 문자열)
private static final String PLAIN_TEXT = "{\"userId\":\"U001\",\"name\":\"test\"}";
private static final byte[] PLAIN_BYTES = PLAIN_TEXT.getBytes(StandardCharsets.UTF_8);
// 더미 암호문 bytes + Base64 표현
private static final byte[] CIPHER_BYTES = new byte[]{0x10, 0x20, 0x30, 0x40};
private static final String ENC_BASE64 = Base64.getEncoder().encodeToString(CIPHER_BYTES);
// 기본 httpHeaderGroup 헤더 JSON (groupSeq|empNo 형태)
private static final String HEADER_JSON_WITH_PIPE = "{\"x-emp-nm\":\"G001|E001\"}";
private static final String HEADER_JSON_WITHOUT_PIPE = "{\"x-emp-nm\":\"G001\"}";
private static GenericApplicationContext ctx;
private static CryptoModuleService mockCryptoService;
private DJBErpCryptoFilter filter;
private HttpServletRequest mockRequest;
private Properties prop;
// =========================================================================
// 클래스 초기화 Spring ApplicationContext + Mock CryptoModuleService
// =========================================================================
@BeforeAll
static void setUpClass() throws Exception {
mockCryptoService = mock(CryptoModuleService.class);
ctx = new GenericApplicationContext();
ctx.getBeanFactory().registerSingleton("cryptoModuleService", mockCryptoService);
ctx.registerBeanDefinition("applicationContextProvider",
BeanDefinitionBuilder.genericBeanDefinition(ApplicationContextProvider.class)
.getBeanDefinition());
ctx.refresh();
when(mockCryptoService.decrypt(anyString(), anyMap(), any(byte[].class)))
.thenReturn(PLAIN_BYTES);
when(mockCryptoService.encrypt(anyString(), anyMap(), any(byte[].class)))
.thenReturn(CIPHER_BYTES);
}
@AfterAll
static void tearDownClass() {
if (ctx != null) ctx.close();
}
@BeforeEach
void setUp() {
clearInvocations(mockCryptoService); // 이전 테스트의 호출 이력 초기화 (stubbing은 유지)
filter = new DJBErpCryptoFilter();
mockRequest = mock(HttpServletRequest.class);
prop = new Properties();
prop.setProperty(DJBErpCryptoFilter.PROP_MODULE_NAME, MODULE_NAME);
}
// =========================================================================
// 1. buildRuntimeContext
// =========================================================================
@Test
@DisplayName("1-1. x-emp-nm이 'groupSeq|empNo' 형태이면 '|' 앞부분만 groupSeq로 추출")
void buildRuntimeContext_pipeFormat_extractsGroupSeqOnly() {
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn(HEADER_JSON_WITH_PIPE);
Map<String, String> runtimeCtx = filter.buildRuntimeContext(prop, mockRequest);
assertEquals("G001", runtimeCtx.get("groupSeq"));
assertEquals(1, runtimeCtx.size());
}
@Test
@DisplayName("1-2. x-emp-nm에 '|'가 없으면 전체 값을 groupSeq로 사용")
void buildRuntimeContext_noPipe_usesFullValue() {
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn(HEADER_JSON_WITHOUT_PIPE);
Map<String, String> runtimeCtx = filter.buildRuntimeContext(prop, mockRequest);
assertEquals("G001", runtimeCtx.get("groupSeq"));
}
@Test
@DisplayName("1-3. httpHeaderGroup 헤더가 없으면 빈 Map 반환")
void buildRuntimeContext_headerMissing_returnsEmptyMap() {
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn(null);
Map<String, String> runtimeCtx = filter.buildRuntimeContext(prop, mockRequest);
assertTrue(runtimeCtx.isEmpty());
}
@Test
@DisplayName("1-4. 헤더 JSON에 x-emp-nm 필드가 없으면 빈 Map 반환")
void buildRuntimeContext_fieldMissingInJson_returnsEmptyMap() {
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn("{\"other-field\":\"value\"}");
Map<String, String> runtimeCtx = filter.buildRuntimeContext(prop, mockRequest);
assertTrue(runtimeCtx.isEmpty());
}
@Test
@DisplayName("1-5. 프로퍼티로 헤더명/필드명/컨텍스트키를 커스터마이징할 수 있다")
void buildRuntimeContext_customProps_overrideDefaults() {
prop.setProperty(DJBErpCryptoFilter.PROP_CONTEXT_HEADER, "X-Custom-Header");
prop.setProperty(DJBErpCryptoFilter.PROP_CONTEXT_HEADER_FIELD, "emp-id");
prop.setProperty(DJBErpCryptoFilter.PROP_CONTEXT_KEY, "empGroup");
when(mockRequest.getHeader("X-Custom-Header")).thenReturn("{\"emp-id\":\"GRP99|EMP99\"}");
Map<String, String> runtimeCtx = filter.buildRuntimeContext(prop, mockRequest);
assertEquals("GRP99", runtimeCtx.get("empGroup"));
}
// =========================================================================
// 2. doPreFilter 복호화
// =========================================================================
@Test
@DisplayName("2-1. crypto.dec.enabled=N 이면 message를 그대로 반환하고 복호화하지 않는다")
void doPreFilter_decDisabled_returnsOriginalWithoutDecrypt() throws Exception {
prop.setProperty("crypto.dec.enabled", "N");
String original = "{\"encryptedData\":\"" + ENC_BASE64 + "\"}";
Object result = filter.doPreFilter(null, null, original, prop, mockRequest, null);
assertSame(original, result);
verifyNoInteractions(mockCryptoService);
}
@Test
@DisplayName("2-2. FIELD scope: /encryptedData 복호화 후 dec.to.path=/ 이면 body 전체를 평문으로 교체")
void doPreFilter_fieldScope_toRoot_replacesEntireBody() throws Exception {
setFieldDecryptProps("/encryptedData", "/");
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn(HEADER_JSON_WITH_PIPE);
String body = "{\"encryptedData\":\"" + ENC_BASE64 + "\"}";
Object result = filter.doPreFilter(null, null, body, prop, mockRequest, null);
assertEquals(PLAIN_TEXT, result);
}
@Test
@DisplayName("2-3. FIELD scope: dec.to.path가 특정 경로이면 해당 필드에 복호화 결과를 설정")
void doPreFilter_fieldScope_toSpecificPath_setsFieldInBody() throws Exception {
setFieldDecryptProps("/encryptedData", "/plainData");
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn(HEADER_JSON_WITH_PIPE);
String body = "{\"encryptedData\":\"" + ENC_BASE64 + "\"}";
String result = (String) filter.doPreFilter(null, null, body, prop, mockRequest, null);
assertTrue(result.contains("\"encryptedData\""), "원본 필드가 유지되어야 한다");
assertTrue(result.contains("\"plainData\""), "복호화 결과 필드가 추가되어야 한다");
}
@Test
@DisplayName("2-4. FIELD scope: 복호화 대상 필드가 JSON에 없으면 원본 body를 그대로 반환")
void doPreFilter_fieldScope_missingEncryptedField_returnsOriginalBody() throws Exception {
setFieldDecryptProps("/encryptedData", "/");
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn(HEADER_JSON_WITH_PIPE);
String body = "{\"otherField\":\"value\"}";
Object result = filter.doPreFilter(null, null, body, prop, mockRequest, null);
assertEquals(body, result);
}
@Test
@DisplayName("2-5. BODY scope: message가 Base64 String이면 전체 복호화")
void doPreFilter_bodyScope_stringMessage_decryptsWholeBody() throws Exception {
prop.setProperty("crypto.scope", "BODY");
Object result = filter.doPreFilter(null, null, ENC_BASE64, prop, mockRequest, null);
assertEquals(PLAIN_TEXT, result);
}
@Test
@DisplayName("2-6. message가 byte[]이면 UTF-8 변환 후 FIELD 복호화 처리")
void doPreFilter_fieldScope_byteArrayMessage_convertsAndDecrypts() throws Exception {
setFieldDecryptProps("/encryptedData", "/");
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn(HEADER_JSON_WITH_PIPE);
byte[] bodyBytes = ("{\"encryptedData\":\"" + ENC_BASE64 + "\"}").getBytes(StandardCharsets.UTF_8);
Object result = filter.doPreFilter(null, null, bodyBytes, prop, mockRequest, null);
assertEquals(PLAIN_TEXT, result);
}
@SuppressWarnings("unchecked")
@Test
@DisplayName("2-7. message가 JSONObject이면 toString() 변환 후 FIELD 복호화 처리")
void doPreFilter_fieldScope_jsonObjectMessage_convertsAndDecrypts() throws Exception {
setFieldDecryptProps("/encryptedData", "/");
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn(HEADER_JSON_WITH_PIPE);
JSONObject jsonMsg = new JSONObject();
jsonMsg.put("encryptedData", ENC_BASE64);
Object result = filter.doPreFilter(null, null, jsonMsg, prop, mockRequest, null);
assertEquals(PLAIN_TEXT, result);
}
@SuppressWarnings("unchecked")
@Test
@DisplayName("2-8. FIELD scope: runtimeContext에 groupSeq가 올바르게 전달된다")
void doPreFilter_fieldScope_runtimeContextPassedToDecrypt() throws Exception {
setFieldDecryptProps("/encryptedData", "/");
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn(HEADER_JSON_WITH_PIPE);
String body = "{\"encryptedData\":\"" + ENC_BASE64 + "\"}";
filter.doPreFilter(null, null, body, prop, mockRequest, null);
ArgumentCaptor<Map> ctxCaptor = ArgumentCaptor.forClass(Map.class);
verify(mockCryptoService).decrypt(eq(MODULE_NAME), ctxCaptor.capture(), any(byte[].class));
assertEquals("G001", ctxCaptor.getValue().get("groupSeq"));
}
// =========================================================================
// 3. doPostFilter 암호화
// =========================================================================
@Test
@DisplayName("3-1. crypto.enc.enabled 기본값(N) — resultMessage를 그대로 반환하고 암호화하지 않는다")
void doPostFilter_encDisabledByDefault_returnsOriginalWithoutEncrypt() throws Exception {
String original = "{\"result\":\"ok\"}";
Object result = filter.doPostFilter(null, null, original, prop, mockRequest, null);
assertSame(original, result);
verifyNoInteractions(mockCryptoService);
}
@Test
@DisplayName("3-2. BODY scope, enc.enabled=Y — body 전체를 암호화하여 Base64 반환")
void doPostFilter_bodyScope_encEnabled_returnsBase64() throws Exception {
prop.setProperty("crypto.scope", "BODY");
prop.setProperty("crypto.enc.enabled", "Y");
Object result = filter.doPostFilter(null, null, PLAIN_TEXT, prop, mockRequest, null);
assertEquals(ENC_BASE64, result);
}
@Test
@DisplayName("3-3. FIELD scope, enc.from.path=/ — body 전체 암호화 후 enc.to.path 필드로 래핑")
void doPostFilter_fieldScope_fromRoot_wrapsEncryptedInJson() throws Exception {
prop.setProperty("crypto.scope", "FIELD");
prop.setProperty("crypto.enc.enabled", "Y");
prop.setProperty("crypto.enc.from.path", "/");
prop.setProperty("crypto.enc.to.path", "/encryptedData");
Object result = filter.doPostFilter(null, null, PLAIN_TEXT, prop, mockRequest, null);
assertEquals("{\"encryptedData\":\"" + ENC_BASE64 + "\"}", result);
}
@SuppressWarnings("unchecked")
@Test
@DisplayName("3-4. FIELD scope: runtimeContext에 groupSeq가 올바르게 전달된다")
void doPostFilter_fieldScope_runtimeContextPassedToEncrypt() throws Exception {
prop.setProperty("crypto.scope", "FIELD");
prop.setProperty("crypto.enc.enabled", "Y");
prop.setProperty("crypto.enc.from.path", "/");
prop.setProperty("crypto.enc.to.path", "/encryptedData");
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn(HEADER_JSON_WITH_PIPE);
filter.doPostFilter(null, null, PLAIN_TEXT, prop, mockRequest, null);
ArgumentCaptor<Map> ctxCaptor = ArgumentCaptor.forClass(Map.class);
verify(mockCryptoService).encrypt(eq(MODULE_NAME), ctxCaptor.capture(), any(byte[].class));
assertEquals("G001", ctxCaptor.getValue().get("groupSeq"));
}
// =========================================================================
// 헬퍼
// =========================================================================
private void setFieldDecryptProps(String fromPath, String toPath) {
prop.setProperty("crypto.scope", "FIELD");
prop.setProperty("crypto.dec.from.path", fromPath);
prop.setProperty("crypto.dec.to.path", toPath);
}
}
@@ -0,0 +1,239 @@
package com.eactive.eai.custom.inbound.processor;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.test.util.ReflectionTestUtils;
import com.eactive.eai.common.inflow.Bucket;
import com.eactive.eai.common.inflow.InflowTargetVO;
import com.eactive.eai.common.inflow.dual.ClientDualBucket;
import com.eactive.eai.common.inflow.dual.DualBucket;
import com.eactive.eai.common.inflow.dual.DualCustomBucket;
import com.eactive.eai.common.server.EAIServerManager;
import com.eactive.eai.common.util.ApplicationContextProvider;
/**
* DJBRequestProcessor 단위 테스트.
*
* <p>RequestProcessor 클래스는 static 초기화 블록에서 EAIServerManager.getInstance() 호출한다.
* @BeforeAll에서 mock ApplicationContext를 주입한 DJBRequestProcessor를 최초 로딩시킨다.
*
* <p>주의: DJBRequestProcessor를 필드 타입으로 선언하면 테스트 클래스 로딩 함께 로딩되어
* @BeforeAll 실행 전에 NPE가 발생한다. 반드시 메서드 본문 내에서만 참조해야 한다.
*/
class DJBRequestProcessorTest {
@BeforeAll
static void setupMockApplicationContext() {
ApplicationContext mockContext = mock(ApplicationContext.class);
EAIServerManager mockServerManager = mock(EAIServerManager.class);
when(mockContext.getBean(EAIServerManager.class)).thenReturn(mockServerManager);
when(mockServerManager.getLocalServerName()).thenReturn("TEST-SERVER");
when(mockServerManager.getGroupInstId()).thenReturn("TEST-INST");
ReflectionTestUtils.setField(ApplicationContextProvider.class, "context", mockContext);
}
private InflowTargetVO makeVO(String name, long perSec, long threshold, String unit) {
InflowTargetVO vo = new InflowTargetVO();
vo.setName(name);
vo.setThresholdPerSecond(perSec);
vo.setThreshold(threshold);
vo.setThresholdTimeUnit(unit);
vo.setActivate(true);
return vo;
}
// -------------------------------------------------------------------------
// checkAdapterInflow
// -------------------------------------------------------------------------
@Test
void checkAdapterInflow_dualBucket_pass_returnsNull() {
DJBRequestProcessor processor = new DJBRequestProcessor();
DualBucket mockBucket = mock(DualBucket.class);
when(mockBucket.isAdapterPassDetail("ADAPTER_A")).thenReturn(null);
assertNull(processor.checkAdapterInflow(mockBucket, "ADAPTER_A"));
verify(mockBucket).isAdapterPassDetail("ADAPTER_A");
}
@Test
void checkAdapterInflow_dualBucket_blockedPerSecond() {
DJBRequestProcessor processor = new DJBRequestProcessor();
DualBucket mockBucket = mock(DualBucket.class);
when(mockBucket.isAdapterPassDetail("ADAPTER_A")).thenReturn(DualCustomBucket.RESULT_BLOCKED_PER_SECOND);
assertEquals(DualCustomBucket.RESULT_BLOCKED_PER_SECOND,
processor.checkAdapterInflow(mockBucket, "ADAPTER_A"));
}
@Test
void checkAdapterInflow_dualBucket_blockedThreshold() {
DJBRequestProcessor processor = new DJBRequestProcessor();
DualBucket mockBucket = mock(DualBucket.class);
when(mockBucket.isAdapterPassDetail("ADAPTER_A")).thenReturn(DualCustomBucket.RESULT_BLOCKED_THRESHOLD);
assertEquals(DualCustomBucket.RESULT_BLOCKED_THRESHOLD,
processor.checkAdapterInflow(mockBucket, "ADAPTER_A"));
}
@Test
void checkAdapterInflow_nonDualBucket_pass_returnsNull() {
DJBRequestProcessor processor = new DJBRequestProcessor();
Bucket mockBucket = mock(Bucket.class);
when(mockBucket.isAdapterPass("ADAPTER_A")).thenReturn(true);
assertNull(processor.checkAdapterInflow(mockBucket, "ADAPTER_A"));
}
@Test
void checkAdapterInflow_nonDualBucket_blocked_returnsBlocked() {
DJBRequestProcessor processor = new DJBRequestProcessor();
Bucket mockBucket = mock(Bucket.class);
when(mockBucket.isAdapterPass("ADAPTER_A")).thenReturn(false);
assertEquals("BLOCKED", processor.checkAdapterInflow(mockBucket, "ADAPTER_A"));
}
// -------------------------------------------------------------------------
// checkInterfaceInflow
// -------------------------------------------------------------------------
@Test
void checkInterfaceInflow_dualBucket_pass_returnsNull() {
DJBRequestProcessor processor = new DJBRequestProcessor();
DualBucket mockBucket = mock(DualBucket.class);
when(mockBucket.isInterfacePassDetail("IF_001")).thenReturn(null);
assertNull(processor.checkInterfaceInflow(mockBucket, "IF_001"));
verify(mockBucket).isInterfacePassDetail("IF_001");
}
@Test
void checkInterfaceInflow_dualBucket_blockedPerSecond() {
DJBRequestProcessor processor = new DJBRequestProcessor();
DualBucket mockBucket = mock(DualBucket.class);
when(mockBucket.isInterfacePassDetail("IF_001")).thenReturn(DualCustomBucket.RESULT_BLOCKED_PER_SECOND);
assertEquals(DualCustomBucket.RESULT_BLOCKED_PER_SECOND,
processor.checkInterfaceInflow(mockBucket, "IF_001"));
}
@Test
void checkInterfaceInflow_nonDualBucket_pass_returnsNull() {
DJBRequestProcessor processor = new DJBRequestProcessor();
Bucket mockBucket = mock(Bucket.class);
when(mockBucket.isInterfacePass("IF_001")).thenReturn(true);
assertNull(processor.checkInterfaceInflow(mockBucket, "IF_001"));
}
@Test
void checkInterfaceInflow_nonDualBucket_blocked_returnsBlocked() {
DJBRequestProcessor processor = new DJBRequestProcessor();
Bucket mockBucket = mock(Bucket.class);
when(mockBucket.isInterfacePass("IF_001")).thenReturn(false);
assertEquals("BLOCKED", processor.checkInterfaceInflow(mockBucket, "IF_001"));
}
// -------------------------------------------------------------------------
// checkClientInflow ClientDualBucket 기반
// -------------------------------------------------------------------------
@Test
void checkClientInflow_clientDualBucket_pass_returnsNull() {
DJBRequestProcessor processor = new DJBRequestProcessor();
ClientDualBucket mockBucket = mock(ClientDualBucket.class);
when(mockBucket.isClientPassDetail("CLIENT_A")).thenReturn(null);
assertNull(processor.checkClientInflow(mockBucket, "CLIENT_A"));
verify(mockBucket).isClientPassDetail("CLIENT_A");
}
@Test
void checkClientInflow_clientDualBucket_blocked() {
DJBRequestProcessor processor = new DJBRequestProcessor();
ClientDualBucket mockBucket = mock(ClientDualBucket.class);
when(mockBucket.isClientPassDetail("CLIENT_A")).thenReturn(DualCustomBucket.RESULT_BLOCKED_THRESHOLD);
assertEquals(DualCustomBucket.RESULT_BLOCKED_THRESHOLD,
processor.checkClientInflow(mockBucket, "CLIENT_A"));
}
@Test
void checkClientInflow_nonClientDualBucket_returnsNull() {
DJBRequestProcessor processor = new DJBRequestProcessor();
Bucket mockBucket = mock(Bucket.class);
assertNull(processor.checkClientInflow(mockBucket, "CLIENT_A"));
}
@Test
void checkClientInflow_blankClientId_returnsNull() {
DJBRequestProcessor processor = new DJBRequestProcessor();
ClientDualBucket mockBucket = mock(ClientDualBucket.class);
assertNull(processor.checkClientInflow(mockBucket, ""));
verify(mockBucket, never()).isClientPassDetail(any());
}
// -------------------------------------------------------------------------
// buildInflowTargetErrorMsg
// -------------------------------------------------------------------------
@Test
void buildInflowTargetErrorMsg_perSecond_includesReqPerSec() {
DJBRequestProcessor processor = new DJBRequestProcessor();
InflowTargetVO vo = makeVO("결제API", 30, 1000, "MIN");
String msg = processor.buildInflowTargetErrorMsg(vo, DualCustomBucket.RESULT_BLOCKED_PER_SECOND);
assertEquals("API 호출 한도 초과 [결제API: 30req/sec]", msg);
}
@Test
void buildInflowTargetErrorMsg_threshold_includesReqPerUnit() {
DJBRequestProcessor processor = new DJBRequestProcessor();
InflowTargetVO vo = makeVO("결제API", 30, 1000, "MIN");
String msg = processor.buildInflowTargetErrorMsg(vo, DualCustomBucket.RESULT_BLOCKED_THRESHOLD);
assertEquals("API 호출 한도 초과 [결제API: 1000req/MIN]", msg);
}
@Test
void buildInflowTargetErrorMsg_blockedFallback_simpleFormat() {
DJBRequestProcessor processor = new DJBRequestProcessor();
InflowTargetVO vo = makeVO("결제API", 30, 1000, "MIN");
String msg = processor.buildInflowTargetErrorMsg(vo, "BLOCKED");
assertEquals("API 호출 한도 초과 [결제API]", msg);
}
@Test
void buildInflowTargetErrorMsg_nullBlockedType_simpleFormat() {
DJBRequestProcessor processor = new DJBRequestProcessor();
InflowTargetVO vo = makeVO("결제API", 30, 1000, "MIN");
String msg = processor.buildInflowTargetErrorMsg(vo, null);
assertEquals("API 호출 한도 초과 [결제API]", msg);
}
@Test
void buildInflowTargetErrorMsg_hourUnit() {
DJBRequestProcessor processor = new DJBRequestProcessor();
InflowTargetVO vo = makeVO("조회API", 10, 500, "HOUR");
String msg = processor.buildInflowTargetErrorMsg(vo, DualCustomBucket.RESULT_BLOCKED_THRESHOLD);
assertEquals("API 호출 한도 초과 [조회API: 500req/HOUR]", msg);
}
}
@@ -0,0 +1,106 @@
package com.eactive.eai.custom.inflow;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.ResponseEntity;
import org.springframework.test.util.ReflectionTestUtils;
import com.eactive.eai.manage.inflow.TargetBucketStatusDTO;
/**
* ClientInflowTargetBucketController 단위 테스트.
*/
class ClientInflowTargetBucketControllerTest {
private ClientInflowTargetBucketController controller;
private ClientInflowTargetBucketService mockService;
@BeforeEach
void setUp() {
controller = new ClientInflowTargetBucketController();
mockService = mock(ClientInflowTargetBucketService.class);
ReflectionTestUtils.setField(controller, "bucketService", mockService);
}
private TargetBucketStatusDTO makeDTO(String id, String type) {
TargetBucketStatusDTO dto = new TargetBucketStatusDTO();
dto.setTargetId(id);
dto.setTargetType(type);
dto.setActivate(true);
dto.setBuckets(Collections.emptyList());
return dto;
}
@SuppressWarnings("unchecked")
private Map<String, Object> body(ResponseEntity<?> response) {
return (Map<String, Object>) response.getBody();
}
// =========================================================================
// 단일 조회
// =========================================================================
@Test
void getClientBucketStatus_found_successTrueAndDataPresent() {
TargetBucketStatusDTO dto = makeDTO("CLIENT_A", "CLIENT");
when(mockService.getClientBucketStatus("CLIENT_A")).thenReturn(dto);
ResponseEntity<?> response = controller.getClientBucketStatus("CLIENT_A");
Map<String, Object> body = body(response);
assertEquals(200, response.getStatusCodeValue());
assertEquals(Boolean.TRUE, body.get("success"));
assertSame(dto, body.get("data"));
assertFalse(body.containsKey("message"));
}
@Test
void getClientBucketStatus_notFound_successFalseWithClientId() {
when(mockService.getClientBucketStatus("CLIENT_X")).thenReturn(null);
ResponseEntity<?> response = controller.getClientBucketStatus("CLIENT_X");
Map<String, Object> body = body(response);
assertEquals(Boolean.FALSE, body.get("success"));
assertTrue(body.get("message").toString().contains("CLIENT_X"));
}
// =========================================================================
// 전체 조회
// =========================================================================
@Test
void getAllClientBucketStatus_returnsListAndCount() {
List<TargetBucketStatusDTO> list = Arrays.asList(
makeDTO("CLIENT_A", "CLIENT"),
makeDTO("CLIENT_B", "CLIENT"),
makeDTO("CLIENT_C", "CLIENT")
);
when(mockService.getAllClientBucketStatus()).thenReturn(list);
ResponseEntity<?> response = controller.getAllClientBucketStatus();
Map<String, Object> body = body(response);
assertEquals(Boolean.TRUE, body.get("success"));
assertSame(list, body.get("data"));
assertEquals(3, body.get("count"));
}
@Test
void getAllClientBucketStatus_emptyList_countZero() {
when(mockService.getAllClientBucketStatus()).thenReturn(Collections.emptyList());
Map<String, Object> body = body(controller.getAllClientBucketStatus());
assertEquals(Boolean.TRUE, body.get("success"));
assertEquals(0, body.get("count"));
}
}
@@ -0,0 +1,208 @@
package com.eactive.eai.custom.inflow;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.junit.jupiter.api.Test;
import com.eactive.eai.common.inflow.InflowTargetVO;
import com.eactive.eai.common.inflow.dual.ClientDualInflowControlManager;
import com.eactive.eai.common.inflow.dual.DualCustomBucket;
import com.eactive.eai.manage.inflow.GroupBucketStatusDTO;
import com.eactive.eai.manage.inflow.TargetBucketStatusDTO;
import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Bucket4j;
import io.github.bucket4j.local.LocalBucket;
/**
* ClientInflowTargetBucketService 단위 테스트.
*/
class ClientInflowTargetBucketServiceTest {
// -------------------------------------------------------------------------
// 테스트용 서브클래스
// -------------------------------------------------------------------------
private static ClientInflowTargetBucketService serviceWith(ClientDualInflowControlManager manager) {
return new ClientInflowTargetBucketService() {
@Override
protected ClientDualInflowControlManager getClientDualManager() { return manager; }
};
}
// -------------------------------------------------------------------------
// Helpers
// -------------------------------------------------------------------------
private InflowTargetVO makeVO(String name, long perSec, long threshold, String unit, boolean activate) {
InflowTargetVO vo = new InflowTargetVO();
vo.setName(name);
vo.setThresholdPerSecond(perSec);
vo.setThreshold(threshold);
vo.setThresholdTimeUnit(unit);
vo.setActivate(activate);
return vo;
}
private LocalBucket freshBucket(long capacity) {
return Bucket4j.builder()
.addLimit(Bandwidth.simple(capacity, Duration.ofSeconds(1)))
.build();
}
private LocalBucket exhaustedBucket(long capacity) {
LocalBucket b = freshBucket(capacity);
b.tryConsume(capacity);
return b;
}
private DualCustomBucket makeDualBucket(String name, long perSec, long threshold) {
return new DualCustomBucket(freshBucket(perSec), freshBucket(threshold),
makeVO(name, perSec, threshold, "DAY", true));
}
// =========================================================================
// ClientDualManager null (비활성 환경)
// =========================================================================
@Test
void getClientBucketStatus_managerIsNull_returnsNull() {
assertNull(serviceWith(null).getClientBucketStatus("CLIENT_A"));
}
@Test
void getAllClientBucketStatus_managerIsNull_returnsEmptyList() {
assertTrue(serviceWith(null).getAllClientBucketStatus().isEmpty());
}
// =========================================================================
// 버킷 미존재
// =========================================================================
@Test
void getClientBucketStatus_notFound_returnsNull() {
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
when(manager.getClientBucket("CLIENT_A")).thenReturn(null);
assertNull(serviceWith(manager).getClientBucketStatus("CLIENT_A"));
}
// =========================================================================
// 단일 조회 targetType, targetId 매핑
// =========================================================================
@Test
void getClientBucketStatus_found_mapsClientType() {
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
when(manager.getClientBucket("CLIENT_A")).thenReturn(makeDualBucket("CLIENT_A", 50, 5000));
TargetBucketStatusDTO dto = serviceWith(manager).getClientBucketStatus("CLIENT_A");
assertNotNull(dto);
assertEquals("CLIENT_A", dto.getTargetId());
assertEquals("CLIENT", dto.getTargetType());
assertTrue(dto.isActivate());
assertEquals(2, dto.getBuckets().size());
}
// =========================================================================
// BucketInfo 타입별 포함 여부
// =========================================================================
@Test
void toDto_onlyThreshold_bucketInfoHasOneThresholdEntry() {
InflowTargetVO vo = makeVO("C1", 0, 1000, "DAY", true);
DualCustomBucket bucket = new DualCustomBucket(null, freshBucket(1000), vo);
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
when(manager.getClientBucket("C1")).thenReturn(bucket);
TargetBucketStatusDTO dto = serviceWith(manager).getClientBucketStatus("C1");
assertEquals(1, dto.getBuckets().size());
assertEquals("threshold", dto.getBuckets().get(0).getType());
}
@Test
void toDto_onlyPerSecond_bucketInfoHasOnePerSecondEntry() {
InflowTargetVO vo = makeVO("C2", 100, 0, null, true);
DualCustomBucket bucket = new DualCustomBucket(freshBucket(100), null, vo);
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
when(manager.getClientBucket("C2")).thenReturn(bucket);
TargetBucketStatusDTO dto = serviceWith(manager).getClientBucketStatus("C2");
assertEquals(1, dto.getBuckets().size());
assertEquals("perSecond", dto.getBuckets().get(0).getType());
}
@Test
void toDto_bothBuckets_bucketInfoHasTwoEntries() {
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
when(manager.getClientBucket("C3")).thenReturn(makeDualBucket("C3", 100, 5000));
TargetBucketStatusDTO dto = serviceWith(manager).getClientBucketStatus("C3");
assertEquals(2, dto.getBuckets().size());
assertEquals("perSecond", dto.getBuckets().get(0).getType());
assertEquals("threshold", dto.getBuckets().get(1).getType());
}
// =========================================================================
// 사용률 계산
// =========================================================================
@Test
void toDto_exhaustedThreshold_usagePercentIs100() {
InflowTargetVO vo = makeVO("C4", 0, 100, "DAY", true);
DualCustomBucket bucket = new DualCustomBucket(null, exhaustedBucket(100), vo);
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
when(manager.getClientBucket("C4")).thenReturn(bucket);
TargetBucketStatusDTO dto = serviceWith(manager).getClientBucketStatus("C4");
GroupBucketStatusDTO.BucketInfo info = dto.getBuckets().get(0);
assertEquals(0, info.getAvailableTokens());
assertEquals(100.0, info.getUsagePercent(), 0.01);
}
@Test
void toDto_freshBucket_usagePercentIsZero() {
InflowTargetVO vo = makeVO("C5", 0, 100, "DAY", true);
DualCustomBucket bucket = new DualCustomBucket(null, freshBucket(100), vo);
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
when(manager.getClientBucket("C5")).thenReturn(bucket);
TargetBucketStatusDTO dto = serviceWith(manager).getClientBucketStatus("C5");
GroupBucketStatusDTO.BucketInfo info = dto.getBuckets().get(0);
assertEquals(100, info.getAvailableTokens());
assertEquals(0.0, info.getUsagePercent(), 0.01);
}
// =========================================================================
// 전체 목록 조회
// =========================================================================
@Test
void getAllClientBucketStatus_twoEntries_returnsBoth() {
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
Map<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("CLIENT_A", makeDualBucket("CLIENT_A", 10, 1000));
map.put("CLIENT_B", makeDualBucket("CLIENT_B", 20, 2000));
when(manager.getClientBucketMap()).thenReturn(map);
List<TargetBucketStatusDTO> result = serviceWith(manager).getAllClientBucketStatus();
assertEquals(2, result.size());
}
}
@@ -0,0 +1,144 @@
package com.eactive.eai.custom.inflow;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.ResponseEntity;
import org.springframework.test.util.ReflectionTestUtils;
import com.eactive.eai.manage.inflow.TargetMetricDTO;
/**
* ClientInflowTargetMetricController 단위 테스트.
*
* <p>Spring MVC를 기동하지 않고 컨트롤러를 직접 인스턴스화하여
* 응답 구조(success, data, count, message) 검증한다.
*/
class ClientInflowTargetMetricControllerTest {
private ClientInflowTargetMetricController controller;
private ClientInflowTargetMetricService mockService;
@BeforeEach
void setUp() {
controller = new ClientInflowTargetMetricController();
mockService = mock(ClientInflowTargetMetricService.class);
ReflectionTestUtils.setField(controller, "metricService", mockService);
}
private TargetMetricDTO makeDTO(String targetId, String targetType,
long allowed, long rejPs, long rejTh) {
TargetMetricDTO dto = new TargetMetricDTO();
dto.setTargetId(targetId);
dto.setTargetType(targetType);
dto.setActivate(true);
dto.setAllowed(allowed);
dto.setRejectedPerSecond(rejPs);
dto.setRejectedThreshold(rejTh);
long total = allowed + rejPs + rejTh;
dto.setTotalRequests(total);
dto.setRejectRatio(total > 0 ? (double)(rejPs + rejTh) / total * 100 : 0.0);
return dto;
}
@SuppressWarnings("unchecked")
private Map<String, Object> body(ResponseEntity<?> response) {
return (Map<String, Object>) response.getBody();
}
// =========================================================================
// 단일 조회
// =========================================================================
@Test
void getClientMetric_found_successTrueAndDataPresent() {
TargetMetricDTO dto = makeDTO("C1", "CLIENT", 300, 50, 20);
when(mockService.getClientMetric("C1")).thenReturn(dto);
Map<String, Object> body = body(controller.getClientMetric("C1"));
assertEquals(Boolean.TRUE, body.get("success"));
assertSame(dto, body.get("data"));
assertFalse(body.containsKey("message"));
}
@Test
void getClientMetric_notFound_successFalseWithMessage() {
when(mockService.getClientMetric("GHOST")).thenReturn(null);
Map<String, Object> body = body(controller.getClientMetric("GHOST"));
assertEquals(Boolean.FALSE, body.get("success"));
assertTrue(body.get("message").toString().contains("GHOST"));
}
// =========================================================================
// 전체 조회
// =========================================================================
@Test
void getAllClientMetrics_returnsListAndCount() {
List<TargetMetricDTO> list = Arrays.asList(
makeDTO("C1", "CLIENT", 100, 5, 5),
makeDTO("C2", "CLIENT", 200, 0, 0),
makeDTO("C3", "CLIENT", 50, 10, 0)
);
when(mockService.getAllClientMetrics()).thenReturn(list);
Map<String, Object> body = body(controller.getAllClientMetrics());
assertEquals(Boolean.TRUE, body.get("success"));
assertSame(list, body.get("data"));
assertEquals(3, body.get("count"));
}
@Test
void getAllClientMetrics_emptyList_countZero() {
when(mockService.getAllClientMetrics()).thenReturn(Collections.emptyList());
Map<String, Object> body = body(controller.getAllClientMetrics());
assertEquals(Boolean.TRUE, body.get("success"));
assertEquals(0, body.get("count"));
}
// =========================================================================
// reset
// =========================================================================
@Test
void resetClientMetric_success_successTrueWithTargetId() {
when(mockService.resetClientMetric("C1")).thenReturn(true);
Map<String, Object> body = body(controller.resetClientMetric("C1"));
assertEquals(Boolean.TRUE, body.get("success"));
assertTrue(body.get("message").toString().contains("C1"));
}
@Test
void resetClientMetric_notFound_successFalseWithTargetId() {
when(mockService.resetClientMetric("GHOST")).thenReturn(false);
Map<String, Object> body = body(controller.resetClientMetric("GHOST"));
assertEquals(Boolean.FALSE, body.get("success"));
assertTrue(body.get("message").toString().contains("GHOST"));
}
@Test
void resetAllClientMetrics_callsDelegateOnce() {
doNothing().when(mockService).resetAllClientMetrics();
controller.resetAllClientMetrics();
verify(mockService, times(1)).resetAllClientMetrics();
}
}
@@ -0,0 +1,177 @@
package com.eactive.eai.custom.inflow;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.util.List;
import org.junit.jupiter.api.Test;
import com.eactive.eai.common.inflow.InflowTargetVO;
import com.eactive.eai.common.inflow.dual.ClientDualInflowControlManager;
import com.eactive.eai.common.inflow.dual.DualInflowControlManager;
import com.eactive.eai.manage.inflow.TargetMetricDTO;
class ClientInflowTargetMetricServiceTest {
private static ClientInflowTargetMetricService serviceWith(ClientDualInflowControlManager manager) {
return new ClientInflowTargetMetricService() {
@Override
protected ClientDualInflowControlManager getClientDualManager() { return manager; }
};
}
private InflowTargetVO makeVO(String name) {
InflowTargetVO vo = new InflowTargetVO();
vo.setName(name);
vo.setActivate(true);
return vo;
}
private DualInflowControlManager.TargetMetrics makeMetrics(long allowed, long rejPs, long rejTh) {
DualInflowControlManager.TargetMetrics m = new DualInflowControlManager.TargetMetrics();
m.allowed.set(allowed);
m.rejectedPerSecond.set(rejPs);
m.rejectedThreshold.set(rejTh);
return m;
}
// =========================================================================
// null 관리자 (비활성 환경)
// =========================================================================
@Test
void getClientMetric_managerIsNull_returnsNull() {
assertNull(serviceWith(null).getClientMetric("C1"));
}
@Test
void getAllClientMetrics_managerIsNull_returnsEmptyList() {
assertTrue(serviceWith(null).getAllClientMetrics().isEmpty());
}
@Test
void resetClientMetric_managerIsNull_returnsFalse() {
assertFalse(serviceWith(null).resetClientMetric("C1"));
}
@Test
void resetAllClientMetrics_managerIsNull_noException() {
assertDoesNotThrow(() -> serviceWith(null).resetAllClientMetrics());
}
// =========================================================================
// 단일 조회
// =========================================================================
@Test
void getClientMetric_found_mapsFields() {
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
when(manager.getClientInflowThreshold("C1")).thenReturn(makeVO("C1"));
when(manager.getClientMetrics("C1")).thenReturn(makeMetrics(200, 30, 20));
TargetMetricDTO dto = serviceWith(manager).getClientMetric("C1");
assertNotNull(dto);
assertEquals("C1", dto.getTargetId());
assertEquals("CLIENT", dto.getTargetType());
assertTrue(dto.isActivate());
assertEquals(200, dto.getAllowed());
assertEquals(30, dto.getRejectedPerSecond());
assertEquals(20, dto.getRejectedThreshold());
assertEquals(250, dto.getTotalRequests());
}
@Test
void getClientMetric_notRegistered_returnsNull() {
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
when(manager.getClientInflowThreshold("C1")).thenReturn(null);
assertNull(serviceWith(manager).getClientMetric("C1"));
}
@Test
void getClientMetric_noMetricsYet_returnsZeroCounters() {
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
when(manager.getClientInflowThreshold("C1")).thenReturn(makeVO("C1"));
when(manager.getClientMetrics("C1")).thenReturn(null);
TargetMetricDTO dto = serviceWith(manager).getClientMetric("C1");
assertNotNull(dto);
assertEquals(0, dto.getAllowed());
assertEquals(0, dto.getTotalRequests());
assertEquals(0.0, dto.getRejectRatio(), 0.001);
}
@Test
void getClientMetric_rejectRatioCalculation() {
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
when(manager.getClientInflowThreshold("C1")).thenReturn(makeVO("C1"));
// allowed=90, rejPs=5, rejTh=5 reject=10/100 = 10.00%
when(manager.getClientMetrics("C1")).thenReturn(makeMetrics(90, 5, 5));
TargetMetricDTO dto = serviceWith(manager).getClientMetric("C1");
assertEquals(10.0, dto.getRejectRatio(), 0.01);
}
// =========================================================================
// 전체 조회
// =========================================================================
@Test
void getAllClientMetrics_twoEntries_returnsBoth() {
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
java.util.Map<String, com.eactive.eai.common.inflow.dual.DualCustomBucket> bucketMap =
new java.util.LinkedHashMap<>();
bucketMap.put("C1", null);
bucketMap.put("C2", null);
when(manager.getClientBucketMap()).thenReturn(bucketMap);
when(manager.getClientInflowThreshold("C1")).thenReturn(makeVO("C1"));
when(manager.getClientInflowThreshold("C2")).thenReturn(makeVO("C2"));
when(manager.getClientMetrics("C1")).thenReturn(makeMetrics(10, 0, 0));
when(manager.getClientMetrics("C2")).thenReturn(makeMetrics(20, 5, 0));
List<TargetMetricDTO> result = serviceWith(manager).getAllClientMetrics();
assertEquals(2, result.size());
}
@Test
void getAllClientMetrics_noKeys_returnsEmptyList() {
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
when(manager.getClientBucketMap()).thenReturn(new java.util.HashMap<>());
assertTrue(serviceWith(manager).getAllClientMetrics().isEmpty());
}
// =========================================================================
// reset
// =========================================================================
@Test
void resetClientMetric_success_returnsTrueAndCallsManager() {
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
when(manager.getClientInflowThreshold("C1")).thenReturn(makeVO("C1"));
assertTrue(serviceWith(manager).resetClientMetric("C1"));
verify(manager).resetClientMetrics("C1");
}
@Test
void resetClientMetric_notRegistered_returnsFalseAndNoReset() {
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
when(manager.getClientInflowThreshold("C1")).thenReturn(null);
assertFalse(serviceWith(manager).resetClientMetric("C1"));
verify(manager, never()).resetClientMetrics(any());
}
@Test
void resetAllClientMetrics_callsManager() {
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
serviceWith(manager).resetAllClientMetrics();
verify(manager).resetAllClientMetrics();
}
}
@@ -0,0 +1,179 @@
package com.eactive.eai.custom.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.util.ApplicationContextProvider;
import com.eactive.eai.custom.security.keyderiv.strategy.HsmContextSha256KeyDerivationStrategy;
/**
* 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);
}
}
@@ -18,6 +18,7 @@ import org.springframework.test.util.ReflectionTestUtils;
*
* <p>Spring MVC를 기동하지 않고 컨트롤러를 직접 인스턴스화하여
* 응답 구조(success, data, count, message) 검증한다.
* 클라이언트 관련 테스트는 ClientInflowTargetBucketControllerTest 에서 검증한다.
*/
class InflowTargetBucketControllerTest {
@@ -148,64 +149,4 @@ class InflowTargetBucketControllerTest {
assertEquals(Boolean.TRUE, body.get("success"));
assertEquals(1, body.get("count"));
}
// =========================================================================
// 클라이언트 단일 조회
// =========================================================================
@Test
void getClientBucketStatus_found_successTrueAndDataPresent() {
TargetBucketStatusDTO dto = makeDTO("CLIENT_A", "CLIENT");
when(mockService.getClientBucketStatus("CLIENT_A")).thenReturn(dto);
ResponseEntity<?> response = controller.getClientBucketStatus("CLIENT_A");
Map<String, Object> body = body(response);
assertEquals(200, response.getStatusCodeValue());
assertEquals(Boolean.TRUE, body.get("success"));
assertSame(dto, body.get("data"));
assertFalse(body.containsKey("message"));
}
@Test
void getClientBucketStatus_notFound_successFalseWithClientId() {
when(mockService.getClientBucketStatus("CLIENT_X")).thenReturn(null);
ResponseEntity<?> response = controller.getClientBucketStatus("CLIENT_X");
Map<String, Object> body = body(response);
assertEquals(Boolean.FALSE, body.get("success"));
assertTrue(body.get("message").toString().contains("CLIENT_X"));
}
// =========================================================================
// 클라이언트 전체 조회
// =========================================================================
@Test
void getAllClientBucketStatus_returnsListAndCount() {
List<TargetBucketStatusDTO> list = Arrays.asList(
makeDTO("CLIENT_A", "CLIENT"),
makeDTO("CLIENT_B", "CLIENT"),
makeDTO("CLIENT_C", "CLIENT")
);
when(mockService.getAllClientBucketStatus()).thenReturn(list);
ResponseEntity<?> response = controller.getAllClientBucketStatus();
Map<String, Object> body = body(response);
assertEquals(Boolean.TRUE, body.get("success"));
assertSame(list, body.get("data"));
assertEquals(3, body.get("count"));
}
@Test
void getAllClientBucketStatus_emptyList_countZero() {
when(mockService.getAllClientBucketStatus()).thenReturn(Collections.emptyList());
Map<String, Object> body = body(controller.getAllClientBucketStatus());
assertEquals(Boolean.TRUE, body.get("success"));
assertEquals(0, body.get("count"));
}
}
@@ -21,8 +21,8 @@ import io.github.bucket4j.local.LocalBucket;
/**
* InflowTargetBucketService 단위 테스트.
*
* <p>getDualManager() protected로 오버라이드하는 내부 테스트 서브클래스 사용하여
* DualInflowControlManager 의존성을 주입한다.
* <p>어댑터/인터페이스: getDualManager() 오버라이드하는 서브클래스 사용.
* 클라이언트 관련 테스트는 ClientInflowTargetBucketServiceTest 에서 검증한다.
*/
class InflowTargetBucketServiceTest {
@@ -33,9 +33,7 @@ class InflowTargetBucketServiceTest {
private static InflowTargetBucketService serviceWith(DualInflowControlManager manager) {
return new InflowTargetBucketService() {
@Override
protected DualInflowControlManager getDualManager() {
return manager;
}
protected DualInflowControlManager getDualManager() { return manager; }
};
}
@@ -96,16 +94,6 @@ class InflowTargetBucketServiceTest {
assertTrue(serviceWith(null).getAllInterfaceBucketStatus().isEmpty());
}
@Test
void getClientBucketStatus_managerIsNull_returnsNull() {
assertNull(serviceWith(null).getClientBucketStatus("CLIENT_A"));
}
@Test
void getAllClientBucketStatus_managerIsNull_returnsEmptyList() {
assertTrue(serviceWith(null).getAllClientBucketStatus().isEmpty());
}
// =========================================================================
// 버킷 미존재
// =========================================================================
@@ -126,14 +114,6 @@ class InflowTargetBucketServiceTest {
assertNull(serviceWith(manager).getInterfaceBucketStatus("IF_001"));
}
@Test
void getClientBucketStatus_notFound_returnsNull() {
DualInflowControlManager manager = mock(DualInflowControlManager.class);
when(manager.getClientBucket("CLIENT_A")).thenReturn(null);
assertNull(serviceWith(manager).getClientBucketStatus("CLIENT_A"));
}
// =========================================================================
// 단일 조회 targetType, targetId 매핑
// =========================================================================
@@ -166,98 +146,10 @@ class InflowTargetBucketServiceTest {
assertEquals(2, dto.getBuckets().size());
}
@Test
void getClientBucketStatus_found_mapsClientType() {
DualInflowControlManager manager = mock(DualInflowControlManager.class);
when(manager.getClientBucket("CLIENT_A")).thenReturn(makeDualBucket("CLIENT_A", 50, 5000));
TargetBucketStatusDTO dto = serviceWith(manager).getClientBucketStatus("CLIENT_A");
assertNotNull(dto);
assertEquals("CLIENT_A", dto.getTargetId());
assertEquals("CLIENT", dto.getTargetType());
assertTrue(dto.isActivate());
assertEquals(2, dto.getBuckets().size());
}
// =========================================================================
// BucketInfo 타입별 포함 여부
// BucketInfo 용량/시간단위 매핑
// =========================================================================
@Test
void toDto_onlyThreshold_bucketInfoHasOneThresholdEntry() {
InflowTargetVO vo = makeVO("C1", 0, 1000, "DAY", true);
DualCustomBucket bucket = new DualCustomBucket(null, freshBucket(1000), vo);
DualInflowControlManager manager = mock(DualInflowControlManager.class);
when(manager.getClientBucket("C1")).thenReturn(bucket);
TargetBucketStatusDTO dto = serviceWith(manager).getClientBucketStatus("C1");
assertEquals(1, dto.getBuckets().size());
assertEquals("threshold", dto.getBuckets().get(0).getType());
}
@Test
void toDto_onlyPerSecond_bucketInfoHasOnePerSecondEntry() {
InflowTargetVO vo = makeVO("C2", 100, 0, "SEC", true);
DualCustomBucket bucket = new DualCustomBucket(freshBucket(100), null, vo);
DualInflowControlManager manager = mock(DualInflowControlManager.class);
when(manager.getClientBucket("C2")).thenReturn(bucket);
TargetBucketStatusDTO dto = serviceWith(manager).getClientBucketStatus("C2");
assertEquals(1, dto.getBuckets().size());
assertEquals("perSecond", dto.getBuckets().get(0).getType());
}
@Test
void toDto_bothBuckets_bucketInfoHasTwoEntries() {
DualInflowControlManager manager = mock(DualInflowControlManager.class);
when(manager.getClientBucket("C3")).thenReturn(makeDualBucket("C3", 100, 5000));
TargetBucketStatusDTO dto = serviceWith(manager).getClientBucketStatus("C3");
assertEquals(2, dto.getBuckets().size());
assertEquals("perSecond", dto.getBuckets().get(0).getType());
assertEquals("threshold", dto.getBuckets().get(1).getType());
}
// =========================================================================
// 사용률 계산
// =========================================================================
@Test
void toDto_exhaustedThreshold_usagePercentIs100() {
InflowTargetVO vo = makeVO("C4", 0, 100, "DAY", true);
DualCustomBucket bucket = new DualCustomBucket(null, exhaustedBucket(100), vo);
DualInflowControlManager manager = mock(DualInflowControlManager.class);
when(manager.getClientBucket("C4")).thenReturn(bucket);
TargetBucketStatusDTO dto = serviceWith(manager).getClientBucketStatus("C4");
GroupBucketStatusDTO.BucketInfo info = dto.getBuckets().get(0);
assertEquals(0, info.getAvailableTokens());
assertEquals(100.0, info.getUsagePercent(), 0.01);
}
@Test
void toDto_freshBucket_usagePercentIsZero() {
InflowTargetVO vo = makeVO("C5", 0, 100, "DAY", true);
DualCustomBucket bucket = new DualCustomBucket(null, freshBucket(100), vo);
DualInflowControlManager manager = mock(DualInflowControlManager.class);
when(manager.getClientBucket("C5")).thenReturn(bucket);
TargetBucketStatusDTO dto = serviceWith(manager).getClientBucketStatus("C5");
GroupBucketStatusDTO.BucketInfo info = dto.getBuckets().get(0);
assertEquals(100, info.getAvailableTokens());
assertEquals(0.0, info.getUsagePercent(), 0.01);
}
@Test
void toDto_capacity_perSecondBucketInfoCapacityMatchesVO() {
DualInflowControlManager manager = mock(DualInflowControlManager.class);
@@ -278,19 +170,6 @@ class InflowTargetBucketServiceTest {
// 전체 목록 조회
// =========================================================================
@Test
void getAllClientBucketStatus_twoEntries_returnsBoth() {
DualInflowControlManager manager = mock(DualInflowControlManager.class);
Map<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("CLIENT_A", makeDualBucket("CLIENT_A", 10, 1000));
map.put("CLIENT_B", makeDualBucket("CLIENT_B", 20, 2000));
when(manager.getClientBucketMap()).thenReturn(map);
List<TargetBucketStatusDTO> result = serviceWith(manager).getAllClientBucketStatus();
assertEquals(2, result.size());
}
@Test
void getAllAdapterBucketStatus_emptyMap_returnsEmptyList() {
DualInflowControlManager manager = mock(DualInflowControlManager.class);
@@ -210,92 +210,4 @@ class InflowTargetMetricControllerTest {
verify(mockService, times(1)).resetAllInterfaceMetrics();
}
// =========================================================================
// 클라이언트 단일 조회
// =========================================================================
@Test
void getClientMetric_found_successTrueAndDataPresent() {
TargetMetricDTO dto = makeDTO("C1", "CLIENT", 300, 50, 20);
when(mockService.getClientMetric("C1")).thenReturn(dto);
Map<String, Object> body = body(controller.getClientMetric("C1"));
assertEquals(Boolean.TRUE, body.get("success"));
assertSame(dto, body.get("data"));
}
@Test
void getClientMetric_notFound_successFalseWithMessage() {
when(mockService.getClientMetric("GHOST")).thenReturn(null);
Map<String, Object> body = body(controller.getClientMetric("GHOST"));
assertEquals(Boolean.FALSE, body.get("success"));
assertTrue(body.get("message").toString().contains("GHOST"));
}
// =========================================================================
// 클라이언트 전체 조회
// =========================================================================
@Test
void getAllClientMetrics_returnsListAndCount() {
List<TargetMetricDTO> list = Arrays.asList(
makeDTO("C1", "CLIENT", 100, 5, 5),
makeDTO("C2", "CLIENT", 200, 0, 0),
makeDTO("C3", "CLIENT", 50, 10, 0)
);
when(mockService.getAllClientMetrics()).thenReturn(list);
Map<String, Object> body = body(controller.getAllClientMetrics());
assertEquals(Boolean.TRUE, body.get("success"));
assertSame(list, body.get("data"));
assertEquals(3, body.get("count"));
}
@Test
void getAllClientMetrics_emptyList_countZero() {
when(mockService.getAllClientMetrics()).thenReturn(Collections.emptyList());
Map<String, Object> body = body(controller.getAllClientMetrics());
assertEquals(Boolean.TRUE, body.get("success"));
assertEquals(0, body.get("count"));
}
// =========================================================================
// 클라이언트 reset
// =========================================================================
@Test
void resetClientMetric_success_successTrue() {
when(mockService.resetClientMetric("C1")).thenReturn(true);
Map<String, Object> body = body(controller.resetClientMetric("C1"));
assertEquals(Boolean.TRUE, body.get("success"));
assertTrue(body.get("message").toString().contains("C1"));
}
@Test
void resetClientMetric_notFound_successFalse() {
when(mockService.resetClientMetric("GHOST")).thenReturn(false);
Map<String, Object> body = body(controller.resetClientMetric("GHOST"));
assertEquals(Boolean.FALSE, body.get("success"));
assertTrue(body.get("message").toString().contains("GHOST"));
}
@Test
void resetAllClientMetrics_callsDelegateOnce() {
doNothing().when(mockService).resetAllClientMetrics();
controller.resetAllClientMetrics();
verify(mockService, times(1)).resetAllClientMetrics();
}
}
@@ -13,12 +13,12 @@ import com.eactive.eai.common.inflow.dual.DualInflowControlManager;
/**
* InflowTargetMetricService 단위 테스트.
*
* <p>getDualManager() 오버라이드하여 DualInflowControlManager 의존성을 주입한다.
* <p>어댑터/인터페이스 테스트는 getDualManager() 오버라이드하여 DualInflowControlManager 주입.
*/
class InflowTargetMetricServiceTest {
// -------------------------------------------------------------------------
// 테스트용 서브클래스
// 테스트용 서브클래스 어댑터/인터페이스용
// -------------------------------------------------------------------------
private static InflowTargetMetricService serviceWith(DualInflowControlManager manager) {
@@ -76,11 +76,6 @@ class InflowTargetMetricServiceTest {
assertNull(serviceWith(null).getInterfaceMetric("IF1"));
}
@Test
void getClientMetric_managerIsNull_returnsNull() {
assertNull(serviceWith(null).getClientMetric("C1"));
}
// =========================================================================
// 어댑터 단일 조회
// =========================================================================
@@ -271,55 +266,4 @@ class InflowTargetMetricServiceTest {
serviceWith(manager).resetAllInterfaceMetrics();
verify(manager).resetAllInterfaceMetrics();
}
// =========================================================================
// 클라이언트 단일 조회
// =========================================================================
@Test
void getClientMetric_found_mapsFields() {
DualInflowControlManager manager = mock(DualInflowControlManager.class);
when(manager.getClientInflowThreshold("C1")).thenReturn(makeVO("C1"));
when(manager.getClientMetrics("C1")).thenReturn(makeMetrics(200, 30, 20));
TargetMetricDTO dto = serviceWith(manager).getClientMetric("C1");
assertNotNull(dto);
assertEquals("C1", dto.getTargetId());
assertEquals("CLIENT", dto.getTargetType());
assertEquals(200, dto.getAllowed());
assertEquals(250, dto.getTotalRequests());
}
@Test
void getClientMetric_notRegistered_returnsNull() {
DualInflowControlManager manager = mock(DualInflowControlManager.class);
when(manager.getClientInflowThreshold("C1")).thenReturn(null);
assertNull(serviceWith(manager).getClientMetric("C1"));
}
@Test
void resetClientMetric_success_returnsTrueAndCallsManager() {
DualInflowControlManager manager = mock(DualInflowControlManager.class);
when(manager.getClientInflowThreshold("C1")).thenReturn(makeVO("C1"));
assertTrue(serviceWith(manager).resetClientMetric("C1"));
verify(manager).resetClientMetrics("C1");
}
@Test
void resetClientMetric_notRegistered_returnsFalse() {
DualInflowControlManager manager = mock(DualInflowControlManager.class);
when(manager.getClientInflowThreshold("C1")).thenReturn(null);
assertFalse(serviceWith(manager).resetClientMetric("C1"));
}
@Test
void resetAllClientMetrics_callsManager() {
DualInflowControlManager manager = mock(DualInflowControlManager.class);
serviceWith(manager).resetAllClientMetrics();
verify(manager).resetAllClientMetrics();
}
}