17 Commits

Author SHA1 Message Date
curry772 c4010147db 테스트 거래 시 forwardproxy 사용하지 않도록 변경 2026-05-11 16:17:26 +09:00
curry772 5994befbb6 테스트 거래 시 forwardproxy 사용하지 않도록 변경 2026-05-11 16:16:26 +09:00
curry772 07569e62da HTTP도 REST 처럼 simulator 호출 기능, mock server(test master) 호출로 변경 2026-05-11 16:11:10 +09:00
curry772 e5638f22bb Outbound HeaderGroup 전체 전달 'ALL' 지원 2026-05-11 16:10:20 +09:00
curry772 e64319e7d2 Merge branch 'feature/inflow-control-improvement' into master 2026-05-08 10:51:21 +09:00
curry772 43548a90c4 fix: AbstractInflowControlManager Bandwidth.simple → classic+intervally 버킷 생성 버그 수정 및 테스트 추가
- makeBucketUsingInflowVO: 어댑터/인터페이스 단일 버킷 threshold 리필을 greedy → intervally 변경
- makeGroupBucket: 그룹 threshold 버킷 동일하게 수정
- DualInflowControlManagerMakeBucketTest: 버킷 생성 로직 직접 검증 테스트 추가
- InflowControlManagerTest: @BeforeEach reload + spike/burst 경계 케이스 테스트 추가
- SQL 픽스처: MIN 단위 TEST_ADAPTER/TEST_INTERFACE/test-group-quota 항목 추가

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-08 10:21:57 +09:00
curry772 8900966d71 refactor: DualBucket/DualInflowControlManager 클라이언트 분리 및 Bandwidth 방식 변경
- DualBucket 인터페이스에서 클라이언트 메서드 분리 → ClientDualBucket 신규 인터페이스
- DualInflowControlManager 클라이언트 구현 분리 → ClientDualInflowControlManager
- DualInflowControlManager @Component 제거 (ClientDualInflowControlManager가 단일 빈)
- makeBucket: Bandwidth.simple → Bandwidth.classic + Refill.greedy/intervally 변경
  (threshold 버킷을 진짜 기간 쿼터로 동작하도록 수정)
- DualRequestProcessor → eapim-online custom 패키지로 이동 (삭제)
- ReloadInflowClientControlCommand / RemoveInflowClientControlCommand:
  instanceof 타입을 ClientDualInflowControlManager로 변경
- 단위 테스트: ClientDualInflowControlManagerMetricsTest 추가,
  DualInflowControlManagerMetricsTest 클라이언트 케이스 분리

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 18:02:34 +09:00
curry772 32a7723fa4 Merge branch 'feature/crypto-module' into master 2026-05-07 15:38:47 +09:00
curry772 580686886c feat: HTTP 어댑터 암복호화 필터 기반 클래스 추가 및 ReloadCryptoModuleCommand 개선
- CryptoFilter (abstract): BODY/FIELD scope 암복호화, buildRuntimeContext 추상화
  - String/byte[]/JSONObject 타입 message 처리 (toBodyString)
  - STATIC/DYNAMIC 키 모듈 공통 지원 (CryptoModuleManager가 내부 분기)
- ReloadCryptoModuleCommand: 로깅 추가, 성공 시 "success" 반환, 에러코드 정의

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 15:03:47 +09:00
curry772 bf1135f9ad feat: 암호화모듈 프레임워크 신규 구현
- CryptoModuleExtension 인터페이스: BC 프로바이더, AAD, 편의 메서드 오버로드 추가
- AESCryptoModuleExtension: CBC/GCM/ECB/FF1 지원, GCM 랜덤 nonce, AAD 처리
- ARIACryptoModuleExtension: ARIA 알고리즘 지원
- CryptoModuleConfigVO: JPA Entity 분리를 위한 Lombok VO
- CryptoModuleManager: VO 패턴 적용, FQCN 기반 전략 동적 로딩(Class.forName)
- CryptoModuleService: STATIC/DYNAMIC × AAD 조합 8가지 오버로드
- CryptoModuleConfigMapper: MapStruct Entity→VO 매퍼
- KeyDerivationStrategy 인터페이스 및 DerivedKey
- HsmContextXorKeyDerivationStrategy: HSM 마스터키 XOR 컨텍스트값 전략
- ReloadCryptoModuleCommand: 설정 런타임 재로드 커맨드
- build.gradle: BouncyCastle bcprov-jdk15on:1.70 의존성 추가
- 단위 테스트 전체 추가

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-06 16:49:33 +09:00
curry772 8f70451477 Merge branch 'feature/inflow-control-improvement'
- AbstractInflowControlManager 상속 구조 리팩토링
- DualInflowControlManager DAO 이중 호출 제거 및 타겟 메트릭 추가
- ReloadInflowClientControlCommandTest / RemoveInflowClientControlCommandTest 수정
2026-04-30 10:16:52 +09:00
curry772 437961e7d5 test: ReloadInflowClientControlCommandTest / RemoveInflowClientControlCommandTest 수정
PropManager NPE 및 정적 캐시 미초기화로 인한 테스트 실패 수정.
InflowControlUtil.cachedInflowControlManager를 ReflectionTestUtils로
직접 주입/초기화하는 방식으로 변경.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-30 10:15:27 +09:00
curry772 496bdd1468 feat: DualInflowControlManager DAO 이중 호출 제거 및 타겟 메트릭 추가
- 베이스 맵 메서드 오버라이드(getAdapterAllKeys, getInterfaceAllKeys,
  getAdapterInflowThreashold, getInterfaceInflowThreashold,
  removeAdapter, removeInterface)로 DAO 이중 호출 제거
- super.reload*() 호출 제거
- 어댑터/인터페이스/클라이언트별 TargetMetrics 수집 추가
  (allowed, rejectedPerSecond, rejectedThreshold)
- 메트릭 조회/초기화 API 메서드 추가
- 단위테스트: DualInflowControlManagerBucketMethodsTest(18건),
  DualInflowControlManagerMetricsTest 확장

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-30 10:15:04 +09:00
curry772 2bfc3d0bde refactor: AbstractInflowControlManager 상속 구조 리팩토링 및 커맨드 클래스 타입 변경
InflowControlManager에서 공통 로직을 AbstractInflowControlManager로 분리하고,
커맨드 클래스들이 AbstractInflowControlManager 타입을 사용하도록 변경.
InflowControlUtil에 cachedInflowControlManager 정적 캐시 도입.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-30 10:14:31 +09:00
curry772 9589bc635a test: 클라이언트 유량제어 Command 단위 테스트 추가
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-29 15:15:11 +09:00
curry772 ca8be26583 feat: 클라이언트 유량제어 Command 추가 및 removeClient() 구현
- ReloadInflowClientControlCommand: 클라이언트 버킷 전체/개별 리로드
- RemoveInflowClientControlCommand: 클라이언트 버킷 제거
- DualInflowControlManager.removeClient(clientId) 메서드 추가
  (기존 removeAdapter/removeInterface와 동일한 패턴)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-29 14:59:15 +09:00
