DJBank 암복호화필터 설계

- 기관별 InCryptoFilter를 상속한 필터 설계
- 기관별 OutCryptoFilter를 상송한 필터 설계
- 대상 기관 : 카카오뱅크, 카카오페이, 네이버Fn, 토스뱅크, 제주은행, DJErp
This commit is contained in:
curry772
2026-05-26 09:51:53 +09:00
parent 13608ebc8e
commit 1f285c3bfd
15 changed files with 321 additions and 403 deletions
@@ -1,317 +0,0 @@
package com.eactive.eai.custom.adapter.http.dynamic.filter;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
import java.util.Properties;
import org.mockito.ArgumentCaptor;
import javax.servlet.http.HttpServletRequest;
import org.json.simple.JSONObject;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.context.support.GenericApplicationContext;
import com.eactive.eai.common.security.CryptoModuleService;
import com.eactive.eai.common.util.ApplicationContextProvider;
@TestMethodOrder(MethodOrderer.DisplayName.class)
class DJBErpCryptoFilterTest {
private static final String MODULE_NAME = "TEST_MODULE";
// 복호화 후 평문 (JSON 문자열)
private static final String PLAIN_TEXT = "{\"userId\":\"U001\",\"name\":\"test\"}";
private static final byte[] PLAIN_BYTES = PLAIN_TEXT.getBytes(StandardCharsets.UTF_8);
// 더미 암호문 bytes + Base64 표현
private static final byte[] CIPHER_BYTES = new byte[]{0x10, 0x20, 0x30, 0x40};
private static final String ENC_BASE64 = Base64.getEncoder().encodeToString(CIPHER_BYTES);
// 기본 httpHeaderGroup 헤더 JSON (groupSeq|empNo 형태)
private static final String HEADER_JSON_WITH_PIPE = "{\"x-emp-nm\":\"G001|E001\"}";
private static final String HEADER_JSON_WITHOUT_PIPE = "{\"x-emp-nm\":\"G001\"}";
private static GenericApplicationContext ctx;
private static CryptoModuleService mockCryptoService;
private DJBErpCryptoFilter filter;
private HttpServletRequest mockRequest;
private Properties prop;
// =========================================================================
// 클래스 초기화 — Spring ApplicationContext + Mock CryptoModuleService
// =========================================================================
@BeforeAll
static void setUpClass() throws Exception {
mockCryptoService = mock(CryptoModuleService.class);
ctx = new GenericApplicationContext();
ctx.getBeanFactory().registerSingleton("cryptoModuleService", mockCryptoService);
ctx.registerBeanDefinition("applicationContextProvider",
BeanDefinitionBuilder.genericBeanDefinition(ApplicationContextProvider.class)
.getBeanDefinition());
ctx.refresh();
when(mockCryptoService.decrypt(anyString(), anyMap(), any(byte[].class)))
.thenReturn(PLAIN_BYTES);
when(mockCryptoService.encrypt(anyString(), anyMap(), any(byte[].class)))
.thenReturn(CIPHER_BYTES);
}
@AfterAll
static void tearDownClass() {
if (ctx != null) ctx.close();
}
@BeforeEach
void setUp() {
clearInvocations(mockCryptoService); // 이전 테스트의 호출 이력 초기화 (stubbing은 유지)
filter = new DJBErpCryptoFilter();
mockRequest = mock(HttpServletRequest.class);
prop = new Properties();
prop.setProperty(DJBErpCryptoFilter.PROP_MODULE_NAME, MODULE_NAME);
}
// =========================================================================
// 1. buildRuntimeContext
// =========================================================================
@Test
@DisplayName("1-1. x-emp-nm이 'groupSeq|empNo' 형태이면 '|' 앞부분만 groupSeq로 추출")
void buildRuntimeContext_pipeFormat_extractsGroupSeqOnly() {
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn(HEADER_JSON_WITH_PIPE);
Map<String, String> runtimeCtx = filter.buildRuntimeContext(prop, mockRequest);
assertEquals("G001", runtimeCtx.get("groupSeq"));
assertEquals(1, runtimeCtx.size());
}
@Test
@DisplayName("1-2. x-emp-nm에 '|'가 없으면 전체 값을 groupSeq로 사용")
void buildRuntimeContext_noPipe_usesFullValue() {
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn(HEADER_JSON_WITHOUT_PIPE);
Map<String, String> runtimeCtx = filter.buildRuntimeContext(prop, mockRequest);
assertEquals("G001", runtimeCtx.get("groupSeq"));
}
@Test
@DisplayName("1-3. httpHeaderGroup 헤더가 없으면 빈 Map 반환")
void buildRuntimeContext_headerMissing_returnsEmptyMap() {
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn(null);
Map<String, String> runtimeCtx = filter.buildRuntimeContext(prop, mockRequest);
assertTrue(runtimeCtx.isEmpty());
}
@Test
@DisplayName("1-4. 헤더 JSON에 x-emp-nm 필드가 없으면 빈 Map 반환")
void buildRuntimeContext_fieldMissingInJson_returnsEmptyMap() {
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn("{\"other-field\":\"value\"}");
Map<String, String> runtimeCtx = filter.buildRuntimeContext(prop, mockRequest);
assertTrue(runtimeCtx.isEmpty());
}
@Test
@DisplayName("1-5. 프로퍼티로 헤더명/필드명/컨텍스트키를 커스터마이징할 수 있다")
void buildRuntimeContext_customProps_overrideDefaults() {
prop.setProperty(DJBErpCryptoFilter.PROP_CONTEXT_HEADER, "X-Custom-Header");
prop.setProperty(DJBErpCryptoFilter.PROP_CONTEXT_HEADER_FIELD, "emp-id");
prop.setProperty(DJBErpCryptoFilter.PROP_CONTEXT_KEY, "empGroup");
when(mockRequest.getHeader("X-Custom-Header")).thenReturn("{\"emp-id\":\"GRP99|EMP99\"}");
Map<String, String> runtimeCtx = filter.buildRuntimeContext(prop, mockRequest);
assertEquals("GRP99", runtimeCtx.get("empGroup"));
}
// =========================================================================
// 2. doPreFilter — 복호화
// =========================================================================
@Test
@DisplayName("2-1. crypto.dec.enabled=N 이면 message를 그대로 반환하고 복호화하지 않는다")
void doPreFilter_decDisabled_returnsOriginalWithoutDecrypt() throws Exception {
prop.setProperty("crypto.dec.enabled", "N");
String original = "{\"encryptedData\":\"" + ENC_BASE64 + "\"}";
Object result = filter.doPreFilter(null, null, original, prop, mockRequest, null);
assertSame(original, result);
verifyNoInteractions(mockCryptoService);
}
@Test
@DisplayName("2-2. FIELD scope: /encryptedData 복호화 후 dec.to.path=/ 이면 body 전체를 평문으로 교체")
void doPreFilter_fieldScope_toRoot_replacesEntireBody() throws Exception {
setFieldDecryptProps("/encryptedData", "/");
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn(HEADER_JSON_WITH_PIPE);
String body = "{\"encryptedData\":\"" + ENC_BASE64 + "\"}";
Object result = filter.doPreFilter(null, null, body, prop, mockRequest, null);
assertEquals(PLAIN_TEXT, result);
}
@Test
@DisplayName("2-3. FIELD scope: dec.to.path가 특정 경로이면 해당 필드에 복호화 결과를 설정")
void doPreFilter_fieldScope_toSpecificPath_setsFieldInBody() throws Exception {
setFieldDecryptProps("/encryptedData", "/plainData");
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn(HEADER_JSON_WITH_PIPE);
String body = "{\"encryptedData\":\"" + ENC_BASE64 + "\"}";
String result = (String) filter.doPreFilter(null, null, body, prop, mockRequest, null);
assertTrue(result.contains("\"encryptedData\""), "원본 필드가 유지되어야 한다");
assertTrue(result.contains("\"plainData\""), "복호화 결과 필드가 추가되어야 한다");
}
@Test
@DisplayName("2-4. FIELD scope: 복호화 대상 필드가 JSON에 없으면 원본 body를 그대로 반환")
void doPreFilter_fieldScope_missingEncryptedField_returnsOriginalBody() throws Exception {
setFieldDecryptProps("/encryptedData", "/");
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn(HEADER_JSON_WITH_PIPE);
String body = "{\"otherField\":\"value\"}";
Object result = filter.doPreFilter(null, null, body, prop, mockRequest, null);
assertEquals(body, result);
}
@Test
@DisplayName("2-5. BODY scope: message가 Base64 String이면 전체 복호화")
void doPreFilter_bodyScope_stringMessage_decryptsWholeBody() throws Exception {
prop.setProperty("crypto.scope", "BODY");
Object result = filter.doPreFilter(null, null, ENC_BASE64, prop, mockRequest, null);
assertEquals(PLAIN_TEXT, result);
}
@Test
@DisplayName("2-6. message가 byte[]이면 UTF-8 변환 후 FIELD 복호화 처리")
void doPreFilter_fieldScope_byteArrayMessage_convertsAndDecrypts() throws Exception {
setFieldDecryptProps("/encryptedData", "/");
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn(HEADER_JSON_WITH_PIPE);
byte[] bodyBytes = ("{\"encryptedData\":\"" + ENC_BASE64 + "\"}").getBytes(StandardCharsets.UTF_8);
Object result = filter.doPreFilter(null, null, bodyBytes, prop, mockRequest, null);
assertEquals(PLAIN_TEXT, result);
}
@SuppressWarnings("unchecked")
@Test
@DisplayName("2-7. message가 JSONObject이면 toString() 변환 후 FIELD 복호화 처리")
void doPreFilter_fieldScope_jsonObjectMessage_convertsAndDecrypts() throws Exception {
setFieldDecryptProps("/encryptedData", "/");
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn(HEADER_JSON_WITH_PIPE);
JSONObject jsonMsg = new JSONObject();
jsonMsg.put("encryptedData", ENC_BASE64);
Object result = filter.doPreFilter(null, null, jsonMsg, prop, mockRequest, null);
assertEquals(PLAIN_TEXT, result);
}
@SuppressWarnings("unchecked")
@Test
@DisplayName("2-8. FIELD scope: runtimeContext에 groupSeq가 올바르게 전달된다")
void doPreFilter_fieldScope_runtimeContextPassedToDecrypt() throws Exception {
setFieldDecryptProps("/encryptedData", "/");
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn(HEADER_JSON_WITH_PIPE);
String body = "{\"encryptedData\":\"" + ENC_BASE64 + "\"}";
filter.doPreFilter(null, null, body, prop, mockRequest, null);
ArgumentCaptor<Map> ctxCaptor = ArgumentCaptor.forClass(Map.class);
verify(mockCryptoService).decrypt(eq(MODULE_NAME), ctxCaptor.capture(), any(byte[].class));
assertEquals("G001", ctxCaptor.getValue().get("groupSeq"));
}
// =========================================================================
// 3. doPostFilter — 암호화
// =========================================================================
@Test
@DisplayName("3-1. crypto.enc.enabled 기본값(N) — resultMessage를 그대로 반환하고 암호화하지 않는다")
void doPostFilter_encDisabledByDefault_returnsOriginalWithoutEncrypt() throws Exception {
String original = "{\"result\":\"ok\"}";
Object result = filter.doPostFilter(null, null, original, prop, mockRequest, null);
assertSame(original, result);
verifyNoInteractions(mockCryptoService);
}
@Test
@DisplayName("3-2. BODY scope, enc.enabled=Y — body 전체를 암호화하여 Base64 반환")
void doPostFilter_bodyScope_encEnabled_returnsBase64() throws Exception {
prop.setProperty("crypto.scope", "BODY");
prop.setProperty("crypto.enc.enabled", "Y");
Object result = filter.doPostFilter(null, null, PLAIN_TEXT, prop, mockRequest, null);
assertEquals(ENC_BASE64, result);
}
@Test
@DisplayName("3-3. FIELD scope, enc.from.path=/ — body 전체 암호화 후 enc.to.path 필드로 래핑")
void doPostFilter_fieldScope_fromRoot_wrapsEncryptedInJson() throws Exception {
prop.setProperty("crypto.scope", "FIELD");
prop.setProperty("crypto.enc.enabled", "Y");
prop.setProperty("crypto.enc.from.path", "/");
prop.setProperty("crypto.enc.to.path", "/encryptedData");
Object result = filter.doPostFilter(null, null, PLAIN_TEXT, prop, mockRequest, null);
assertEquals("{\"encryptedData\":\"" + ENC_BASE64 + "\"}", result);
}
@SuppressWarnings("unchecked")
@Test
@DisplayName("3-4. FIELD scope: runtimeContext에 groupSeq가 올바르게 전달된다")
void doPostFilter_fieldScope_runtimeContextPassedToEncrypt() throws Exception {
prop.setProperty("crypto.scope", "FIELD");
prop.setProperty("crypto.enc.enabled", "Y");
prop.setProperty("crypto.enc.from.path", "/");
prop.setProperty("crypto.enc.to.path", "/encryptedData");
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn(HEADER_JSON_WITH_PIPE);
filter.doPostFilter(null, null, PLAIN_TEXT, prop, mockRequest, null);
ArgumentCaptor<Map> ctxCaptor = ArgumentCaptor.forClass(Map.class);
verify(mockCryptoService).encrypt(eq(MODULE_NAME), ctxCaptor.capture(), any(byte[].class));
assertEquals("G001", ctxCaptor.getValue().get("groupSeq"));
}
// =========================================================================
// 헬퍼
// =========================================================================
private void setFieldDecryptProps(String fromPath, String toPath) {
prop.setProperty("crypto.scope", "FIELD");
prop.setProperty("crypto.dec.from.path", fromPath);
prop.setProperty("crypto.dec.to.path", toPath);
}
}