curry772 5641baff35 Merge branch 'feature/circuit-breaker-test' into master 2026-04-29 14:47:15 +09:00
49 changed files with 4573 additions and 975 deletions
+2
View File
@@ -82,6 +82,8 @@ dependencies {
api 'com.nimbusds:nimbus-jose-jwt:9.24.3'
api 'org.bouncycastle:bcprov-jdk15on:1.70'
api "io.undertow:undertow-servlet:${undertowVersion}"
api 'org.java-websocket:Java-WebSocket:1.3.9'
api 'javax.cache:cache-api:1.1.1'
@@ -40,7 +40,9 @@ import com.eactive.eai.adapter.AdapterManager;
import com.eactive.eai.adapter.Keys;
import com.eactive.eai.adapter.http.secure.HttpClient5SSLContextFactory;
import com.eactive.eai.common.TransactionContextKeys;
import com.eactive.eai.common.message.EAIMessageKeys;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.server.EAIServerManager;
import com.eactive.eai.common.util.HttpAdapterExtraLogUtil;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.httpouttlsinfo.HttpOutTlsInfoVO;
@@ -566,4 +568,10 @@ public abstract class HttpClient5AdapterServiceSupport implements HttpClientAdap
}
public abstract Object execute(Properties prop, Object message, Properties tempProp) throws Exception;
protected boolean isTas(Properties tempProp) {
String simYn = tempProp.getProperty("SIM_YN");
return EAIServerManager.getInstance().isTASEnabledEAIServer()
&& StringUtils.equals(simYn, EAIMessageKeys.TRANTYPE_TAS);
}
}
@@ -41,14 +41,11 @@ public class HttpClient5AdapterServiceBody extends HttpClient5AdapterServiceSupp
boolean useForwardProxy = StringUtils.equalsIgnoreCase(prop.getProperty("FORWARD_PROXY_USE_YN", "N"), "Y");
String forwardProxyUrl = prop.getProperty("FORWARD_PROXY_URL");
if(useForwardProxy) {
if(useForwardProxy && !isTas(tempProp)) {
java.net.URL url = new java.net.URL(forwardProxyUrl);
// 프로토콜, 호스트, 포트 추출
String protocol = url.getProtocol();
String host = url.getHost();
int port = url.getPort();
HttpHost proxy = new HttpHost(protocol,host, port);
HttpHost proxy = new HttpHost(url.getProtocol(), url.getHost(), url.getPort());
requestConfigBuilder.setProxy(proxy);
}
@@ -11,6 +11,7 @@ import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -294,14 +295,11 @@ public class HttpClient5AdapterServiceRest extends HttpClient5AdapterServiceSupp
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
if(useForwardProxy) {
if(useForwardProxy && !isTas(tempProp)) {
java.net.URL url = new java.net.URL(forwardProxyUrl);
// 프로토콜, 호스트, 포트 추출
String protocol = url.getProtocol();
String host = url.getHost();
int port = url.getPort();
HttpHost proxy = new HttpHost(protocol,host, port);
HttpHost proxy = new HttpHost(url.getProtocol(), url.getHost(), url.getPort());
requestConfigBuilder.setProxy(proxy);
}
@@ -708,12 +706,19 @@ public class HttpClient5AdapterServiceRest extends HttpClient5AdapterServiceSupp
return new String(responseMessage, encode);
}
String[] relayKeyArr = org.springframework.util.StringUtils.tokenizeToStringArray(relayHeaderKeys, ",");
JSONObject headerJson = new JSONObject();
if (StringUtils.equalsIgnoreCase(relayHeaderKeys, "ALL")) {
for (Enumeration<Object> e = responseHeaderProp.keys(); e.hasMoreElements(); ) {
String key = (String)e.nextElement();
headerJson.put(StringUtils.lowerCase(key), responseHeaderProp.getProperty(key));
}
} else {
String[] relayKeyArr = org.springframework.util.StringUtils.tokenizeToStringArray(relayHeaderKeys, ",");
for (String key : relayKeyArr) {
String value = responseHeaderProp.getProperty(key);
if (StringUtils.isNotBlank(value)) {
headerJson.put(key, value);
headerJson.put(StringUtils.lowerCase(key), value);
}
}
}
@@ -0,0 +1,222 @@
package com.eactive.eai.adapter.http.dynamic.filter;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import com.eactive.eai.common.security.CryptoModuleService;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.util.JsonPathUtil;
/**
* HTTP 어댑터 요청/응답 암복호화 필터 기반 클래스.
*
* 서브클래스는 {@link #buildRuntimeContext} 구현하여
* DYNAMIC 도출에 필요한 컨텍스트 맵을 제공한다.
* STATIC 모듈을 사용하는 경우 Map을 반환하면 된다.
* (CryptoModuleManager가 KEY_SOURCE_TYPE=STATIC이면 runtimeContext를 무시하고 고정 키를 사용한다.)
*
* 어댑터 프로퍼티 :
* crypto.module.name 필수. DB에 등록된 암호화 모듈명.
* crypto.scope BODY | FIELD (기본 BODY)
* BODY : 메시지 전체를 암복호화 (Base64 인코딩/디코딩)
* FIELD : 특정 JSON 경로의 값만 암복호화
* crypto.dec.enabled Y | N (기본 Y). doPreFilter(요청) 복호화 수행 여부.
* crypto.enc.enabled Y | N (기본 N). doPostFilter(응답) 암호화 수행 여부.
*
* FIELD 범위 전용:
* crypto.dec.from.path 복호화 대상 JSON 경로 (: /encryptedData)
* crypto.dec.to.path 복호화 결과 반영 경로. "/" = 전체 body 교체.
* crypto.enc.from.path 암호화 대상 JSON 경로. "/" = 전체 body 암호화.
* crypto.enc.to.path 암호화 결과(Base64) 넣을 JSON 경로 (: /encryptedData)
*/
public abstract class CryptoFilter implements HttpAdapterFilter {
protected static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
public static final String PROP_MODULE_NAME = "crypto.module.name";
public static final String PROP_SCOPE = "crypto.scope";
public static final String PROP_DEC_ENABLED = "crypto.dec.enabled";
public static final String PROP_ENC_ENABLED = "crypto.enc.enabled";
public static final String PROP_DEC_FROM_PATH = "crypto.dec.from.path";
public static final String PROP_DEC_TO_PATH = "crypto.dec.to.path";
public static final String PROP_ENC_FROM_PATH = "crypto.enc.from.path";
public static final String PROP_ENC_TO_PATH = "crypto.enc.to.path";
protected static final String SCOPE_BODY = "BODY";
protected static final String SCOPE_FIELD = "FIELD";
protected static final String PATH_ROOT = "/";
// ------------------------------------------------------------------
// 추상 메서드
// ------------------------------------------------------------------
/**
* DYNAMIC 도출에 필요한 runtimeContext 맵을 구성한다.
* STATIC 모듈이면 Map({@code new HashMap<>()}) 반환한다.
*/
protected abstract Map<String, String> buildRuntimeContext(Properties prop, HttpServletRequest request);
// ------------------------------------------------------------------
// doPreFilter: 요청 복호화
// ------------------------------------------------------------------
@Override
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
HttpServletRequest request, HttpServletResponse response) throws Exception {
if (!isEnabled(prop, PROP_DEC_ENABLED, "Y")) {
return message;
}
String moduleName = required(prop, PROP_MODULE_NAME);
String scope = prop.getProperty(PROP_SCOPE, SCOPE_BODY).toUpperCase();
String body = toBodyString(message);
Map<String, String> runtimeCtx = buildRuntimeContext(prop, request);
if (SCOPE_FIELD.equals(scope)) {
return decryptField(body, moduleName, runtimeCtx,
required(prop, PROP_DEC_FROM_PATH),
prop.getProperty(PROP_DEC_TO_PATH, PATH_ROOT));
}
return decryptBody(body, moduleName, runtimeCtx);
}
// ------------------------------------------------------------------
// doPostFilter: 응답 암호화
// ------------------------------------------------------------------
@Override
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
HttpServletRequest request, HttpServletResponse response) throws Exception {
if (!isEnabled(prop, PROP_ENC_ENABLED, "N")) {
return resultMessage;
}
String moduleName = required(prop, PROP_MODULE_NAME);
String scope = prop.getProperty(PROP_SCOPE, SCOPE_BODY).toUpperCase();
String body = toBodyString(resultMessage);
Map<String, String> runtimeCtx = buildRuntimeContext(prop, request);
if (SCOPE_FIELD.equals(scope)) {
return encryptField(body, moduleName, runtimeCtx,
prop.getProperty(PROP_ENC_FROM_PATH, PATH_ROOT),
required(prop, PROP_ENC_TO_PATH));
}
return encryptBody(body, moduleName, runtimeCtx);
}
// ------------------------------------------------------------------
// 복호화 구현
// ------------------------------------------------------------------
private String decryptBody(String body, String moduleName, Map<String, String> runtimeCtx) throws Exception {
byte[] cipherBytes = Base64.getDecoder().decode(body.trim());
byte[] plainBytes = CryptoModuleService.getInstance().decrypt(moduleName, runtimeCtx, cipherBytes);
return new String(plainBytes, StandardCharsets.UTF_8);
}
/**
* fromPath의 Base64 값을 복호화하여 toPath에 반영.
* toPath = "/" 복호화된 텍스트로 body 전체 교체.
*/
private String decryptField(String body, String moduleName, Map<String, String> runtimeCtx,
String fromPath, String toPath) throws Exception {
String encBase64 = JsonPathUtil.getValueAtPath(body, fromPath);
if (StringUtils.isBlank(encBase64)) {
logger.warn("CryptoFilter] 복호화 대상 필드 없음: path=" + fromPath);
return body;
}
byte[] cipherBytes = Base64.getDecoder().decode(encBase64.trim());
byte[] plainBytes = CryptoModuleService.getInstance().decrypt(moduleName, runtimeCtx, cipherBytes);
String plainText = new String(plainBytes, StandardCharsets.UTF_8);
if (PATH_ROOT.equals(toPath)) {
return plainText;
}
return JsonPathUtil.setValueAtPath(body, toPath, plainText, false);
}
// ------------------------------------------------------------------
// 암호화 구현
// ------------------------------------------------------------------
private String encryptBody(String body, String moduleName, Map<String, String> runtimeCtx) throws Exception {
byte[] cipherBytes = CryptoModuleService.getInstance().encrypt(moduleName, runtimeCtx,
body.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(cipherBytes);
}
/**
* fromPath 값을 암호화하여 toPath(Base64) 반영.
* fromPath = "/" body 전체를 암호화하여 toPath 필드명으로 래핑.
*/
private String encryptField(String body, String moduleName, Map<String, String> runtimeCtx,
String fromPath, String toPath) throws Exception {
String plainText;
if (PATH_ROOT.equals(fromPath)) {
plainText = body;
} else {
plainText = JsonPathUtil.getValueAtPath(body, fromPath);
if (StringUtils.isBlank(plainText)) {
logger.warn("CryptoFilter] 암호화 대상 필드 없음: path=" + fromPath);
return body;
}
}
byte[] cipherBytes = CryptoModuleService.getInstance().encrypt(moduleName, runtimeCtx,
plainText.getBytes(StandardCharsets.UTF_8));
String encBase64 = Base64.getEncoder().encodeToString(cipherBytes);
if (PATH_ROOT.equals(fromPath)) {
String fieldName = toPath.replaceFirst("^/", "");
return "{\"" + fieldName + "\":\"" + encBase64 + "\"}";
}
return JsonPathUtil.setValueAtPath(body, toPath, encBase64, false);
}
// ------------------------------------------------------------------
// 유틸
// ------------------------------------------------------------------
/**
* 필터로 전달되는 message 객체를 JSON 문자열로 변환한다.
* <ul>
* <li>{@code String} 그대로 반환</li>
* <li>{@code byte[]} UTF-8 디코딩</li>
* <li>{@code JSONObject} / 기타 {@code toString()} 호출
* (json-simple JSONObject는 toString() toJSONString() 위임함)</li>
* </ul>
*/
protected String toBodyString(Object message) {
if (message instanceof String) {
return (String) message;
}
if (message instanceof byte[]) {
return new String((byte[]) message, StandardCharsets.UTF_8);
}
return message.toString();
}
private boolean isEnabled(Properties prop, String key, String defaultVal) {
return !"N".equalsIgnoreCase(prop.getProperty(key, defaultVal));
}
protected String required(Properties prop, String key) {
String v = prop.getProperty(key);
if (StringUtils.isBlank(v)) {
throw new IllegalArgumentException("CryptoFilter 필수 프로퍼티 누락: " + key);
}
return v;
}
}
@@ -2,7 +2,8 @@ package com.eactive.eai.agent.inflow;
import com.eactive.eai.agent.command.Command;
import com.eactive.eai.agent.command.CommandException;
import com.eactive.eai.common.inflow.InflowControlManager;
import com.eactive.eai.common.inflow.AbstractInflowControlManager;
import com.eactive.eai.common.inflow.InflowControlUtil;
import com.eactive.eai.common.util.Logger;
public class ReloadInflowAdapterControlCommand extends Command {
@@ -27,7 +28,7 @@ public class ReloadInflowAdapterControlCommand extends Command {
String keyName = (String) args;
try {
InflowControlManager manager = InflowControlManager.getInstance();
AbstractInflowControlManager manager = InflowControlUtil.getInflowControlManager();
if (keyName != null) {
if ("ALL".equals(keyName)) {
@@ -0,0 +1,60 @@
package com.eactive.eai.agent.inflow;
import com.eactive.eai.agent.command.Command;
import com.eactive.eai.agent.command.CommandException;
import com.eactive.eai.common.inflow.AbstractInflowControlManager;
import com.eactive.eai.common.inflow.InflowControlUtil;
import com.eactive.eai.common.inflow.dual.ClientDualInflowControlManager;
import com.eactive.eai.common.util.Logger;
public class ReloadInflowClientControlCommand extends Command {
private static final long serialVersionUID = 1L;
public ReloadInflowClientControlCommand() {
super("ReloadInflowClientControlCommand");
}
public Object execute() throws CommandException {
Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
if (logger.isInfo())
logger.info(this.name + " is executed");
if (!(args instanceof String)) {
String rspErrorCode = "RECEAIMCM001";
String msg = makeException(rspErrorCode, null);
if (logger.isError())
logger.error(msg);
throw new CommandException(msg);
}
String keyName = (String) args;
try {
AbstractInflowControlManager base = InflowControlUtil.getInflowControlManager();
if (!(base instanceof ClientDualInflowControlManager)) {
throw new IllegalStateException("ClientDualInflowControlManager 가 활성화되지 않았습니다.");
}
ClientDualInflowControlManager manager = (ClientDualInflowControlManager) base;
if (keyName != null) {
if ("ALL".equals(keyName)) {
manager.reloadClient();
if (logger.isWarn())
logger.warn(this.name + "] all rule Reload.");
} else {
manager.reloadClient(keyName);
if (logger.isWarn())
logger.warn(this.name + "] " + keyName + " Reload.");
}
}
} catch (Exception e) {
String rspErrorCode = "RECEAIMCM002";
String msg = makeException(rspErrorCode, e);
if (logger.isError())
logger.error(msg, e);
throw new CommandException(msg);
}
return "success";
}
}
@@ -2,7 +2,8 @@ package com.eactive.eai.agent.inflow;
import com.eactive.eai.agent.command.Command;
import com.eactive.eai.agent.command.CommandException;
import com.eactive.eai.common.inflow.InflowControlManager;
import com.eactive.eai.common.inflow.AbstractInflowControlManager;
import com.eactive.eai.common.inflow.InflowControlUtil;
import com.eactive.eai.common.util.Logger;
public class ReloadInflowGroupControlCommand extends Command {
@@ -28,7 +29,7 @@ public class ReloadInflowGroupControlCommand extends Command {
String keyName = (String) args;
try {
InflowControlManager manager = InflowControlManager.getInstance();
AbstractInflowControlManager manager = InflowControlUtil.getInflowControlManager();
if (keyName != null) {
if ("ALL".equals(keyName)) {
@@ -2,7 +2,8 @@ package com.eactive.eai.agent.inflow;
import com.eactive.eai.agent.command.Command;
import com.eactive.eai.agent.command.CommandException;
import com.eactive.eai.common.inflow.InflowControlManager;
import com.eactive.eai.common.inflow.AbstractInflowControlManager;
import com.eactive.eai.common.inflow.InflowControlUtil;
import com.eactive.eai.common.util.Logger;
public class ReloadInflowInterfaceControlCommand extends Command {
@@ -28,7 +29,7 @@ public class ReloadInflowInterfaceControlCommand extends Command {
String keyName = (String) args;
try {
InflowControlManager manager = InflowControlManager.getInstance();
AbstractInflowControlManager manager = InflowControlUtil.getInflowControlManager();
if (keyName != null) {
if ("ALL".equals(keyName)) {
@@ -2,7 +2,8 @@ package com.eactive.eai.agent.inflow;
import com.eactive.eai.agent.command.Command;
import com.eactive.eai.agent.command.CommandException;
import com.eactive.eai.common.inflow.InflowControlManager;
import com.eactive.eai.common.inflow.AbstractInflowControlManager;
import com.eactive.eai.common.inflow.InflowControlUtil;
import com.eactive.eai.common.util.Logger;
public class RemoveInflowAdapterControlCommand extends Command {
@@ -26,7 +27,7 @@ public class RemoveInflowAdapterControlCommand extends Command {
String key = (String) args;
try {
InflowControlManager manager = InflowControlManager.getInstance();
AbstractInflowControlManager manager = InflowControlUtil.getInflowControlManager();
manager.removeAdapter(key);
} catch (Exception e) {
String rspErrorCode = "RECEAIMCM002";
@@ -0,0 +1,50 @@
package com.eactive.eai.agent.inflow;
import com.eactive.eai.agent.command.Command;
import com.eactive.eai.agent.command.CommandException;
import com.eactive.eai.common.inflow.AbstractInflowControlManager;
import com.eactive.eai.common.inflow.InflowControlUtil;
import com.eactive.eai.common.inflow.dual.ClientDualInflowControlManager;
import com.eactive.eai.common.util.Logger;
public class RemoveInflowClientControlCommand extends Command {
private static final long serialVersionUID = 1L;
public RemoveInflowClientControlCommand() {
super("RemoveInflowClientControlCommand");
}
public Object execute() throws CommandException {
Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
if (logger.isInfo())
logger.info(this.name + " is executed");
if (!(args instanceof String)) {
String rspErrorCode = "RECEAIMCM001";
String msg = makeException(rspErrorCode, null);
if (logger.isError())
logger.error(msg);
throw new CommandException(msg);
}
String key = (String) args;
try {
AbstractInflowControlManager base = InflowControlUtil.getInflowControlManager();
if (!(base instanceof ClientDualInflowControlManager)) {
throw new IllegalStateException("ClientDualInflowControlManager 가 활성화되지 않았습니다.");
}
ClientDualInflowControlManager manager = (ClientDualInflowControlManager) base;
manager.removeClient(key);
if (logger.isWarn())
logger.warn(this.name + "] " + key + " removed.");
} catch (Exception e) {
String rspErrorCode = "RECEAIMCM002";
String msg = makeException(rspErrorCode, e);
if (logger.isError())
logger.error(msg, e);
throw new CommandException(msg);
}
return "success";
}
}
@@ -2,7 +2,8 @@ package com.eactive.eai.agent.inflow;
import com.eactive.eai.agent.command.Command;
import com.eactive.eai.agent.command.CommandException;
import com.eactive.eai.common.inflow.InflowControlManager;
import com.eactive.eai.common.inflow.AbstractInflowControlManager;
import com.eactive.eai.common.inflow.InflowControlUtil;
import com.eactive.eai.common.util.Logger;
public class RemoveInflowGroupControlCommand extends Command {
@@ -28,7 +29,7 @@ public class RemoveInflowGroupControlCommand extends Command {
String key = (String) args;
try {
InflowControlManager manager = InflowControlManager.getInstance();
AbstractInflowControlManager manager = InflowControlUtil.getInflowControlManager();
manager.removeGroup(key);
if (logger.isWarn())
logger.warn(this.name + "] group " + key + " removed.");
@@ -2,7 +2,8 @@ package com.eactive.eai.agent.inflow;
import com.eactive.eai.agent.command.Command;
import com.eactive.eai.agent.command.CommandException;
import com.eactive.eai.common.inflow.InflowControlManager;
import com.eactive.eai.common.inflow.AbstractInflowControlManager;
import com.eactive.eai.common.inflow.InflowControlUtil;
import com.eactive.eai.common.util.Logger;
public class RemoveInflowInterfaceControlCommand extends Command {
@@ -25,7 +26,7 @@ public class RemoveInflowInterfaceControlCommand extends Command {
String key = (String) args;
try {
InflowControlManager manager = InflowControlManager.getInstance();
AbstractInflowControlManager manager = InflowControlUtil.getInflowControlManager();
manager.removeInterface(key);
} catch (Exception e) {
String rspErrorCode = "RECEAIMCM002";
@@ -0,0 +1,28 @@
package com.eactive.eai.agent.security;
import com.eactive.eai.agent.command.Command;
import com.eactive.eai.agent.command.CommandException;
import com.eactive.eai.common.security.CryptoModuleManager;
import com.eactive.eai.common.util.Logger;
public class ReloadCryptoModuleCommand extends Command {
private static final long serialVersionUID = 1032982004418318100L;
@Override
public Object execute() throws CommandException {
Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
try {
String cryptoId = (String) args;
CryptoModuleManager.getInstance().reload(cryptoId);
return "success";
} catch (Exception e) {
String rspErrorCode = "RECEAIMCM002";
String msg = this.makeException(rspErrorCode, e);
if (logger.isError()) {
logger.error(msg, e);
}
throw new CommandException(e.getMessage());
}
}
}
@@ -0,0 +1,501 @@
package com.eactive.eai.common.inflow;
import java.time.Duration;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.lifecycle.Lifecycle;
import com.eactive.eai.common.lifecycle.LifecycleException;
import com.eactive.eai.common.lifecycle.LifecycleListener;
import com.eactive.eai.common.lifecycle.LifecycleSupport;
import com.eactive.eai.common.util.Logger;
import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Bucket4j;
import io.github.bucket4j.Refill;
import io.github.bucket4j.local.LocalBucket;
import io.github.bucket4j.local.LocalBucketBuilder;
public abstract class AbstractInflowControlManager implements Lifecycle, Bucket {
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
public static final String QUOTA_TIMEUNIT_SECOND = "SEC";
public static final String QUOTA_TIMEUNIT_MINUTE = "MIN";
public static final String QUOTA_TIMEUNIT_HOUR = "HOU";
public static final String QUOTA_TIMEUNIT_DAY = "DAY";
public static final String QUOTA_TIMEUNIT_MONTH = "MON";
private volatile Map<String, CustomBucket> adapterBucketList = new ConcurrentHashMap<>();
private volatile Map<String, CustomBucket> interfaceBucketList = new ConcurrentHashMap<>();
private volatile Map<String, CustomGroupBucket> groupBucketList = new ConcurrentHashMap<>();
private volatile Map<String, String> interfaceToGroupMap = new ConcurrentHashMap<>();
private volatile Map<String, InflowGroupVO> groupVoMap = new ConcurrentHashMap<>();
private boolean started;
private LifecycleSupport lifecycle = new LifecycleSupport(this);
@Autowired
protected InflowControlDAO inflowControlDAO;
public void start() throws LifecycleException {
if (started)
throw new LifecycleException("RECEAICMM201");
lifecycle.fireLifecycleEvent(STARTING_EVENT, this);
try {
init();
} catch (Exception e) {
throw new LifecycleException(ExceptionUtil.getErrorCode(e, "RECEAICMM202"));
}
started = true;
lifecycle.fireLifecycleEvent(STARTED_EVENT, this);
}
private void init() throws Exception {
initAdapter();
initInterface();
initGroup();
}
private void initAdapter() throws Exception {
Map<String, CustomBucket> newMap = new HashMap<>();
List<InflowTargetVO> inflowAdapterVoList = inflowControlDAO.getInflowAdapterList();
for (InflowTargetVO inflowVo : inflowAdapterVoList) {
if (AbstractInflowControlManager.isInflowTarget(inflowVo)) {
CustomBucket bucket = makeBucketUsingInflowVO(inflowVo);
if (bucket != null) {
newMap.put(inflowVo.getName(), bucket);
}
}
}
this.adapterBucketList = newMap;
}
private void initInterface() throws Exception {
Map<String, CustomBucket> newMap = new HashMap<>();
List<InflowTargetVO> inflowInterfaceVoList = inflowControlDAO.getInflowInterfaceList();
for (InflowTargetVO inflowVo : inflowInterfaceVoList) {
if (AbstractInflowControlManager.isInflowTarget(inflowVo)) {
CustomBucket bucket = makeBucketUsingInflowVO(inflowVo);
if (bucket != null) {
newMap.put(inflowVo.getName(), bucket);
}
}
}
this.interfaceBucketList = newMap;
}
private void initGroup() throws Exception {
Map<String, CustomGroupBucket> newGroupBucketList = new HashMap<>();
Map<String, String> newInterfaceToGroupMap = new HashMap<>();
Map<String, InflowGroupVO> newGroupVoMap = new HashMap<>();
List<InflowGroupVO> inflowGroupVoList = inflowControlDAO.getInflowGroupList();
for (InflowGroupVO groupVo : inflowGroupVoList) {
if (isInflowGroupTarget(groupVo)) {
CustomGroupBucket bucket = makeGroupBucket(groupVo);
if (bucket != null) {
newGroupBucketList.put(groupVo.getGroupId(), bucket);
newGroupVoMap.put(groupVo.getGroupId(), groupVo);
for (String interfaceId : groupVo.getInterfaceList()) {
newInterfaceToGroupMap.put(interfaceId, groupVo.getGroupId());
}
}
}
}
if (logger.isInfo()) {
logger.info("InflowControlManager] initGroup completed. groups=" + newGroupBucketList.size()
+ ", mappings=" + newInterfaceToGroupMap.size());
}
this.groupBucketList = newGroupBucketList;
this.interfaceToGroupMap = newInterfaceToGroupMap;
this.groupVoMap = newGroupVoMap;
}
public synchronized void reloadAdapter() throws Exception {
if (logger.isWarn()) {
logger.warn("InflowControlManager] reload all Started ...");
}
initAdapter();
if (logger.isWarn()) {
logger.warn("InflowControlManager] reload all finished ...");
}
}
public synchronized void reloadInterface() throws Exception {
if (logger.isWarn()) {
logger.warn("InflowControlManager] reload all Started ...");
}
initInterface();
if (logger.isWarn()) {
logger.warn("InflowControlManager] reload all finished ...");
}
}
public synchronized void reloadAdapter(String adapter) throws Exception {
if (logger.isWarn()) {
logger.warn("InflowControlManager] reload Started ...");
}
Map<String, InflowTargetVO> map = inflowControlDAO.getInflowTargetByAdater(adapter);
if (map != null) {
Iterator<String> it = map.keySet().iterator();
String key = "";
while (it.hasNext()) {
key = it.next();
InflowTargetVO inflowTarget = map.get(key);
if (AbstractInflowControlManager.isInflowTarget(inflowTarget)) {
CustomBucket bucket = makeBucketUsingInflowVO(inflowTarget);
if (bucket != null) {
adapterBucketList.put(inflowTarget.getName(), bucket);
} else {
adapterBucketList.remove(inflowTarget.getName());
}
} else {
adapterBucketList.remove(inflowTarget.getName());
}
}
}
if (logger.isWarn()) {
logger.warn("InflowControlManager] reload finished ...");
}
}
public synchronized void reloadInterface(String inter) throws Exception {
if (logger.isWarn()) {
logger.warn("InflowControlManager] reload Started ...");
}
Map<String, InflowTargetVO> map = inflowControlDAO.getInflowTargetByInterface(inter);
if (map != null) {
Iterator<String> it = map.keySet().iterator();
String key = "";
while (it.hasNext()) {
key = it.next();
InflowTargetVO inflowTarget = map.get(key);
if (AbstractInflowControlManager.isInflowTarget(inflowTarget)) {
CustomBucket bucket = makeBucketUsingInflowVO(inflowTarget);
if (bucket != null) {
interfaceBucketList.put(inflowTarget.getName(), bucket);
} else {
interfaceBucketList.remove(inflowTarget.getName());
}
} else {
interfaceBucketList.remove(inflowTarget.getName());
}
}
}
if (logger.isWarn()) {
logger.warn("InflowControlManager] reload finished ...");
}
}
public synchronized void reloadGroup() throws Exception {
if (logger.isWarn()) {
logger.warn("InflowControlManager] reloadGroup all Started ...");
}
initGroup();
if (logger.isWarn()) {
logger.warn("InflowControlManager] reloadGroup all finished ...");
}
}
public synchronized void reloadGroup(String groupId) throws Exception {
if (logger.isWarn()) {
logger.warn("InflowControlManager] reloadGroup Started ... groupId=" + groupId);
}
Map<String, InflowGroupVO> map = inflowControlDAO.getInflowTargetByGroup(groupId);
if (map != null) {
Iterator<Map.Entry<String, String>> mappingIt = interfaceToGroupMap.entrySet().iterator();
while (mappingIt.hasNext()) {
Map.Entry<String, String> entry = mappingIt.next();
if (groupId.equals(entry.getValue())) {
mappingIt.remove();
}
}
Iterator<String> it = map.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
InflowGroupVO groupVo = map.get(key);
if (isInflowGroupTarget(groupVo)) {
CustomGroupBucket bucket = makeGroupBucket(groupVo);
if (bucket != null) {
groupBucketList.put(groupVo.getGroupId(), bucket);
groupVoMap.put(groupVo.getGroupId(), groupVo);
for (String interfaceId : groupVo.getInterfaceList()) {
interfaceToGroupMap.put(interfaceId, groupVo.getGroupId());
}
} else {
groupBucketList.remove(groupVo.getGroupId());
groupVoMap.remove(groupVo.getGroupId());
}
} else {
groupBucketList.remove(groupVo.getGroupId());
groupVoMap.remove(groupVo.getGroupId());
}
}
}
if (logger.isWarn()) {
logger.warn("InflowControlManager] reloadGroup finished ...");
}
}
public void stop() throws LifecycleException {
if (!started)
throw new LifecycleException("RECEAICMM203");
lifecycle.fireLifecycleEvent(STOPING_EVENT, this);
adapterBucketList = new ConcurrentHashMap<>();
interfaceBucketList = new ConcurrentHashMap<>();
groupBucketList = new ConcurrentHashMap<>();
interfaceToGroupMap = new ConcurrentHashMap<>();
groupVoMap = new ConcurrentHashMap<>();
started = false;
lifecycle.fireLifecycleEvent(STOPPED_EVENT, this);
}
public void addLifecycleListener(LifecycleListener listener) {
lifecycle.addLifecycleListener(listener);
}
public LifecycleListener[] findLifecycleListeners() {
return lifecycle.findLifecycleListeners();
}
public void removeLifecycleListener(LifecycleListener listener) {
lifecycle.removeLifecycleListener(listener);
}
public boolean isStarted() {
return this.started;
}
public String[] getAdapterAllKeys() {
Iterator<String> it = this.adapterBucketList.keySet().iterator();
String[] svcCd = new String[this.adapterBucketList.size()];
for (int i = 0; it.hasNext(); i++) {
svcCd[i] = it.next();
}
Arrays.sort(svcCd);
return svcCd;
}
public String[] getInterfaceAllKeys() {
Iterator<String> it = this.interfaceBucketList.keySet().iterator();
String[] svcCd = new String[this.interfaceBucketList.size()];
for (int i = 0; it.hasNext(); i++) {
svcCd[i] = it.next();
}
Arrays.sort(svcCd);
return svcCd;
}
public synchronized void removeAdapter(String adapter) {
adapterBucketList.remove(adapter);
}
public synchronized void removeInterface(String inter) {
interfaceBucketList.remove(inter);
}
public synchronized void removeGroup(String groupId) {
groupBucketList.remove(groupId);
groupVoMap.remove(groupId);
Iterator<Map.Entry<String, String>> it = interfaceToGroupMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
if (groupId.equals(entry.getValue())) {
it.remove();
}
}
}
public String[] getGroupAllKeys() {
Iterator<String> it = this.groupBucketList.keySet().iterator();
String[] groupIds = new String[this.groupBucketList.size()];
for (int i = 0; it.hasNext(); i++) {
groupIds[i] = it.next();
}
Arrays.sort(groupIds);
return groupIds;
}
public CustomGroupBucket getGroupBucket(String groupId) {
return groupBucketList.get(groupId);
}
private CustomBucket makeBucketUsingInflowVO(InflowTargetVO inflowTarget) {
if (AbstractInflowControlManager.isInflowTarget(inflowTarget)) {
LocalBucketBuilder builder = Bucket4j.builder();
if (inflowTarget.getThresholdPerSecond() > 0) {
builder.addLimit(Bandwidth.classic(inflowTarget.getThresholdPerSecond(),
Refill.greedy(inflowTarget.getThresholdPerSecond(), Duration.ofSeconds(1))));
}
if (inflowTarget.getThreshold() > 0 && StringUtils.isNotBlank(inflowTarget.getThresholdTimeUnit())) {
builder.addLimit(Bandwidth.classic(inflowTarget.getThreshold(),
Refill.intervally(inflowTarget.getThreshold(),
AbstractInflowControlManager.getPeriod(inflowTarget.getThresholdTimeUnit()))));
}
return new CustomBucket(builder.build(), inflowTarget);
}
return null;
}
private CustomGroupBucket makeGroupBucket(InflowGroupVO groupVo) {
if (!isInflowGroupTarget(groupVo)) {
return null;
}
LocalBucket perSecondBucket = null;
LocalBucket thresholdBucket = null;
if (groupVo.getThresholdPerSecond() > 0) {
perSecondBucket = Bucket4j.builder()
.addLimit(Bandwidth.classic(groupVo.getThresholdPerSecond(),
Refill.greedy(groupVo.getThresholdPerSecond(), Duration.ofSeconds(1))))
.build();
}
if (groupVo.getThreshold() > 0 && StringUtils.isNotBlank(groupVo.getThresholdTimeUnit())) {
thresholdBucket = Bucket4j.builder()
.addLimit(Bandwidth.classic(groupVo.getThreshold(),
Refill.intervally(groupVo.getThreshold(),
AbstractInflowControlManager.getPeriod(groupVo.getThresholdTimeUnit()))))
.build();
}
return new CustomGroupBucket(perSecondBucket, thresholdBucket, groupVo);
}
@Override
public boolean isAdapterPass(String adapter) {
CustomBucket b = adapterBucketList.get(adapter);
if (b == null)
return true;
return b.getLocalBucket().tryConsume(1);
}
@Override
public boolean isInterfacePass(String inter) {
CustomBucket b = interfaceBucketList.get(inter);
if (b == null)
return true;
return b.getLocalBucket().tryConsume(1);
}
@Override
public InflowTargetVO getAdapterInflowThreashold(String adapter) {
CustomBucket b = adapterBucketList.get(adapter);
if (b == null)
return null;
return b.getInflowTargetVo();
}
@Override
public InflowTargetVO getInterfaceInflowThreashold(String inter) {
CustomBucket b = interfaceBucketList.get(inter);
if (b == null)
return null;
return b.getInflowTargetVo();
}
@Override
public InflowTargetVO getInflowThreashold(String inter) {
return null;
}
public InflowTargetVO getAdapterInflow(String adapter) {
return getAdapterInflowThreashold(adapter);
}
public InflowTargetVO getInterfaceInflow(String inter) {
return getInterfaceInflowThreashold(inter);
}
@Override
public String isGroupPass(String groupId) {
CustomGroupBucket b = groupBucketList.get(groupId);
if (b == null)
return null;
return b.tryConsume();
}
@Override
public InflowGroupVO getGroupInflowThreshold(String groupId) {
return groupVoMap.get(groupId);
}
@Override
public String getGroupIdByInterface(String interfaceId) {
return interfaceToGroupMap.get(interfaceId);
}
public InflowGroupVO getGroupInflow(String groupId) {
return getGroupInflowThreshold(groupId);
}
public static boolean isInflowTarget(InflowTargetVO inflowTarget) {
if (inflowTarget == null || !inflowTarget.isActivate()) {
return false;
}
return inflowTarget.getThresholdPerSecond() > 0 || (inflowTarget.getThreshold() > 0 && StringUtils
.equalsAnyIgnoreCase(inflowTarget.getThresholdTimeUnit(), QUOTA_TIMEUNIT_DAY, QUOTA_TIMEUNIT_SECOND,
QUOTA_TIMEUNIT_MINUTE, QUOTA_TIMEUNIT_HOUR, QUOTA_TIMEUNIT_DAY, QUOTA_TIMEUNIT_MONTH));
}
public static boolean isInflowGroupTarget(InflowGroupVO groupVo) {
if (groupVo == null || !groupVo.isActivate()) {
return false;
}
return groupVo.getThresholdPerSecond() > 0 || (groupVo.getThreshold() > 0 && StringUtils
.equalsAnyIgnoreCase(groupVo.getThresholdTimeUnit(), QUOTA_TIMEUNIT_DAY, QUOTA_TIMEUNIT_SECOND,
QUOTA_TIMEUNIT_MINUTE, QUOTA_TIMEUNIT_HOUR, QUOTA_TIMEUNIT_DAY, QUOTA_TIMEUNIT_MONTH));
}
public static Duration getPeriod(String timeUnit) {
if (StringUtils.equalsIgnoreCase(timeUnit, QUOTA_TIMEUNIT_SECOND)) {
return Duration.ofSeconds(1);
} else if (StringUtils.equalsIgnoreCase(timeUnit, QUOTA_TIMEUNIT_MINUTE)) {
return Duration.ofMinutes(1);
} else if (StringUtils.equalsIgnoreCase(timeUnit, QUOTA_TIMEUNIT_HOUR)) {
return Duration.ofHours(1);
} else if (StringUtils.equalsIgnoreCase(timeUnit, QUOTA_TIMEUNIT_DAY)) {
return Duration.ofDays(1);
} else if (StringUtils.equalsIgnoreCase(timeUnit, QUOTA_TIMEUNIT_MONTH)) {
Calendar calendar = Calendar.getInstance();
return Duration.ofDays(calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
} else {
return null;
}
}
}
@@ -1,55 +1,11 @@
package com.eactive.eai.common.inflow;
import java.time.Duration;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.lifecycle.Lifecycle;
import com.eactive.eai.common.lifecycle.LifecycleException;
import com.eactive.eai.common.lifecycle.LifecycleListener;
import com.eactive.eai.common.lifecycle.LifecycleSupport;
import com.eactive.eai.common.message.EAIMessage;
import com.eactive.eai.common.server.EAIServerManager;
import com.eactive.eai.common.util.ApplicationContextProvider;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.common.util.MessageUtil;
import com.eactive.eai.message.service.InterfaceMapper;
import com.ext.eai.common.stdmessage.STDMessageKeys;
import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Bucket4j;
import io.github.bucket4j.local.LocalBucket;
import io.github.bucket4j.local.LocalBucketBuilder;
@Component
public class InflowControlManager implements Lifecycle, Bucket {
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
public static final String QUOTA_TIMEUNIT_SECOND = "SEC";
public static final String QUOTA_TIMEUNIT_MINUTE = "MIN";
public static final String QUOTA_TIMEUNIT_HOUR = "HOU";
public static final String QUOTA_TIMEUNIT_DAY = "DAY";
public static final String QUOTA_TIMEUNIT_MONTH = "MON";
private volatile Map<String, CustomBucket> adapterBucketList = new ConcurrentHashMap<>();
private volatile Map<String, CustomBucket> interfaceBucketList = new ConcurrentHashMap<>();
private volatile Map<String, CustomGroupBucket> groupBucketList = new ConcurrentHashMap<>();
private volatile Map<String, String> interfaceToGroupMap = new ConcurrentHashMap<>();
private volatile Map<String, InflowGroupVO> groupVoMap = new ConcurrentHashMap<>();
private boolean started;
private LifecycleSupport lifecycle = new LifecycleSupport(this);
@Autowired
private InflowControlDAO inflowControlDAO;
public class InflowControlManager extends AbstractInflowControlManager {
public static synchronized InflowControlManager getInstance() {
return ApplicationContextProvider.getContext().getBean(InflowControlManager.class);
@@ -58,485 +14,4 @@ public class InflowControlManager implements Lifecycle, Bucket {
public static synchronized Bucket getBucket() {
return ApplicationContextProvider.getContext().getBean(InflowControlManager.class);
}
/**
* 유량제어 대상인 거래인지 체크한다.(사이트에 맞게 구성)
*
* @param eaiServerManager
* @param eaiMessage
* @return
*/
public static Boolean isTargetOfInflowControl(EAIServerManager eaiServerManager, EAIMessage eaiMessage) {
InterfaceMapper mapper = eaiMessage.getMapper();
String returnType = mapper.getSendRecvDivision(eaiMessage.getStandardMessage()); // S|R
if (STDMessageKeys.SEND_RECV_CD_SEND.equals(returnType)) {
return Boolean.valueOf(true);
}
return Boolean.valueOf(false);
}
public void start() throws LifecycleException {
if (started)
throw new LifecycleException("RECEAICMM201");
lifecycle.fireLifecycleEvent(STARTING_EVENT, this);
try {
init();
} catch (Exception e) {
throw new LifecycleException(ExceptionUtil.getErrorCode(e, "RECEAICMM202"));
}
started = true;
lifecycle.fireLifecycleEvent(STARTED_EVENT, this);
}
private void init() throws Exception {
initAdapter();
initInterface();
initGroup();
}
private void initAdapter() throws Exception {
Map<String, CustomBucket> newMap = new HashMap<>();
List<InflowTargetVO> inflowAdapterVoList = inflowControlDAO.getInflowAdapterList();
for (InflowTargetVO inflowVo : inflowAdapterVoList) {
if (InflowControlManager.isInflowTarget(inflowVo)) {
CustomBucket bucket = makeBucketUsingInflowVO(inflowVo);
if (bucket != null) {
newMap.put(inflowVo.getName(), bucket);
}
}
}
this.adapterBucketList = newMap;
}
private void initInterface() throws Exception {
Map<String, CustomBucket> newMap = new HashMap<>();
List<InflowTargetVO> inflowInterfaceVoList = inflowControlDAO.getInflowInterfaceList();
for (InflowTargetVO inflowVo : inflowInterfaceVoList) {
if (InflowControlManager.isInflowTarget(inflowVo)) {
CustomBucket bucket = makeBucketUsingInflowVO(inflowVo);
if (bucket != null) {
newMap.put(inflowVo.getName(), bucket);
}
}
}
this.interfaceBucketList = newMap;
}
private void initGroup() throws Exception {
Map<String, CustomGroupBucket> newGroupBucketList = new HashMap<>();
Map<String, String> newInterfaceToGroupMap = new HashMap<>();
Map<String, InflowGroupVO> newGroupVoMap = new HashMap<>();
List<InflowGroupVO> inflowGroupVoList = inflowControlDAO.getInflowGroupList();
for (InflowGroupVO groupVo : inflowGroupVoList) {
if (isInflowGroupTarget(groupVo)) {
CustomGroupBucket bucket = makeGroupBucket(groupVo);
if (bucket != null) {
newGroupBucketList.put(groupVo.getGroupId(), bucket);
newGroupVoMap.put(groupVo.getGroupId(), groupVo);
// 인터페이스 그룹 매핑 등록
for (String interfaceId : groupVo.getInterfaceList()) {
newInterfaceToGroupMap.put(interfaceId, groupVo.getGroupId());
}
}
}
}
if (logger.isInfo()) {
logger.info("InflowControlManager] initGroup completed. groups=" + newGroupBucketList.size()
+ ", mappings=" + newInterfaceToGroupMap.size());
}
this.groupBucketList = newGroupBucketList;
this.interfaceToGroupMap = newInterfaceToGroupMap;
this.groupVoMap = newGroupVoMap;
}
public synchronized void reloadAdapter() throws Exception {
if (logger.isWarn()) {
logger.warn("InflowControlManager] reload all Started ...");
}
initAdapter();
if (logger.isWarn()) {
logger.warn("InflowControlManager] reload all finished ...");
}
}
public synchronized void reloadInterface() throws Exception {
if (logger.isWarn()) {
logger.warn("InflowControlManager] reload all Started ...");
}
initInterface();
if (logger.isWarn()) {
logger.warn("InflowControlManager] reload all finished ...");
}
}
public synchronized void reloadAdapter(String adapter) throws Exception {
if (logger.isWarn()) {
logger.warn("InflowControlManager] reload Started ...");
}
Map<String, InflowTargetVO> map = inflowControlDAO.getInflowTargetByAdater(adapter);
if (map != null) {
Iterator<String> it = map.keySet().iterator();
String key = "";
while (it.hasNext()) {
key = it.next();
InflowTargetVO inflowTarget = map.get(key);
if (InflowControlManager.isInflowTarget(inflowTarget)) {
CustomBucket bucket = makeBucketUsingInflowVO(inflowTarget);
if (bucket != null) {
adapterBucketList.put(inflowTarget.getName(), bucket);
} else {
adapterBucketList.remove(inflowTarget.getName());
}
} else {
adapterBucketList.remove(inflowTarget.getName());
}
}
}
if (logger.isWarn()) {
logger.warn("InflowControlManager] reload finished ...");
}
}
public synchronized void reloadInterface(String inter) throws Exception {
if (logger.isWarn()) {
logger.warn("InflowControlManager] reload Started ...");
}
Map<String, InflowTargetVO> map = inflowControlDAO.getInflowTargetByInterface(inter);
if (map != null) {
Iterator<String> it = map.keySet().iterator();
String key = "";
while (it.hasNext()) {
key = it.next();
InflowTargetVO inflowTarget = map.get(key);
if (InflowControlManager.isInflowTarget(inflowTarget)) {
CustomBucket bucket = makeBucketUsingInflowVO(inflowTarget);
if (bucket != null) {
interfaceBucketList.put(inflowTarget.getName(), bucket);
} else {
interfaceBucketList.remove(inflowTarget.getName());
}
} else {
interfaceBucketList.remove(inflowTarget.getName());
}
}
}
if (logger.isWarn()) {
logger.warn("InflowControlManager] reload finished ...");
}
}
public synchronized void reloadGroup() throws Exception {
if (logger.isWarn()) {
logger.warn("InflowControlManager] reloadGroup all Started ...");
}
initGroup();
if (logger.isWarn()) {
logger.warn("InflowControlManager] reloadGroup all finished ...");
}
}
public synchronized void reloadGroup(String groupId) throws Exception {
if (logger.isWarn()) {
logger.warn("InflowControlManager] reloadGroup Started ... groupId=" + groupId);
}
Map<String, InflowGroupVO> map = inflowControlDAO.getInflowTargetByGroup(groupId);
if (map != null) {
// 기존 그룹에 속한 인터페이스 매핑 제거
Iterator<Map.Entry<String, String>> mappingIt = interfaceToGroupMap.entrySet().iterator();
while (mappingIt.hasNext()) {
Map.Entry<String, String> entry = mappingIt.next();
if (groupId.equals(entry.getValue())) {
mappingIt.remove();
}
}
Iterator<String> it = map.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
InflowGroupVO groupVo = map.get(key);
if (isInflowGroupTarget(groupVo)) {
CustomGroupBucket bucket = makeGroupBucket(groupVo);
if (bucket != null) {
groupBucketList.put(groupVo.getGroupId(), bucket);
groupVoMap.put(groupVo.getGroupId(), groupVo);
// 인터페이스 그룹 매핑 재등록
for (String interfaceId : groupVo.getInterfaceList()) {
interfaceToGroupMap.put(interfaceId, groupVo.getGroupId());
}
} else {
groupBucketList.remove(groupVo.getGroupId());
groupVoMap.remove(groupVo.getGroupId());
}
} else {
groupBucketList.remove(groupVo.getGroupId());
groupVoMap.remove(groupVo.getGroupId());
}
}
}
if (logger.isWarn()) {
logger.warn("InflowControlManager] reloadGroup finished ...");
}
}
public void stop() throws LifecycleException {
// Validate and update our current component state
if (!started)
throw new LifecycleException("RECEAICMM203");
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(STOPING_EVENT, this);
adapterBucketList = new ConcurrentHashMap<>();
interfaceBucketList = new ConcurrentHashMap<>();
groupBucketList = new ConcurrentHashMap<>();
interfaceToGroupMap = new ConcurrentHashMap<>();
groupVoMap = new ConcurrentHashMap<>();
started = false;
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(STOPPED_EVENT, this);
}
public void addLifecycleListener(LifecycleListener listener) {
lifecycle.addLifecycleListener(listener);
}
public LifecycleListener[] findLifecycleListeners() {
return lifecycle.findLifecycleListeners();
}
public void removeLifecycleListener(LifecycleListener listener) {
lifecycle.removeLifecycleListener(listener);
}
public boolean isStarted() {
return this.started;
}
public String[] getAdapterAllKeys() {
Iterator<String> it = this.adapterBucketList.keySet().iterator();
String[] svcCd = new String[this.adapterBucketList.size()];
for (int i = 0; it.hasNext(); i++) {
svcCd[i] = it.next();
}
Arrays.sort(svcCd);
return svcCd;
}
public String[] getInterfaceAllKeys() {
Iterator<String> it = this.interfaceBucketList.keySet().iterator();
String[] svcCd = new String[this.interfaceBucketList.size()];
for (int i = 0; it.hasNext(); i++) {
svcCd[i] = it.next();
}
Arrays.sort(svcCd);
return svcCd;
}
public synchronized void removeAdapter(String adapter) {
adapterBucketList.remove(adapter);
}
public synchronized void removeInterface(String inter) {
interfaceBucketList.remove(inter);
}
public synchronized void removeGroup(String groupId) {
groupBucketList.remove(groupId);
groupVoMap.remove(groupId);
// 해당 그룹에 속한 인터페이스 매핑도 제거
Iterator<Map.Entry<String, String>> it = interfaceToGroupMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
if (groupId.equals(entry.getValue())) {
it.remove();
}
}
}
public String[] getGroupAllKeys() {
Iterator<String> it = this.groupBucketList.keySet().iterator();
String[] groupIds = new String[this.groupBucketList.size()];
for (int i = 0; it.hasNext(); i++) {
groupIds[i] = it.next();
}
Arrays.sort(groupIds);
return groupIds;
}
public CustomGroupBucket getGroupBucket(String groupId) {
return groupBucketList.get(groupId);
}
private CustomBucket makeBucketUsingInflowVO(InflowTargetVO inflowTarget) {
if (InflowControlManager.isInflowTarget(inflowTarget)) {
LocalBucketBuilder builder = Bucket4j.builder();
if (inflowTarget.getThresholdPerSecond() > 0) {
builder.addLimit(Bandwidth.simple(inflowTarget.getThresholdPerSecond(), Duration.ofSeconds(1)));
}
if (inflowTarget.getThreshold() > 0 && StringUtils.isNotBlank(inflowTarget.getThresholdTimeUnit())) {
builder.addLimit(Bandwidth.simple(inflowTarget.getThreshold(),
InflowControlManager.getPeriod(inflowTarget.getThresholdTimeUnit())));
}
return new CustomBucket(builder.build(), inflowTarget);
}
return null;
}
/**
* 그룹용 버킷 생성 - 초당/추가 임계치를 별도 버킷으로 분리
*/
private CustomGroupBucket makeGroupBucket(InflowGroupVO groupVo) {
if (!isInflowGroupTarget(groupVo)) {
return null;
}
LocalBucket perSecondBucket = null;
LocalBucket thresholdBucket = null;
// 초당 임계치 버킷 (별도)
if (groupVo.getThresholdPerSecond() > 0) {
perSecondBucket = Bucket4j.builder()
.addLimit(Bandwidth.simple(groupVo.getThresholdPerSecond(), Duration.ofSeconds(1)))
.build();
}
// 추가 임계치 버킷 (별도)
if (groupVo.getThreshold() > 0 && StringUtils.isNotBlank(groupVo.getThresholdTimeUnit())) {
thresholdBucket = Bucket4j.builder()
.addLimit(Bandwidth.simple(groupVo.getThreshold(),
InflowControlManager.getPeriod(groupVo.getThresholdTimeUnit())))
.build();
}
return new CustomGroupBucket(perSecondBucket, thresholdBucket, groupVo);
}
@Override
public boolean isAdapterPass(String adapter) {
CustomBucket b = adapterBucketList.get(adapter);
if (b == null)
return true;
return b.getLocalBucket().tryConsume(1);
}
@Override
public boolean isInterfacePass(String inter) {
CustomBucket b = interfaceBucketList.get(inter);
if (b == null)
return true;
return b.getLocalBucket().tryConsume(1);
}
@Override
public InflowTargetVO getAdapterInflowThreashold(String adapter) {
CustomBucket b = adapterBucketList.get(adapter);
if (b == null)
return null;
return b.getInflowTargetVo();
}
@Override
public InflowTargetVO getInterfaceInflowThreashold(String inter) {
CustomBucket b = interfaceBucketList.get(inter);
if (b == null)
return null;
return b.getInflowTargetVo();
}
@Override
public InflowTargetVO getInflowThreashold(String inter) {
return null;
}
public InflowTargetVO getAdapterInflow(String adapter) {
return getAdapterInflowThreashold(adapter);
}
public InflowTargetVO getInterfaceInflow(String inter) {
return getInterfaceInflowThreashold(inter);
}
@Override
public String isGroupPass(String groupId) {
CustomGroupBucket b = groupBucketList.get(groupId);
if (b == null)
return null;
return b.tryConsume();
}
@Override
public InflowGroupVO getGroupInflowThreshold(String groupId) {
return groupVoMap.get(groupId);
}
@Override
public String getGroupIdByInterface(String interfaceId) {
return interfaceToGroupMap.get(interfaceId);
}
public InflowGroupVO getGroupInflow(String groupId) {
return getGroupInflowThreshold(groupId);
}
public static boolean isInflowTarget(InflowTargetVO inflowTarget) {
if (inflowTarget == null || !inflowTarget.isActivate()) {
return false;
}
return inflowTarget.getThresholdPerSecond() > 0 || (inflowTarget.getThreshold() > 0 && StringUtils
.equalsAnyIgnoreCase(inflowTarget.getThresholdTimeUnit(), QUOTA_TIMEUNIT_DAY, QUOTA_TIMEUNIT_SECOND,
QUOTA_TIMEUNIT_MINUTE, QUOTA_TIMEUNIT_HOUR, QUOTA_TIMEUNIT_DAY, QUOTA_TIMEUNIT_MONTH));
}
public static boolean isInflowGroupTarget(InflowGroupVO groupVo) {
if (groupVo == null || !groupVo.isActivate()) {
return false;
}
return groupVo.getThresholdPerSecond() > 0 || (groupVo.getThreshold() > 0 && StringUtils
.equalsAnyIgnoreCase(groupVo.getThresholdTimeUnit(), QUOTA_TIMEUNIT_DAY, QUOTA_TIMEUNIT_SECOND,
QUOTA_TIMEUNIT_MINUTE, QUOTA_TIMEUNIT_HOUR, QUOTA_TIMEUNIT_DAY, QUOTA_TIMEUNIT_MONTH));
}
public static Duration getPeriod(String timeUnit) {
if (StringUtils.equalsIgnoreCase(timeUnit, QUOTA_TIMEUNIT_SECOND)) {
return Duration.ofSeconds(1);
} else if (StringUtils.equalsIgnoreCase(timeUnit, QUOTA_TIMEUNIT_MINUTE)) {
return Duration.ofMinutes(1);
} else if (StringUtils.equalsIgnoreCase(timeUnit, QUOTA_TIMEUNIT_HOUR)) {
return Duration.ofHours(1);
} else if (StringUtils.equalsIgnoreCase(timeUnit, QUOTA_TIMEUNIT_DAY)) {
return Duration.ofDays(1);
} else if (StringUtils.equalsIgnoreCase(timeUnit, QUOTA_TIMEUNIT_MONTH)) {
Calendar calendar = Calendar.getInstance();
return Duration.ofDays(calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
} else {
return null;
}
}
}
@@ -8,7 +8,10 @@ import org.apache.commons.lang3.StringUtils;
import com.eactive.eai.common.message.EAIMessage;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.server.EAIServerManager;
import com.eactive.eai.common.util.ApplicationContextProvider;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.message.service.InterfaceMapper;
import com.ext.eai.common.stdmessage.STDMessageKeys;
public class InflowControlUtil {
private InflowControlUtil() {
@@ -16,28 +19,70 @@ public class InflowControlUtil {
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
private static volatile AbstractInflowControlManager cachedInflowControlManager;
private static volatile Bucket cachedBucket;
/**
* INFLOW.properties의 inflow.control.bucket.className 설정에 따라
* 활성화된 InflowControlManager 구현체를 반환한다.
*
* getBean(InflowControlManager.class) 대신 설정된 구체 타입으로 조회하므로
* InflowControlManager와 DualInflowControlManager가 모두 Bean으로 등록된
* 환경에서도 NoUniqueBeanDefinitionException 없이 올바른 인스턴스를 반환한다.
*
* 최초 1회만 조회하고 이후에는 캐시된 인스턴스를 반환한다.
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Bucket getBucket() {
public static AbstractInflowControlManager getInflowControlManager() {
if (cachedInflowControlManager == null) {
synchronized (InflowControlUtil.class) {
if (cachedInflowControlManager == null) {
Properties inFlowProp = PropManager.getInstance().getProperties("INFLOW");
String className = inFlowProp.getProperty("inflow.control.bucket.className");
if (StringUtils.isBlank(className)
|| StringUtils.equals(className, "com.eactive.eai.common.inflow.InflowControlManager")) {
return InflowControlManager.getBucket();
cachedInflowControlManager = InflowControlManager.getInstance();
} else {
try {
Class clazz = Class.forName(className);
cachedInflowControlManager = (AbstractInflowControlManager) ApplicationContextProvider.getContext().getBean(clazz);
} catch (Exception e) {
logger.error("getInflowControlManager error class= {}", className);
logger.error(e.getMessage());
}
}
}
}
}
return cachedInflowControlManager;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Bucket getBucket() {
if (cachedBucket == null) {
synchronized (InflowControlUtil.class) {
if (cachedBucket == null) {
Properties inFlowProp = PropManager.getInstance().getProperties("INFLOW");
String className = inFlowProp.getProperty("inflow.control.bucket.className");
if (StringUtils.isBlank(className)
|| StringUtils.equals(className, "com.eactive.eai.common.inflow.InflowControlManager")) {
cachedBucket = InflowControlManager.getBucket();
} else {
try {
Class clazz = Class.forName(className);
Method method = clazz.getMethod("getBucket", (Class<?>[]) null);
return (Bucket) method.invoke(null, (Object[]) null);
cachedBucket = (Bucket) method.invoke(null, (Object[]) null);
} catch (Exception e) {
logger.error("Method call error class= {}, method= getBucket", className);
logger.error(e.getMessage());
}
}
return null;
}
}
}
return cachedBucket;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static boolean isTargetOfInflowControl(EAIServerManager eaiServerManager, EAIMessage eaiMessage) {
Properties inFlowProp = PropManager.getInstance().getProperties("INFLOW");
String controlInflow = inFlowProp.getProperty("inflow.control.yn", "N");
@@ -46,20 +91,17 @@ public class InflowControlUtil {
return false;
}
String className = inFlowProp.getProperty("inflow.control.bucket.className");
if (StringUtils.isBlank(className)
|| StringUtils.equals(className, "com.eactive.eai.common.inflow.InflowControlManager")) {
return InflowControlManager.isTargetOfInflowControl(eaiServerManager, eaiMessage).booleanValue();
} else {
try {
Class clazz = Class.forName(className);
Method method = clazz.getMethod("isTargetOfInflowControl", EAIServerManager.class, EAIMessage.class);
Boolean returnBoolean = (Boolean) method.invoke(null, eaiServerManager, eaiMessage);
return returnBoolean.booleanValue();
} catch (Exception e) {
logger.error("Method call error class= {}, method= isTargetOfInflowControl", className);
logger.error(e.getMessage());
InterfaceMapper mapper = eaiMessage.getMapper();
String returnType = mapper.getSendRecvDivision(eaiMessage.getStandardMessage()); // S|R
if (STDMessageKeys.SEND_RECV_CD_SEND.equals(returnType)) {
return Boolean.valueOf(true);
}
return Boolean.valueOf(false);
} catch (Exception e) {
logger.error("isTargetOfInflowControl call error", e.getMessage());
}
return false;
@@ -0,0 +1,22 @@
package com.eactive.eai.common.inflow.dual;
import com.eactive.eai.common.inflow.InflowTargetVO;
/**
* DualBucket에 클라이언트 유량제어 메서드를 추가한 인터페이스.
* {@link ClientDualInflowControlManager} 구현한다.
*/
public interface ClientDualBucket extends DualBucket {
/**
* 클라이언트 유량제어 체크 차단 원인 포함.
* @return null이면 통과, "PER_SECOND" 또는 "THRESHOLD"이면 해당 버킷에서 차단
*/
String isClientPassDetail(String clientId);
/**
* 클라이언트 유량제어 설정 조회 에러 메시지 생성용.
* @return 등록된 설정이 없으면 null
*/
InflowTargetVO getClientInflowThreshold(String clientId);
}
@@ -0,0 +1,112 @@
package com.eactive.eai.common.inflow.dual;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.stereotype.Component;
import com.eactive.eai.common.inflow.Bucket;
import com.eactive.eai.common.inflow.InflowTargetVO;
import com.eactive.eai.common.inflow.InflowType;
import com.eactive.eai.common.lifecycle.LifecycleException;
import com.eactive.eai.common.util.ApplicationContextProvider;
import com.eactive.eai.common.util.Logger;
/**
* 어댑터/인터페이스 이중 버킷(DualInflowControlManager) 클라이언트 유량제어를 추가한 관리자.
*
* <p>적용 방법: INFLOW.properties에 아래 추가.
* <pre>inflow.control.bucket.className=com.eactive.eai.common.inflow.dual.ClientDualInflowControlManager</pre>
*/
@Component
public class ClientDualInflowControlManager extends DualInflowControlManager implements ClientDualBucket {
private static final Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
public static synchronized Bucket getBucket() {
return ApplicationContextProvider.getContext().getBean(ClientDualInflowControlManager.class);
}
private volatile Map<String, DualCustomBucket> clientBucketMap = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, TargetMetrics> clientMetricsMap = new ConcurrentHashMap<>();
// -------------------------------------------------------------------------
// Lifecycle
// -------------------------------------------------------------------------
@Override
public void start() throws LifecycleException {
super.start();
try {
initClients();
} catch (Exception e) {
throw new LifecycleException("ClientDualInflowControlManager init failed: " + e.getMessage());
}
}
// -------------------------------------------------------------------------
// 초기화 / 리로드
// -------------------------------------------------------------------------
private void initClients() throws Exception {
this.clientBucketMap = loadBucketMap(InflowType.CLIENT);
if (logger.isInfo()) logger.info("ClientDualInflowControlManager] initClients: " + clientBucketMap.size() + " buckets");
}
public synchronized void reloadClient() throws Exception {
initClients();
clientMetricsMap.clear();
}
public synchronized void reloadClient(String clientId) throws Exception {
reloadBucketMap(clientBucketMap, InflowType.CLIENT, clientId);
TargetMetrics m = clientMetricsMap.get(clientId);
if (m != null) m.reset();
}
public synchronized void removeClient(String clientId) {
clientBucketMap.remove(clientId);
clientMetricsMap.remove(clientId);
}
// -------------------------------------------------------------------------
// 클라이언트 메트릭 접근자
// -------------------------------------------------------------------------
public TargetMetrics getClientMetrics(String clientId) { return clientMetricsMap.get(clientId); }
public Map<String, TargetMetrics> getAllClientMetrics() { return Collections.unmodifiableMap(clientMetricsMap); }
public void resetClientMetrics(String clientId) { TargetMetrics m = clientMetricsMap.get(clientId); if (m != null) m.reset(); }
public void resetAllClientMetrics() { clientMetricsMap.values().forEach(TargetMetrics::reset); }
// -------------------------------------------------------------------------
// ClientDualBucket 클라이언트 유량제어
// -------------------------------------------------------------------------
@Override
public String isClientPassDetail(String clientId) {
DualCustomBucket b = clientBucketMap.get(clientId);
if (b == null) return DualCustomBucket.RESULT_PASS;
String result = b.tryConsume();
recordMetrics(clientMetricsMap, clientId, result);
return result;
}
@Override
public InflowTargetVO getClientInflowThreshold(String clientId) {
DualCustomBucket b = clientBucketMap.get(clientId);
return (b == null) ? null : b.getInflowTargetVo();
}
// -------------------------------------------------------------------------
// 모니터링용 접근자
// -------------------------------------------------------------------------
public DualCustomBucket getClientBucket(String clientId) {
return clientBucketMap.get(clientId);
}
public Map<String, DualCustomBucket> getClientBucketMap() {
return clientBucketMap;
}
}
@@ -1,13 +1,13 @@
package com.eactive.eai.common.inflow.dual;
import com.eactive.eai.common.inflow.Bucket;
import com.eactive.eai.common.inflow.InflowTargetVO;
/**
* Bucket 인터페이스 확장.
* 기존 isAdapterPass/isInterfacePass(boolean) 더해
* 어느 버킷(PER_SECOND/THRESHOLD)에서 차단됐는지 반환하는 메서드 추가.
* 클라이언트별 유량제어 메서드도 포함.
*
* <p>클라이언트 유량제어는 {@link ClientDualBucket}으로 분리됨.
*/
public interface DualBucket extends Bucket {
@@ -22,16 +22,4 @@ public interface DualBucket extends Bucket {
* @return null이면 통과, "PER_SECOND" 또는 "THRESHOLD"이면 해당 버킷에서 차단
*/
String isInterfacePassDetail(String inter);
/**
* 클라이언트 유량제어 체크 차단 원인 포함.
* @return null이면 통과, "PER_SECOND" 또는 "THRESHOLD"이면 해당 버킷에서 차단
*/
String isClientPassDetail(String clientId);
/**
* 클라이언트 유량제어 설정 조회 에러 메시지 생성용.
* @return 등록된 설정이 없으면 null
*/
InflowTargetVO getClientInflowThreshold(String clientId);
}
@@ -1,47 +1,38 @@
package com.eactive.eai.common.inflow.dual;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.eactive.eai.common.inflow.AbstractInflowControlManager;
import com.eactive.eai.common.inflow.Bucket;
import com.eactive.eai.common.inflow.CustomGroupBucket;
import com.eactive.eai.common.inflow.InflowControlDAO;
import com.eactive.eai.common.inflow.InflowControlManager;
import com.eactive.eai.common.inflow.InflowTargetVO;
import com.eactive.eai.common.inflow.InflowType;
import com.eactive.eai.common.lifecycle.LifecycleException;
import com.eactive.eai.common.message.EAIMessage;
import com.eactive.eai.common.server.EAIServerManager;
import com.eactive.eai.common.util.ApplicationContextProvider;
import com.eactive.eai.common.util.Logger;
import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Bucket4j;
import io.github.bucket4j.Refill;
import io.github.bucket4j.local.LocalBucket;
/**
* 어댑터/인터페이스/클라이언트 버킷을 이중 구조(perSecond + threshold) 관리하는 유량제어 관리자.
* 어댑터/인터페이스 버킷을 이중 구조(perSecond + threshold) 관리하는 유량제어 관리자.
*
* <p>기존 InflowControlManager는 어댑터/인터페이스에 단일 LocalBucket(복수 Bandwidth) 사용하여
* 차단 어느 한도(초당/기간) 초과했는지 없었다.
* 클래스는 그룹 버킷(CustomGroupBucket) 동일하게 버킷을 분리하고
* {@link DualBucket#isAdapterPassDetail}/{@link DualBucket#isInterfacePassDetail}
* 차단 원인을 반환한다. 그룹 버킷 통과 여부는 {@link TargetMetrics} 카운팅된다.
* <p>클라이언트 유량제어는 {@link ClientDualInflowControlManager} 분리됨.
*
* <p>적용 방법: INFLOW.properties에 아래 추가.
* <pre>inflow.control.bucket.className=com.eactive.eai.common.inflow.dual.DualInflowControlManager</pre>
* <pre>inflow.control.bucket.className=com.eactive.eai.common.inflow.dual.ClientDualInflowControlManager</pre>
*/
@Component
public class DualInflowControlManager extends InflowControlManager implements DualBucket {
public class DualInflowControlManager extends AbstractInflowControlManager implements DualBucket {
private static final Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
@@ -50,17 +41,11 @@ public class DualInflowControlManager extends InflowControlManager implements Du
return ApplicationContextProvider.getContext().getBean(DualInflowControlManager.class);
}
public static Boolean isTargetOfInflowControl(EAIServerManager eaiServerManager, EAIMessage eaiMessage) {
return InflowControlManager.isTargetOfInflowControl(eaiServerManager, eaiMessage);
}
@Autowired
private InflowControlDAO dualDao;
private volatile Map<String, DualCustomBucket> adapterBucketMap = new ConcurrentHashMap<>();
private volatile Map<String, DualCustomBucket> interfaceBucketMap = new ConcurrentHashMap<>();
private volatile Map<String, DualCustomBucket> clientBucketMap = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, TargetMetrics> adapterMetricsMap = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, TargetMetrics> interfaceMetricsMap = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, TargetMetrics> groupMetricsMap = new ConcurrentHashMap<>();
public static class TargetMetrics {
@@ -87,7 +72,6 @@ public class DualInflowControlManager extends InflowControlManager implements Du
try {
initAdapters();
initInterfaces();
initClients();
} catch (Exception e) {
throw new LifecycleException("DualInflowControlManager init failed: " + e.getMessage());
}
@@ -107,14 +91,9 @@ public class DualInflowControlManager extends InflowControlManager implements Du
if (logger.isInfo()) logger.info("DualInflowControlManager] initInterfaces: " + interfaceBucketMap.size() + " buckets");
}
private void initClients() throws Exception {
this.clientBucketMap = loadBucketMap(InflowType.CLIENT);
if (logger.isInfo()) logger.info("DualInflowControlManager] initClients: " + clientBucketMap.size() + " buckets");
}
private Map<String, DualCustomBucket> loadBucketMap(InflowType type) throws Exception {
protected Map<String, DualCustomBucket> loadBucketMap(InflowType type) throws Exception {
Map<String, DualCustomBucket> newMap = new HashMap<>();
for (InflowTargetVO vo : dualDao.getInflowList(type)) {
for (InflowTargetVO vo : inflowControlDAO.getInflowList(type)) {
DualCustomBucket bucket = makeBucket(vo);
if (bucket != null) newMap.put(vo.getName(), bucket);
}
@@ -123,34 +102,28 @@ public class DualInflowControlManager extends InflowControlManager implements Du
@Override
public synchronized void reloadAdapter() throws Exception {
super.reloadAdapter();
initAdapters();
adapterMetricsMap.clear();
}
@Override
public synchronized void reloadAdapter(String adapter) throws Exception {
super.reloadAdapter(adapter);
reloadBucketMap(adapterBucketMap, InflowType.ADAPTER, adapter);
TargetMetrics m = adapterMetricsMap.get(adapter);
if (m != null) m.reset();
}
@Override
public synchronized void reloadInterface() throws Exception {
super.reloadInterface();
initInterfaces();
interfaceMetricsMap.clear();
}
@Override
public synchronized void reloadInterface(String inter) throws Exception {
super.reloadInterface(inter);
reloadBucketMap(interfaceBucketMap, InflowType.INTERFACE, inter);
}
public synchronized void reloadClient() throws Exception {
initClients();
}
public synchronized void reloadClient(String clientId) throws Exception {
reloadBucketMap(clientBucketMap, InflowType.CLIENT, clientId);
TargetMetrics m = interfaceMetricsMap.get(inter);
if (m != null) m.reset();
}
@Override
@@ -166,8 +139,8 @@ public class DualInflowControlManager extends InflowControlManager implements Du
if (m != null) m.reset();
}
private void reloadBucketMap(Map<String, DualCustomBucket> targetMap, InflowType type, String name) throws Exception {
Map<String, InflowTargetVO> updated = dualDao.getInflowMap(type, name);
protected void reloadBucketMap(Map<String, DualCustomBucket> targetMap, InflowType type, String name) throws Exception {
Map<String, InflowTargetVO> updated = inflowControlDAO.getInflowMap(type, name);
if (updated == null) return;
for (InflowTargetVO vo : updated.values()) {
DualCustomBucket bucket = makeBucket(vo);
@@ -176,6 +149,22 @@ public class DualInflowControlManager extends InflowControlManager implements Du
}
}
// -------------------------------------------------------------------------
// 어댑터/인터페이스 메트릭 접근자
// -------------------------------------------------------------------------
public TargetMetrics getAdapterMetrics(String adapter) { return adapterMetricsMap.get(adapter); }
public TargetMetrics getInterfaceMetrics(String inter) { return interfaceMetricsMap.get(inter); }
public Map<String, TargetMetrics> getAllAdapterMetrics() { return Collections.unmodifiableMap(adapterMetricsMap); }
public Map<String, TargetMetrics> getAllInterfaceMetrics() { return Collections.unmodifiableMap(interfaceMetricsMap); }
public void resetAdapterMetrics(String adapter) { TargetMetrics m = adapterMetricsMap.get(adapter); if (m != null) m.reset(); }
public void resetInterfaceMetrics(String inter) { TargetMetrics m = interfaceMetricsMap.get(inter); if (m != null) m.reset(); }
public void resetAllAdapterMetrics() { adapterMetricsMap.values().forEach(TargetMetrics::reset); }
public void resetAllInterfaceMetrics() { interfaceMetricsMap.values().forEach(TargetMetrics::reset); }
// -------------------------------------------------------------------------
// 그룹 메트릭 isGroupPass() 카운팅 접근자
// -------------------------------------------------------------------------
@@ -218,31 +207,30 @@ public class DualInflowControlManager extends InflowControlManager implements Du
@Override
public String isAdapterPassDetail(String adapter) {
DualCustomBucket b = adapterBucketMap.get(adapter);
return (b == null) ? DualCustomBucket.RESULT_PASS : b.tryConsume();
if (b == null) return DualCustomBucket.RESULT_PASS;
String result = b.tryConsume();
recordMetrics(adapterMetricsMap, adapter, result);
return result;
}
@Override
public String isInterfacePassDetail(String inter) {
DualCustomBucket b = interfaceBucketMap.get(inter);
return (b == null) ? DualCustomBucket.RESULT_PASS : b.tryConsume();
if (b == null) return DualCustomBucket.RESULT_PASS;
String result = b.tryConsume();
recordMetrics(interfaceMetricsMap, inter, result);
return result;
}
@Override
public String isClientPassDetail(String clientId) {
DualCustomBucket b = clientBucketMap.get(clientId);
return (b == null) ? DualCustomBucket.RESULT_PASS : b.tryConsume();
}
@Override
public InflowTargetVO getClientInflowThreshold(String clientId) {
DualCustomBucket b = clientBucketMap.get(clientId);
return (b == null) ? null : b.getInflowTargetVo();
protected void recordMetrics(ConcurrentHashMap<String, TargetMetrics> metricsMap, String key, String result) {
TargetMetrics m = metricsMap.computeIfAbsent(key, k -> new TargetMetrics());
if (result == null) m.allowed.incrementAndGet();
else if (DualCustomBucket.RESULT_BLOCKED_PER_SECOND.equals(result)) m.rejectedPerSecond.incrementAndGet();
else m.rejectedThreshold.incrementAndGet();
}
// -------------------------------------------------------------------------
// Bucket 인터페이스 오버라이드 이중 버킷으로 교체 (boolean 반환 유지)
// isAdapterPassDetail/isInterfacePassDetail이 토큰을 소비하므로
// 메서드를 동일 요청에서 중복 호출하면 토큰이 이중 소비됨에 주의.
// -------------------------------------------------------------------------
@Override
@@ -255,6 +243,48 @@ public class DualInflowControlManager extends InflowControlManager implements Du
return isInterfacePassDetail(inter) == DualCustomBucket.RESULT_PASS;
}
// -------------------------------------------------------------------------
// 어댑터/인터페이스 ·VO·삭제 Dual 기준으로 오버라이드
// -------------------------------------------------------------------------
@Override
public String[] getAdapterAllKeys() {
String[] keys = adapterBucketMap.keySet().toArray(new String[0]);
Arrays.sort(keys);
return keys;
}
@Override
public String[] getInterfaceAllKeys() {
String[] keys = interfaceBucketMap.keySet().toArray(new String[0]);
Arrays.sort(keys);
return keys;
}
@Override
public InflowTargetVO getAdapterInflowThreashold(String adapter) {
DualCustomBucket b = adapterBucketMap.get(adapter);
return (b == null) ? null : b.getInflowTargetVo();
}
@Override
public InflowTargetVO getInterfaceInflowThreashold(String inter) {
DualCustomBucket b = interfaceBucketMap.get(inter);
return (b == null) ? null : b.getInflowTargetVo();
}
@Override
public synchronized void removeAdapter(String adapter) {
adapterBucketMap.remove(adapter);
adapterMetricsMap.remove(adapter);
}
@Override
public synchronized void removeInterface(String inter) {
interfaceBucketMap.remove(inter);
interfaceMetricsMap.remove(inter);
}
// -------------------------------------------------------------------------
// 모니터링용 접근자
// -------------------------------------------------------------------------
@@ -275,20 +305,17 @@ public class DualInflowControlManager extends InflowControlManager implements Du
return interfaceBucketMap;
}
public DualCustomBucket getClientBucket(String clientId) {
return clientBucketMap.get(clientId);
}
public Map<String, DualCustomBucket> getClientBucketMap() {
return clientBucketMap;
}
// -------------------------------------------------------------------------
// 버킷 팩토리
// -------------------------------------------------------------------------
private DualCustomBucket makeBucket(InflowTargetVO vo) {
if (!InflowControlManager.isInflowTarget(vo)) {
/**
* perSecond 버킷: greedy refill 초당 N개 요청을 균등하게 허용.
* threshold 버킷: intervally refill 기간(// ) 단위 쿼터를 기간 시작 일괄 충전.
* Bandwidth.simple은 버킷 모두 greedy로 생성되어 시간 단위 구분이 없어지므로 classic으로 교체.
*/
protected DualCustomBucket makeBucket(InflowTargetVO vo) {
if (!AbstractInflowControlManager.isInflowTarget(vo)) {
return null;
}
@@ -297,14 +324,16 @@ public class DualInflowControlManager extends InflowControlManager implements Du
if (vo.getThresholdPerSecond() > 0) {
perSecondBucket = Bucket4j.builder()
.addLimit(Bandwidth.simple(vo.getThresholdPerSecond(), Duration.ofSeconds(1)))
.addLimit(Bandwidth.classic(vo.getThresholdPerSecond(),
Refill.greedy(vo.getThresholdPerSecond(), Duration.ofSeconds(1))))
.build();
}
if (vo.getThreshold() > 0 && StringUtils.isNotBlank(vo.getThresholdTimeUnit())) {
Duration period = AbstractInflowControlManager.getPeriod(vo.getThresholdTimeUnit());
thresholdBucket = Bucket4j.builder()
.addLimit(Bandwidth.simple(vo.getThreshold(),
InflowControlManager.getPeriod(vo.getThresholdTimeUnit())))
.addLimit(Bandwidth.classic(vo.getThreshold(),
Refill.intervally(vo.getThreshold(), period)))
.build();
}
@@ -0,0 +1,173 @@
package com.eactive.eai.common.security;
import java.nio.ByteBuffer;
import java.security.Key;
import java.security.SecureRandom;
import java.security.Security;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jcajce.spec.FPEParameterSpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class AESCryptoModuleExtension implements CryptoModuleExtension {
private static final int GCM_IV_LENGTH = 12;
private static final int GCM_TAG_LENGTH = 128;
private static final String DEFAULT_PROVIDER = "BC";
private Cipher encryptEngine;
private Cipher decryptEngine;
private String mode;
private String pad;
private byte[] iv;
private byte[] encKey;
private byte[] decKey;
/** 명시적 프로바이더. null이면 모든 모드에서 BC(DEFAULT_PROVIDER)를 사용한다. */
private String provider;
// ------------------------------------------------------------------
// init 모든 오버로드는 최종적으로 6+provider 버전에 위임한다
// ------------------------------------------------------------------
@Override
public void init(String alg, String mode, String pad, byte[] encKey, byte[] decKey) throws Exception {
init(alg, mode, pad, null, encKey, decKey, null);
}
@Override
public void init(String alg, String mode, String pad, byte[] iv, byte[] encKey, byte[] decKey) throws Exception {
init(alg, mode, pad, iv, encKey, decKey, null);
}
@Override
public void init(String alg, String mode, String pad, byte[] encKey, byte[] decKey, String provider) throws Exception {
init(alg, mode, pad, null, encKey, decKey, provider);
}
@Override
public void init(String alg, String mode, String pad, byte[] iv, byte[] encKey, byte[] decKey, String provider) throws Exception {
this.mode = mode;
this.pad = pad;
this.iv = iv;
this.encKey = encKey;
this.decKey = decKey;
this.provider = (provider != null && !provider.isEmpty()) ? provider : null;
// GCM 포함 모든 모드에서 BC 프로바이더를 사용 기본값 BC
if (Security.getProvider("BC") == null) {
Security.addProvider(new BouncyCastleProvider());
}
if (!mode.equalsIgnoreCase("GCM")) {
String m = mode != null ? mode : "";
String p = pad != null ? pad : "";
String transformation = String.format("AES/%s/%s", m, p);
Key encKeySpec = new SecretKeySpec(encKey, "AES");
Key decKeySpec = new SecretKeySpec(decKey, "AES");
AlgorithmParameterSpec param = iv != null ? new IvParameterSpec(iv) : null;
if (m.toLowerCase().contains("ff")) {
param = new FPEParameterSpec(256, iv);
}
String prov = this.provider != null ? this.provider : DEFAULT_PROVIDER;
this.encryptEngine = Cipher.getInstance(transformation, prov);
this.decryptEngine = Cipher.getInstance(transformation, prov);
this.encryptEngine.init(Cipher.ENCRYPT_MODE, encKeySpec, param, (SecureRandom) null);
this.decryptEngine.init(Cipher.DECRYPT_MODE, decKeySpec, param, (SecureRandom) null);
}
}
// ------------------------------------------------------------------
// encrypt
// ------------------------------------------------------------------
@Override
public int encrypt(byte[] src, int sindex, int slength, byte[] dst, int dindex) throws Exception {
return this.encryptEngine.doFinal(src, sindex, slength, dst, dindex);
}
@Override
public byte[] encrypt(byte[] src, int sindex, int slength) throws Exception {
return encrypt(src, sindex, slength, null);
}
/**
* AAD를 명시한 암호화.
* GCM 모드에서 aad != null 이면 해당 값을 사용하고, null 이면 iv를 AAD로 사용하는 기본 동작을 따른다.
* -GCM 모드는 AAD를 무시하고 사전 초기화된 엔진으로 처리한다.
*/
@Override
public byte[] encrypt(byte[] src, int sindex, int slength, byte[] aad) throws Exception {
if (this.mode.equalsIgnoreCase("GCM")) {
Key key = new SecretKeySpec(this.encKey, "AES");
byte[] nonce = new byte[GCM_IV_LENGTH];
new SecureRandom().nextBytes(nonce);
GCMParameterSpec gcmSpec = new GCMParameterSpec(GCM_TAG_LENGTH, nonce);
String prov = this.provider != null ? this.provider : DEFAULT_PROVIDER;
Cipher cipher = Cipher.getInstance(String.format("AES/%s/%s", this.mode, this.pad), prov);
cipher.init(Cipher.ENCRYPT_MODE, key, gcmSpec);
byte[] effectiveAad = aad != null ? aad : this.iv;
if (effectiveAad != null) cipher.updateAAD(effectiveAad);
byte[] cipherTextWithTag = cipher.doFinal(src, sindex, slength);
byte[] output = new byte[GCM_IV_LENGTH + cipherTextWithTag.length];
System.arraycopy(nonce, 0, output, 0, GCM_IV_LENGTH);
System.arraycopy(cipherTextWithTag, 0, output, GCM_IV_LENGTH, cipherTextWithTag.length);
return output;
}
int outLen = this.encryptEngine.getOutputSize(slength);
byte[] dst = new byte[outLen];
int actual = encrypt(src, sindex, slength, dst, 0);
return ByteBuffer.allocate(actual).put(dst, 0, actual).array();
}
// ------------------------------------------------------------------
// decrypt
// ------------------------------------------------------------------
@Override
public int decrypt(byte[] src, int sindex, int slength, byte[] dst, int dindex) throws Exception {
return this.decryptEngine.doFinal(src, sindex, slength, dst, dindex);
}
@Override
public byte[] decrypt(byte[] src, int sindex, int slength) throws Exception {
return decrypt(src, sindex, slength, null);
}
/**
* AAD를 명시한 복호화.
* GCM 모드에서 aad != null 이면 해당 값을 사용하고, null 이면 iv를 AAD로 사용하는 기본 동작을 따른다.
* -GCM 모드는 AAD를 무시하고 사전 초기화된 엔진으로 처리한다.
*/
@Override
public byte[] decrypt(byte[] src, int sindex, int slength, byte[] aad) throws Exception {
if (this.mode.equalsIgnoreCase("GCM")) {
Key key = new SecretKeySpec(this.decKey, "AES");
byte[] nonce = new byte[GCM_IV_LENGTH];
System.arraycopy(src, sindex, nonce, 0, GCM_IV_LENGTH);
byte[] cipherTextWithTag = new byte[slength - GCM_IV_LENGTH];
System.arraycopy(src, sindex + GCM_IV_LENGTH, cipherTextWithTag, 0, cipherTextWithTag.length);
GCMParameterSpec gcmSpec = new GCMParameterSpec(GCM_TAG_LENGTH, nonce);
String prov = this.provider != null ? this.provider : DEFAULT_PROVIDER;
Cipher cipher = Cipher.getInstance(String.format("AES/%s/%s", this.mode, this.pad), prov);
cipher.init(Cipher.DECRYPT_MODE, key, gcmSpec);
byte[] effectiveAad = aad != null ? aad : this.iv;
if (effectiveAad != null) cipher.updateAAD(effectiveAad);
return cipher.doFinal(cipherTextWithTag);
}
return this.decryptEngine.doFinal(src, sindex, slength);
}
}
@@ -0,0 +1,68 @@
package com.eactive.eai.common.security;
import java.nio.ByteBuffer;
import java.security.Key;
import java.security.SecureRandom;
import java.security.Security;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jcajce.spec.FPEParameterSpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class ARIACryptoModuleExtension implements CryptoModuleExtension {
private Cipher encryptEngine;
private Cipher decryptEngine;
@Override
public void init(String alg, String mode, String pad, byte[] encKey, byte[] decKey) throws Exception {
this.init("ARIA", mode, pad, (byte[]) null, encKey, decKey);
}
@Override
public void init(String alg, String mode, String pad, byte[] iv, byte[] encKey, byte[] decKey) throws Exception {
if (Security.getProvider("BC") == null) {
Security.addProvider(new BouncyCastleProvider());
}
String m = mode != null ? mode : "";
String p = pad != null ? pad : "";
Key encKeySpec = new SecretKeySpec(encKey, "ARIA");
Key decKeySpec = new SecretKeySpec(decKey, "ARIA");
AlgorithmParameterSpec param = iv != null ? new IvParameterSpec(iv) : null;
if (m.toLowerCase().contains("ff")) {
param = new FPEParameterSpec(256, iv);
}
this.encryptEngine = Cipher.getInstance(String.format("ARIA/%s/%s", m, p));
this.encryptEngine.init(Cipher.ENCRYPT_MODE, encKeySpec, param, (SecureRandom) null);
this.decryptEngine = Cipher.getInstance(String.format("ARIA/%s/%s", m, p));
this.decryptEngine.init(Cipher.DECRYPT_MODE, decKeySpec, param, (SecureRandom) null);
}
@Override
public int encrypt(byte[] src, int sindex, int slength, byte[] dst, int dindex) throws Exception {
return this.encryptEngine.doFinal(src, sindex, slength, dst, dindex);
}
@Override
public byte[] encrypt(byte[] src, int sindex, int slength) throws Exception {
int size = (slength + 17) / this.encryptEngine.getBlockSize() * this.encryptEngine.getBlockSize();
size += (slength + 17) % this.encryptEngine.getBlockSize() == 0 ? 0 : this.encryptEngine.getBlockSize();
byte[] dst = new byte[this.encryptEngine.getOutputSize(size)];
size = this.encrypt(src, sindex, slength, dst, 0);
return ByteBuffer.allocate(size).put(dst, 0, size).array();
}
@Override
public int decrypt(byte[] src, int sindex, int slength, byte[] dst, int dindex) throws Exception {
return this.decryptEngine.doFinal(src, sindex, slength, dst, dindex);
}
@Override
public byte[] decrypt(byte[] src, int sindex, int slength) throws Exception {
return this.decryptEngine.doFinal(src, sindex, slength);
}
}
@@ -0,0 +1,23 @@
package com.eactive.eai.common.security;
import lombok.Data;
@Data
public class CryptoModuleConfigVO {
String cryptoId;
String cryptoName;
String cryptoDesc;
String algType;
String cipherMode;
String padding;
String ivHex;
String keySourceType;
String encKeyHex;
String decKeyHex;
String keyDerivStrategy;
String keyDerivParams;
String cacheYn;
Integer cacheTtlSec;
String useYn;
}
@@ -0,0 +1,52 @@
package com.eactive.eai.common.security;
public interface CryptoModuleExtension {
void init(String alg, String mode, String pad, byte[] encKey, byte[] decKey) throws Exception;
void init(String alg, String mode, String pad, byte[] iv, byte[] encKey, byte[] decKey) throws Exception;
/** 프로바이더를 명시한 초기화. 미지원 구현체는 provider를 무시하고 기본 동작한다. */
default void init(String alg, String mode, String pad, byte[] encKey, byte[] decKey, String provider) throws Exception {
init(alg, mode, pad, encKey, decKey);
}
/** 프로바이더를 명시한 초기화 (IV 포함). 미지원 구현체는 provider를 무시하고 기본 동작한다. */
default void init(String alg, String mode, String pad, byte[] iv, byte[] encKey, byte[] decKey, String provider) throws Exception {
init(alg, mode, pad, iv, encKey, decKey);
}
int encrypt(byte[] src, int sindex, int slength, byte[] dst, int dindex) throws Exception;
byte[] encrypt(byte[] src, int sindex, int slength) throws Exception;
/** AAD를 명시한 암호화. null이면 구현체 기본 동작(IV를 AAD로 사용하거나 AAD 없음)을 따른다. */
default byte[] encrypt(byte[] src, int sindex, int slength, byte[] aad) throws Exception {
return encrypt(src, sindex, slength);
}
default byte[] encrypt(byte[] src) throws Exception {
return encrypt(src, 0, src.length);
}
default byte[] encrypt(byte[] src, byte[] aad) throws Exception {
return encrypt(src, 0, src.length, aad);
}
int decrypt(byte[] src, int sindex, int slength, byte[] dst, int dindex) throws Exception;
byte[] decrypt(byte[] src, int sindex, int slength) throws Exception;
/** AAD를 명시한 복호화. null이면 구현체 기본 동작을 따른다. */
default byte[] decrypt(byte[] src, int sindex, int slength, byte[] aad) throws Exception {
return decrypt(src, sindex, slength);
}
default byte[] decrypt(byte[] src) throws Exception {
return decrypt(src, 0, src.length);
}
default byte[] decrypt(byte[] src, byte[] aad) throws Exception {
return decrypt(src, 0, src.length, aad);
}
}
@@ -0,0 +1,244 @@
package com.eactive.eai.common.security;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.xml.bind.DatatypeConverter;
import org.springframework.stereotype.Component;
import com.eactive.eai.common.lifecycle.Lifecycle;
import com.eactive.eai.common.lifecycle.LifecycleException;
import com.eactive.eai.common.lifecycle.LifecycleListener;
import com.eactive.eai.common.lifecycle.LifecycleSupport;
import com.eactive.eai.common.security.keyderiv.DerivedKey;
import com.eactive.eai.common.security.keyderiv.KeyDerivationStrategy;
import com.eactive.eai.common.security.loader.CryptoModuleConfigLoader;
import com.eactive.eai.common.security.mapper.CryptoModuleConfigMapper;
import com.eactive.eai.common.util.ApplicationContextProvider;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.data.entity.onl.security.CryptoModuleConfig;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
@Component
public class CryptoModuleManager implements Lifecycle {
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
private static final ObjectMapper objectMapper = new ObjectMapper();
private final ConcurrentHashMap<String, CryptoModuleConfigVO> configMap = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, KeyDerivationStrategy> strategyCache = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, CachedDerivedKey> dynamicKeyCache = new ConcurrentHashMap<>();
private boolean started;
private final LifecycleSupport lifecycle = new LifecycleSupport(this);
private CryptoModuleManager() {}
public static CryptoModuleManager getInstance() {
return ApplicationContextProvider.getContext().getBean(CryptoModuleManager.class);
}
@Override
public void start() throws LifecycleException {
if (started) throw new LifecycleException("RECEAICRY001");
lifecycle.fireLifecycleEvent(STARTING_EVENT, this);
try {
loadAll();
} catch (Exception e) {
throw new LifecycleException("RECEAICRY002");
}
started = true;
lifecycle.fireLifecycleEvent(STARTED_EVENT, this);
}
@Override
public void stop() throws LifecycleException {
if (!started) throw new LifecycleException("RECEAICRY003");
lifecycle.fireLifecycleEvent(STOPING_EVENT, this);
configMap.clear();
dynamicKeyCache.clear();
strategyCache.clear();
started = false;
lifecycle.fireLifecycleEvent(STOPPED_EVENT, this);
}
private void loadAll() {
CryptoModuleConfigLoader loader = ctx().getBean(CryptoModuleConfigLoader.class);
CryptoModuleConfigMapper mapper = ctx().getBean(CryptoModuleConfigMapper.class);
List<CryptoModuleConfig> all = loader.findAll();
configMap.clear();
for (CryptoModuleConfig entity : all) {
if ("Y".equalsIgnoreCase(entity.getUseYn())) {
CryptoModuleConfigVO vo = mapper.toVo(entity);
configMap.put(vo.getCryptoName(), vo);
}
}
logger.warn("CryptoModuleManager] 암호화모듈 로드 완료. 건수=" + configMap.size());
}
public void reload(String cryptoId) {
CryptoModuleConfigLoader loader = ctx().getBean(CryptoModuleConfigLoader.class);
CryptoModuleConfigMapper mapper = ctx().getBean(CryptoModuleConfigMapper.class);
configMap.values().removeIf(vo -> cryptoId.equals(vo.getCryptoId()));
evictDynamicCache(cryptoId);
loader.findById(cryptoId).ifPresent(entity -> {
if ("Y".equalsIgnoreCase(entity.getUseYn())) {
CryptoModuleConfigVO vo = mapper.toVo(entity);
configMap.put(vo.getCryptoName(), vo);
logger.warn("CryptoModuleManager] 재로드 완료: " + vo.getCryptoName());
}
});
}
/**
* STATIC 방식 초기화된 CryptoModuleExtension 반환.
* Cipher는 thread-safe하지 않으므로 호출마다 인스턴스를 생성한다.
*/
public CryptoModuleExtension createExtension(String cryptoName) throws Exception {
CryptoModuleConfigVO vo = getVO(cryptoName);
byte[] encKey = DatatypeConverter.parseHexBinary(vo.getEncKeyHex());
byte[] decKey = vo.getDecKeyHex() != null
? DatatypeConverter.parseHexBinary(vo.getDecKeyHex())
: encKey;
byte[] iv = vo.getIvHex() != null ? DatatypeConverter.parseHexBinary(vo.getIvHex()) : null;
return buildExtension(vo, iv, encKey, decKey);
}
/**
* DYNAMIC 방식 전략으로 키를 도출하고 캐시를 적용한 CryptoModuleExtension 반환.
*/
public CryptoModuleExtension createExtension(String cryptoName, Map<String, String> runtimeContext)
throws Exception {
CryptoModuleConfigVO vo = getVO(cryptoName);
if ("STATIC".equalsIgnoreCase(vo.getKeySourceType())) {
return createExtension(cryptoName);
}
KeyDerivationStrategy strategy = resolveStrategy(vo.getKeyDerivStrategy());
Map<String, String> params = parseParams(vo.getKeyDerivParams());
String cacheKey = strategy.buildCacheKey(cryptoName, params, runtimeContext);
DerivedKey derivedKey = null;
if ("Y".equalsIgnoreCase(vo.getCacheYn())) {
CachedDerivedKey cached = dynamicKeyCache.get(cacheKey);
if (cached != null && !cached.isExpired()) {
derivedKey = cached.getDerivedKey();
}
}
if (derivedKey == null) {
derivedKey = strategy.deriveKey(params, runtimeContext);
if ("Y".equalsIgnoreCase(vo.getCacheYn())) {
int ttl = vo.getCacheTtlSec() != null ? vo.getCacheTtlSec() : 300;
dynamicKeyCache.put(cacheKey, new CachedDerivedKey(derivedKey, ttl));
}
}
byte[] iv = vo.getIvHex() != null ? DatatypeConverter.parseHexBinary(vo.getIvHex()) : null;
return buildExtension(vo, iv, derivedKey.getEncKey(), derivedKey.getDecKey());
}
private CryptoModuleConfigVO getVO(String cryptoName) {
CryptoModuleConfigVO vo = configMap.get(cryptoName);
if (vo == null) {
throw new IllegalArgumentException("암호화모듈 미등록: " + cryptoName);
}
return vo;
}
private CryptoModuleExtension buildExtension(CryptoModuleConfigVO vo, byte[] iv,
byte[] encKey, byte[] decKey) throws Exception {
CryptoModuleExtension ext = "ARIA".equalsIgnoreCase(vo.getAlgType())
? new ARIACryptoModuleExtension()
: new AESCryptoModuleExtension();
ext.init(vo.getAlgType(), vo.getCipherMode(), vo.getPadding(), iv, encKey, decKey);
return ext;
}
/**
* DB key_deriv_strategy 컬럼에 저장된 FQCN으로 전략 클래스를 로드한다.
* 로드된 인스턴스는 strategyCache에 보관하여 재사용한다.
*/
private KeyDerivationStrategy resolveStrategy(String fqcn) {
return strategyCache.computeIfAbsent(fqcn, key -> {
try {
Class<?> clazz = Class.forName(key);
return (KeyDerivationStrategy) clazz.getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new IllegalArgumentException("전략 클래스 로드 실패: " + key, e);
}
});
}
private Map<String, String> parseParams(String json) throws Exception {
if (json == null || json.trim().isEmpty()) {
return new HashMap<>();
}
return objectMapper.readValue(json, new TypeReference<Map<String, String>>() {});
}
private void evictDynamicCache(String cryptoId) {
configMap.values().stream()
.filter(vo -> cryptoId.equals(vo.getCryptoId()))
.map(CryptoModuleConfigVO::getCryptoName)
.forEach(name -> {
Iterator<String> it = dynamicKeyCache.keySet().iterator();
while (it.hasNext()) {
if (it.next().startsWith(name + ":")) it.remove();
}
});
}
private org.springframework.context.ApplicationContext ctx() {
return ApplicationContextProvider.getContext();
}
@Override
public void addLifecycleListener(LifecycleListener listener) {
lifecycle.addLifecycleListener(listener);
}
@Override
public LifecycleListener[] findLifecycleListeners() {
return lifecycle.findLifecycleListeners();
}
@Override
public void removeLifecycleListener(LifecycleListener listener) {
lifecycle.removeLifecycleListener(listener);
}
@Override
public boolean isStarted() {
return started;
}
private static class CachedDerivedKey {
private final DerivedKey derivedKey;
private final long expireAt;
CachedDerivedKey(DerivedKey derivedKey, int ttlSec) {
this.derivedKey = derivedKey;
this.expireAt = System.currentTimeMillis() + (ttlSec * 1000L);
}
boolean isExpired() {
return System.currentTimeMillis() > expireAt;
}
DerivedKey getDerivedKey() {
return derivedKey;
}
}
}
@@ -0,0 +1,77 @@
package com.eactive.eai.common.security;
import java.util.Map;
import org.springframework.stereotype.Service;
import com.eactive.eai.common.util.ApplicationContextProvider;
/**
* 어댑터 필터 등에서 암복호화를 위임하는 진입점.
*
* STATIC 방식:
* service.encrypt("MODULE_NAME", plainBytes);
*
* DYNAMIC 방식 (런타임 컨텍스트 전달):
* Map<String,String> ctx = Map.of("X-Api-Enc-Key", request.getHeader("X-Api-Enc-Key"));
* service.encrypt("MODULE_NAME", ctx, plainBytes);
*
* AAD 명시 방식 (GCM 인증 데이터 전달):
* byte[] aad = request.getHeader("X-Api-Request-Id").getBytes(StandardCharsets.UTF_8);
* service.encrypt("MODULE_NAME", ctx, aad, plainBytes);
*/
@Service
public class CryptoModuleService {
public static CryptoModuleService getInstance() {
return ApplicationContextProvider.getContext().getBean(CryptoModuleService.class);
}
// ------------------------------------------------------------------
// STATIC
// ------------------------------------------------------------------
public byte[] encrypt(String cryptoName, byte[] plainBytes) throws Exception {
CryptoModuleExtension ext = CryptoModuleManager.getInstance().createExtension(cryptoName);
return ext.encrypt(plainBytes, 0, plainBytes.length);
}
public byte[] encrypt(String cryptoName, byte[] aad, byte[] plainBytes) throws Exception {
CryptoModuleExtension ext = CryptoModuleManager.getInstance().createExtension(cryptoName);
return ext.encrypt(plainBytes, 0, plainBytes.length, aad);
}
public byte[] decrypt(String cryptoName, byte[] cipherBytes) throws Exception {
CryptoModuleExtension ext = CryptoModuleManager.getInstance().createExtension(cryptoName);
return ext.decrypt(cipherBytes, 0, cipherBytes.length);
}
public byte[] decrypt(String cryptoName, byte[] aad, byte[] cipherBytes) throws Exception {
CryptoModuleExtension ext = CryptoModuleManager.getInstance().createExtension(cryptoName);
return ext.decrypt(cipherBytes, 0, cipherBytes.length, aad);
}
// ------------------------------------------------------------------
// DYNAMIC
// ------------------------------------------------------------------
public byte[] encrypt(String cryptoName, Map<String, String> runtimeContext, byte[] plainBytes) throws Exception {
CryptoModuleExtension ext = CryptoModuleManager.getInstance().createExtension(cryptoName, runtimeContext);
return ext.encrypt(plainBytes, 0, plainBytes.length);
}
public byte[] encrypt(String cryptoName, Map<String, String> runtimeContext, byte[] aad, byte[] plainBytes) throws Exception {
CryptoModuleExtension ext = CryptoModuleManager.getInstance().createExtension(cryptoName, runtimeContext);
return ext.encrypt(plainBytes, 0, plainBytes.length, aad);
}
public byte[] decrypt(String cryptoName, Map<String, String> runtimeContext, byte[] cipherBytes) throws Exception {
CryptoModuleExtension ext = CryptoModuleManager.getInstance().createExtension(cryptoName, runtimeContext);
return ext.decrypt(cipherBytes, 0, cipherBytes.length);
}
public byte[] decrypt(String cryptoName, Map<String, String> runtimeContext, byte[] aad, byte[] cipherBytes) throws Exception {
CryptoModuleExtension ext = CryptoModuleManager.getInstance().createExtension(cryptoName, runtimeContext);
return ext.decrypt(cipherBytes, 0, cipherBytes.length, aad);
}
}
@@ -0,0 +1,20 @@
package com.eactive.eai.common.security.keyderiv;
public class DerivedKey {
private final byte[] encKey;
private final byte[] decKey;
public DerivedKey(byte[] encKey, byte[] decKey) {
this.encKey = encKey;
this.decKey = decKey != null ? decKey : encKey;
}
public byte[] getEncKey() {
return encKey;
}
public byte[] getDecKey() {
return decKey;
}
}
@@ -0,0 +1,23 @@
package com.eactive.eai.common.security.keyderiv;
import java.util.Map;
public interface KeyDerivationStrategy {
/**
* 키를 도출한다.
*
* @param params DB의 key_deriv_params (JSON 파싱된 Map)
* @param runtimeContext 런타임 컨텍스트 (HTTP 헤더, 거래 정보 호출자가 채워서 전달)
*/
DerivedKey deriveKey(Map<String, String> params, Map<String, String> runtimeContext) throws Exception;
/**
* 캐시 키를 생성한다. 전략마다 어떤 runtimeContext 값이 키를 결정하는지 다르다.
*
* @param cryptoName 암호화모듈 이름
* @param params DB의 key_deriv_params
* @param runtimeContext 런타임 컨텍스트
*/
String buildCacheKey(String cryptoName, Map<String, String> params, Map<String, String> runtimeContext);
}
@@ -0,0 +1,80 @@
package com.eactive.eai.common.security.keyderiv.strategy;
import java.util.Arrays;
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 마스터키 + 런타임 컨텍스트값 XOR 조합으로 키를 도출하는 전략.
*
* key_deriv_params (JSON) 예시:
* {
* "hsmKeyAlias" : "MASTER_KEY_AES",
* "contextKey" : "X-Api-Enc-Key", -- runtimeContext에서 꺼낼 이름
* "offset" : "0", -- contextKey 사용할 시작 위치 (byte)
* "length" : "16" -- contextKey 사용할 길이 (byte)
* }
*/
public class HsmContextXorKeyDerivationStrategy implements KeyDerivationStrategy {
/** DB key_deriv_strategy 컬럼에 사용하는 FQCN 참조용 상수. */
public static final String STRATEGY_CLASS = HsmContextXorKeyDerivationStrategy.class.getName();
private static final String PARAM_HSM_KEY_ALIAS = "hsmKeyAlias";
private static final String PARAM_CONTEXT_KEY = "contextKey";
private static final String PARAM_OFFSET = "offset";
private static final String PARAM_LENGTH = "length";
@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);
int offset = Integer.parseInt(params.getOrDefault(PARAM_OFFSET, "0"));
int length = Integer.parseInt(required(params, PARAM_LENGTH));
SecretKey masterKey = hsmCryptoService().getSecretKey(hsmKeyAlias);
byte[] masterBytes = masterKey.getEncoded();
String contextValue = runtimeContext.getOrDefault(contextKey, "");
byte[] contextBytes = contextValue.getBytes("UTF-8");
byte[] derived = xor(masterBytes, contextBytes, offset, length);
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 byte[] xor(byte[] masterBytes, byte[] contextBytes, int offset, int length) {
byte[] derived = Arrays.copyOf(masterBytes, masterBytes.length);
for (int i = 0; i < length && i < derived.length; i++) {
int contextIdx = offset + i;
if (contextIdx < contextBytes.length) {
derived[i] ^= contextBytes[contextIdx];
}
}
return derived;
}
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);
}
}
@@ -0,0 +1,19 @@
package com.eactive.eai.common.security.mapper;
import org.mapstruct.InheritInverseConfiguration;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
import com.eactive.eai.common.security.CryptoModuleConfigVO;
import com.eactive.eai.data.entity.onl.security.CryptoModuleConfig;
import com.eactive.eai.data.mapper.GenericMapper;
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface CryptoModuleConfigMapper extends GenericMapper<CryptoModuleConfigVO, CryptoModuleConfig> {
@Override
CryptoModuleConfigVO toVo(CryptoModuleConfig entity);
@InheritInverseConfiguration
CryptoModuleConfig toEntity(CryptoModuleConfigVO vo);
}
@@ -1,79 +0,0 @@
package com.eactive.eai.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.DualBucket;
import com.eactive.eai.common.inflow.dual.DualCustomBucket;
/**
* 어댑터/인터페이스 유량제어 차단 어느 버킷(PER_SECOND/THRESHOLD)에서 차단됐는지
* 에러 메시지에 포함하는 RequestProcessor 확장.
*
* <p>DualInflowControlManager와 함께 사용:
* <pre>
* inflow.control.bucket.className=com.eactive.eai.common.inflow.dual.DualInflowControlManager
* </pre>
*
* <p>Spring Bean 등록 기존 RequestProcessor 대신 클래스를 어댑터에 설정한다.
*/
public class DualRequestProcessor extends RequestProcessor {
@Override
protected String checkClientInflow(Bucket bucket, String clientId) {
if (StringUtils.isBlank(clientId)) return null;
if (bucket instanceof DualBucket) {
return ((DualBucket) bucket).isClientPassDetail(clientId);
}
return null;
}
@Override
protected InflowTargetVO resolveClientInflowThreshold(Bucket bucket, String clientId) {
if (bucket instanceof DualBucket) {
return ((DualBucket) 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);
}
}
@@ -17,6 +17,7 @@ import com.eactive.eai.adapter.AdapterPropManager;
import com.eactive.eai.adapter.AdapterVO;
import com.eactive.eai.adapter.http.HttpStatusException;
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
import com.eactive.eai.common.EAIKeys;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.header.HeaderAction;
@@ -352,24 +353,26 @@ public class HTTPProcess extends DefaultProcess {
this.tempProp.put(HttpClientAdapterServiceKey.INSTANCE_ID, instanceId);
}
EAIServerManager eaiServerManager = EAIServerManager.getInstance();
AdapterManager adapterManager = AdapterManager.getInstance();
AdapterGroupVO adptGrpVO = adapterManager.getAdapterGroupVO(reqEaiMsg.getCurrentSvcMsg().getPsvSysItfTp());
if (eaiServerManager.isTASEnabledEAIServer() && EAIMessageKeys.TRANTYPE_TAS.equals(reqEaiMsg.getTranType())
// RESTAdapter는 교체하지 않는다
&& !StringUtils.equals(adptGrpVO.getType(), com.eactive.eai.adapter.Keys.TYPE_REST)) {
PropManager manager = PropManager.getInstance();
Properties prop = manager.getProperties(RouteKeys.SIM);
// EAIServerManager eaiServerManager = EAIServerManager.getInstance();
// AdapterManager adapterManager = AdapterManager.getInstance();
// AdapterGroupVO adptGrpVO = adapterManager.getAdapterGroupVO(reqEaiMsg.getCurrentSvcMsg().getPsvSysItfTp());
// if (eaiServerManager.isTASEnabledEAIServer() && EAIMessageKeys.TRANTYPE_TAS.equals(reqEaiMsg.getTranType())
// // RESTAdapter는 교체하지 않는다
// && !StringUtils.equals(adptGrpVO.getType(), com.eactive.eai.adapter.Keys.TYPE_REST)) {
// PropManager manager = PropManager.getInstance();
// Properties prop = manager.getProperties(RouteKeys.SIM);
//
// if (reqEaiMsg.getCurrentSvcMsg().isSyncItfTp()) {
// this.adapterGroupName = prop.getProperty(RouteKeys.SIM_ADAPTER_SYNC, "_SIM_OU_HTT_SyC");
// } else {
// this.adapterGroupName = prop.getProperty(RouteKeys.SIM_ADAPTER_ASYNC, "_SIM_OU_HTT_AsC");
// }
// this.reqEaiMsg.getSvcMsg(0).setPsvSysItfTp(this.adapterGroupName);
// } else {
// this.adapterGroupName = reqEaiMsg.getCurrentSvcMsg().getPsvSysItfTp();
// }
if (reqEaiMsg.getCurrentSvcMsg().isSyncItfTp()) {
this.adapterGroupName = prop.getProperty(RouteKeys.SIM_ADAPTER_SYNC, "_SIM_OU_HTT_SyC");
} else {
this.adapterGroupName = prop.getProperty(RouteKeys.SIM_ADAPTER_ASYNC, "_SIM_OU_HTT_AsC");
}
this.reqEaiMsg.getSvcMsg(0).setPsvSysItfTp(this.adapterGroupName);
} else {
this.adapterGroupName = reqEaiMsg.getCurrentSvcMsg().getPsvSysItfTp();
}
this.svcTsmtUsgTp = this.reqEaiMsg.getSvcTsmtUsgTp(); // Inbound 호출방식
this.psvItfTp = this.reqEaiMsg.getCurrentSvcMsg().getPsvItfTp(); // 호출방식
@@ -404,6 +407,7 @@ public class HTTPProcess extends DefaultProcess {
}
// Inbound Adapter mesageType
AdapterManager adapterManager = AdapterManager.getInstance();
AdapterGroupVO inAdptGrpVO = adapterManager.getAdapterGroupVO(this.reqEaiMsg.getSngSysItfTp());
this.inAdapterMsgType = MessageType.ASC;
@@ -592,6 +596,22 @@ public class HTTPProcess extends DefaultProcess {
logger.debug(guidLogPrefix + " HTTP NONSTANDARD Request Message : "
+ MessageUtil.toAdapterTypeString(this.reqObject, this.inboundCharset));
}
// TAS 선택시 시뮬레이터 url로 변경, HTT 어댑터도 RST 처럼 방식을 변경하였다.
EAIServerManager eaiServerManager = EAIServerManager.getInstance();
if (eaiServerManager.isTASEnabledEAIServer() && EAIMessageKeys.TRANTYPE_TAS.equals(reqEaiMsg.getTranType())) {
PropManager manager = PropManager.getInstance();
Properties prop = manager.getProperties(RouteKeys.SIM);
String simAddr = prop.getProperty(RouteKeys.SIM_REST_MOCKSERVER);
if (StringUtils.isBlank(simAddr)) {
throw new Exception(String.format("Properties %s > %s not setted", RouteKeys.SIM,
RouteKeys.SIM_REST_MOCKSERVER));
}
String url = StringUtils.removeEnd(simAddr, "/") + "/mockapi/" + this.reqEaiMsg.getEAISvcCd();
this.outboundProp.put(HttpClientAdapterServiceKey.URL, url);
this.tempProp.remove(HttpAdapterServiceKey.INBOUND_REWRITE_PATH);
logger.debug("simUrl=" + url);
}
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.reqEaiMsg.getEAISvcCd();
@@ -0,0 +1,103 @@
package com.eactive.eai.agent.inflow;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.test.util.ReflectionTestUtils;
import com.eactive.eai.agent.command.CommandException;
import com.eactive.eai.common.inflow.InflowControlManager;
import com.eactive.eai.common.inflow.InflowControlUtil;
import com.eactive.eai.common.inflow.dual.ClientDualInflowControlManager;
/**
* ReloadInflowClientControlCommand 단위 테스트.
*
* <p>InflowControlUtil의 cachedInflowControlManager 필드에 mock을 직접 주입하여
* PropManager/ApplicationContext 없이 동작을 검증한다.
*/
class ReloadInflowClientControlCommandTest {
private ClientDualInflowControlManager mockDualManager;
@BeforeEach
void setUp() {
mockDualManager = mock(ClientDualInflowControlManager.class);
ReflectionTestUtils.setField(InflowControlUtil.class, "cachedInflowControlManager", null);
}
@AfterEach
void tearDown() {
ReflectionTestUtils.setField(InflowControlUtil.class, "cachedInflowControlManager", null);
}
private ReloadInflowClientControlCommand commandWith(Object args) {
ReloadInflowClientControlCommand cmd = new ReloadInflowClientControlCommand();
cmd.setArgs(args);
return cmd;
}
// =========================================================================
// args 타입 검증 실패
// =========================================================================
@Test
void execute_argsIsInteger_throwsCommandException() {
// args 검증이 getInflowControlManager() 호출 이전에 발생하므로 캐시 설정 불필요
assertThrows(CommandException.class, commandWith(Integer.valueOf(1))::execute);
}
// =========================================================================
// ClientDualInflowControlManager 비활성
// =========================================================================
@Test
void execute_notClientDualManager_throwsCommandException() {
InflowControlManager baseMgr = mock(InflowControlManager.class);
ReflectionTestUtils.setField(InflowControlUtil.class, "cachedInflowControlManager", baseMgr);
assertThrows(CommandException.class, commandWith("CLIENT_A")::execute);
}
// =========================================================================
// 전체 재로드 (ALL)
// =========================================================================
@Test
void execute_argsIsALL_callsReloadClientNoArgs() throws Exception {
ReflectionTestUtils.setField(InflowControlUtil.class, "cachedInflowControlManager", mockDualManager);
Object result = commandWith("ALL").execute();
assertEquals("success", result);
verify(mockDualManager).reloadClient();
verify(mockDualManager, never()).reloadClient(anyString());
}
// =========================================================================
// 개별 재로드 (ClientId)
// =========================================================================
@Test
void execute_argsIsClientId_callsReloadClientWithId() throws Exception {
ReflectionTestUtils.setField(InflowControlUtil.class, "cachedInflowControlManager", mockDualManager);
Object result = commandWith("CLIENT_A").execute();
assertEquals("success", result);
verify(mockDualManager).reloadClient("CLIENT_A");
verify(mockDualManager, never()).reloadClient();
}
@Test
void execute_differentClientId_callsReloadClientWithThatId() throws Exception {
ReflectionTestUtils.setField(InflowControlUtil.class, "cachedInflowControlManager", mockDualManager);
commandWith("CLIENT_B").execute();
verify(mockDualManager).reloadClient("CLIENT_B");
}
}
@@ -0,0 +1,96 @@
package com.eactive.eai.agent.inflow;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.test.util.ReflectionTestUtils;
import com.eactive.eai.agent.command.CommandException;
import com.eactive.eai.common.inflow.InflowControlManager;
import com.eactive.eai.common.inflow.InflowControlUtil;
import com.eactive.eai.common.inflow.dual.ClientDualInflowControlManager;
/**
* RemoveInflowClientControlCommand 단위 테스트.
*
* <p>InflowControlUtil의 cachedInflowControlManager 필드에 mock을 직접 주입하여
* PropManager/ApplicationContext 없이 동작을 검증한다.
*/
class RemoveInflowClientControlCommandTest {
private ClientDualInflowControlManager mockDualManager;
@BeforeEach
void setUp() {
mockDualManager = mock(ClientDualInflowControlManager.class);
ReflectionTestUtils.setField(InflowControlUtil.class, "cachedInflowControlManager", null);
}
@AfterEach
void tearDown() {
ReflectionTestUtils.setField(InflowControlUtil.class, "cachedInflowControlManager", null);
}
private RemoveInflowClientControlCommand commandWith(Object args) {
RemoveInflowClientControlCommand cmd = new RemoveInflowClientControlCommand();
cmd.setArgs(args);
return cmd;
}
// =========================================================================
// args 타입 검증 실패
// =========================================================================
@Test
void execute_argsIsInteger_throwsCommandException() {
assertThrows(CommandException.class, commandWith(Integer.valueOf(1))::execute);
}
// =========================================================================
// ClientDualInflowControlManager 비활성
// =========================================================================
@Test
void execute_notClientDualManager_throwsCommandException() {
InflowControlManager baseMgr = mock(InflowControlManager.class);
ReflectionTestUtils.setField(InflowControlUtil.class, "cachedInflowControlManager", baseMgr);
assertThrows(CommandException.class, commandWith("CLIENT_A")::execute);
}
// =========================================================================
// 정상 제거
// =========================================================================
@Test
void execute_validClientId_callsRemoveClient() throws CommandException {
ReflectionTestUtils.setField(InflowControlUtil.class, "cachedInflowControlManager", mockDualManager);
Object result = commandWith("CLIENT_A").execute();
assertEquals("success", result);
verify(mockDualManager).removeClient("CLIENT_A");
}
@Test
void execute_differentClientId_callsRemoveClientWithThatId() throws Exception {
ReflectionTestUtils.setField(InflowControlUtil.class, "cachedInflowControlManager", mockDualManager);
commandWith("CLIENT_B").execute();
verify(mockDualManager).removeClient("CLIENT_B");
}
@Test
void execute_validClientId_doesNotCallReload() throws Exception {
ReflectionTestUtils.setField(InflowControlUtil.class, "cachedInflowControlManager", mockDualManager);
commandWith("CLIENT_A").execute();
verify(mockDualManager, never()).reloadClient();
verify(mockDualManager, never()).reloadClient(anyString());
}
}
@@ -1,5 +1,7 @@
package com.eactive.eai.common.inflow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -36,9 +38,13 @@ class InflowControlManagerTest {
InflowControlManager inflowControlManager;
@BeforeEach
void setUp() throws LifecycleException {
void setUp() throws Exception {
if (!inflowControlManager.isStarted()) {
inflowControlManager.start();
} else {
inflowControlManager.reloadAdapter();
inflowControlManager.reloadInterface();
inflowControlManager.reloadGroup();
}
}
@@ -57,4 +63,22 @@ class InflowControlManagerTest {
assertNull(inflowControlManager.getGroupBucket("non-existent-group"));
}
@Test
void adapter_spikePasses_thenBurstBlocked() {
for (int i = 0; i < 5; i++) assertTrue(inflowControlManager.isAdapterPass("TEST_ADAPTER"));
assertFalse(inflowControlManager.isAdapterPass("TEST_ADAPTER"));
}
@Test
void interface_spikePasses_thenBurstBlocked() {
for (int i = 0; i < 5; i++) assertTrue(inflowControlManager.isInterfacePass("TEST_INTERFACE"));
assertFalse(inflowControlManager.isInterfacePass("TEST_INTERFACE"));
}
@Test
void group_spikePasses_thenBurstBlocked() {
for (int i = 0; i < 5; i++) assertNull(inflowControlManager.isGroupPass("test-group-quota"));
assertEquals(CustomGroupBucket.RESULT_BLOCKED_THRESHOLD, inflowControlManager.isGroupPass("test-group-quota"));
}
}
@@ -0,0 +1,190 @@
package com.eactive.eai.common.inflow.dual;
import static org.junit.jupiter.api.Assertions.*;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.test.util.ReflectionTestUtils;
import com.eactive.eai.common.inflow.InflowTargetVO;
import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Bucket4j;
import io.github.bucket4j.local.LocalBucket;
/**
* ClientDualInflowControlManager 클라이언트 메트릭 단위 테스트.
*/
class ClientDualInflowControlManagerMetricsTest {
private ClientDualInflowControlManager manager;
@BeforeEach
void setUp() {
manager = new ClientDualInflowControlManager();
}
// -------------------------------------------------------------------------
// Helpers
// -------------------------------------------------------------------------
private InflowTargetVO makeTargetVO(String name) {
InflowTargetVO vo = new InflowTargetVO();
vo.setName(name);
vo.setThresholdPerSecond(100);
vo.setThreshold(10000);
vo.setThresholdTimeUnit("DAY");
vo.setActivate(true);
return vo;
}
private LocalBucket stableBucket(long capacity) {
return Bucket4j.builder()
.addLimit(Bandwidth.simple(capacity, Duration.ofHours(1)))
.build();
}
private LocalBucket exhaustedBucket(long capacity) {
LocalBucket b = stableBucket(capacity);
b.tryConsume(capacity);
return b;
}
private DualCustomBucket passDualBucket(String name) {
return new DualCustomBucket(stableBucket(100), null, makeTargetVO(name));
}
private DualCustomBucket blockedPerSecondDualBucket(String name) {
return new DualCustomBucket(exhaustedBucket(1), null, makeTargetVO(name));
}
private DualCustomBucket blockedThresholdDualBucket(String name) {
return new DualCustomBucket(stableBucket(100), exhaustedBucket(1), makeTargetVO(name));
}
private void injectClientMap(Map<String, DualCustomBucket> map) {
ReflectionTestUtils.setField(manager, "clientBucketMap", map);
}
// =========================================================================
// isClientPassDetail() 카운터 증가
// =========================================================================
@Test
void isClientPassDetail_bucketNotRegistered_noMetricsCreated() {
manager.isClientPassDetail("UNKNOWN");
assertNull(manager.getClientMetrics("UNKNOWN"));
}
@Test
void isClientPassDetail_pass_incrementsAllowed() {
Map<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("C1", passDualBucket("C1"));
injectClientMap(map);
manager.isClientPassDetail("C1");
assertEquals(1, manager.getClientMetrics("C1").allowed.get());
}
@Test
void isClientPassDetail_blockedThreshold_incrementsRejectedThreshold() {
Map<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("C1", blockedThresholdDualBucket("C1"));
injectClientMap(map);
manager.isClientPassDetail("C1");
assertEquals(1, manager.getClientMetrics("C1").rejectedThreshold.get());
}
@Test
void isClientPassDetail_blockedPerSecond_incrementsRejectedPerSecond() {
Map<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("C1", blockedPerSecondDualBucket("C1"));
injectClientMap(map);
manager.isClientPassDetail("C1");
assertEquals(1, manager.getClientMetrics("C1").rejectedPerSecond.get());
}
// =========================================================================
// getAllClientMetrics 조회 불변성
// =========================================================================
@Test
void getAllClientMetrics_empty_returnsEmptyMap() {
assertTrue(manager.getAllClientMetrics().isEmpty());
}
@Test
void getAllClientMetrics_afterCalls_containsEntries() {
Map<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("C1", passDualBucket("C1"));
map.put("C2", passDualBucket("C2"));
injectClientMap(map);
manager.isClientPassDetail("C1");
manager.isClientPassDetail("C2");
Map<String, DualInflowControlManager.TargetMetrics> all = manager.getAllClientMetrics();
assertEquals(2, all.size());
assertTrue(all.containsKey("C1"));
assertTrue(all.containsKey("C2"));
}
// =========================================================================
// resetClientMetrics / resetAllClientMetrics
// =========================================================================
@Test
void resetClientMetrics_resetsTargetClient() {
Map<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("C1", passDualBucket("C1"));
injectClientMap(map);
manager.isClientPassDetail("C1");
manager.resetClientMetrics("C1");
assertEquals(0, manager.getClientMetrics("C1").allowed.get());
}
@Test
void resetAllClientMetrics_resetsAll() {
Map<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("C1", passDualBucket("C1"));
map.put("C2", passDualBucket("C2"));
injectClientMap(map);
manager.isClientPassDetail("C1");
manager.isClientPassDetail("C2");
manager.resetAllClientMetrics();
assertEquals(0, manager.getClientMetrics("C1").allowed.get());
assertEquals(0, manager.getClientMetrics("C2").allowed.get());
}
// =========================================================================
// removeClient 메트릭 자동 삭제
// =========================================================================
@Test
void removeClient_cleansUpMetrics() {
Map<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("C1", passDualBucket("C1"));
injectClientMap(map);
manager.isClientPassDetail("C1");
assertNotNull(manager.getClientMetrics("C1"));
manager.removeClient("C1");
assertNull(manager.getClientMetrics("C1"));
}
}
@@ -0,0 +1,280 @@
package com.eactive.eai.common.inflow.dual;
import static org.junit.jupiter.api.Assertions.*;
import java.time.Duration;
import java.util.concurrent.ConcurrentHashMap;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.test.util.ReflectionTestUtils;
import com.eactive.eai.common.inflow.InflowTargetVO;
import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Bucket4j;
import io.github.bucket4j.local.LocalBucket;
/**
* DualInflowControlManager의 Dual 기반 오버라이드 메서드 단위 테스트.
*
* <p>검증 포인트:
* - getAdapterAllKeys / getInterfaceAllKeys Dual (adapterBucketMap/interfaceBucketMap) 사용
* - getAdapterInflowThreashold / getInterfaceInflowThreashold Dual 맵의 VO 반환
* - removeAdapter / removeInterface Dual 맵에서 항목을 제거
* - base adapterBucketList / interfaceBucketList 상태와 무관하게 동작 (DAO 이중 호출 제거 효과)
*/
class DualInflowControlManagerBucketMethodsTest {
private DualInflowControlManager manager;
@BeforeEach
void setUp() {
manager = new DualInflowControlManager();
}
// -------------------------------------------------------------------------
// Helpers
// -------------------------------------------------------------------------
private InflowTargetVO makeVO(String name) {
InflowTargetVO vo = new InflowTargetVO();
vo.setName(name);
vo.setThresholdPerSecond(100);
vo.setThreshold(10000);
vo.setThresholdTimeUnit("DAY");
vo.setActivate(true);
return vo;
}
private LocalBucket bucket(long capacity) {
return Bucket4j.builder()
.addLimit(Bandwidth.simple(capacity, Duration.ofSeconds(1)))
.build();
}
private DualCustomBucket dualBucket(String name) {
return new DualCustomBucket(bucket(100), bucket(1000), makeVO(name));
}
private void setAdapterMap(ConcurrentHashMap<String, DualCustomBucket> map) {
ReflectionTestUtils.setField(manager, "adapterBucketMap", map);
}
private void setInterfaceMap(ConcurrentHashMap<String, DualCustomBucket> map) {
ReflectionTestUtils.setField(manager, "interfaceBucketMap", map);
}
// =========================================================================
// getAdapterAllKeys
// =========================================================================
@Test
void getAdapterAllKeys_emptyMap_returnsEmptyArray() {
setAdapterMap(new ConcurrentHashMap<>());
assertEquals(0, manager.getAdapterAllKeys().length);
}
@Test
void getAdapterAllKeys_twoEntries_returnsSortedKeys() {
ConcurrentHashMap<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("ADAPTER_B", dualBucket("ADAPTER_B"));
map.put("ADAPTER_A", dualBucket("ADAPTER_A"));
setAdapterMap(map);
String[] keys = manager.getAdapterAllKeys();
assertArrayEquals(new String[]{"ADAPTER_A", "ADAPTER_B"}, keys);
}
@Test
void getAdapterAllKeys_usesDualMap_notBaseList() {
// Dual 맵에만 항목 존재 base adapterBucketList 비어 있음
ConcurrentHashMap<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("DUAL_ONLY", dualBucket("DUAL_ONLY"));
setAdapterMap(map);
String[] keys = manager.getAdapterAllKeys();
assertEquals(1, keys.length);
assertEquals("DUAL_ONLY", keys[0]);
}
// =========================================================================
// getInterfaceAllKeys
// =========================================================================
@Test
void getInterfaceAllKeys_emptyMap_returnsEmptyArray() {
setInterfaceMap(new ConcurrentHashMap<>());
assertEquals(0, manager.getInterfaceAllKeys().length);
}
@Test
void getInterfaceAllKeys_threeEntries_returnsSortedKeys() {
ConcurrentHashMap<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("IF_C", dualBucket("IF_C"));
map.put("IF_A", dualBucket("IF_A"));
map.put("IF_B", dualBucket("IF_B"));
setInterfaceMap(map);
String[] keys = manager.getInterfaceAllKeys();
assertArrayEquals(new String[]{"IF_A", "IF_B", "IF_C"}, keys);
}
@Test
void getInterfaceAllKeys_usesDualMap_notBaseList() {
ConcurrentHashMap<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("DUAL_IF", dualBucket("DUAL_IF"));
setInterfaceMap(map);
String[] keys = manager.getInterfaceAllKeys();
assertEquals(1, keys.length);
assertEquals("DUAL_IF", keys[0]);
}
// =========================================================================
// getAdapterInflowThreashold
// =========================================================================
@Test
void getAdapterInflowThreashold_found_returnsVO() {
InflowTargetVO vo = makeVO("ADAPTER_A");
ConcurrentHashMap<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("ADAPTER_A", new DualCustomBucket(bucket(10), bucket(100), vo));
setAdapterMap(map);
InflowTargetVO result = manager.getAdapterInflowThreashold("ADAPTER_A");
assertSame(vo, result);
}
@Test
void getAdapterInflowThreashold_notFound_returnsNull() {
setAdapterMap(new ConcurrentHashMap<>());
assertNull(manager.getAdapterInflowThreashold("MISSING"));
}
@Test
void getAdapterInflowThreashold_usesDualMap_notBaseList() {
// base adapterBucketList 에는 항목 없고 Dual 맵에만 존재
InflowTargetVO vo = makeVO("ADAPTER_A");
ConcurrentHashMap<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("ADAPTER_A", new DualCustomBucket(null, null, vo));
setAdapterMap(map);
assertSame(vo, manager.getAdapterInflowThreashold("ADAPTER_A"));
}
// =========================================================================
// getInterfaceInflowThreashold
// =========================================================================
@Test
void getInterfaceInflowThreashold_found_returnsVO() {
InflowTargetVO vo = makeVO("IF_001");
ConcurrentHashMap<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("IF_001", new DualCustomBucket(bucket(10), bucket(100), vo));
setInterfaceMap(map);
assertSame(vo, manager.getInterfaceInflowThreashold("IF_001"));
}
@Test
void getInterfaceInflowThreashold_notFound_returnsNull() {
setInterfaceMap(new ConcurrentHashMap<>());
assertNull(manager.getInterfaceInflowThreashold("MISSING"));
}
@Test
void getInterfaceInflowThreashold_usesDualMap_notBaseList() {
InflowTargetVO vo = makeVO("IF_001");
ConcurrentHashMap<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("IF_001", new DualCustomBucket(null, null, vo));
setInterfaceMap(map);
assertSame(vo, manager.getInterfaceInflowThreashold("IF_001"));
}
// =========================================================================
// removeAdapter
// =========================================================================
@Test
void removeAdapter_existingKey_removedFromDualMap() {
ConcurrentHashMap<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("ADAPTER_A", dualBucket("ADAPTER_A"));
map.put("ADAPTER_B", dualBucket("ADAPTER_B"));
setAdapterMap(map);
manager.removeAdapter("ADAPTER_A");
assertNull(manager.getAdapterBucket("ADAPTER_A"));
assertNotNull(manager.getAdapterBucket("ADAPTER_B"));
}
@Test
void removeAdapter_keysReflectRemoval() {
ConcurrentHashMap<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("ADAPTER_A", dualBucket("ADAPTER_A"));
map.put("ADAPTER_B", dualBucket("ADAPTER_B"));
setAdapterMap(map);
manager.removeAdapter("ADAPTER_A");
String[] keys = manager.getAdapterAllKeys();
assertEquals(1, keys.length);
assertEquals("ADAPTER_B", keys[0]);
}
@Test
void removeAdapter_missingKey_noException() {
setAdapterMap(new ConcurrentHashMap<>());
assertDoesNotThrow(() -> manager.removeAdapter("NOT_EXISTS"));
}
// =========================================================================
// removeInterface
// =========================================================================
@Test
void removeInterface_existingKey_removedFromDualMap() {
ConcurrentHashMap<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("IF_001", dualBucket("IF_001"));
map.put("IF_002", dualBucket("IF_002"));
setInterfaceMap(map);
manager.removeInterface("IF_001");
assertNull(manager.getInterfaceBucket("IF_001"));
assertNotNull(manager.getInterfaceBucket("IF_002"));
}
@Test
void removeInterface_keysReflectRemoval() {
ConcurrentHashMap<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("IF_001", dualBucket("IF_001"));
map.put("IF_002", dualBucket("IF_002"));
setInterfaceMap(map);
manager.removeInterface("IF_001");
String[] keys = manager.getInterfaceAllKeys();
assertEquals(1, keys.length);
assertEquals("IF_002", keys[0]);
}
@Test
void removeInterface_missingKey_noException() {
setInterfaceMap(new ConcurrentHashMap<>());
assertDoesNotThrow(() -> manager.removeInterface("NOT_EXISTS"));
}
}
@@ -0,0 +1,92 @@
package com.eactive.eai.common.inflow.dual;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import com.eactive.eai.common.inflow.InflowTargetVO;
/**
* DualInflowControlManager.makeBucket() 버킷 생성 동작 검증.
*
* <p>검증 포인트:
* - threshold/perSecond 버킷이 실제로 생성되는지
* - 할당량 이내 spike는 통과하고 초과 burst는 차단되는지
* - perSecond/threshold 어느 쪽이 binding 제약인지 구분되는지
*/
class DualInflowControlManagerMakeBucketTest {
private final DualInflowControlManager manager = new DualInflowControlManager();
private InflowTargetVO vo(long perSecond, long threshold, String timeUnit) {
InflowTargetVO vo = new InflowTargetVO();
vo.setName("TEST");
vo.setThresholdPerSecond(perSecond);
vo.setThreshold(threshold);
vo.setThresholdTimeUnit(timeUnit);
vo.setActivate(true);
return vo;
}
// =========================================================================
// threshold 단독 (5건/)
// =========================================================================
@Test
void thresholdOnly_spikePasses_thenBurstBlocked() {
DualCustomBucket bucket = manager.makeBucket(vo(0, 5, "MIN"));
for (int i = 0; i < 5; i++) assertNull(bucket.tryConsume());
assertEquals(DualCustomBucket.RESULT_BLOCKED_THRESHOLD, bucket.tryConsume());
}
// =========================================================================
// perSecond 단독
// =========================================================================
@Test
void perSecondOnly_spikePasses_thenBurstBlocked() {
DualCustomBucket bucket = manager.makeBucket(vo(5, 0, null));
for (int i = 0; i < 5; i++) assertNull(bucket.tryConsume());
assertEquals(DualCustomBucket.RESULT_BLOCKED_PER_SECOND, bucket.tryConsume());
}
// =========================================================================
// perSecond + threshold 동시 설정 binding 제약 구분
// =========================================================================
@Test
void both_perSecondIsBinding_blockedByPerSecond() {
// perSecond=3 binding: threshold=100/MIN은 여유 있음
DualCustomBucket bucket = manager.makeBucket(vo(3, 100, "MIN"));
for (int i = 0; i < 3; i++) assertNull(bucket.tryConsume());
assertEquals(DualCustomBucket.RESULT_BLOCKED_PER_SECOND, bucket.tryConsume());
}
@Test
void both_thresholdIsBinding_blockedByThreshold() {
// threshold=3/MIN binding: perSecond=100은 여유 있음
DualCustomBucket bucket = manager.makeBucket(vo(100, 3, "MIN"));
for (int i = 0; i < 3; i++) assertNull(bucket.tryConsume());
assertEquals(DualCustomBucket.RESULT_BLOCKED_THRESHOLD, bucket.tryConsume());
}
// =========================================================================
// 비활성 / 조건 미충족 null 반환
// =========================================================================
@Test
void inactiveVO_returnsNull() {
InflowTargetVO vo = vo(5, 0, null);
vo.setActivate(false);
assertNull(manager.makeBucket(vo));
}
@Test
void noLimitsSet_returnsNull() {
assertNull(manager.makeBucket(vo(0, 0, null)));
}
}
@@ -12,16 +12,17 @@ import org.springframework.test.util.ReflectionTestUtils;
import com.eactive.eai.common.inflow.CustomGroupBucket;
import com.eactive.eai.common.inflow.InflowGroupVO;
import com.eactive.eai.common.inflow.InflowTargetVO;
import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Bucket4j;
import io.github.bucket4j.local.LocalBucket;
/**
* DualInflowControlManager 그룹 메트릭 단위 테스트.
* DualInflowControlManager 메트릭 단위 테스트.
*
* <p>start() 없이 groupBucketList를 ReflectionTestUtils로 직접 주입하여
* isGroupPass() 카운팅과 getGroupMetrics / reset 메서드를 검증한다.
* <p>어댑터/인터페이스/그룹 메트릭을 검증한다.
* 클라이언트 메트릭은 ClientDualInflowControlManagerMetricsTest 에서 검증한다.
*/
class DualInflowControlManagerMetricsTest {
@@ -68,6 +69,36 @@ class DualInflowControlManagerMetricsTest {
return new CustomGroupBucket(stableBucket(100), exhaustedBucket(1), makeGroupVO(groupId, groupId + "-name"));
}
private InflowTargetVO makeTargetVO(String name) {
InflowTargetVO vo = new InflowTargetVO();
vo.setName(name);
vo.setThresholdPerSecond(100);
vo.setThreshold(10000);
vo.setThresholdTimeUnit("DAY");
vo.setActivate(true);
return vo;
}
private DualCustomBucket passDualBucket(String name) {
return new DualCustomBucket(stableBucket(100), null, makeTargetVO(name));
}
private DualCustomBucket blockedPerSecondDualBucket(String name) {
return new DualCustomBucket(exhaustedBucket(1), null, makeTargetVO(name));
}
private DualCustomBucket blockedThresholdDualBucket(String name) {
return new DualCustomBucket(stableBucket(100), exhaustedBucket(1), makeTargetVO(name));
}
private void injectAdapterMap(Map<String, DualCustomBucket> map) {
ReflectionTestUtils.setField(manager, "adapterBucketMap", map);
}
private void injectInterfaceMap(Map<String, DualCustomBucket> map) {
ReflectionTestUtils.setField(manager, "interfaceBucketMap", map);
}
private void injectGroupBucketList(Map<String, CustomGroupBucket> map) {
ReflectionTestUtils.setField(manager, "groupBucketList", map);
}
@@ -315,4 +346,246 @@ class DualInflowControlManagerMetricsTest {
assertNotNull(manager.getGroupMetrics("G1"));
assertNotNull(manager.getGroupMetrics("G2"));
}
// =========================================================================
// isAdapterPassDetail() 카운터 증가
// =========================================================================
@Test
void isAdapterPassDetail_bucketNotRegistered_noMetricsCreated() {
manager.isAdapterPassDetail("UNKNOWN");
assertNull(manager.getAdapterMetrics("UNKNOWN"));
}
@Test
void isAdapterPassDetail_pass_incrementsAllowed() {
Map<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("A1", passDualBucket("A1"));
injectAdapterMap(map);
String result = manager.isAdapterPassDetail("A1");
assertNull(result);
DualInflowControlManager.TargetMetrics m = manager.getAdapterMetrics("A1");
assertNotNull(m);
assertEquals(1, m.allowed.get());
assertEquals(0, m.rejectedPerSecond.get());
assertEquals(0, m.rejectedThreshold.get());
}
@Test
void isAdapterPassDetail_blockedPerSecond_incrementsRejectedPerSecond() {
Map<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("A1", blockedPerSecondDualBucket("A1"));
injectAdapterMap(map);
String result = manager.isAdapterPassDetail("A1");
assertEquals(DualCustomBucket.RESULT_BLOCKED_PER_SECOND, result);
DualInflowControlManager.TargetMetrics m = manager.getAdapterMetrics("A1");
assertEquals(0, m.allowed.get());
assertEquals(1, m.rejectedPerSecond.get());
assertEquals(0, m.rejectedThreshold.get());
}
@Test
void isAdapterPassDetail_blockedThreshold_incrementsRejectedThreshold() {
Map<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("A1", blockedThresholdDualBucket("A1"));
injectAdapterMap(map);
String result = manager.isAdapterPassDetail("A1");
assertEquals(DualCustomBucket.RESULT_BLOCKED_THRESHOLD, result);
DualInflowControlManager.TargetMetrics m = manager.getAdapterMetrics("A1");
assertEquals(0, m.allowed.get());
assertEquals(0, m.rejectedPerSecond.get());
assertEquals(1, m.rejectedThreshold.get());
}
@Test
void isAdapterPassDetail_multipleCalls_countersAccumulate() {
Map<String, DualCustomBucket> map = new ConcurrentHashMap<>();
LocalBucket b = stableBucket(3);
map.put("A1", new DualCustomBucket(b, null, makeTargetVO("A1")));
injectAdapterMap(map);
for (int i = 0; i < 5; i++) manager.isAdapterPassDetail("A1");
DualInflowControlManager.TargetMetrics m = manager.getAdapterMetrics("A1");
assertEquals(3, m.allowed.get());
assertEquals(2, m.rejectedPerSecond.get());
assertEquals(5, m.allowed.get() + m.rejectedPerSecond.get() + m.rejectedThreshold.get());
}
// =========================================================================
// isInterfacePassDetail() 카운터 증가
// =========================================================================
@Test
void isInterfacePassDetail_bucketNotRegistered_noMetricsCreated() {
manager.isInterfacePassDetail("UNKNOWN");
assertNull(manager.getInterfaceMetrics("UNKNOWN"));
}
@Test
void isInterfacePassDetail_pass_incrementsAllowed() {
Map<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("IF1", passDualBucket("IF1"));
injectInterfaceMap(map);
manager.isInterfacePassDetail("IF1");
assertEquals(1, manager.getInterfaceMetrics("IF1").allowed.get());
}
@Test
void isInterfacePassDetail_blockedPerSecond_incrementsRejectedPerSecond() {
Map<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("IF1", blockedPerSecondDualBucket("IF1"));
injectInterfaceMap(map);
manager.isInterfacePassDetail("IF1");
assertEquals(1, manager.getInterfaceMetrics("IF1").rejectedPerSecond.get());
}
@Test
void isInterfacePassDetail_differentInterfaces_independentMetrics() {
Map<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("IF1", passDualBucket("IF1"));
map.put("IF2", blockedPerSecondDualBucket("IF2"));
injectInterfaceMap(map);
manager.isInterfacePassDetail("IF1");
manager.isInterfacePassDetail("IF1");
manager.isInterfacePassDetail("IF2");
assertEquals(2, manager.getInterfaceMetrics("IF1").allowed.get());
assertEquals(1, manager.getInterfaceMetrics("IF2").rejectedPerSecond.get());
}
// =========================================================================
// getAllXxxMetrics 조회 불변성
// =========================================================================
@Test
void getAllAdapterMetrics_afterCalls_containsEntries() {
Map<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("A1", passDualBucket("A1"));
map.put("A2", passDualBucket("A2"));
injectAdapterMap(map);
manager.isAdapterPassDetail("A1");
manager.isAdapterPassDetail("A2");
Map<String, DualInflowControlManager.TargetMetrics> all = manager.getAllAdapterMetrics();
assertEquals(2, all.size());
assertTrue(all.containsKey("A1"));
assertTrue(all.containsKey("A2"));
}
@Test
void getAllAdapterMetrics_returnsUnmodifiableView() {
Map<String, DualInflowControlManager.TargetMetrics> all = manager.getAllAdapterMetrics();
assertThrows(UnsupportedOperationException.class, () -> all.put("NEW", null));
}
@Test
void getAllInterfaceMetrics_empty_returnsEmptyMap() {
assertTrue(manager.getAllInterfaceMetrics().isEmpty());
}
// =========================================================================
// resetXxxMetrics / resetAllXxxMetrics
// =========================================================================
@Test
void resetAdapterMetrics_resetsTargetAdapter() {
Map<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("A1", passDualBucket("A1"));
map.put("A2", passDualBucket("A2"));
injectAdapterMap(map);
manager.isAdapterPassDetail("A1");
manager.isAdapterPassDetail("A1");
manager.isAdapterPassDetail("A2");
manager.resetAdapterMetrics("A1");
assertEquals(0, manager.getAdapterMetrics("A1").allowed.get());
assertEquals(1, manager.getAdapterMetrics("A2").allowed.get());
}
@Test
void resetAdapterMetrics_nonExistent_noException() {
assertDoesNotThrow(() -> manager.resetAdapterMetrics("NONE"));
}
@Test
void resetAllAdapterMetrics_resetsAll() {
Map<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("A1", passDualBucket("A1"));
map.put("A2", passDualBucket("A2"));
injectAdapterMap(map);
manager.isAdapterPassDetail("A1");
manager.isAdapterPassDetail("A2");
manager.resetAllAdapterMetrics();
assertEquals(0, manager.getAdapterMetrics("A1").allowed.get());
assertEquals(0, manager.getAdapterMetrics("A2").allowed.get());
}
@Test
void resetInterfaceMetrics_resetsTargetInterface() {
Map<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("IF1", passDualBucket("IF1"));
injectInterfaceMap(map);
manager.isInterfacePassDetail("IF1");
manager.isInterfacePassDetail("IF1");
manager.resetInterfaceMetrics("IF1");
assertEquals(0, manager.getInterfaceMetrics("IF1").allowed.get());
}
@Test
void resetAllInterfaceMetrics_emptyMap_noException() {
assertDoesNotThrow(() -> manager.resetAllInterfaceMetrics());
}
// =========================================================================
// remove 메트릭 자동 삭제
// =========================================================================
@Test
void removeAdapter_cleansUpMetrics() {
Map<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("A1", passDualBucket("A1"));
ReflectionTestUtils.setField(manager, "adapterBucketMap", map);
manager.isAdapterPassDetail("A1");
assertNotNull(manager.getAdapterMetrics("A1"));
manager.removeAdapter("A1");
assertNull(manager.getAdapterMetrics("A1"));
}
@Test
void removeInterface_cleansUpMetrics() {
Map<String, DualCustomBucket> map = new ConcurrentHashMap<>();
map.put("IF1", passDualBucket("IF1"));
ReflectionTestUtils.setField(manager, "interfaceBucketMap", map);
manager.isInterfacePassDetail("IF1");
assertNotNull(manager.getInterfaceMetrics("IF1"));
manager.removeInterface("IF1");
assertNull(manager.getInterfaceMetrics("IF1"));
}
}
@@ -0,0 +1,399 @@
package com.eactive.eai.common.security;
import static org.junit.jupiter.api.Assertions.*;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
/**
* AESCryptoModuleExtension 단위 테스트
* Spring 컨텍스트 없이 순수 암복호화 로직만 검증한다.
*/
@TestMethodOrder(MethodOrderer.DisplayName.class)
class AESCryptoModuleExtensionTest {
private static final byte[] KEY_128 = "0123456789abcdef".getBytes(StandardCharsets.UTF_8);
private static final byte[] KEY_256 = "0123456789abcdef0123456789abcdef".getBytes(StandardCharsets.UTF_8);
private static final byte[] IV_16 = "abcdef0123456789".getBytes(StandardCharsets.UTF_8);
private static final byte[] PLAIN = "암호화 테스트 평문 데이터입니다.".getBytes(StandardCharsets.UTF_8);
// =========================================================================
// 1. CBC 모드
// =========================================================================
@Test
@DisplayName("1-1. AES/CBC/PKCS5Padding 128bit — 암복호화 라운드트립")
void testCbc128_roundTrip() throws Exception {
AESCryptoModuleExtension ext = new AESCryptoModuleExtension();
ext.init("AES", "CBC", "PKCS5Padding", IV_16, KEY_128, KEY_128);
byte[] encrypted = ext.encrypt(PLAIN, 0, PLAIN.length);
byte[] decrypted = ext.decrypt(encrypted, 0, encrypted.length);
assertNotNull(encrypted);
assertFalse(Arrays.equals(PLAIN, encrypted), "암호문은 평문과 달라야 한다");
assertArrayEquals(PLAIN, decrypted, "복호화 결과가 원문과 일치해야 한다");
}
@Test
@DisplayName("1-2. AES/CBC/PKCS5Padding 256bit — 암복호화 라운드트립")
void testCbc256_roundTrip() throws Exception {
AESCryptoModuleExtension ext = new AESCryptoModuleExtension();
ext.init("AES", "CBC", "PKCS5Padding", IV_16, KEY_256, KEY_256);
byte[] encrypted = ext.encrypt(PLAIN, 0, PLAIN.length);
byte[] decrypted = ext.decrypt(encrypted, 0, encrypted.length);
assertArrayEquals(PLAIN, decrypted);
}
@Test
@DisplayName("1-3. AES/CBC — 암호화 결과는 블록 크기(16바이트)의 배수")
void testCbc_ciphertextIsMultipleOfBlockSize() throws Exception {
AESCryptoModuleExtension ext = new AESCryptoModuleExtension();
ext.init("AES", "CBC", "PKCS5Padding", IV_16, KEY_128, KEY_128);
byte[] encrypted = ext.encrypt(PLAIN, 0, PLAIN.length);
assertEquals(0, encrypted.length % 16, "CBC 암호문 길이는 16 바이트 배수여야 한다");
}
@Test
@DisplayName("1-4. AES/CBC — 잘못된 키로 복호화 시 예외 발생")
void testCbc_wrongKeyThrowsException() throws Exception {
AESCryptoModuleExtension encExt = new AESCryptoModuleExtension();
encExt.init("AES", "CBC", "PKCS5Padding", IV_16, KEY_128, KEY_128);
byte[] encrypted = encExt.encrypt(PLAIN, 0, PLAIN.length);
byte[] wrongKey = "wrongkey12345678".getBytes(StandardCharsets.UTF_8);
AESCryptoModuleExtension decExt = new AESCryptoModuleExtension();
decExt.init("AES", "CBC", "PKCS5Padding", IV_16, wrongKey, wrongKey);
assertThrows(Exception.class, () -> decExt.decrypt(encrypted, 0, encrypted.length),
"잘못된 키로 복호화 시 예외가 발생해야 한다");
}
// =========================================================================
// 2. GCM 모드
// =========================================================================
@Test
@DisplayName("2-1. AES/GCM/NoPadding 128bit — 암복호화 라운드트립")
void testGcm128_roundTrip() throws Exception {
AESCryptoModuleExtension ext = new AESCryptoModuleExtension();
ext.init("AES", "GCM", "NoPadding", IV_16, KEY_128, KEY_128);
byte[] encrypted = ext.encrypt(PLAIN, 0, PLAIN.length);
byte[] decrypted = ext.decrypt(encrypted, 0, encrypted.length);
assertNotNull(encrypted);
assertArrayEquals(PLAIN, decrypted, "GCM 복호화 결과가 원문과 일치해야 한다");
}
@Test
@DisplayName("2-2. AES/GCM — 암호화마다 랜덤 Nonce → 동일 평문도 다른 암호문 생성")
void testGcm_randomNonce_differentCiphertextEachCall() throws Exception {
AESCryptoModuleExtension ext1 = new AESCryptoModuleExtension();
ext1.init("AES", "GCM", "NoPadding", IV_16, KEY_128, KEY_128);
AESCryptoModuleExtension ext2 = new AESCryptoModuleExtension();
ext2.init("AES", "GCM", "NoPadding", IV_16, KEY_128, KEY_128);
byte[] enc1 = ext1.encrypt(PLAIN, 0, PLAIN.length);
byte[] enc2 = ext2.encrypt(PLAIN, 0, PLAIN.length);
assertFalse(Arrays.equals(enc1, enc2), "GCM은 랜덤 Nonce로 매번 다른 암호문을 생성해야 한다");
}
@Test
@DisplayName("2-3. AES/GCM — 암호문 앞 12바이트가 Nonce")
void testGcm_ciphertextStartsWithNonce() throws Exception {
AESCryptoModuleExtension ext = new AESCryptoModuleExtension();
ext.init("AES", "GCM", "NoPadding", IV_16, KEY_128, KEY_128);
byte[] encrypted = ext.encrypt(PLAIN, 0, PLAIN.length);
assertTrue(encrypted.length > 12, "GCM 암호문은 Nonce(12바이트) + 암호문 + Tag(16바이트) 구조여야 한다");
}
@Test
@DisplayName("2-4. AES/GCM — 256bit 키 라운드트립")
void testGcm256_roundTrip() throws Exception {
AESCryptoModuleExtension ext = new AESCryptoModuleExtension();
ext.init("AES", "GCM", "NoPadding", IV_16, KEY_256, KEY_256);
byte[] encrypted = ext.encrypt(PLAIN, 0, PLAIN.length);
byte[] decrypted = ext.decrypt(encrypted, 0, encrypted.length);
assertArrayEquals(PLAIN, decrypted);
}
// =========================================================================
// 3. init 편의 메서드 (IV 없는 버전)
// =========================================================================
@Test
@DisplayName("3-1. init(alg, mode, pad, encKey, decKey) — IV null로 CBC 초기화 시 예외")
void testInitWithoutIv_cbcThrowsException() {
AESCryptoModuleExtension ext = new AESCryptoModuleExtension();
assertThrows(Exception.class,
() -> ext.init("AES", "CBC", "PKCS5Padding", KEY_128, KEY_128),
"IV 없이 CBC 초기화 시 예외가 발생해야 한다");
}
// =========================================================================
// 4. 바이트 배열 오프셋/길이 encrypt/decrypt
// =========================================================================
@Test
@DisplayName("4-1. encrypt(src, sindex, slength, dst, dindex) — 버퍼 직접 지정 라운드트립")
void testEncryptDecryptWithBuffer() throws Exception {
AESCryptoModuleExtension ext = new AESCryptoModuleExtension();
ext.init("AES", "CBC", "PKCS5Padding", IV_16, KEY_128, KEY_128);
byte[] dst = new byte[256];
int encLen = ext.encrypt(PLAIN, 0, PLAIN.length, dst, 0);
byte[] decDst = new byte[256];
int decLen = ext.decrypt(dst, 0, encLen, decDst, 0);
assertArrayEquals(PLAIN, Arrays.copyOf(decDst, decLen));
}
// =========================================================================
// 5. 프로바이더 파라미터
// =========================================================================
@Test
@DisplayName("5-1. provider=BC 명시 — CBC 암복호화 라운드트립")
void testProvider_bc_cbcRoundTrip() throws Exception {
AESCryptoModuleExtension ext = new AESCryptoModuleExtension();
ext.init("AES", "CBC", "PKCS5Padding", IV_16, KEY_128, KEY_128, "BC");
byte[] encrypted = ext.encrypt(PLAIN, 0, PLAIN.length);
byte[] decrypted = ext.decrypt(encrypted, 0, encrypted.length);
assertArrayEquals(PLAIN, decrypted, "BC 프로바이더 명시 시 CBC 암복호화가 성공해야 한다");
}
@Test
@DisplayName("5-2. provider=BC 명시 — GCM 암복호화 라운드트립")
void testProvider_bc_gcmRoundTrip() throws Exception {
AESCryptoModuleExtension ext = new AESCryptoModuleExtension();
ext.init("AES", "GCM", "NoPadding", IV_16, KEY_128, KEY_128, "BC");
byte[] encrypted = ext.encrypt(PLAIN, 0, PLAIN.length);
byte[] decrypted = ext.decrypt(encrypted, 0, encrypted.length);
assertArrayEquals(PLAIN, decrypted, "BC 프로바이더 명시 시 GCM 암복호화가 성공해야 한다");
}
@Test
@DisplayName("5-3. provider null — GCM 기본 동작(BC) 라운드트립")
void testProvider_null_gcmDefaultBcRoundTrip() throws Exception {
AESCryptoModuleExtension enc = new AESCryptoModuleExtension();
enc.init("AES", "GCM", "NoPadding", IV_16, KEY_128, KEY_128, (String) null);
AESCryptoModuleExtension dec = new AESCryptoModuleExtension();
dec.init("AES", "GCM", "NoPadding", IV_16, KEY_128, KEY_128, (String) null);
byte[] encrypted = enc.encrypt(PLAIN, 0, PLAIN.length);
byte[] decrypted = dec.decrypt(encrypted, 0, encrypted.length);
assertArrayEquals(PLAIN, decrypted, "provider=null이면 GCM은 BC 기본값으로 동작해야 한다");
}
@Test
@DisplayName("5-4. provider 파라미터 없는 CBC init — provider 없는 버전과 동일 결과")
void testProvider_cbcWithAndWithoutProvider_sameResult() throws Exception {
AESCryptoModuleExtension ext1 = new AESCryptoModuleExtension();
ext1.init("AES", "CBC", "PKCS5Padding", IV_16, KEY_128, KEY_128);
AESCryptoModuleExtension ext2 = new AESCryptoModuleExtension();
ext2.init("AES", "CBC", "PKCS5Padding", IV_16, KEY_128, KEY_128, "BC");
byte[] enc1 = ext1.encrypt(PLAIN, 0, PLAIN.length);
byte[] enc2 = ext2.encrypt(PLAIN, 0, PLAIN.length);
assertArrayEquals(enc1, enc2, "동일 키/IV에서 provider 유무와 무관하게 CBC 암호문이 같아야 한다");
}
// =========================================================================
// 6. AAD (Additional Authenticated Data)
// =========================================================================
@Test
@DisplayName("6-1. GCM — 명시적 AAD로 암복호화 라운드트립")
void testGcm_explicitAad_roundTrip() throws Exception {
byte[] aad = "header-context-data".getBytes(StandardCharsets.UTF_8);
AESCryptoModuleExtension enc = new AESCryptoModuleExtension();
enc.init("AES", "GCM", "NoPadding", IV_16, KEY_128, KEY_128);
AESCryptoModuleExtension dec = new AESCryptoModuleExtension();
dec.init("AES", "GCM", "NoPadding", IV_16, KEY_128, KEY_128);
byte[] encrypted = enc.encrypt(PLAIN, 0, PLAIN.length, aad);
byte[] decrypted = dec.decrypt(encrypted, 0, encrypted.length, aad);
assertArrayEquals(PLAIN, decrypted, "명시적 AAD로 암복호화 라운드트립이 성공해야 한다");
}
@Test
@DisplayName("6-2. GCM — AAD null이면 IV를 AAD로 사용하는 기본 동작")
void testGcm_nullAad_defaultIvAsAad() throws Exception {
AESCryptoModuleExtension enc = new AESCryptoModuleExtension();
enc.init("AES", "GCM", "NoPadding", IV_16, KEY_128, KEY_128);
AESCryptoModuleExtension dec = new AESCryptoModuleExtension();
dec.init("AES", "GCM", "NoPadding", IV_16, KEY_128, KEY_128);
// aad=null IV_16을 AAD로 사용 (기본 동작)
byte[] encrypted = enc.encrypt(PLAIN, 0, PLAIN.length, null);
byte[] decrypted = dec.decrypt(encrypted, 0, encrypted.length, null);
assertArrayEquals(PLAIN, decrypted, "AAD=null이면 IV를 AAD로 사용하는 기본 동작이어야 한다");
}
@Test
@DisplayName("6-3. GCM — encrypt(aad=null)과 encrypt() 결과가 복호화 상호 호환")
void testGcm_nullAadCompatibleWithNoAadMethod() throws Exception {
AESCryptoModuleExtension enc = new AESCryptoModuleExtension();
enc.init("AES", "GCM", "NoPadding", IV_16, KEY_128, KEY_128);
AESCryptoModuleExtension dec = new AESCryptoModuleExtension();
dec.init("AES", "GCM", "NoPadding", IV_16, KEY_128, KEY_128);
byte[] encryptedByNoArg = enc.encrypt(PLAIN, 0, PLAIN.length);
byte[] decryptedByNullAad = dec.decrypt(encryptedByNoArg, 0, encryptedByNoArg.length, null);
assertArrayEquals(PLAIN, decryptedByNullAad, "encrypt()와 decrypt(null)은 상호 호환되어야 한다");
}
@Test
@DisplayName("6-4. GCM — 다른 AAD로 복호화 시 인증 실패 예외")
void testGcm_wrongAad_throwsAuthException() throws Exception {
byte[] aad = "correct-aad-value".getBytes(StandardCharsets.UTF_8);
byte[] wrongAad = "wrong-aad-value!!".getBytes(StandardCharsets.UTF_8);
AESCryptoModuleExtension enc = new AESCryptoModuleExtension();
enc.init("AES", "GCM", "NoPadding", IV_16, KEY_128, KEY_128);
byte[] encrypted = enc.encrypt(PLAIN, 0, PLAIN.length, aad);
AESCryptoModuleExtension dec = new AESCryptoModuleExtension();
dec.init("AES", "GCM", "NoPadding", IV_16, KEY_128, KEY_128);
assertThrows(Exception.class,
() -> dec.decrypt(encrypted, 0, encrypted.length, wrongAad),
"잘못된 AAD로 GCM 복호화 시 인증 실패 예외가 발생해야 한다");
}
@Test
@DisplayName("6-5. GCM — AAD 있는 암호문을 AAD 없이(null IV) 복호화 시 인증 실패")
void testGcm_encryptedWithAad_decryptWithoutAad_fails() throws Exception {
byte[] aad = "must-have-aad".getBytes(StandardCharsets.UTF_8);
AESCryptoModuleExtension enc = new AESCryptoModuleExtension();
enc.init("AES", "GCM", "NoPadding", null, KEY_128, KEY_128);
byte[] encrypted = enc.encrypt(PLAIN, 0, PLAIN.length, aad);
AESCryptoModuleExtension dec = new AESCryptoModuleExtension();
dec.init("AES", "GCM", "NoPadding", null, KEY_128, KEY_128);
assertThrows(Exception.class,
() -> dec.decrypt(encrypted, 0, encrypted.length, null),
"AAD로 암호화된 데이터를 AAD 없이 복호화하면 예외가 발생해야 한다");
}
@Test
@DisplayName("6-6. CBC — AAD 파라미터는 무시되고 정상 동작")
void testCbc_aadIgnored_normalOperation() throws Exception {
byte[] aad = "ignored-in-cbc".getBytes(StandardCharsets.UTF_8);
AESCryptoModuleExtension ext = new AESCryptoModuleExtension();
ext.init("AES", "CBC", "PKCS5Padding", IV_16, KEY_128, KEY_128);
byte[] encrypted = ext.encrypt(PLAIN, 0, PLAIN.length, aad);
byte[] decrypted = ext.decrypt(encrypted, 0, encrypted.length, aad);
assertArrayEquals(PLAIN, decrypted, "CBC 모드에서 AAD는 무시되고 정상 암복호화되어야 한다");
}
// =========================================================================
// 7. 오프셋/길이 없는 편의 메서드
// =========================================================================
@Test
@DisplayName("7-1. CBC — encrypt(byte[]) / decrypt(byte[]) 라운드트립")
void testCbc_noOffsetEncryptDecrypt_roundTrip() throws Exception {
AESCryptoModuleExtension ext = new AESCryptoModuleExtension();
ext.init("AES", "CBC", "PKCS5Padding", IV_16, KEY_128, KEY_128);
byte[] encrypted = ext.encrypt(PLAIN);
byte[] decrypted = ext.decrypt(encrypted);
assertArrayEquals(PLAIN, decrypted);
}
@Test
@DisplayName("7-2. GCM — encrypt(byte[]) / decrypt(byte[]) 라운드트립")
void testGcm_noOffsetEncryptDecrypt_roundTrip() throws Exception {
AESCryptoModuleExtension ext = new AESCryptoModuleExtension();
ext.init("AES", "GCM", "NoPadding", IV_16, KEY_128, KEY_128);
byte[] encrypted = ext.encrypt(PLAIN);
byte[] decrypted = ext.decrypt(encrypted);
assertArrayEquals(PLAIN, decrypted);
}
@Test
@DisplayName("7-3. GCM — encrypt(byte[], aad) / decrypt(byte[], aad) 라운드트립")
void testGcm_noOffsetWithAad_roundTrip() throws Exception {
byte[] aad = "request-header-ctx".getBytes(StandardCharsets.UTF_8);
AESCryptoModuleExtension enc = new AESCryptoModuleExtension();
enc.init("AES", "GCM", "NoPadding", IV_16, KEY_128, KEY_128);
AESCryptoModuleExtension dec = new AESCryptoModuleExtension();
dec.init("AES", "GCM", "NoPadding", IV_16, KEY_128, KEY_128);
byte[] encrypted = enc.encrypt(PLAIN, aad);
byte[] decrypted = dec.decrypt(encrypted, aad);
assertArrayEquals(PLAIN, decrypted);
}
@Test
@DisplayName("7-4. CBC — encrypt(byte[], aad) 는 AAD 무시 후 정상 라운드트립")
void testCbc_noOffsetWithAad_aadIgnored() throws Exception {
byte[] aad = "ignored".getBytes(StandardCharsets.UTF_8);
AESCryptoModuleExtension ext = new AESCryptoModuleExtension();
ext.init("AES", "CBC", "PKCS5Padding", IV_16, KEY_128, KEY_128);
byte[] encrypted = ext.encrypt(PLAIN, aad);
byte[] decrypted = ext.decrypt(encrypted, aad);
assertArrayEquals(PLAIN, decrypted);
}
@Test
@DisplayName("7-5. encrypt(byte[])와 encrypt(src, 0, src.length) 결과 동일 — CBC")
void testCbc_noOffsetEquivalentToFullOffset() throws Exception {
AESCryptoModuleExtension ext1 = new AESCryptoModuleExtension();
ext1.init("AES", "CBC", "PKCS5Padding", IV_16, KEY_128, KEY_128);
AESCryptoModuleExtension ext2 = new AESCryptoModuleExtension();
ext2.init("AES", "CBC", "PKCS5Padding", IV_16, KEY_128, KEY_128);
byte[] enc1 = ext1.encrypt(PLAIN);
byte[] enc2 = ext2.encrypt(PLAIN, 0, PLAIN.length);
assertArrayEquals(enc1, enc2, "편의 메서드와 오프셋 메서드의 결과가 동일해야 한다");
}
}
@@ -0,0 +1,154 @@
package com.eactive.eai.common.security;
import static org.junit.jupiter.api.Assertions.*;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
/**
* ARIACryptoModuleExtension 단위 테스트
* BouncyCastle ARIA 암복호화 로직을 검증한다.
*/
@TestMethodOrder(MethodOrderer.DisplayName.class)
class ARIACryptoModuleExtensionTest {
private static final byte[] KEY_128 = "0123456789abcdef".getBytes(StandardCharsets.UTF_8);
private static final byte[] KEY_256 = "0123456789abcdef0123456789abcdef".getBytes(StandardCharsets.UTF_8);
private static final byte[] IV_16 = "abcdef0123456789".getBytes(StandardCharsets.UTF_8);
private static final byte[] PLAIN = "ARIA 암호화 테스트 평문입니다.".getBytes(StandardCharsets.UTF_8);
// =========================================================================
// 1. CBC 모드
// =========================================================================
@Test
@DisplayName("1-1. ARIA/CBC/PKCS5Padding 128bit — 암복호화 라운드트립")
void testCbc128_roundTrip() throws Exception {
ARIACryptoModuleExtension ext = new ARIACryptoModuleExtension();
ext.init("ARIA", "CBC", "PKCS5Padding", IV_16, KEY_128, KEY_128);
byte[] encrypted = ext.encrypt(PLAIN, 0, PLAIN.length);
byte[] decrypted = ext.decrypt(encrypted, 0, encrypted.length);
assertNotNull(encrypted);
assertFalse(Arrays.equals(PLAIN, encrypted), "암호문은 평문과 달라야 한다");
assertArrayEquals(PLAIN, decrypted, "복호화 결과가 원문과 일치해야 한다");
}
@Test
@DisplayName("1-2. ARIA/CBC/PKCS5Padding 256bit — 암복호화 라운드트립")
void testCbc256_roundTrip() throws Exception {
ARIACryptoModuleExtension ext = new ARIACryptoModuleExtension();
ext.init("ARIA", "CBC", "PKCS5Padding", IV_16, KEY_256, KEY_256);
byte[] encrypted = ext.encrypt(PLAIN, 0, PLAIN.length);
byte[] decrypted = ext.decrypt(encrypted, 0, encrypted.length);
assertArrayEquals(PLAIN, decrypted);
}
@Test
@DisplayName("1-3. ARIA/CBC — 암호화 결과는 블록 크기(16바이트)의 배수")
void testCbc_ciphertextIsMultipleOfBlockSize() throws Exception {
ARIACryptoModuleExtension ext = new ARIACryptoModuleExtension();
ext.init("ARIA", "CBC", "PKCS5Padding", IV_16, KEY_128, KEY_128);
byte[] encrypted = ext.encrypt(PLAIN, 0, PLAIN.length);
assertEquals(0, encrypted.length % 16, "ARIA CBC 암호문 길이는 16 바이트 배수여야 한다");
}
@Test
@DisplayName("1-4. ARIA/CBC — 다른 IV로 암호화 시 다른 암호문 생성")
void testCbc_differentIv_differentCiphertext() throws Exception {
byte[] iv2 = "9876543210fedcba".getBytes(StandardCharsets.UTF_8);
ARIACryptoModuleExtension ext1 = new ARIACryptoModuleExtension();
ext1.init("ARIA", "CBC", "PKCS5Padding", IV_16, KEY_128, KEY_128);
ARIACryptoModuleExtension ext2 = new ARIACryptoModuleExtension();
ext2.init("ARIA", "CBC", "PKCS5Padding", iv2, KEY_128, KEY_128);
byte[] enc1 = ext1.encrypt(PLAIN, 0, PLAIN.length);
byte[] enc2 = ext2.encrypt(PLAIN, 0, PLAIN.length);
assertFalse(Arrays.equals(enc1, enc2), "IV가 다르면 암호문도 달라야 한다");
}
@Test
@DisplayName("1-5. ARIA/CBC — 잘못된 키로 복호화 시 예외 발생")
void testCbc_wrongKeyThrowsException() throws Exception {
ARIACryptoModuleExtension encExt = new ARIACryptoModuleExtension();
encExt.init("ARIA", "CBC", "PKCS5Padding", IV_16, KEY_128, KEY_128);
byte[] encrypted = encExt.encrypt(PLAIN, 0, PLAIN.length);
byte[] wrongKey = "wrongkey12345678".getBytes(StandardCharsets.UTF_8);
ARIACryptoModuleExtension decExt = new ARIACryptoModuleExtension();
decExt.init("ARIA", "CBC", "PKCS5Padding", IV_16, wrongKey, wrongKey);
assertThrows(Exception.class, () -> decExt.decrypt(encrypted, 0, encrypted.length),
"잘못된 키로 복호화 시 예외가 발생해야 한다");
}
// =========================================================================
// 2. /복호화 분리
// =========================================================================
@Test
@DisplayName("2-1. init(alg, mode, pad, encKey, decKey) — IV null 편의 메서드")
void testInitWithoutIv() throws Exception {
ARIACryptoModuleExtension ext = new ARIACryptoModuleExtension();
// IV 없이 초기화 (null IvParameterSpec도 null CBC에서 예외)
assertThrows(Exception.class,
() -> ext.init("ARIA", "CBC", "PKCS5Padding", KEY_128, KEY_128),
"IV 없이 CBC 초기화 시 예외가 발생해야 한다");
}
// =========================================================================
// 3. 바이트 배열 오프셋/길이 encrypt/decrypt
// =========================================================================
@Test
@DisplayName("3-1. encrypt(src, sindex, slength, dst, dindex) — 버퍼 직접 지정 라운드트립")
void testEncryptDecryptWithBuffer() throws Exception {
ARIACryptoModuleExtension ext = new ARIACryptoModuleExtension();
ext.init("ARIA", "CBC", "PKCS5Padding", IV_16, KEY_128, KEY_128);
byte[] dst = new byte[256];
int encLen = ext.encrypt(PLAIN, 0, PLAIN.length, dst, 0);
byte[] decDst = new byte[256];
int decLen = ext.decrypt(dst, 0, encLen, decDst, 0);
assertArrayEquals(PLAIN, Arrays.copyOf(decDst, decLen));
}
// =========================================================================
// 4. BouncyCastle Provider 자동 등록
// =========================================================================
@Test
@DisplayName("4-1. 동일 평문을 여러 번 암호화 — 각각 새 인스턴스로 독립 처리")
void testMultipleInstances_independentEncryption() throws Exception {
ARIACryptoModuleExtension ext1 = new ARIACryptoModuleExtension();
ext1.init("ARIA", "CBC", "PKCS5Padding", IV_16, KEY_128, KEY_128);
ARIACryptoModuleExtension ext2 = new ARIACryptoModuleExtension();
ext2.init("ARIA", "CBC", "PKCS5Padding", IV_16, KEY_128, KEY_128);
byte[] enc1 = ext1.encrypt(PLAIN, 0, PLAIN.length);
byte[] enc2 = ext2.encrypt(PLAIN, 0, PLAIN.length);
// 같은 /IV 같은 암호문
assertArrayEquals(enc1, enc2, "동일 키/IV라면 암호문이 동일해야 한다");
// 각자 복호화
assertArrayEquals(PLAIN, ext1.decrypt(enc1, 0, enc1.length));
assertArrayEquals(PLAIN, ext2.decrypt(enc2, 0, enc2.length));
}
}
@@ -0,0 +1,391 @@
package com.eactive.eai.common.security;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
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.hsm.HsmCryptoService;
import com.eactive.eai.common.security.loader.CryptoModuleConfigLoader;
import com.eactive.eai.common.security.mapper.CryptoModuleConfigMapper;
import com.eactive.eai.common.util.ApplicationContextProvider;
import com.eactive.eai.data.entity.onl.security.CryptoModuleConfig;
/**
* CryptoModuleManager 단위 테스트
* DB / Spring 컨텍스트 없이 Mock으로 동작한다.
*/
@TestMethodOrder(MethodOrderer.DisplayName.class)
class CryptoModuleManagerTest {
private static final byte[] KEY_128 = "0123456789abcdef".getBytes(StandardCharsets.UTF_8);
private static final byte[] IV_16 = "abcdef0123456789".getBytes(StandardCharsets.UTF_8);
private static final String ENC_KEY_HEX = toHex(KEY_128);
private static final String IV_HEX = toHex(IV_16);
private static GenericApplicationContext ctx;
private static CryptoModuleConfigLoader mockLoader;
private static HsmCryptoService mockHsmCryptoService;
private static CryptoModuleManager manager;
@BeforeAll
static void setUpClass() throws Exception {
mockLoader = mock(CryptoModuleConfigLoader.class);
mockHsmCryptoService = mock(HsmCryptoService.class);
SecretKey masterKey = new SecretKeySpec(KEY_128, "AES");
when(mockHsmCryptoService.getSecretKey(anyString())).thenReturn(masterKey);
when(mockLoader.findAll()).thenReturn(Collections.emptyList());
Constructor<CryptoModuleManager> ctor = CryptoModuleManager.class.getDeclaredConstructor();
ctor.setAccessible(true);
manager = ctor.newInstance();
ctx = new GenericApplicationContext();
ctx.getBeanFactory().registerSingleton("cryptoModuleConfigLoader", mockLoader);
ctx.getBeanFactory().registerSingleton("hsmCryptoService", mockHsmCryptoService);
ctx.getBeanFactory().registerSingleton("cryptoModuleManager", manager);
ctx.getBeanFactory().registerSingleton("cryptoModuleConfigMapper", testMapper());
ctx.registerBeanDefinition("applicationContextProvider",
BeanDefinitionBuilder.genericBeanDefinition(ApplicationContextProvider.class)
.getBeanDefinition());
ctx.refresh();
manager.start();
}
@AfterAll
static void tearDownClass() {
if (ctx != null) ctx.close();
}
@BeforeEach
void resetMocks() {
reset(mockLoader);
when(mockLoader.findAll()).thenReturn(Collections.emptyList());
}
// =========================================================================
// 1. start / stop Lifecycle
// =========================================================================
@Test
@DisplayName("1-1. start() 후 isStarted() = true")
void testIsStarted() {
assertTrue(manager.isStarted());
}
// =========================================================================
// 2. STATIC createExtension
// =========================================================================
@Test
@DisplayName("2-1. STATIC AES/CBC — createExtension 반환 및 암복호화 동작")
void testCreateExtension_staticAesCbc_roundTrip() throws Exception {
CryptoModuleConfig config = buildStaticConfig("AES_CBC", "AES", "CBC", "PKCS5Padding");
when(mockLoader.findAll()).thenReturn(Arrays.asList(config));
reload();
byte[] plain = "테스트 평문".getBytes(StandardCharsets.UTF_8);
CryptoModuleExtension ext = manager.createExtension("AES_CBC");
byte[] encrypted = ext.encrypt(plain, 0, plain.length);
CryptoModuleExtension extDec = manager.createExtension("AES_CBC");
byte[] decrypted = extDec.decrypt(encrypted, 0, encrypted.length);
assertArrayEquals(plain, decrypted, "STATIC AES/CBC 암복호화 라운드트립 성공해야 한다");
}
@Test
@DisplayName("2-2. STATIC ARIA/CBC — createExtension 반환 및 암복호화 동작")
void testCreateExtension_staticAriaCbc_roundTrip() throws Exception {
CryptoModuleConfig config = buildStaticConfig("ARIA_CBC", "ARIA", "CBC", "PKCS5Padding");
when(mockLoader.findAll()).thenReturn(Arrays.asList(config));
reload();
byte[] plain = "ARIA 테스트".getBytes(StandardCharsets.UTF_8);
CryptoModuleExtension ext = manager.createExtension("ARIA_CBC");
byte[] encrypted = ext.encrypt(plain, 0, plain.length);
CryptoModuleExtension extDec = manager.createExtension("ARIA_CBC");
byte[] decrypted = extDec.decrypt(encrypted, 0, encrypted.length);
assertArrayEquals(plain, decrypted);
}
@Test
@DisplayName("2-3. 미등록 cryptoName — IllegalArgumentException")
void testCreateExtension_unknownName_throwsException() {
assertThrows(IllegalArgumentException.class,
() -> manager.createExtension("UNKNOWN_MODULE"),
"미등록 cryptoName은 IllegalArgumentException이어야 한다");
}
@Test
@DisplayName("2-4. use_yn=N 설정 — configMap 미등록")
void testLoadAll_disabledConfig_notRegistered() throws Exception {
CryptoModuleConfig config = buildStaticConfig("DISABLED_MOD", "AES", "CBC", "PKCS5Padding");
config.setUseYn("N");
when(mockLoader.findAll()).thenReturn(Arrays.asList(config));
reload();
assertThrows(IllegalArgumentException.class,
() -> manager.createExtension("DISABLED_MOD"),
"use_yn=N 설정은 로드되지 않아야 한다");
}
// =========================================================================
// 3. DYNAMIC createExtension with runtimeContext
// =========================================================================
@Test
@DisplayName("3-1. DYNAMIC AES/CBC — runtimeContext 전달 시 암복호화 동작")
void testCreateExtension_dynamicAesCbc_roundTrip() throws Exception {
CryptoModuleConfig config = buildDynamicConfig("DYN_AES_CBC", "AES", "CBC", "PKCS5Padding");
when(mockLoader.findAll()).thenReturn(Arrays.asList(config));
reload();
Map<String, String> ctx = new HashMap<>();
ctx.put("X-Api-Enc-Key", "clientKeyValue01");
byte[] plain = "DYNAMIC 키 테스트".getBytes(StandardCharsets.UTF_8);
CryptoModuleExtension ext = manager.createExtension("DYN_AES_CBC", ctx);
byte[] encrypted = ext.encrypt(plain, 0, plain.length);
CryptoModuleExtension extDec = manager.createExtension("DYN_AES_CBC", ctx);
byte[] decrypted = extDec.decrypt(encrypted, 0, encrypted.length);
assertArrayEquals(plain, decrypted, "DYNAMIC AES/CBC 암복호화 라운드트립 성공해야 한다");
}
@Test
@DisplayName("3-2. DYNAMIC — 동일 runtimeContext로 2회 호출 시 HSM은 1회만 호출 (캐시 적용)")
void testCreateExtension_dynamicCached_hsmCalledOnce() throws Exception {
CryptoModuleConfig config = buildDynamicConfig("DYN_CACHE", "AES", "CBC", "PKCS5Padding");
when(mockLoader.findAll()).thenReturn(Arrays.asList(config));
reload();
Map<String, String> runtimeCtx = new HashMap<>();
runtimeCtx.put("X-Api-Enc-Key", "cachedKeyValue01");
manager.createExtension("DYN_CACHE", runtimeCtx);
manager.createExtension("DYN_CACHE", runtimeCtx);
verify(mockHsmCryptoService, times(1)).getSecretKey(anyString());
}
@Test
@DisplayName("3-3. DYNAMIC — 잘못된 전략 FQCN — IllegalArgumentException")
void testCreateExtension_invalidStrategyFqcn_throwsException() throws Exception {
CryptoModuleConfig config = buildDynamicConfig("DYN_BAD_FQCN", "AES", "CBC", "PKCS5Padding");
config.setKeyDerivStrategy("com.example.NonExistentStrategy");
when(mockLoader.findAll()).thenReturn(Arrays.asList(config));
reload();
Map<String, String> runtimeCtx = new HashMap<>();
runtimeCtx.put("X-Api-Enc-Key", "clientKeyValue01");
assertThrows(IllegalArgumentException.class,
() -> manager.createExtension("DYN_BAD_FQCN", runtimeCtx),
"존재하지 않는 FQCN이면 IllegalArgumentException이 발생해야 한다");
}
@Test
@DisplayName("3-4. DYNAMIC — 동일 FQCN 반복 호출 시 strategyCache에서 재사용")
void testCreateExtension_sameFqcn_strategyCacheReused() throws Exception {
CryptoModuleConfig config = buildDynamicConfig("DYN_CACHE_STRAT", "AES", "CBC", "PKCS5Padding");
when(mockLoader.findAll()).thenReturn(Arrays.asList(config));
reload();
Map<String, String> runtimeCtx = new HashMap<>();
runtimeCtx.put("X-Api-Enc-Key", "clientKeyValue01");
manager.createExtension("DYN_CACHE_STRAT", runtimeCtx);
manager.createExtension("DYN_CACHE_STRAT", runtimeCtx);
Field stratCacheField = CryptoModuleManager.class.getDeclaredField("strategyCache");
stratCacheField.setAccessible(true);
Map<?, ?> stratCache = (Map<?, ?>) stratCacheField.get(manager);
assertEquals(1, stratCache.size(), "동일 FQCN은 strategyCache에 하나만 존재해야 한다");
}
@Test
@DisplayName("3-5. DYNAMIC — 다른 runtimeContext 값은 다른 키 도출 (동적 키 캐시 미사용)")
void testCreateExtension_dynamicDifferentContext_differentKey() throws Exception {
CryptoModuleConfig config = buildDynamicConfig("DYN_DIFF", "AES", "CBC", "PKCS5Padding");
when(mockLoader.findAll()).thenReturn(Arrays.asList(config));
reload();
Map<String, String> ctx1 = new HashMap<>();
ctx1.put("X-Api-Enc-Key", "keyValueAAA00001");
Map<String, String> ctx2 = new HashMap<>();
ctx2.put("X-Api-Enc-Key", "keyValueBBB00001");
manager.createExtension("DYN_DIFF", ctx1);
manager.createExtension("DYN_DIFF", ctx2);
// 컨텍스트 값이 달라 동적 캐시 미사용 HSM 2회 호출
verify(mockHsmCryptoService, times(2)).getSecretKey(anyString());
}
// =========================================================================
// 4. reload
// =========================================================================
@Test
@DisplayName("4-1. reload(cryptoId) — 변경된 설정 반영")
void testReload_specificId_configUpdated() throws Exception {
CryptoModuleConfig config = buildStaticConfig("RELOAD_MOD", "AES", "CBC", "PKCS5Padding");
config.setCryptoId("reload-id-001");
when(mockLoader.findAll()).thenReturn(Arrays.asList(config));
reload();
CryptoModuleConfig updated = buildStaticConfig("RELOAD_MOD", "ARIA", "CBC", "PKCS5Padding");
updated.setCryptoId("reload-id-001");
when(mockLoader.findById("reload-id-001")).thenReturn(Optional.of(updated));
manager.reload("reload-id-001");
// 변경된 설정(ARIA)으로 암복호화 가능한지 확인
byte[] plain = "리로드 테스트".getBytes(StandardCharsets.UTF_8);
CryptoModuleExtension ext = manager.createExtension("RELOAD_MOD");
assertNotNull(ext);
}
@Test
@DisplayName("4-2. reload(cryptoId) use_yn=N — configMap에서 제거")
void testReload_specificId_disabled_removedFromMap() throws Exception {
CryptoModuleConfig config = buildStaticConfig("RM_MOD", "AES", "CBC", "PKCS5Padding");
config.setCryptoId("rm-id-001");
when(mockLoader.findAll()).thenReturn(Arrays.asList(config));
reload();
CryptoModuleConfig disabled = buildStaticConfig("RM_MOD", "AES", "CBC", "PKCS5Padding");
disabled.setCryptoId("rm-id-001");
disabled.setUseYn("N");
when(mockLoader.findById("rm-id-001")).thenReturn(Optional.of(disabled));
manager.reload("rm-id-001");
assertThrows(IllegalArgumentException.class,
() -> manager.createExtension("RM_MOD"),
"비활성화된 모듈은 configMap에서 제거되어야 한다");
}
// =========================================================================
// 헬퍼
// =========================================================================
private void reload() throws Exception {
clearField("configMap");
clearField("dynamicKeyCache");
clearField("strategyCache");
Method loadAll = CryptoModuleManager.class.getDeclaredMethod("loadAll");
loadAll.setAccessible(true);
loadAll.invoke(manager);
reset(mockHsmCryptoService);
SecretKey masterKey = new SecretKeySpec(KEY_128, "AES");
when(mockHsmCryptoService.getSecretKey(anyString())).thenReturn(masterKey);
}
private void clearField(String fieldName) throws Exception {
Field field = CryptoModuleManager.class.getDeclaredField(fieldName);
field.setAccessible(true);
((Map<?, ?>) field.get(manager)).clear();
}
private CryptoModuleConfig buildStaticConfig(String name, String alg, String mode, String padding) {
CryptoModuleConfig c = new CryptoModuleConfig();
c.setCryptoId(java.util.UUID.randomUUID().toString());
c.setCryptoName(name);
c.setAlgType(alg);
c.setCipherMode(mode);
c.setPadding(padding);
c.setIvHex(IV_HEX);
c.setKeySourceType("STATIC");
c.setEncKeyHex(ENC_KEY_HEX);
c.setDecKeyHex(ENC_KEY_HEX);
c.setCacheYn("Y");
c.setCacheTtlSec(300);
c.setUseYn("Y");
return c;
}
private CryptoModuleConfig buildDynamicConfig(String name, String alg, String mode, String padding) {
CryptoModuleConfig c = new CryptoModuleConfig();
c.setCryptoId(java.util.UUID.randomUUID().toString());
c.setCryptoName(name);
c.setAlgType(alg);
c.setCipherMode(mode);
c.setPadding(padding);
c.setIvHex(IV_HEX);
c.setKeySourceType("DYNAMIC");
c.setKeyDerivStrategy("com.eactive.eai.common.security.keyderiv.strategy.HsmContextXorKeyDerivationStrategy");
c.setKeyDerivParams("{\"hsmKeyAlias\":\"MASTER_KEY\",\"contextKey\":\"X-Api-Enc-Key\",\"offset\":\"0\",\"length\":\"16\"}");
c.setCacheYn("Y");
c.setCacheTtlSec(300);
c.setUseYn("Y");
return c;
}
private static String toHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) sb.append(String.format("%02x", b));
return sb.toString();
}
/** MapStruct APT 없이도 동작하는 인라인 매퍼 구현체 */
private static CryptoModuleConfigMapper testMapper() {
return new CryptoModuleConfigMapper() {
@Override
public CryptoModuleConfigVO toVo(CryptoModuleConfig e) {
CryptoModuleConfigVO vo = new CryptoModuleConfigVO();
vo.setCryptoId(e.getCryptoId());
vo.setCryptoName(e.getCryptoName());
vo.setCryptoDesc(e.getCryptoDesc());
vo.setAlgType(e.getAlgType());
vo.setCipherMode(e.getCipherMode());
vo.setPadding(e.getPadding());
vo.setIvHex(e.getIvHex());
vo.setKeySourceType(e.getKeySourceType());
vo.setEncKeyHex(e.getEncKeyHex());
vo.setDecKeyHex(e.getDecKeyHex());
vo.setKeyDerivStrategy(e.getKeyDerivStrategy());
vo.setKeyDerivParams(e.getKeyDerivParams());
vo.setCacheYn(e.getCacheYn());
vo.setCacheTtlSec(e.getCacheTtlSec());
vo.setUseYn(e.getUseYn());
return vo;
}
@Override
public CryptoModuleConfig toEntity(CryptoModuleConfigVO vo) {
return null;
}
};
}
}
@@ -0,0 +1,292 @@
package com.eactive.eai.common.security;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.lang.reflect.Constructor;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
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.loader.CryptoModuleConfigLoader;
import com.eactive.eai.common.security.mapper.CryptoModuleConfigMapper;
import com.eactive.eai.common.util.ApplicationContextProvider;
import com.eactive.eai.data.entity.onl.security.CryptoModuleConfig;
/**
* CryptoModuleService 단위 테스트
* CryptoModuleManager를 통한 암복호화 진입점 전체 흐름을 검증한다.
*/
@TestMethodOrder(MethodOrderer.DisplayName.class)
class CryptoModuleServiceTest {
private static final byte[] KEY_128 = "0123456789abcdef".getBytes(StandardCharsets.UTF_8);
private static final byte[] IV_16 = "abcdef0123456789".getBytes(StandardCharsets.UTF_8);
private static final String ENC_KEY_HEX = toHex(KEY_128);
private static final String IV_HEX = toHex(IV_16);
private static GenericApplicationContext ctx;
private static CryptoModuleManager manager;
private static CryptoModuleService service;
private static CryptoModuleConfigLoader mockLoader;
private static HsmCryptoService mockHsm;
@BeforeAll
static void setUpClass() throws Exception {
mockLoader = mock(CryptoModuleConfigLoader.class);
mockHsm = mock(HsmCryptoService.class);
SecretKey masterKey = new SecretKeySpec(KEY_128, "AES");
when(mockHsm.getSecretKey(anyString())).thenReturn(masterKey);
CryptoModuleConfig aes = buildStatic("AES_SVC", "AES", "CBC", "PKCS5Padding");
CryptoModuleConfig aria = buildStatic("ARIA_SVC", "ARIA", "CBC", "PKCS5Padding");
CryptoModuleConfig ecb = buildStaticNoIv("AES_ECB_SVC", "AES", "ECB", "NoPadding");
CryptoModuleConfig dyn = buildDynamic("DYN_SVC", "AES", "CBC", "PKCS5Padding");
when(mockLoader.findAll()).thenReturn(Arrays.asList(aes, aria, ecb, dyn));
Constructor<CryptoModuleManager> ctor = CryptoModuleManager.class.getDeclaredConstructor();
ctor.setAccessible(true);
manager = ctor.newInstance();
service = new CryptoModuleService();
ctx = new GenericApplicationContext();
ctx.getBeanFactory().registerSingleton("cryptoModuleConfigLoader", mockLoader);
ctx.getBeanFactory().registerSingleton("hsmCryptoService", mockHsm);
ctx.getBeanFactory().registerSingleton("cryptoModuleManager", manager);
ctx.getBeanFactory().registerSingleton("cryptoModuleService", service);
ctx.getBeanFactory().registerSingleton("cryptoModuleConfigMapper", testMapper());
ctx.registerBeanDefinition("applicationContextProvider",
BeanDefinitionBuilder.genericBeanDefinition(ApplicationContextProvider.class)
.getBeanDefinition());
ctx.refresh();
manager.start();
}
@AfterAll
static void tearDownClass() {
if (ctx != null) ctx.close();
}
// =========================================================================
// 1. STATIC encrypt / decrypt
// =========================================================================
@Test
@DisplayName("1-1. STATIC AES/CBC — encrypt → decrypt 라운드트립")
void testStaticAes_encryptDecrypt() throws Exception {
byte[] plain = "CryptoModuleService AES 테스트".getBytes(StandardCharsets.UTF_8);
byte[] encrypted = service.encrypt("AES_SVC", plain);
byte[] decrypted = service.decrypt("AES_SVC", encrypted);
assertArrayEquals(plain, decrypted);
}
@Test
@DisplayName("1-2. STATIC ARIA/CBC — encrypt → decrypt 라운드트립")
void testStaticAria_encryptDecrypt() throws Exception {
byte[] plain = "CryptoModuleService ARIA 테스트".getBytes(StandardCharsets.UTF_8);
byte[] encrypted = service.encrypt("ARIA_SVC", plain);
byte[] decrypted = service.decrypt("ARIA_SVC", encrypted);
assertArrayEquals(plain, decrypted);
}
@Test
@DisplayName("1-3. 암호문은 평문과 다른 바이트 배열")
void testEncrypt_ciphertextDiffersFromPlaintext() throws Exception {
byte[] plain = "평문입니다.".getBytes(StandardCharsets.UTF_8);
byte[] encrypted = service.encrypt("AES_SVC", plain);
assertFalse(java.util.Arrays.equals(plain, encrypted));
}
@Test
@DisplayName("1-4. 미등록 모듈명 — IllegalArgumentException")
void testEncrypt_unknownModule_throwsException() {
byte[] plain = "test".getBytes(StandardCharsets.UTF_8);
assertThrows(IllegalArgumentException.class,
() -> service.encrypt("UNKNOWN_SVC", plain));
}
// =========================================================================
// 2. DYNAMIC encrypt / decrypt
// =========================================================================
@Test
@DisplayName("2-1. DYNAMIC AES/CBC — runtimeContext 전달 encrypt → decrypt 라운드트립")
void testDynamicAes_encryptDecrypt() throws Exception {
Map<String, String> runtimeCtx = new HashMap<>();
runtimeCtx.put("X-Api-Enc-Key", "clientKey0000001");
byte[] plain = "DYNAMIC 키 서비스 테스트".getBytes(StandardCharsets.UTF_8);
byte[] encrypted = service.encrypt("DYN_SVC", runtimeCtx, plain);
byte[] decrypted = service.decrypt("DYN_SVC", runtimeCtx, encrypted);
assertArrayEquals(plain, decrypted);
}
@Test
@DisplayName("2-2. DYNAMIC — 다른 runtimeContext 값으로 복호화 시 실패")
void testDynamic_differentContext_decryptFails() throws Exception {
Map<String, String> encCtx = new HashMap<>();
encCtx.put("X-Api-Enc-Key", "encryptKeyValue0");
Map<String, String> decCtx = new HashMap<>();
decCtx.put("X-Api-Enc-Key", "differentKeyVal0");
byte[] plain = "키불일치 테스트".getBytes(StandardCharsets.UTF_8);
byte[] encrypted = service.encrypt("DYN_SVC", encCtx, plain);
assertThrows(Exception.class,
() -> service.decrypt("DYN_SVC", decCtx, encrypted),
"다른 컨텍스트 키로 복호화 시 예외가 발생해야 한다");
}
// =========================================================================
// 3. AES/ECB/NoPadding
// =========================================================================
@Test
@DisplayName("3-1. AES/ECB/NoPadding — 16바이트 평문 encrypt → decrypt 라운드트립")
void testEcb_encryptDecrypt_exactBlock() throws Exception {
byte[] plain = "ExactSixteenByte".getBytes(StandardCharsets.UTF_8); // 정확히 16바이트
byte[] encrypted = service.encrypt("AES_ECB_SVC", plain);
byte[] decrypted = service.decrypt("AES_ECB_SVC", encrypted);
assertArrayEquals(plain, decrypted);
}
@Test
@DisplayName("3-2. AES/ECB/NoPadding — 동일 평문은 항상 동일 암호문 (ECB 특성)")
void testEcb_deterministicOutput() throws Exception {
byte[] plain = "ExactSixteenByte".getBytes(StandardCharsets.UTF_8);
byte[] enc1 = service.encrypt("AES_ECB_SVC", plain);
byte[] enc2 = service.encrypt("AES_ECB_SVC", plain);
assertArrayEquals(enc1, enc2, "ECB는 IV 없으므로 동일 평문 → 동일 암호문");
}
@Test
@DisplayName("3-3. AES/ECB/NoPadding — 16 배수 아닌 평문 → 예외")
void testEcb_nonBlockAligned_throwsException() {
byte[] plain = "NotSixteenBytes!X".getBytes(StandardCharsets.UTF_8); // 17바이트
assertThrows(Exception.class,
() -> service.encrypt("AES_ECB_SVC", plain),
"NoPadding 모드에서 블록 크기 미정렬 평문은 예외가 발생해야 한다");
}
// =========================================================================
// 헬퍼
// =========================================================================
private static CryptoModuleConfig buildStatic(String name, String alg, String mode, String padding) {
CryptoModuleConfig c = new CryptoModuleConfig();
c.setCryptoId(UUID.randomUUID().toString());
c.setCryptoName(name);
c.setAlgType(alg);
c.setCipherMode(mode);
c.setPadding(padding);
c.setIvHex(IV_HEX);
c.setKeySourceType("STATIC");
c.setEncKeyHex(ENC_KEY_HEX);
c.setDecKeyHex(ENC_KEY_HEX);
c.setCacheYn("Y");
c.setCacheTtlSec(300);
c.setUseYn("Y");
return c;
}
private static CryptoModuleConfig buildStaticNoIv(String name, String alg, String mode, String padding) {
CryptoModuleConfig c = new CryptoModuleConfig();
c.setCryptoId(UUID.randomUUID().toString());
c.setCryptoName(name);
c.setAlgType(alg);
c.setCipherMode(mode);
c.setPadding(padding);
c.setKeySourceType("STATIC");
c.setEncKeyHex(ENC_KEY_HEX);
c.setDecKeyHex(ENC_KEY_HEX);
c.setCacheYn("Y");
c.setCacheTtlSec(300);
c.setUseYn("Y");
return c;
}
private static CryptoModuleConfig buildDynamic(String name, String alg, String mode, String padding) {
CryptoModuleConfig c = new CryptoModuleConfig();
c.setCryptoId(UUID.randomUUID().toString());
c.setCryptoName(name);
c.setAlgType(alg);
c.setCipherMode(mode);
c.setPadding(padding);
c.setIvHex(IV_HEX);
c.setKeySourceType("DYNAMIC");
c.setKeyDerivStrategy("com.eactive.eai.common.security.keyderiv.strategy.HsmContextXorKeyDerivationStrategy");
c.setKeyDerivParams("{\"hsmKeyAlias\":\"MASTER_KEY\",\"contextKey\":\"X-Api-Enc-Key\",\"offset\":\"0\",\"length\":\"16\"}");
c.setCacheYn("Y");
c.setCacheTtlSec(300);
c.setUseYn("Y");
return c;
}
private static String toHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) sb.append(String.format("%02x", b));
return sb.toString();
}
/** MapStruct APT 없이도 동작하는 인라인 매퍼 구현체 */
private static CryptoModuleConfigMapper testMapper() {
return new CryptoModuleConfigMapper() {
@Override
public CryptoModuleConfigVO toVo(CryptoModuleConfig e) {
CryptoModuleConfigVO vo = new CryptoModuleConfigVO();
vo.setCryptoId(e.getCryptoId());
vo.setCryptoName(e.getCryptoName());
vo.setCryptoDesc(e.getCryptoDesc());
vo.setAlgType(e.getAlgType());
vo.setCipherMode(e.getCipherMode());
vo.setPadding(e.getPadding());
vo.setIvHex(e.getIvHex());
vo.setKeySourceType(e.getKeySourceType());
vo.setEncKeyHex(e.getEncKeyHex());
vo.setDecKeyHex(e.getDecKeyHex());
vo.setKeyDerivStrategy(e.getKeyDerivStrategy());
vo.setKeyDerivParams(e.getKeyDerivParams());
vo.setCacheYn(e.getCacheYn());
vo.setCacheTtlSec(e.getCacheTtlSec());
vo.setUseYn(e.getUseYn());
return vo;
}
@Override
public CryptoModuleConfig toEntity(CryptoModuleConfigVO vo) {
return null;
}
};
}
}
@@ -0,0 +1,39 @@
package com.eactive.eai.common.security.keyderiv;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class DerivedKeyTest {
@Test
@DisplayName("1-1. encKey/decKey 모두 지정 — 각각 독립적으로 반환")
void testBothKeysProvided() {
byte[] encKey = {1, 2, 3};
byte[] decKey = {4, 5, 6};
DerivedKey dk = new DerivedKey(encKey, decKey);
assertArrayEquals(encKey, dk.getEncKey());
assertArrayEquals(decKey, dk.getDecKey());
}
@Test
@DisplayName("1-2. decKey null — encKey로 대체")
void testNullDecKey_fallsBackToEncKey() {
byte[] encKey = {1, 2, 3};
DerivedKey dk = new DerivedKey(encKey, null);
assertArrayEquals(encKey, dk.getEncKey());
assertArrayEquals(encKey, dk.getDecKey(), "decKey가 null이면 encKey와 동일해야 한다");
}
@Test
@DisplayName("1-3. 대칭 알고리즘 — encKey == decKey 동일 참조 허용")
void testSymmetricKey_sameReference() {
byte[] key = {0x10, 0x20, 0x30};
DerivedKey dk = new DerivedKey(key, key);
assertSame(dk.getEncKey(), dk.getDecKey());
}
}
@@ -0,0 +1,192 @@
package com.eactive.eai.common.security.keyderiv;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
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.strategy.HsmContextXorKeyDerivationStrategy;
import com.eactive.eai.common.util.ApplicationContextProvider;
/**
* HsmContextXorKeyDerivationStrategy 단위 테스트
* HsmCryptoService는 Mockito Mock으로 대체한다.
*/
@TestMethodOrder(MethodOrderer.DisplayName.class)
class HsmContextXorKeyDerivationStrategyTest {
private static final String HSM_KEY_ALIAS = "MASTER_KEY_AES";
private static final byte[] MASTER_KEY = "0123456789abcdef".getBytes(java.nio.charset.StandardCharsets.UTF_8);
private static GenericApplicationContext ctx;
private static HsmCryptoService mockHsmCryptoService;
private static HsmContextXorKeyDerivationStrategy 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 HsmContextXorKeyDerivationStrategy();
}
@BeforeEach
void setUpParams() {
params = new HashMap<>();
params.put("hsmKeyAlias", HSM_KEY_ALIAS);
params.put("contextKey", "X-Api-Enc-Key");
params.put("offset", "0");
params.put("length", "16");
runtimeContext = new HashMap<>();
runtimeContext.put("X-Api-Enc-Key", "clientKeyValue01");
}
// =========================================================================
// 1. deriveKey
// =========================================================================
@Test
@DisplayName("1-1. 정상 파라미터 — DerivedKey 반환")
void testDeriveKey_validParams_returnsDerivedKey() throws Exception {
DerivedKey dk = strategy.deriveKey(params, runtimeContext);
assertNotNull(dk);
assertNotNull(dk.getEncKey());
assertNotNull(dk.getDecKey());
assertEquals(16, dk.getEncKey().length, "도출된 키 길이는 마스터키 길이(16)여야 한다");
}
@Test
@DisplayName("1-2. XOR 계산 결과 검증")
void testDeriveKey_xorResultIsCorrect() throws Exception {
DerivedKey dk = strategy.deriveKey(params, runtimeContext);
byte[] contextBytes = "clientKeyValue01".getBytes(java.nio.charset.StandardCharsets.UTF_8);
byte[] expected = new byte[MASTER_KEY.length];
for (int i = 0; i < MASTER_KEY.length; i++) {
expected[i] = (i < contextBytes.length)
? (byte) (MASTER_KEY[i] ^ contextBytes[i])
: MASTER_KEY[i];
}
assertArrayEquals(expected, dk.getEncKey(), "XOR 계산 결과가 일치해야 한다");
}
@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 값 없음 — 빈 문자열로 처리 (XOR 불변)")
void testDeriveKey_missingContextValue_noXorChange() throws Exception {
runtimeContext.remove("X-Api-Enc-Key");
DerivedKey dk = strategy.deriveKey(params, runtimeContext);
assertArrayEquals(MASTER_KEY, dk.getEncKey(), "컨텍스트 값이 없으면 마스터키 그대로 반환되어야 한다");
}
@Test
@DisplayName("1-5. offset 지정 — 해당 위치부터 XOR 적용")
void testDeriveKey_withOffset() throws Exception {
params.put("offset", "4");
params.put("length", "8");
runtimeContext.put("X-Api-Enc-Key", "01234567890abcde");
DerivedKey dk = strategy.deriveKey(params, runtimeContext);
assertNotNull(dk);
assertEquals(MASTER_KEY.length, dk.getEncKey().length);
}
@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이 발생해야 한다");
}
@Test
@DisplayName("1-8. 다른 runtimeContext 값 — 다른 DerivedKey 생성")
void testDeriveKey_differentContextValue_differentKey() throws Exception {
DerivedKey dk1 = strategy.deriveKey(params, runtimeContext);
runtimeContext.put("X-Api-Enc-Key", "differentValue00");
DerivedKey dk2 = strategy.deriveKey(params, runtimeContext);
assertFalse(java.util.Arrays.equals(dk1.getEncKey(), dk2.getEncKey()),
"컨텍스트 값이 다르면 도출된 키도 달라야 한다");
}
// =========================================================================
// 2. buildCacheKey
// =========================================================================
@Test
@DisplayName("2-1. buildCacheKey — cryptoName:contextValue 형식")
void testBuildCacheKey_format() {
String cacheKey = strategy.buildCacheKey("CRYPTO_A", params, runtimeContext);
assertEquals("CRYPTO_A:clientKeyValue01", cacheKey);
}
@Test
@DisplayName("2-2. buildCacheKey — contextKey 값 없으면 빈 문자열")
void testBuildCacheKey_missingContextValue_emptyString() {
runtimeContext.remove("X-Api-Enc-Key");
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);
}
}
@@ -1,197 +0,0 @@
package com.eactive.eai.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.DualBucket;
import com.eactive.eai.common.inflow.dual.DualCustomBucket;
import com.eactive.eai.common.server.EAIServerManager;
import com.eactive.eai.common.util.ApplicationContextProvider;
/**
* DualRequestProcessor 단위 테스트.
*
* <p>RequestProcessor 클래스는 static 초기화 블록에서 EAIServerManager.getInstance() 호출한다.
* @BeforeAll에서 mock ApplicationContext를 주입한 DualRequestProcessor를 최초 로딩시킨다.
*
* <p>주의: DualRequestProcessor를 필드 타입으로 선언하면 테스트 클래스 로딩 함께 로딩되어
* @BeforeAll 실행 전에 NPE가 발생한다. 반드시 메서드 본문 내에서만 참조해야 한다.
*/
class DualRequestProcessorTest {
@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() {
DualRequestProcessor processor = new DualRequestProcessor();
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() {
DualRequestProcessor processor = new DualRequestProcessor();
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() {
DualRequestProcessor processor = new DualRequestProcessor();
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() {
DualRequestProcessor processor = new DualRequestProcessor();
Bucket mockBucket = mock(Bucket.class);
when(mockBucket.isAdapterPass("ADAPTER_A")).thenReturn(true);
assertNull(processor.checkAdapterInflow(mockBucket, "ADAPTER_A"));
}
@Test
void checkAdapterInflow_nonDualBucket_blocked_returnsBlocked() {
DualRequestProcessor processor = new DualRequestProcessor();
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() {
DualRequestProcessor processor = new DualRequestProcessor();
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() {
DualRequestProcessor processor = new DualRequestProcessor();
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() {
DualRequestProcessor processor = new DualRequestProcessor();
Bucket mockBucket = mock(Bucket.class);
when(mockBucket.isInterfacePass("IF_001")).thenReturn(true);
assertNull(processor.checkInterfaceInflow(mockBucket, "IF_001"));
}
@Test
void checkInterfaceInflow_nonDualBucket_blocked_returnsBlocked() {
DualRequestProcessor processor = new DualRequestProcessor();
Bucket mockBucket = mock(Bucket.class);
when(mockBucket.isInterfacePass("IF_001")).thenReturn(false);
assertEquals("BLOCKED", processor.checkInterfaceInflow(mockBucket, "IF_001"));
}
// -------------------------------------------------------------------------
// buildInflowTargetErrorMsg
// -------------------------------------------------------------------------
@Test
void buildInflowTargetErrorMsg_perSecond_includesReqPerSec() {
DualRequestProcessor processor = new DualRequestProcessor();
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() {
DualRequestProcessor processor = new DualRequestProcessor();
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() {
DualRequestProcessor processor = new DualRequestProcessor();
InflowTargetVO vo = makeVO("결제API", 30, 1000, "MIN");
String msg = processor.buildInflowTargetErrorMsg(vo, "BLOCKED");
assertEquals("API 호출 한도 초과 [결제API]", msg);
}
@Test
void buildInflowTargetErrorMsg_nullBlockedType_simpleFormat() {
DualRequestProcessor processor = new DualRequestProcessor();
InflowTargetVO vo = makeVO("결제API", 30, 1000, "MIN");
String msg = processor.buildInflowTargetErrorMsg(vo, null);
assertEquals("API 호출 한도 초과 [결제API]", msg);
}
@Test
void buildInflowTargetErrorMsg_hourUnit() {
DualRequestProcessor processor = new DualRequestProcessor();
InflowTargetVO vo = makeVO("조회API", 10, 500, "HOUR");
String msg = processor.buildInflowTargetErrorMsg(vo, DualCustomBucket.RESULT_BLOCKED_THRESHOLD);
assertEquals("API 호출 한도 초과 [조회API: 500req/HOUR]", msg);
}
}
@@ -1,2 +1,3 @@
INSERT INTO inflow_control_group (group_id, group_name, threshold, threshold_per_second, threshold_time_unit, use_yn) VALUES
('test-group-001', '테스트 그룹', 100, 10, 'MIN', '1');
('test-group-001', '테스트 그룹', 100, 10, 'MIN', '1'),
('test-group-quota', '쿼터전용 그룹', 5, 0, 'MIN', '1');
@@ -3,4 +3,6 @@ INSERT INTO tseaifr09 (type,name,threshold,useyn,thresholdpersecond,thresholdtim
('01','_AB0_IN_NET_AsS',3,'1',0,NULL),
('01','_TST_IN_NET_AsS',1,'1',0,NULL),
('02','FASSFEP00000004S2',10,'1',0,NULL),
('02','FDASFEP00000009S2',2,'1',0,NULL);
('02','FDASFEP00000009S2',2,'1',0,NULL),
('01','TEST_ADAPTER',5,'1',0,'MIN'),
('02','TEST_INTERFACE',5,'1',0,'MIN');