Compare commits

...

72 Commits

Author SHA1 Message Date
2bbda10eb5 261102_01_ENH: 요청 사용자 Context Provider 공용화 및 beta.1.7.1 버전 상향 2026-11-02 13:59:34 +09:00
59a4281cea 261016_01_ENH: ExcelRead에 읽기 전용으로 열기 추가 2026-10-16 10:01:20 +09:00
7cd170fe6e 261012_01_ENH: RequestUserContext Swagger 입력 숨김 처리 2026-10-12 17:17:09 +09:00
65e31079ac 261008_01_ENH: 외부 API 및 bypass 원본 오류 응답 전파 기능 추가 2026-10-08 10:58:29 +09:00
16dc89ac92 261006_01_DOC: 공용 백엔드 참조 문서 및 에이전트 스킬 정비 2026-10-06 10:19:15 +09:00
1adb692661 260916_01_ENH: 공통 암호화 및 해시 기능 추가 2026-09-16 12:30:30 +09:00
333709fbfc 260826_01_ENH: 하네스 관련 버전업 2026-08-26 12:27:40 +09:00
8fde2e84d3 docs: define backend project instruction budget 2026-08-26 10:11:31 +09:00
de800b79f1 chore: bump version to beta.1.6.4 2026-08-07 14:36:29 +09:00
ea3492d0d9 chore: refresh generated agent instructions 2026-08-06 15:14:46 +09:00
f08ecf4da0 260806_03_ENH: mutipart 한글 꺠짐 개선 2026-08-06 13:57:18 +09:00
e8888794c3 260806_02_ENH: 패키지가 생성되어 있길래 혹시몰라 버전 한번더 올림 2026-08-06 12:01:39 +09:00
0816878e60 260806_02_ENH: multipart 데이터 ascii -> utf-8로 변경 중 2026-08-06 11:57:21 +09:00
0d9f1ff196 260806_01_ENH: multipart 데이터 ascii -> utf-8로 변경 2026-08-06 11:13:29 +09:00
1ac8dab45a 260804_01_ENH: api key에 특정 경로 허용 제외 추가 2026-08-04 16:56:42 +09:00
2954565fc7 260722_01_ENH: pageable에 sort alias 추가 2026-07-22 11:19:48 +09:00
895eb13656 260720_01_ENH: API multipart 호출 post put 추가 2026-07-20 11:38:25 +09:00
0013636a88 260720_01_ENH: API multipart 호출 post put 추가 2026-07-20 11:38:04 +09:00
94ea2592a7 260710_01_ENH: API Bypass 기능 추가 2026-07-10 12:05:04 +09:00
68dba04fd6 260702_03_TST: 웹훅 토큰 변경 테스트 2026-07-02 10:08:45 +09:00
db1540cf06 260702_02_TST: 웹훅 토큰 변경 테스트 2026-07-02 10:03:36 +09:00
5b8d7a83d8 260702_01_TST: 웹훅 토큰 변경 테스트 2026-07-02 09:55:37 +09:00
83b098dc91 260701_01_ENH: IP 화이트 리스트 기능 추가 없으면 모든 IP허용 2026-07-01 14:03:33 +09:00
11eaca9197 260626_03_ENH: admin용 swagger 안뜨던 문제 수정 2026-06-26 15:52:25 +09:00
c36f53bd5f 260626_02_ENH: admin용 swagger 안뜨던 문제 수정 2026-06-26 15:37:49 +09:00
a921e2b97e 260626_01_ENH: admin용 swagger 안뜨던 문제 수정 2026-06-26 15:32:59 +09:00
2bd2f4415f 260612_05_ENH: 엑셀 날짜 값 읽는 부분 포맷 지정 2026-06-12 17:00:20 +09:00
42b2c0442f 260612_04_ENH: 엑셀 값 읽어오는 부분 수정(소수점 숫자) 2026-06-12 16:54:51 +09:00
0f17acf127 260612_03_ENH: 엑셀 값 읽어오는 부분 수정(날짜) 2026-06-12 16:51:57 +09:00
8f94e1c999 260612_02_ENH: 엑셀 값 읽어오는 부분 수정 2026-06-12 16:45:49 +09:00
2e194fb597 260612_01_ENH: length로 uuid 생성하는 유틸 추가 2026-06-12 10:54:06 +09:00
2439631e40 260610_01_ENH: 컬럼명으로 entity 접근하는 유틸 추가 2026-06-10 13:56:32 +09:00
94a8b31fa7 260605_03_ENH: 배포를 위해 버전업 2026-06-05 11:54:51 +09:00
8419d6a6d1 260605_02_ENH: 배포 자동화에서 버전 안바뀌면 배포 실패 처리 2026-06-05 11:53:18 +09:00
53785f520a 260605_01_ENH: gitea 웹훅을 적용하여 jenkins로 패키지 배포 자동화2 2026-06-05 11:29:05 +09:00
621679af58 260605_01_ENH: gitea 웹훅을 적용하여 jenkins로 패키지 배포 자동화 2026-06-05 11:25:39 +09:00
29b1fa1e97 260511_01_ENH: CollectionUtil 추가 2026-05-11 12:25:48 +09:00
e376eb3bd1 260429_01_ENH: StringUtil에 escape 메서드들 추가 2026-04-29 15:34:12 +09:00
a35bacc497 260421_03_ENH: 전체적으로 정리2 2026-04-21 14:20:24 +09:00
c90481b4d0 260421_02_ENH: 전체적으로 정리 2026-04-21 13:51:56 +09:00
b65c37d921 260421_01_ENH: Swagger를 대상으로 한 IP 필터링에 대한 중복처리 제거 2026-04-21 12:02:07 +09:00
5a8e26e6cf 260408_01_ENH: normalizeEmail 변경 2026-04-08 09:46:50 +09:00
687a2ebf82 260407_02_ENH: String, Numeric 유틸 추가 2026-04-07 15:33:46 +09:00
59f656b99b 260407_01_ENH: CodeEnum의 내용을 Swagger에 자동으로 표기하는 기능 추가 2026-04-07 10:08:06 +09:00
12b2b72121 260403_01_ENH: 엑셀 매퍼에 스트리밍 옵션 추가하고 기존의 오버로딩 메소드간 연관관계 끊음 2026-04-03 16:22:52 +09:00
7f7cdd4609 260327_04_ENH: 주입된 의존성 중 위험이 보고된 버전 수정 2026-03-27 14:22:55 +09:00
323d1177f5 260327_03_BUG: JWT 버전 충돌 해결 적용 2026-03-27 12:15:24 +09:00
e5bda3f8bd 260327_02_BUG: 리펙토링 중 생긴 버그 수정 2026-03-27 12:01:03 +09:00
905906b923 260327_01_ENH: 프로젝트 구조 리펙토링 및 README.md 갱신 2026-03-27 11:01:47 +09:00
e72d061e58 260320_02_ENH: 버전업 2026-03-20 09:51:39 +09:00
ccdc2e1fa3 260320_01_ENH: 스웨거 허용 IP 필터 추가 2026-03-20 09:50:47 +09:00
3d769724f7 260311_02_ENH: 버전 업 2026-03-11 11:05:51 +09:00
1f06f42687 260311_01_ENH: 엑셀 매퍼에 다중 시트, 시트 지정 추가 2026-03-11 11:05:32 +09:00
1e1b7bb5b7 Remove IDEA project files from git tracking 2026-03-11 11:04:57 +09:00
c1ec207911 260310_01_ENH: 엑셀 매퍼에 디스크에서 파일 stream read write 추가 2026-03-10 08:30:46 +09:00
03a368b120 260309_01_ENH: 엑셀 매퍼에 HeaderRow 지정 기능 추가 2026-03-09 16:24:02 +09:00
cca5a9b5be 260219_01_ENH: 유틸 분리 및 StringUtil 생성 2026-02-20 09:44:55 +09:00
5de2640c18 260212_02_ENH: API Key를 통한 인증도 claims에 정보를 넣도록 수정 2026-02-12 13:54:28 +09:00
88e9845c1c 260212_01_DOC: 프로젝트 전체에 구글 java 스타일 적용 2026-02-12 11:22:05 +09:00
bc5af86bcd 260210_03_ENH: Map, List 캐시 추상 클래스 일부 기능 보완 및 추가 2026-02-10 16:13:05 +09:00
d1965697d3 260210_01_ENH: Map, List 캐시 추상 클래스 추가 2026-02-10 15:08:06 +09:00
afeccdfc1e 260115_01_ENH : ExcelMapper에 Streaming Append Writer추가 2026-01-15 10:29:41 +09:00
5c6439743b 260109_01_ENH : PageRequest, PageResponse 이동, 유틸 생성, 코드 이넘 컨버터 추가 및 등록 2026-01-09 14:22:05 +09:00
6f6abdc385 251222_01_DOC : 중괄호 스타일 통일 2025-12-22 16:51:30 +09:00
838ba80828 251219_01_ENH : LenientLocalDateTime 커스텀 어노테이션 추가 2025-12-19 15:31:43 +09:00
a9207aa3e0 251218_01_ENH : API-KEY DB적재 및 로컬 캐싱 기능 추가 2025-12-18 11:50:35 +09:00
e3700aabff 251211_01_ENH : FileUtil 추가 2025-12-11 14:36:05 +09:00
cf50d427c4 251201_01_ENH : JWT 수정, RequestUserContext 추가, 엑셀 매퍼 및 유틸, Json 유틸, DateTime 유틸 추가 2025-12-01 16:56:24 +09:00
534380f6b2 251121_01_ENH : JWT 수정, CodeEnum 추가, API 통신 모듈 추가 2025-11-21 15:35:09 +09:00
2a35b62a48 251119_01_ENH : Junie로 소스코드 및 README 정리 2025-11-19 08:43:05 +09:00
e5501e1542 251117_02_ENH : Security, Swagger, MVC 기본 설정 추가 2025-11-17 15:33:48 +09:00
9f87ce586b 251117_02_ENH : 버전 업 2025-11-17 09:56:04 +09:00
147 changed files with 10699 additions and 1466 deletions

View File

@@ -0,0 +1,14 @@
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Contract: kri-common
Source: .agent/consumer-references/crypto-contract.md
-->
# KriCommon Crypto Contract
- Crypto APIs are under `com.kri.common.feature.crypto.*` and do not use a central key database.
- AES uses PBKDF2-HMAC-SHA256 key derivation with salt and defaults to AES-256-GCM; callers may supply a master key, salt, IV, AAD, and detached or appended GCM tag representation for legacy interoperability.
- `kri.crypto.aes.keys` and per-call master keys are supported operational compromises. Never log them or commit real values.
- Per-call key material takes precedence over configured keys, and encrypted values retain key ID and KDF metadata for decryption compatibility.
- AES-GCM always requires its authentication tag. Use `AES_256_CBC_PKCS5` only for explicitly identified legacy data that has no tag, and do not treat CBC as authenticated encryption.
- `DigestService` supports SHA-256/SHA-512 plus legacy-only MD5/SHA-1. `AdaptiveHashService` uses BCrypt for short secrets; do not use MD5, SHA-1, or a fast digest for new password or secret storage.

View File

@@ -0,0 +1,36 @@
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Contract: kri-common
Source: .agent/consumer-references/platform-capabilities.md
-->
# KriCommon Platform Capabilities
## Dependency and Configuration Boundary
- Include the matching Spring starter for any optional Web, Security, JPA, Redis, AOP, or Swagger integration the service enables; KriCommon intentionally declares many integrations as compile-only.
- KriCommon configuration uses only `kri.*`. Established groups include `kri.auth.jwt`, `kri.auth.apikey`, `kri.crypto`, `kri.security`, `kri.swagger`, `kri.web`, `kri.web.mdc`, `kri.http.bypass`, `kri.redis`, `kri.scheduling`, and `kri.error.expose`.
- Read the version-matched README and configuration-property classes before setting a property; do not infer a property name or default from an older service.
- Supply production JWT secrets, API keys, credentials, allowlists, and service URLs through the consumer's approved secret and configuration system. Never rely on library example or default secrets in production.
- Preserve consumer override points. KriCommon's default security chain is created only when the consumer does not provide one, and overridable beans should remain explicit.
- Adding a path to API-key allowed paths scopes where API-key authentication is attempted; it does not make the path public or grant authorization.
## Optional Capabilities
- JWT and API-key authentication integrate with Spring Security. API-key JPA preload requires Spring Data JPA; a consumer-provided claims provider can be used without JPA.
- Common Web may register error handling, tracing/MDC, request-user resolution, enum conversion, and CORS behavior. Check for overlap before defining consumer-local equivalents.
- Swagger support requires springdoc and defines the shared Bearer/API-key schemes and grouped paths.
- When Swagger auto-configuration is active (`kri.swagger.enabled=true`, default), `RequestUserContext` controller arguments are ignored as request inputs globally, including their `authenticated`, `clientIp`, and `userRole` properties. Runtime argument resolution is unchanged.
- `RequestUserContextProvider` is a public injectable API for resolving the same request identity and client IP used by controller arguments. Its default registration requires Web integration and JwtService; a consumer provider overrides it. Existing principal/details/verified-Bearer fallback, empty-context behavior, resolver overrides and the JwtService resolver constructor remain unchanged. The provider does not enforce authentication or business authorization.
- Redis and scheduling are opt-in through their `kri.*.enabled` settings and matching runtime dependencies.
- HTTP bypass targets are server-configured. Never accept an arbitrary full target URL from a frontend; retain allowed-path checks and do not forward hop-by-hop headers.
- The external API client returns response bodies as documented, while bypass responses preserve raw bytes and target `Content-Type`.
- Bypass filters all HTTP/2 pseudo headers (names starting with `:`) in addition to existing hop-by-hop headers; use the response status accessor instead of forwarding `:status`.
- `kri.http.bypass.targets.<target>.throw-on-error` defaults to `false`. When enabled, the final response after response customizers throws public `com.kri.common.feature.http.ExternalApiResponseException` for non-2xx status; existing targets retain response-return behavior by default.
- `BypassResponse.requireSuccess()` and `ExternalApiResponse.requireSuccess()` explicitly enforce the same non-2xx guard. `ExternalApiClient` keeps its existing default behavior and decoded `getBody()` API, and `getBodyBytes()` exposes a defensive copy of the original received bytes, including compressed and binary error bodies.
- A response customizer's `ExternalApiResponseException`, including one thrown by `requireSuccess()`, propagates unchanged; other customizer failures keep the existing `BYPASS_RESPONSE_CUSTOMIZE_FAILED` behavior. Response charset parsing ignores charset-like text inside other quoted `Content-Type` parameters and retains the UTF-8 fallback.
- With Spring MVC and Servlet API present and `kri.web.enabled=true` (default), `ExternalApiErrorAutoConfiguration` registers a handler for this dedicated exception before the general error advice. It relays the original status, body bytes, `Content-Type`, and `Content-Encoding`, including empty bodies; authentication, cookie, and transport headers are not relayed by the error handler. Enable this policy only for targets whose raw errors may be exposed to clients. Connection failures remain distinct from upstream HTTP errors.
- A consumer-provided error handler bean named `externalApiResponseAdvice` replaces the default without importing runtime types; explicitly caught/controller-handled exceptions also remain under the consumer's control.
- `ExternalApiClient` multipart requests generate their own boundary and ignore a caller-supplied `Content-Type`. Multipart headers and `formField` values use UTF-8, while file bodies preserve the supplied bytes.
- Multipart filenames, including non-ASCII names, are sent unchanged in the quoted `filename` parameter as raw UTF-8. No ASCII fallback or `filename*` parameter is added; CR/LF rejection and quote/backslash escaping still apply.
- `JsonUtil` requires the consumer's explicit `ObjectMapper`; shared date/time helpers define KST as `Asia/Seoul` and also expose UTC semantics.

View File

@@ -0,0 +1,13 @@
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Contract: kri-common
Source: .agent/consumer-references/upgrade-and-verification.md
-->
# KriCommon Upgrade and Verification
- Review KriCommon release notes, README changes, configuration defaults, auto-configuration conditions, and affected public APIs before upgrading.
- Commit dependency-lock or resolved-version changes according to the consumer repository's policy.
- Run the consumer's focused compile and tests after an upgrade, including application-context startup tests when auto-configuration or security behavior is affected.
- Keep `.agent/project.md` near 2-3 KiB as a routing document. Do not delete material rules to meet the budget; move conditional schema, query, API, and migration details to routed `.agent/references/` documents.
- Do not modify KriCommon or another consumer repository unless it is explicitly included in the approved task scope.

View File

@@ -0,0 +1,8 @@
# KriCommon Crypto Contract
- Crypto APIs are under `com.kri.common.feature.crypto.*` and do not use a central key database.
- AES uses PBKDF2-HMAC-SHA256 key derivation with salt and defaults to AES-256-GCM; callers may supply a master key, salt, IV, AAD, and detached or appended GCM tag representation for legacy interoperability.
- `kri.crypto.aes.keys` and per-call master keys are supported operational compromises. Never log them or commit real values.
- Per-call key material takes precedence over configured keys, and encrypted values retain key ID and KDF metadata for decryption compatibility.
- AES-GCM always requires its authentication tag. Use `AES_256_CBC_PKCS5` only for explicitly identified legacy data that has no tag, and do not treat CBC as authenticated encryption.
- `DigestService` supports SHA-256/SHA-512 plus legacy-only MD5/SHA-1. `AdaptiveHashService` uses BCrypt for short secrets; do not use MD5, SHA-1, or a fast digest for new password or secret storage.

View File

@@ -0,0 +1,30 @@
# KriCommon Platform Capabilities
## Dependency and Configuration Boundary
- Include the matching Spring starter for any optional Web, Security, JPA, Redis, AOP, or Swagger integration the service enables; KriCommon intentionally declares many integrations as compile-only.
- KriCommon configuration uses only `kri.*`. Established groups include `kri.auth.jwt`, `kri.auth.apikey`, `kri.crypto`, `kri.security`, `kri.swagger`, `kri.web`, `kri.web.mdc`, `kri.http.bypass`, `kri.redis`, `kri.scheduling`, and `kri.error.expose`.
- Read the version-matched README and configuration-property classes before setting a property; do not infer a property name or default from an older service.
- Supply production JWT secrets, API keys, credentials, allowlists, and service URLs through the consumer's approved secret and configuration system. Never rely on library example or default secrets in production.
- Preserve consumer override points. KriCommon's default security chain is created only when the consumer does not provide one, and overridable beans should remain explicit.
- Adding a path to API-key allowed paths scopes where API-key authentication is attempted; it does not make the path public or grant authorization.
## Optional Capabilities
- JWT and API-key authentication integrate with Spring Security. API-key JPA preload requires Spring Data JPA; a consumer-provided claims provider can be used without JPA.
- Common Web may register error handling, tracing/MDC, request-user resolution, enum conversion, and CORS behavior. Check for overlap before defining consumer-local equivalents.
- Swagger support requires springdoc and defines the shared Bearer/API-key schemes and grouped paths.
- When Swagger auto-configuration is active (`kri.swagger.enabled=true`, default), `RequestUserContext` controller arguments are ignored as request inputs globally, including their `authenticated`, `clientIp`, and `userRole` properties. Runtime argument resolution is unchanged.
- `RequestUserContextProvider` is a public injectable API for resolving the same request identity and client IP used by controller arguments. Its default registration requires Web integration and JwtService; a consumer provider overrides it. Existing principal/details/verified-Bearer fallback, empty-context behavior, resolver overrides and the JwtService resolver constructor remain unchanged. The provider does not enforce authentication or business authorization.
- Redis and scheduling are opt-in through their `kri.*.enabled` settings and matching runtime dependencies.
- HTTP bypass targets are server-configured. Never accept an arbitrary full target URL from a frontend; retain allowed-path checks and do not forward hop-by-hop headers.
- The external API client returns response bodies as documented, while bypass responses preserve raw bytes and target `Content-Type`.
- Bypass filters all HTTP/2 pseudo headers (names starting with `:`) in addition to existing hop-by-hop headers; use the response status accessor instead of forwarding `:status`.
- `kri.http.bypass.targets.<target>.throw-on-error` defaults to `false`. When enabled, the final response after response customizers throws public `com.kri.common.feature.http.ExternalApiResponseException` for non-2xx status; existing targets retain response-return behavior by default.
- `BypassResponse.requireSuccess()` and `ExternalApiResponse.requireSuccess()` explicitly enforce the same non-2xx guard. `ExternalApiClient` keeps its existing default behavior and decoded `getBody()` API, and `getBodyBytes()` exposes a defensive copy of the original received bytes, including compressed and binary error bodies.
- A response customizer's `ExternalApiResponseException`, including one thrown by `requireSuccess()`, propagates unchanged; other customizer failures keep the existing `BYPASS_RESPONSE_CUSTOMIZE_FAILED` behavior. Response charset parsing ignores charset-like text inside other quoted `Content-Type` parameters and retains the UTF-8 fallback.
- With Spring MVC and Servlet API present and `kri.web.enabled=true` (default), `ExternalApiErrorAutoConfiguration` registers a handler for this dedicated exception before the general error advice. It relays the original status, body bytes, `Content-Type`, and `Content-Encoding`, including empty bodies; authentication, cookie, and transport headers are not relayed by the error handler. Enable this policy only for targets whose raw errors may be exposed to clients. Connection failures remain distinct from upstream HTTP errors.
- A consumer-provided error handler bean named `externalApiResponseAdvice` replaces the default without importing runtime types; explicitly caught/controller-handled exceptions also remain under the consumer's control.
- `ExternalApiClient` multipart requests generate their own boundary and ignore a caller-supplied `Content-Type`. Multipart headers and `formField` values use UTF-8, while file bodies preserve the supplied bytes.
- Multipart filenames, including non-ASCII names, are sent unchanged in the quoted `filename` parameter as raw UTF-8. No ASCII fallback or `filename*` parameter is added; CR/LF rejection and quote/backslash escaping still apply.
- `JsonUtil` requires the consumer's explicit `ObjectMapper`; shared date/time helpers define KST as `Asia/Seoul` and also expose UTC semantics.

View File

@@ -0,0 +1,7 @@
# KriCommon Upgrade and Verification
- Review KriCommon release notes, README changes, configuration defaults, auto-configuration conditions, and affected public APIs before upgrading.
- Commit dependency-lock or resolved-version changes according to the consumer repository's policy.
- Run the consumer's focused compile and tests after an upgrade, including application-context startup tests when auto-configuration or security behavior is affected.
- Keep `.agent/project.md` near 2-3 KiB as a routing document. Do not delete material rules to meet the budget; move conditional schema, query, API, and migration details to routed `.agent/references/` documents.
- Do not modify KriCommon or another consumer repository unless it is explicitly included in the approved task scope.

23
.agent/consumer.md Normal file
View File

@@ -0,0 +1,23 @@
## KriCommon Consumer Contract
- Consume KriCommon as `com.kri.common:starter:<approved-version>` through the repository's established Gradle version-management convention.
- Import service-facing APIs from `com.kri.common.feature.*`; treat `com.kri.common.runtime.*` as internal.
- Prefer a shared feature or approved extension point over duplicating authentication, HTTP, error, enum, Excel, Redis, JSON, date/time, JPA, crypto, or utility behavior locally.
- For HTTP/2 header safety and original upstream error propagation, use the shared HTTP/bypass features documented in the routed platform-capabilities reference instead of implementing consumer-local header filters and raw-response exception handlers.
- Response customizers may call `requireSuccess()`; its upstream exception propagates unchanged. Response charset parsing ignores charset-like text inside other quoted header parameters.
- When Swagger auto-configuration is active, `RequestUserContext` controller arguments are excluded from request input documentation; server-side authentication and client IP injection remain unchanged.
- `RequestUserContextProvider` is a public injectable API for resolving the same request identity and client IP used by controller arguments. Its default registration requires Web integration and JwtService; a consumer provider overrides it. Existing principal/details/verified-Bearer fallback, empty-context behavior, resolver overrides and the JwtService resolver constructor remain unchanged. The provider does not enforce authentication or business authorization.
- ExcelMapper's Path-based readStreaming and readHeaderStreaming use PackageAccess.READ, preserving source bytes, size, and modification time, including repeated reads and callback failures. Read-only files are supported, and file handles are released on success or failure; option validation, exception handling, and SAX streaming remain unchanged.
- Do not modify KriCommon or another consumer repository unless it is explicitly included in the approved task scope.
### Required Shared References
Before each related task, read the current contents of every matching reference, even if it was read earlier in the session.
| Task scope | Required reference |
|---|---|
| Dependency, configuration, security, Web, Swagger, Redis, scheduling, HTTP, JSON, or date/time behavior | `.agent-harness/references/kri-common/platform-capabilities.md` |
| Encryption, hashing, key material, or legacy crypto interoperability | `.agent-harness/references/kri-common/crypto-contract.md` |
| KriCommon version upgrade or consumer verification | `.agent-harness/references/kri-common/upgrade-and-verification.md` |
If a task spans multiple scopes, read every matching reference. Generated files under `.agent-harness/references/` are read-only copies; edit KriCommon's `.agent/consumer.md` or `.agent/consumer-references/` and recompose instead.

15
.agent/profile.yml Normal file
View File

@@ -0,0 +1,15 @@
schema_version: 1
project:
id: kri-common
name: KriCommon
type: library
layer: backend
legacy: false
stack:
- java-springboot
shared_contracts:
provides:
- kri-common

18
.agent/project.md Normal file
View File

@@ -0,0 +1,18 @@
# KriCommon Project Instruction Router
## Required Project References
Before each related task, read the current contents of every matching reference below, even if it was read earlier in the session.
| Task scope | Required reference |
|---|---|
| Any substantive analysis, planning, implementation, debugging, review, or documentation work in this repository | `.agent/references/repository-rules.md` |
If a task spans multiple scopes, read every matching reference. Do not assume remembered content is current.
## Harness Workflow
- `AGENTS.md` and `CLAUDE.md` are generated outputs. Never edit them directly.
- Edit `.agent/project.md` only when routing changes. Store durable project detail in `.agent/references/`.
- A reference-only content change does not require recomposition when its route is unchanged. Run harness verification to validate routing and UTF-8.
- Recompose and verify after changing `.agent/project.md`, `.agent/profile.yml`, or another composed instruction source.

View File

@@ -0,0 +1,41 @@
## KriCommon Repository Rules
### Repository Role and Package Boundaries
- This repository is the Java 17 Spring Boot starter/library `com.kri.common:starter:<commonVer>` built with Gradle `java-library` and `maven-publish`.
- `build.gradle` variable `commonVer` is the version source. Version changes and publication require separate explicit approval.
- Treat types under `com.kri.common.feature`, `kri.*` configuration properties, auto-configuration behavior, optional endpoints, Maven coordinates, and documented defaults as public contracts.
- Put stable service-facing APIs under `com.kri.common.feature`. Keep implementations under `com.kri.common.runtime` and composition under `com.kri.common.autoconfigure`; consumers should not depend on runtime internals.
- Register consumer-active auto-configurations in `src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`.
### Dependency and Auto-Configuration Safety
- Many Spring integrations are intentionally `compileOnly`. Do not assume Spring Web, Security, JPA, Redis, AOP, or springdoc is present in every consumer.
- Guard optional integrations with the appropriate classpath, bean, missing-bean, and property conditions. A consumer-provided bean must remain able to override a default where that is the established contract.
- Do not introduce configuration prefixes outside `kri.*`.
- Do not make an optional starter mandatory without an approved compatibility review and migration plan.
- Never hard-code real secrets, credentials, service URLs, or API keys. Examples must use obvious placeholders or local-only values.
- Do not log or expose raw API keys, bearer tokens, credentials, or unrestricted target URLs.
### Feature Invariants
- Preserve the default security chain's consumer override point and the established order of API-key and JWT filters.
- Path restrictions for API-key authentication scope authentication attempts; they do not grant authorization or replace `kri.security.public-paths`.
- Keep bypass target base URLs server-side, enforce configured allowed paths, and exclude hop-by-hop headers. Preserve response bytes and target `Content-Type`.
- `JsonUtil` requires an explicit `ObjectMapper`; do not introduce hidden global mapper state.
- Preserve `Asia/Seoul` and UTC semantics in shared date/time APIs.
- Keep public enum, JPA, Excel, Redis, HTTP, authentication, web, cache, and utility behavior compatible unless a breaking change is explicitly approved.
### Documentation and Verification
- `AGENTS.md` and `CLAUDE.md` are harness-generated outputs. Never edit either file directly.
- Edit `.agent/project.md` when KriCommon's repository workflow, build, maintenance, or verification rules change.
- Edit `.agent/consumer.md` in the same task when a public API, configuration property, default, auto-configuration condition, endpoint, extension point, dependency requirement, security behavior, or other consumer-facing contract changes.
- A source-code change does not update harness documents automatically. The Agent making a consumer-facing change is responsible for updating `.agent/consumer.md` and the relevant human documentation before completion.
- After an approved harness-source change, run `D:\_____Dev\_________AgentHarnessBase\scripts\agent-harness.cmd compose --project kri-common`, followed by `D:\_____Dev\_________AgentHarnessBase\scripts\agent-harness.cmd verify --project kri-common`.
- If composition cannot be run, leave the authoritative `.agent` source corrected, report that the generated output is stale, and do not patch `AGENTS.md` manually.
- Update `README.md`, `.agent/consumer.md`, configuration metadata, examples, and tests as applicable when public behavior changes.
- Verify property names against their `@ConfigurationProperties` classes and ensure examples import public `com.kri.common.feature.*` APIs unless internals are intentionally documented.
- On Windows, run `.\gradlew.bat compileJava` for relevant source changes. Use additional focused tests and checks when present.
- For auto-configuration changes, verify import registration and all classpath, bean, and property conditions.
- Do not run publish tasks or edit consumer repositories without separate explicit approval. Publishing additionally requires configured Gitea credentials and performs a remote version check.

View File

@@ -0,0 +1,41 @@
---
name: attention-aware-communication
description: Shape substantive answers, progress updates, and completion reports for fast, accurate reading without reducing the underlying work.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/attention-aware-communication/SKILL.md
-->
# Attention-Aware Communication
This skill changes presentation only. Investigate, implement, and verify as deeply as the task requires.
## Default: Attention-kind
- Put the bottom line in the first sentence and use plain Korean.
- Say the least that fully answers, then stop. Remove preambles, padding, repetition, and closing restatements.
- Never omit a number, scope condition, risk, prerequisite, uncertainty, or other fact that could cause the user to act incorrectly.
- For genuine breadth, explain the one or two most important points first, name the remaining areas, and let the user choose whether to expand them. Do not use this to defer required caveats or a complete focused answer.
- When the user asks for a detailed explanation, walkthrough, rationale, or full picture, suspend brevity and provide the necessary detail in scannable sections.
- When asked for a deliverable such as a command, message, snippet, or commit text, return the deliverable without unnecessary framing unless safety or correctness requires context.
- Ask one blocking question at a time and put it last. Keep working when a non-blocking assumption is safe.
## Progress and Completion: Rundown
Use Rundown formatting when a task has multiple steps or mixed states:
- Start with a one-line outcome that includes any blocker.
- Distinguish verified completion, work in progress, work not started, and unknown state. Omit empty categories.
- Put each blocker or material risk on its own line.
- Report only observed states. Mark an unknown as unknown and state what check would resolve it.
- End with the next action or a small numbered choice only when the user must decide.
## Explicit-Only: Spartan
Use Spartan style only when the user explicitly asks for it:
- Lead with the complete answer in one sentence.
- Be terse, blunt, and direct; remove warmth, hedging, transitions, narration, and summaries.
- Keep all load-bearing facts, warnings, and conditions even when they make the answer longer.
- If the user also asks for depth, provide the full detail in short, separated blocks.

View File

@@ -0,0 +1,37 @@
---
name: karpathy-guidelines
description: Keep implementation, refactoring, and code review assumption-aware, simple, surgical, and tied to verifiable success criteria.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/karpathy-guidelines/SKILL.md
-->
# Karpathy Guidelines
Use these guidelines while implementing, refactoring, or reviewing code. They refine execution quality but do not expand the approved task scope.
## Think Before Coding
- Inspect the relevant code and repository conventions before choosing a solution.
- Surface an assumption when different choices would materially change behavior, compatibility, data, or scope.
- Ask only when the decision cannot be discovered safely and a reasonable assumption would be risky. Otherwise proceed with the smallest reasonable assumption and report it.
## Simplicity First
- Implement the smallest complete solution that satisfies the observable requirement.
- Do not add speculative abstractions, extension points, configuration, fallback paths, or dependencies for hypothetical future use.
- Prefer an existing repository pattern or standard-library capability over a new local framework.
## Surgical Changes
- Every changed line must trace to the approved objective, required validation, or a necessary compatibility adjustment.
- Preserve existing naming, structure, public behavior, and formatting outside that boundary.
- Do not mix the task with unrelated cleanup. Remove dead code, duplication, or ceremony introduced by the current change before finishing.
## Goal-Driven Execution
- Translate the request into observable success criteria before implementation.
- Choose the narrowest check that can fail for the behavior being changed, then run broader repository checks when appropriate.
- Iterate only within the approved scope until the criteria pass or a concrete blocker is established.
- Before reporting completion, inspect the final diff for unnecessary code and use `verification-before-completion` for fresh evidence.

View File

@@ -0,0 +1,29 @@
---
name: project-reference-loader
description: Load the current project-specific and shared reference documents routed by AGENTS.md before substantive repository analysis, implementation, debugging, review, or planning.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/project-reference-loader/SKILL.md
-->
# Project Reference Loader
Use the repository's generated `AGENTS.md` as the routing entrypoint.
## Workflow
1. Find the `Required Project References` and shared-contract reference routes that match the current task.
2. Read the current contents of every matching file before relying on remembered project behavior, even when the file was read earlier in the session.
3. If the task crosses multiple scopes, read every matching reference. Do not load unrelated references merely because they exist.
4. Treat routed references as binding project instructions within their stated scope. Resolve conflicts using the precedence rules in `AGENTS.md`.
5. If a required reference is missing, unreadable, outside the repository, or internally inconsistent, stop the affected work and report the exact problem instead of guessing.
## Change Handling
- Edit authored project detail under `.agent/references/` when the durable rule belongs only to that repository.
- Edit the provider's `.agent/consumer-references/` when the rule is part of a shared consumer contract.
- Never edit generated `.agent-harness/references/` copies directly.
- Changing `.agent/references/` does not require recomposing `AGENTS.md` when its route is unchanged; changing routing, `project.md`, `consumer.md`, or shared reference sources does.
Before completion, confirm that the references used still exist and that the result does not contradict them. This skill does not expand authorization to edit, commit, push, deploy, connect to external systems, or perform destructive operations.

View File

@@ -0,0 +1,38 @@
---
name: verification-before-completion
description: Require fresh, claim-specific evidence before reporting work complete, fixed, passing, ready, or safe to commit or publish.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/verification-before-completion/SKILL.md
-->
# Verification Before Completion
No completion claim without fresh evidence. This workflow verifies status; it does not authorize a commit, push, deployment, database operation, or other protected action.
## Verification Gate
Before making a success claim:
1. State the exact claim internally and identify which observable check can prove or disprove it.
2. Run the relevant command or inspection fresh after the final change. Use repository-defined commands; do not invent a substitute that proves a different property.
3. Read the complete result needed for the claim, including the exit code, failure count, skipped checks, and generated changes.
4. Compare the evidence with the claim and the approved acceptance criteria.
5. Report only the status supported by that evidence.
## Evidence Rules
- A passing lint does not prove compilation, a passing build does not prove runtime behavior, and a passing narrow test does not prove unrelated requirements.
- For a regression test, establish that it is capable of detecting the defect when practical; do not treat an always-passing test as proof.
- Recheck the worktree or final diff after generators, formatters, tests, or builds that may create or alter files.
- Separate verified results, failures, checks not run, and pre-existing failures. Never quietly merge them into a success statement.
- For delegated work, inspect the returned changes and run the relevant verification yourself before accepting the completion claim.
- For absence or universal claims such as “no occurrences” or “all projects,” use a check whose scope actually covers the claim.
## Reporting
- Cite the commands or inspections actually run and summarize their observed results.
- If a required check cannot run, state the actual incomplete or blocked status and the exact reason.
- Do not use “should work,” “probably passes,” “seems correct,” or similar language as a substitute for verification.
- Do not claim completion while a required check is failing or while known correctness, encoding, security, or generated-output drift remains unresolved.

View File

@@ -0,0 +1,41 @@
---
name: attention-aware-communication
description: Shape substantive answers, progress updates, and completion reports for fast, accurate reading without reducing the underlying work.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/attention-aware-communication/SKILL.md
-->
# Attention-Aware Communication
This skill changes presentation only. Investigate, implement, and verify as deeply as the task requires.
## Default: Attention-kind
- Put the bottom line in the first sentence and use plain Korean.
- Say the least that fully answers, then stop. Remove preambles, padding, repetition, and closing restatements.
- Never omit a number, scope condition, risk, prerequisite, uncertainty, or other fact that could cause the user to act incorrectly.
- For genuine breadth, explain the one or two most important points first, name the remaining areas, and let the user choose whether to expand them. Do not use this to defer required caveats or a complete focused answer.
- When the user asks for a detailed explanation, walkthrough, rationale, or full picture, suspend brevity and provide the necessary detail in scannable sections.
- When asked for a deliverable such as a command, message, snippet, or commit text, return the deliverable without unnecessary framing unless safety or correctness requires context.
- Ask one blocking question at a time and put it last. Keep working when a non-blocking assumption is safe.
## Progress and Completion: Rundown
Use Rundown formatting when a task has multiple steps or mixed states:
- Start with a one-line outcome that includes any blocker.
- Distinguish verified completion, work in progress, work not started, and unknown state. Omit empty categories.
- Put each blocker or material risk on its own line.
- Report only observed states. Mark an unknown as unknown and state what check would resolve it.
- End with the next action or a small numbered choice only when the user must decide.
## Explicit-Only: Spartan
Use Spartan style only when the user explicitly asks for it:
- Lead with the complete answer in one sentence.
- Be terse, blunt, and direct; remove warmth, hedging, transitions, narration, and summaries.
- Keep all load-bearing facts, warnings, and conditions even when they make the answer longer.
- If the user also asks for depth, provide the full detail in short, separated blocks.

View File

@@ -0,0 +1,37 @@
---
name: karpathy-guidelines
description: Keep implementation, refactoring, and code review assumption-aware, simple, surgical, and tied to verifiable success criteria.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/karpathy-guidelines/SKILL.md
-->
# Karpathy Guidelines
Use these guidelines while implementing, refactoring, or reviewing code. They refine execution quality but do not expand the approved task scope.
## Think Before Coding
- Inspect the relevant code and repository conventions before choosing a solution.
- Surface an assumption when different choices would materially change behavior, compatibility, data, or scope.
- Ask only when the decision cannot be discovered safely and a reasonable assumption would be risky. Otherwise proceed with the smallest reasonable assumption and report it.
## Simplicity First
- Implement the smallest complete solution that satisfies the observable requirement.
- Do not add speculative abstractions, extension points, configuration, fallback paths, or dependencies for hypothetical future use.
- Prefer an existing repository pattern or standard-library capability over a new local framework.
## Surgical Changes
- Every changed line must trace to the approved objective, required validation, or a necessary compatibility adjustment.
- Preserve existing naming, structure, public behavior, and formatting outside that boundary.
- Do not mix the task with unrelated cleanup. Remove dead code, duplication, or ceremony introduced by the current change before finishing.
## Goal-Driven Execution
- Translate the request into observable success criteria before implementation.
- Choose the narrowest check that can fail for the behavior being changed, then run broader repository checks when appropriate.
- Iterate only within the approved scope until the criteria pass or a concrete blocker is established.
- Before reporting completion, inspect the final diff for unnecessary code and use `verification-before-completion` for fresh evidence.

View File

@@ -0,0 +1,29 @@
---
name: project-reference-loader
description: Load the current project-specific and shared reference documents routed by AGENTS.md before substantive repository analysis, implementation, debugging, review, or planning.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/project-reference-loader/SKILL.md
-->
# Project Reference Loader
Use the repository's generated `AGENTS.md` as the routing entrypoint.
## Workflow
1. Find the `Required Project References` and shared-contract reference routes that match the current task.
2. Read the current contents of every matching file before relying on remembered project behavior, even when the file was read earlier in the session.
3. If the task crosses multiple scopes, read every matching reference. Do not load unrelated references merely because they exist.
4. Treat routed references as binding project instructions within their stated scope. Resolve conflicts using the precedence rules in `AGENTS.md`.
5. If a required reference is missing, unreadable, outside the repository, or internally inconsistent, stop the affected work and report the exact problem instead of guessing.
## Change Handling
- Edit authored project detail under `.agent/references/` when the durable rule belongs only to that repository.
- Edit the provider's `.agent/consumer-references/` when the rule is part of a shared consumer contract.
- Never edit generated `.agent-harness/references/` copies directly.
- Changing `.agent/references/` does not require recomposing `AGENTS.md` when its route is unchanged; changing routing, `project.md`, `consumer.md`, or shared reference sources does.
Before completion, confirm that the references used still exist and that the result does not contradict them. This skill does not expand authorization to edit, commit, push, deploy, connect to external systems, or perform destructive operations.

View File

@@ -0,0 +1,38 @@
---
name: verification-before-completion
description: Require fresh, claim-specific evidence before reporting work complete, fixed, passing, ready, or safe to commit or publish.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/verification-before-completion/SKILL.md
-->
# Verification Before Completion
No completion claim without fresh evidence. This workflow verifies status; it does not authorize a commit, push, deployment, database operation, or other protected action.
## Verification Gate
Before making a success claim:
1. State the exact claim internally and identify which observable check can prove or disprove it.
2. Run the relevant command or inspection fresh after the final change. Use repository-defined commands; do not invent a substitute that proves a different property.
3. Read the complete result needed for the claim, including the exit code, failure count, skipped checks, and generated changes.
4. Compare the evidence with the claim and the approved acceptance criteria.
5. Report only the status supported by that evidence.
## Evidence Rules
- A passing lint does not prove compilation, a passing build does not prove runtime behavior, and a passing narrow test does not prove unrelated requirements.
- For a regression test, establish that it is capable of detecting the defect when practical; do not treat an always-passing test as proof.
- Recheck the worktree or final diff after generators, formatters, tests, or builds that may create or alter files.
- Separate verified results, failures, checks not run, and pre-existing failures. Never quietly merge them into a success statement.
- For delegated work, inspect the returned changes and run the relevant verification yourself before accepting the completion claim.
- For absence or universal claims such as “no occurrences” or “all projects,” use a check whose scope actually covers the claim.
## Reporting
- Cite the commands or inspections actually run and summarize their observed results.
- If a required check cannot run, state the actual incomplete or blocked status and the exact reason.
- Do not use “should work,” “probably passes,” “seems correct,” or similar language as a substitute for verification.
- Do not claim completion while a required check is failing or while known correctness, encoding, security, or generated-output drift remains unresolved.

6
.gitattributes vendored Normal file
View File

@@ -0,0 +1,6 @@
# Agent harness sources and generated outputs use deterministic LF endings.
/AGENTS.md text eol=lf
/Agents.md text eol=lf
/CLAUDE.md text eol=lf
/.agent/*.md text eol=lf
/.agent/*.yml text eol=lf

5
.gitignore vendored
View File

@@ -6,10 +6,7 @@ build/
.kotlin .kotlin
### IntelliJ IDEA ### ### IntelliJ IDEA ###
.idea/modules.xml .idea/
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws *.iws
*.iml *.iml
*.ipr *.ipr

8
.idea/.gitignore generated vendored
View File

@@ -1,8 +0,0 @@
# 디폴트 무시된 파일
/shelf/
/workspace.xml
# 에디터 기반 HTTP 클라이언트 요청
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

View File

@@ -1,15 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GitToolBoxProjectSettings">
<option name="commitMessageIssueKeyValidationOverride">
<BoolValueOverride>
<option name="enabled" value="true" />
</BoolValueOverride>
</option>
<option name="commitMessageValidationEnabledOverride">
<BoolValueOverride>
<option name="enabled" value="true" />
</BoolValueOverride>
</option>
</component>
</project>

18
.idea/gradle.xml generated
View File

@@ -1,18 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleMigrationSettings" migrationVersion="1" />
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleHome" value="" />
<option name="gradleJvm" value="ms-17" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
</set>
</option>
</GradleProjectSettings>
</option>
</component>
</project>

View File

@@ -1,12 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="MaterialThemeProjectNewConfig">
<option name="metadata">
<MTProjectMetadataState>
<option name="migrated" value="true" />
<option name="pristineConfig" value="false" />
<option name="userId" value="4859b8f9:19a516124ff:-7ffa" />
</MTProjectMetadataState>
</option>
</component>
</project>

10
.idea/misc.xml generated
View File

@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="FrameworkDetectionExcludesConfiguration">
<file type="web" url="file://$PROJECT_DIR$" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="temurin-17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

6
.idea/vcs.xml generated
View File

@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

271
AGENTS.md Normal file
View File

@@ -0,0 +1,271 @@
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Project: kri-common
Schema version: 1
Edit the source fragments or repository .agent files, then recompose.
-->
# KRI Development Base Instructions
This document defines the shared working rules for KRI development repositories.
Keep project-specific facts and commands in the project profile and project rules.
## Instruction Resolution
Apply repository instructions in this order:
1. Base rules
2. Project-type rules
3. Technology-stack rules
4. Shared consumer contracts
5. Project-specific rules
6. The explicitly approved task scope
Later and more specific instructions may override earlier general instructions only within their stated scope.
- Apply a shared consumer contract only when `.agent/profile.yml` declares it.
- Do not silently resolve a material instruction conflict. Report the conflicting rules and request a decision before changing files.
- Rules involving destructive actions, credentials, external systems, production, deployment, databases, or Git publication require explicit authorization even when a later rule is less restrictive.
## Communication
- Respond to the user in Korean unless the user requests another language.
- Keep code identifiers, commands, paths, protocol names, and external API terms in their original form.
- Follow the repository's existing language conventions for code comments and user-facing messages.
- Lead with the result or decision, then provide only the detail needed to verify it.
- Do not create or retain a full session transcript.
### Attention-Aware Response Style
- Use `attention-aware-communication` for substantive answers, progress updates, and completion reports.
- Default to concise, bottom-line-first Korean without omitting a condition, risk, number, or uncertainty needed for a correct decision.
- Give full detail when the user requests depth. Use Spartan style only when explicitly requested.
- Presentation rules never reduce investigation, implementation, validation, or reporting obligations.
## Work Authorization
- The default workflow is discussion first and explicit execution approval second.
- During discussion, perform only read-only investigation needed to understand the task and propose a concrete plan, unless the user prohibits inspection.
- Read-only investigation may include file inspection, code search, encoding checks, `git status`, `git diff`, `git log`, and sanitized official-documentation lookup.
- Before execution approval, do not edit files, install dependencies, run builds or tests, start services, connect to databases, or change local or external state.
- Before requesting approval, describe the intended scope, affected areas, validation plan, and material risks.
- Treat approval as limited to the presented scope. Pause and discuss again if the work materially expands.
- If the user explicitly requests immediate execution without prior discussion, the discussion gate may be skipped for the stated scope.
- Fast-track authorization does not implicitly authorize protected operations such as destructive commands, production changes, deployments, database mutations, Git publication, or external messages.
## Local Development Environment
- Primary OS: Windows 11.
- Primary shell: PowerShell.
- Use Git Bash only when the repository already depends on Bash or POSIX shell behavior.
- Prefer repository-provided wrappers and scripts over globally installed commands.
- Do not assume that GNU utilities, WSL, Docker, or a Unix-compatible shell are available unless the project profile confirms them.
- Detect Java, Node.js, .NET, Python, package-manager, and database-tool versions from repository configuration.
- Do not install or modify global toolchains as part of a project task.
Preferred human-facing tools:
- Classic ASP: Visual Studio Code
- Java and Spring Boot: IntelliJ IDEA
- C# and .NET: JetBrains Rider
- JavaScript, TypeScript, and Next.js: JetBrains WebStorm
- Python: JetBrains PyCharm
- Microsoft SQL Server: SQL Server Management Studio
- Other databases: JetBrains DataGrip
- These preferences do not authorize launching or controlling a GUI application.
- Prefer IDE-independent commands that can also run in CI.
- Do not modify global IDE settings.
- Do not create or modify `.idea`, `.vscode`, workspace, or run-configuration files unless the approved task requires it.
- Preserve existing shared IDE configuration when it is already tracked.
## PowerShell and Path Safety
- Quote paths containing spaces, brackets, parentheses, Korean characters, or PowerShell metacharacters.
- Prefer `-LiteralPath` when operating on an exact filesystem path.
- Use project-relative paths in committed configuration and documentation. Do not commit machine-specific paths such as `D:\_____Dev\...`.
- Do not pass filesystem targets between PowerShell, `cmd.exe`, and Bash for destructive or recursive operations.
- Keep a filesystem operation within one shell from target resolution through execution.
- Before a recursive delete or move, resolve and verify every absolute target.
- Never use a drive root, workspace root, user profile, unresolved variable, wildcard, or broad glob as a recursive delete target.
- Prefer recoverable operations when practical.
## Change Discipline
- Preserve all existing user changes, including uncommitted and untracked work.
- Keep changes minimal but complete for the approved objective.
- Avoid unrelated cleanup, formatting, renaming, dependency upgrades, and architectural refactoring.
- Do not overwrite or revert unrelated changes.
- Stop and report when the requested change overlaps existing work in a way that cannot be handled safely.
- Prefer changing an authoritative source over editing generated output.
- Treat files marked as generated as read-only unless regeneration is part of the approved plan.
- Do not edit vendored dependencies, build outputs, caches, or generated clients unless explicitly required.
- Do not regenerate a broad set of files for a narrow change without first explaining the expected output scope.
## Text Encoding and Korean Content Safety
- Treat the existing file encoding, BOM state, and line-ending style as part of the file's contract.
- Preserve Korean comments, user-facing messages, error messages, identifiers, and documentation exactly unless the task explicitly requires changing them.
- Do not assume that garbled terminal output means the file itself is corrupted. Verify bytes and encoding before modifying suspicious text.
- Before editing an existing text file, determine its current encoding and BOM state when repository configuration does not already guarantee them.
- Do not convert encoding, add or remove a BOM, or normalize line endings as a side effect of an unrelated change.
- Avoid whole-file rewrites for small changes.
- Do not rewrite source files through `Get-Content | Set-Content`, `Out-File`, shell redirection, or another method whose encoding behavior is implicit.
- Do not use a patching or formatting tool on a non-UTF-8 file unless it is known to preserve that file's encoding.
- Treat a console display problem and an on-disk encoding problem as separate issues.
- After editing Korean text, inspect the diff for replacement characters (`<60>`), mojibake, unexpected escapes, BOM changes, and unrelated line-ending changes.
- Run `.agent/tools/check-encoding.ps1` when it is available and the change touches Korean text or a non-default encoding.
- If encoding cannot be identified confidently, stop before writing and report the affected file and evidence.
- For a new text file, follow repository configuration. If no rule exists, use UTF-8 without BOM.
## Git Safety
- Use `git status`, `git diff`, and `git log` for read-only investigation.
- Do not run `commit`, `push`, `pull`, `fetch`, `merge`, `rebase`, `reset`, `checkout`, `switch`, `stash`, `clean`, `tag`, or force operations unless that specific operation is explicitly approved.
- Source-edit approval does not include commit or push approval.
- Never amend an existing commit unless explicitly requested.
- Before an approved commit, show the intended files, validation results, and proposed commit message.
- Never push directly to a protected branch unless the user names the target branch and explicitly authorizes the push.
## Dependencies and External Actions
- Use the package manager, lockfile, and toolchain already selected by the repository.
- Do not install global packages.
- Do not add, remove, or upgrade a dependency unless it was included in the approved plan.
- Pause for approval if an unplanned dependency becomes necessary.
- Keep lockfiles synchronized with approved dependency changes.
- Do not deploy, publish packages, create releases, send messages or email, call business APIs, or modify external services unless explicitly requested.
- Never upload proprietary source code, internal documents, credentials, customer data, or database contents to an external service.
- Remove secrets and unnecessary internal identifiers from external search queries.
## Database Safety
- Treat writing or reviewing SQL as source code separately from executing SQL against a database.
- SQL files, migrations, schema proposals, and query drafts may be created within an approved source-change scope.
- Do not connect to a shared, staging, or production database without explicit authorization for that environment.
- Read-only queries against a non-local database also require authorization because results may contain sensitive data.
- Do not execute DDL, DML, stored procedures, migrations, administrative commands, or data-correction scripts against a non-disposable database without separate authorization for the exact target and operation.
- Source-change approval does not authorize migration execution.
- Use a disposable local or test database for approved validation only after verifying its identity and disposable nature.
- Never place credentials, connection strings, or sensitive query results in source files, logs, generated documents, or chat output.
## Secrets and Sensitive Data
- Never add credentials, tokens, passwords, private keys, connection strings, session identifiers, or production data to source control.
- Read sensitive files only when the approved task requires it and no safer source exists.
- Prefer inspecting configuration keys and schemas without displaying secret values.
- Never echo secrets into terminal output, chat responses, logs, diffs, generated documents, test fixtures, or screenshots.
- Redact sensitive values when reporting errors or command output.
- If a possible secret is discovered, do not repeat it. Report only its location, type, and recommended containment action.
- Do not rotate, revoke, copy, or otherwise modify credentials unless that exact action is explicitly authorized.
## Workflow Skills
- Use `project-reference-loader` before substantive repository analysis, planning, implementation, debugging, or review. Read only the current project and shared references routed for that task, and reread them for each related task even if they were loaded earlier in the session.
- Use `karpathy-guidelines` when implementing, refactoring, or reviewing code. It keeps assumptions visible, changes surgical, and success criteria verifiable.
- Use `verification-before-completion` before claiming that work is complete, fixed, passing, ready, or safe to commit or publish.
- A skill does not expand task scope or authorize Git publication, database execution, deployment, destructive actions, or external communication.
## Validation
- Discover supported build, test, lint, type-check, and formatting commands from repository files and project instructions. Do not invent commands.
- Include intended validation in the discussion-phase plan.
- After approved changes, run the narrowest relevant validation first, then broader checks when appropriate.
- Limit formatting to files within the approved scope.
- Do not run tests that require a shared database, production service, paid external API, or sensitive data unless separately authorized.
- Do not claim that a check passed unless it was executed successfully.
- If a check cannot be run, state the exact reason.
- Distinguish a current-change failure from a pre-existing failure or an undetermined failure.
- Do not fix unrelated failures without expanding the approved scope.
- Inspect the worktree after validation for unexpected generated files, formatting churn, encoding changes, or lockfile changes.
## Artifacts and Session Records
- Do not create full-session transcripts, automatic HTML copies, analysis reports, or extra documentation unless explicitly requested.
- Store durable information in the repository's existing documentation structure.
- Do not place generated reports or temporary analysis files in the repository root.
- Remove task-specific temporary files created by the current task after validation when removal is safe.
## Completion Report
When implementation is complete, report in Korean:
- what changed and why;
- the main affected files or components;
- validation commands actually executed and their results;
- checks not executed and the reason;
- remaining risks, assumptions, or follow-up work;
- database, deployment, dependency, encoding, and compatibility impact when applicable.
- Do not report completion while required validation is failing or known encoding corruption is unresolved.
- Keep the report concise and do not include a full session transcript.
## Library Project Rules
- Treat exported code, configuration keys, registry schemas, generated artifacts, package coordinates, and documented behavior as consumer-facing contracts.
- Before changing a public surface, classify the change as internal, backward-compatible, deprecating, or breaking.
- Do not remove, rename, relocate, or materially change a public API without an approved compatibility and migration plan.
- Preserve consumer override points and optional integrations.
- Do not make an optional peer, compile-only, or runtime dependency mandatory without reviewing consumer impact.
- Prefer additive evolution and deprecation over immediate removal.
- When a public contract changes, update tests, human documentation, and the library's consumer contract in the same approved change.
- Validate both the source and the distributable artifact when supported.
- Inspect known consumers when available, but do not modify consumer repositories unless they are included in the approved scope.
- Version changes, publication, registry deployment, and package replacement require separate authorization.
- Keep repository-maintainer rules in `.agent/project.md` and downstream usage rules in `.agent/consumer.md`.
## Java and Spring Boot
- Treat the configured JDK, Spring Boot, Gradle, plugin, dependency, and package versions as authoritative.
- Use the repository's Gradle Wrapper. Do not substitute a machine-global Gradle installation.
- Preserve the established package layout and controller, application/service, domain, and persistence boundaries.
- Keep controllers thin, place business rules in the established service/domain layer, and prefer constructor injection.
- Apply request and configuration validation at boundaries and preserve the project's exception and response conventions.
- Make transaction boundaries explicit and narrow; do not add broad transactions to hide lifecycle or query problems.
- Preserve authentication, authorization, auditing, logging, and secret-management conventions.
- Do not edit generated QueryDSL or other generated sources. Change their source definitions and regenerate only when the repository workflow requires it.
- Use the approved KriCommon contract when the project profile includes it; do not duplicate shared backend behavior locally.
- Run the narrowest relevant Gradle compile, test, static-analysis, and build tasks.
## KriCommon Consumer Contract
- Consume KriCommon as `com.kri.common:starter:<approved-version>` through the repository's established Gradle version-management convention.
- Import service-facing APIs from `com.kri.common.feature.*`; treat `com.kri.common.runtime.*` as internal.
- Prefer a shared feature or approved extension point over duplicating authentication, HTTP, error, enum, Excel, Redis, JSON, date/time, JPA, crypto, or utility behavior locally.
- For HTTP/2 header safety and original upstream error propagation, use the shared HTTP/bypass features documented in the routed platform-capabilities reference instead of implementing consumer-local header filters and raw-response exception handlers.
- Response customizers may call `requireSuccess()`; its upstream exception propagates unchanged. Response charset parsing ignores charset-like text inside other quoted header parameters.
- When Swagger auto-configuration is active, `RequestUserContext` controller arguments are excluded from request input documentation; server-side authentication and client IP injection remain unchanged.
- `RequestUserContextProvider` is a public injectable API for resolving the same request identity and client IP used by controller arguments. Its default registration requires Web integration and JwtService; a consumer provider overrides it. Existing principal/details/verified-Bearer fallback, empty-context behavior, resolver overrides and the JwtService resolver constructor remain unchanged. The provider does not enforce authentication or business authorization.
- ExcelMapper's Path-based readStreaming and readHeaderStreaming use PackageAccess.READ, preserving source bytes, size, and modification time, including repeated reads and callback failures. Read-only files are supported, and file handles are released on success or failure; option validation, exception handling, and SAX streaming remain unchanged.
- Do not modify KriCommon or another consumer repository unless it is explicitly included in the approved task scope.
### Required Shared References
Before each related task, read the current contents of every matching reference, even if it was read earlier in the session.
| Task scope | Required reference |
|---|---|
| Dependency, configuration, security, Web, Swagger, Redis, scheduling, HTTP, JSON, or date/time behavior | `.agent-harness/references/kri-common/platform-capabilities.md` |
| Encryption, hashing, key material, or legacy crypto interoperability | `.agent-harness/references/kri-common/crypto-contract.md` |
| KriCommon version upgrade or consumer verification | `.agent-harness/references/kri-common/upgrade-and-verification.md` |
If a task spans multiple scopes, read every matching reference. Generated files under `.agent-harness/references/` are read-only copies; edit KriCommon's `.agent/consumer.md` or `.agent/consumer-references/` and recompose instead.
# KriCommon Project Instruction Router
## Required Project References
Before each related task, read the current contents of every matching reference below, even if it was read earlier in the session.
| Task scope | Required reference |
|---|---|
| Any substantive analysis, planning, implementation, debugging, review, or documentation work in this repository | `.agent/references/repository-rules.md` |
If a task spans multiple scopes, read every matching reference. Do not assume remembered content is current.
## Harness Workflow
- `AGENTS.md` and `CLAUDE.md` are generated outputs. Never edit them directly.
- Edit `.agent/project.md` only when routing changes. Store durable project detail in `.agent/references/`.
- A reference-only content change does not require recomposition when its route is unchanged. Run harness verification to validate routing and UTF-8.
- Recompose and verify after changing `.agent/project.md`, `.agent/profile.yml`, or another composed instruction source.

1
CLAUDE.md Normal file
View File

@@ -0,0 +1 @@
@AGENTS.md

1455
README.md

File diff suppressed because it is too large Load Diff

View File

@@ -3,14 +3,20 @@ plugins {
id 'maven-publish' id 'maven-publish'
} }
//버전 변경은 여기서 // 버전 변경은 여기서
def commonVer = "1.0.3" def commonVer = "beta.1.7.1"
group = 'com.kri.common' group = 'com.kri.common'
version = commonVer version = commonVer
java { java {
toolchain { languageVersion = JavaLanguageVersion.of(17) } toolchain {
languageVersion = JavaLanguageVersion.of(17)
}
}
tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8'
} }
repositories { repositories {
@@ -29,23 +35,37 @@ dependencies {
// ==== 여기부터는 버전 안 써도 됨 (BOM이 버전 정해줌) ==== // ==== 여기부터는 버전 안 써도 됨 (BOM이 버전 정해줌) ====
// JWT // JWT
api 'io.jsonwebtoken:jjwt-api:0.11.5' api 'io.jsonwebtoken:jjwt-api:0.12.6'
runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.5' runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.12.6'
runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.11.5' runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.12.6'
// Security Core // Security Core
api 'org.springframework.security:spring-security-core' api 'org.springframework.security:spring-security-core'
// HttpSecurity, SecurityFilterChain, WebSecurityCustomizer 등 들어있는 모듈들
compileOnly 'org.springframework.security:spring-security-config'
compileOnly 'org.springframework.security:spring-security-web'
// Swagger / OpenAPI 어노테이션 (@Schema 등) - 컴파일용 // Swagger / OpenAPI 어노테이션 (@Schema 등) - 컴파일용
compileOnly 'io.swagger.core.v3:swagger-annotations:2.2.25' compileOnly 'io.swagger.core.v3:swagger-annotations:2.2.25'
compileOnly 'io.swagger.core.v3:swagger-models:2.2.25'
compileOnly 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.6.0'
// JPA AttributeConverter, Entity 등 인터페이스용
compileOnly 'org.springframework.boot:spring-boot-starter-data-jpa'
// Lombok // Lombok
compileOnly 'org.projectlombok:lombok' compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok' annotationProcessor 'org.projectlombok:lombok'
// Json Util
implementation 'com.fasterxml.jackson.core:jackson-databind:2.17.0'
// Excel Util
implementation 'org.apache.poi:poi-ooxml:5.5.1'
// ConfigurationProperties 메타데이터 // ConfigurationProperties 메타데이터
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor' annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
compileOnly 'org.springframework.boot:spring-boot-autoconfigure'
// 자동구성/웹/검증/AOP/Redis는 컴파일만 (전이 방지) // 자동구성/웹/검증/AOP/Redis는 컴파일만 (전이 방지)
compileOnly 'org.springframework.boot:spring-boot-autoconfigure' compileOnly 'org.springframework.boot:spring-boot-autoconfigure'
@@ -55,26 +75,105 @@ dependencies {
compileOnly 'org.springframework.boot:spring-boot-starter-data-redis' compileOnly 'org.springframework.boot:spring-boot-starter-data-redis'
} }
def giteaUser = findProperty("giteaUser") ?: "" def giteaUser = findProperty('giteaUser') ?: System.getenv('GITEA_USER') ?: ''
def giteaToken = findProperty("giteaToken") ?: "" def giteaToken = findProperty('giteaToken') ?: System.getenv('GITEA_TOKEN') ?: ''
publishing { publishing {
publications { publications {
release(MavenPublication) { release(MavenPublication) {
from components.java from components.java
groupId = 'com.kri.common' groupId = 'com.kri.common'
artifactId = 'starter' // 소비 프로젝트에서 쓰는 artifactId artifactId = 'starter'
version = commonVer version = commonVer
} }
} }
repositories { repositories {
maven { maven {
name = "gitea" name = 'gitea'
url = uri("https://gitea.kric.com/api/packages/KRi/maven") // owner=KRi url = uri('https://gitea.kric.com/api/packages/KRi/maven')
//allowInsecureProtocol = true
credentials { credentials {
username = giteaUser // 또는 본인 계정 username = giteaUser
password = giteaToken password = giteaToken
} }
} }
} }
} }
def checkHttpStatus = { String targetUrl, String auth, String method ->
HttpURLConnection conn = null
try {
conn = (HttpURLConnection) new URL(targetUrl).openConnection()
conn.setRequestMethod(method)
conn.setRequestProperty('Authorization', "Basic ${auth}")
conn.setConnectTimeout(10000)
conn.setReadTimeout(10000)
return conn.getResponseCode()
} finally {
if (conn != null) {
conn.disconnect()
}
}
}
tasks.register('checkGiteaPackageVersionNotExists') {
group = 'publishing'
description = 'Gitea Packages에 동일한 Maven package version이 이미 존재하는지 확인합니다.'
doLast {
def packageGroupId = 'com.kri.common'
def packageArtifactId = 'starter'
def packageVersion = commonVer
def packageOwner = 'KRi'
if (!giteaUser || !giteaToken) {
throw new GradleException(
'[GITEA_AUTH_MISSING] Gitea 인증정보가 없습니다. ' +
'giteaUser/giteaToken 또는 GITEA_USER/GITEA_TOKEN을 확인하세요.'
)
}
def groupPath = packageGroupId.replace('.', '/')
def pomUrl = "https://gitea.kric.com/api/packages/${packageOwner}/maven/${groupPath}/${packageArtifactId}/${packageVersion}/${packageArtifactId}-${packageVersion}.pom"
def auth = "${giteaUser}:${giteaToken}".bytes.encodeBase64().toString()
def status = checkHttpStatus(pomUrl, auth, 'HEAD')
if (status == 405) {
status = checkHttpStatus(pomUrl, auth, 'GET')
}
if (status >= 200 && status < 300) {
throw new GradleException(
"[DUPLICATE_PACKAGE_VERSION] 이미 Gitea Packages에 동일 패키지가 존재합니다. " +
"package=${packageGroupId}:${packageArtifactId}:${packageVersion}. " +
"build.gradle의 commonVer를 올린 뒤 다시 배포하세요."
)
}
if (status == 404) {
println "Gitea Packages 중복 없음: ${packageGroupId}:${packageArtifactId}:${packageVersion}"
return
}
if (status == 401 || status == 403) {
throw new GradleException(
"[GITEA_AUTH_FAILED] Gitea Packages 조회 권한 오류입니다. " +
"HTTP status=${status}. Jenkins credential 또는 token 권한을 확인하세요."
)
}
throw new GradleException(
"[GITEA_PACKAGE_CHECK_FAILED] Gitea Packages 중복 확인에 실패했습니다. " +
"HTTP status=${status}, url=${pomUrl}"
)
}
}
tasks.named('publishReleasePublicationToGiteaRepository') {
dependsOn 'checkGiteaPackageVersionNotExists'
}

View File

@@ -1,58 +0,0 @@
package com.kri.common.auth.apikey;
import com.kri.common.auth.jwt.JwtService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
/**
* X-API-Key (또는 설정된 헤더) 기반 API Key 인증 필터.
* - API Key를 검증하는 로직은 ApiKeyUserClaimsProvider 구현체에 위임.
* - 유효하면 JwtUserClaimsDto → Authentication 으로 변환해서 SecurityContext에 세팅.
*/
@RequiredArgsConstructor
public class ApiKeyAuthFilter extends OncePerRequestFilter {
private final ApiKeyProperties apiKeyProperties;
private final ApiKeyUserClaimsProvider apiKeyUserClaimsProvider;
private final JwtService jwtService;
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain)
throws ServletException, IOException {
// API Key 기능이 꺼져 있으면 아무 것도 안 함
if (!apiKeyProperties.isEnabled()) {
filterChain.doFilter(request, response);
return;
}
// 이미 다른 방식(JWT 등)으로 인증되어 있으면 패스
if (SecurityContextHolder.getContext().getAuthentication() != null) {
filterChain.doFilter(request, response);
return;
}
String headerName = apiKeyProperties.getHeaderName();
String apiKey = request.getHeader(headerName);
if (StringUtils.hasText(apiKey)) {
apiKeyUserClaimsProvider.findUserByApiKey(apiKey).ifPresent(dto -> {
Authentication auth = jwtService.toAuthentication(dto);
SecurityContextHolder.getContext().setAuthentication(auth);
});
}
filterChain.doFilter(request, response);
}
}

View File

@@ -1,22 +0,0 @@
package com.kri.common.auth.apikey;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Getter
@Setter
@ConfigurationProperties(prefix = "kri.auth.apikey")
public class ApiKeyProperties {
/**
* API Key 인증 사용 여부
*/
private boolean enabled = false;
/**
* API Key 를 읽어올 헤더 이름
* 예: X-API-Key, X-EXTERNAL-KEY 등
*/
private String headerName = "X-API-Key";
}

View File

@@ -1,19 +0,0 @@
package com.kri.common.auth.apikey;
import com.kri.common.auth.jwt.JwtUserClaimsDto;
import java.util.Optional;
/**
* 외부에서 들어온 API Key를 우리 시스템의 유저 정보(JwtUserClaimsDto)로 매핑하는 인터페이스.
* 각 서비스에서 이 인터페이스 구현체를 Bean으로 등록하면 된다.
*/
public interface ApiKeyUserClaimsProvider {
/**
* API Key 로 사용자 정보를 조회한다.
*
* @param apiKey 요청 헤더에서 받은 API Key
* @return 유효한 키면 JwtUserClaimsDto, 아니면 Optional.empty()
*/
Optional<JwtUserClaimsDto> findUserByApiKey(String apiKey);
}

View File

@@ -1,34 +0,0 @@
package com.kri.common.auth.jwt;
import com.kri.common.auth.apikey.ApiKeyAuthFilter;
import com.kri.common.auth.apikey.ApiKeyProperties;
import com.kri.common.auth.apikey.ApiKeyUserClaimsProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties({JwtProperties.class, ApiKeyProperties.class})
public class JwtAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public JwtService jwtService(JwtProperties properties) {
return new JwtService(properties);
}
/**
* ApiKeyUserClaimsProvider 구현체가 존재할 때만 API Key 필터 자동 생성.
* (실제 필터 체인에 넣는 건 각 서비스의 SecurityConfig 에서 addFilterBefore 로 수행)
*/
@Bean
@ConditionalOnBean(ApiKeyUserClaimsProvider.class)
@ConditionalOnMissingBean
public ApiKeyAuthFilter apiKeyAuthFilter(ApiKeyProperties apiKeyProperties,
ApiKeyUserClaimsProvider provider,
JwtService jwtService) {
return new ApiKeyAuthFilter(apiKeyProperties, provider, jwtService);
}
}

View File

@@ -1,33 +0,0 @@
package com.kri.common.auth.jwt;
import lombok.*;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ConfigurationProperties(prefix = "kri.auth.jwt")
public class JwtProperties {
/**
* HMAC 서명에 사용할 시크릿 키 (최소 32자 이상 권장)
*/
private String secret = "K0r2@#R2s2@rch#!nt2rn@t!0n@l#!T$T2@M";
/**
* 토큰 발급자(issuer)
*/
private String issuer = "kri-it";
/**
* Access Token 유효 시간(초 단위)
*/
private long accessTokenValiditySeconds = 24 * 3600; // 기본 24시간
/**
* (선택) Refresh Token 유효 시간(초 단위)
*/
private long refreshTokenValiditySeconds = 7 * 24 * 3600; // 기본 7일
}

View File

@@ -1,198 +0,0 @@
package com.kri.common.auth.jwt;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.*;
/**
* 공통 JWT 유틸 서비스
* - DTO: JwtUserClaimsDto 기준으로 토큰 생성/파싱
* - 일반 JWT + 내부 고정 토큰 둘 다 지원
*/
@RequiredArgsConstructor
public class JwtService {
private final JwtProperties properties;
private SecretKey key;
@PostConstruct
public void init() {
// secret 문자열을 HMAC 키로 전환
this.key = Keys.hmacShaKeyFor(
properties.getSecret().getBytes(StandardCharsets.UTF_8)
);
}
// ======================================================
// 내부 공통 빌더
// ======================================================
private String buildToken(Map<String, Object> claims, String subject, long validitySeconds) {
Date now = new Date();
Date expiry = new Date(now.getTime() + validitySeconds * 1000);
return Jwts.builder()
.setClaims(claims)
.setSubject(subject)
.setIssuer(properties.getIssuer())
.setIssuedAt(now)
.setExpiration(expiry)
.signWith(key, SignatureAlgorithm.HS256)
.compact();
}
private Map<String, Object> buildClaims(JwtUserClaimsDto dto) {
Map<String, Object> claims = new HashMap<>();
// 필요한 항목만 골라서 claim에 넣어줌
claims.put("userId", dto.getUserId());
claims.put("userTeam", dto.getUserTeam());
claims.put("userName", dto.getUserName());
claims.put("role", dto.getRole());
return claims;
}
// ======================================================
// 토큰 생성 (DTO 기반)
// ======================================================
/**
* JwtUserClaimsDto 기반 Access Token 생성
* - subject = userId
* - claims:
* userId, userTeam, userName, role
*/
public String generateSystemToken(JwtUserClaimsDto userClaims) {
Map<String, Object> claims = buildClaims(userClaims);
return buildToken(
claims,
userClaims.getUserId(),
properties.getAccessTokenValiditySeconds()
);
}
/**
* JwtUserClaimsDto 기반 Access Token 생성
* - subject = userId
* - claims:
* userId, userTeam, userName, role
*/
public String generateAccessToken(JwtUserClaimsDto userClaims) {
Map<String, Object> claims = buildClaims(userClaims);
return buildToken(
claims,
userClaims.getUserId(),
properties.getAccessTokenValiditySeconds()
);
}
/**
* Refresh Token은 보통 userId만 넣고 심플하게 사용
*/
public String generateRefreshToken(String userId) {
return buildToken(
Collections.emptyMap(),
userId,
properties.getRefreshTokenValiditySeconds()
);
}
// ======================================================
// 토큰 파싱
// ======================================================
/**
* 토큰 파싱 + 서명/만료 검증
*/
public Jws<Claims> parseToken(String token) throws JwtException {
return Jwts.parserBuilder()
.requireIssuer(properties.getIssuer())
.setSigningKey(key)
.build()
.parseClaimsJws(token);
}
/**
* 토큰에서 Claims만 추출 (검증 포함)
*/
public Claims getClaims(String token) throws JwtException {
return parseToken(token).getBody();
}
/**
* Claims → JwtUserClaimsDto 변환
*/
public JwtUserClaimsDto toUserClaimsDto(Claims claims) {
// userId는 subject와 별도 claim 둘 다에서 시도
String userId = claims.get("userId", String.class);
if (userId == null) {
userId = claims.getSubject();
}
String userTeam = claims.get("userTeam", String.class);
String userName = claims.get("userName", String.class);
// 숫자는 Integer / Long 등으로 들어올 수 있으니 Number로 받았다가 intValue()
Number roleNumber = claims.get("role", Number.class);
Integer role = roleNumber != null ? roleNumber.intValue() : null;
return JwtUserClaimsDto.builder()
.userId(userId)
.userTeam(userTeam)
.userName(userName)
.role(role)
.build();
}
/**
* 토큰 → JwtUserClaimsDto 바로 추출
*/
public JwtUserClaimsDto toUserClaimsDto(String token) throws JwtException {
Claims claims = getClaims(token);
return toUserClaimsDto(claims);
}
// ======================================================
// Authentication 변환 (Spring Security 연동용)
// ======================================================
/**
* DTO → Spring Security Authentication 변환
* 여기서는 간단하게 "ROLE_{role값}" 형태로 Authority를 구성.
* ex) role = 1 → "ROLE_1"
* 실제 프로젝트에서 0/1/2 같은 값에 대한 의미 매핑이 명확하다면,
* 이 메서드 안의 매핑 로직만 교체해서 쓰면 됨.
*/
public Authentication toAuthentication(JwtUserClaimsDto dto) {
String principal = dto.getUserId();
List<GrantedAuthority> authorities = new ArrayList<>();
if (dto.getRole() != null) {
String authority = "ROLE_" + dto.getRole();
authorities.add(new SimpleGrantedAuthority(authority));
}
return new UsernamePasswordAuthenticationToken(
principal,
null,
authorities
);
}
/**
* 토큰 → Authentication 변환 (JWT 파싱 + DTO 변환까지 한 번에)
*/
public Authentication toAuthentication(String token) throws JwtException {
JwtUserClaimsDto dto = toUserClaimsDto(token);
return toAuthentication(dto);
}
}

View File

@@ -1,26 +0,0 @@
package com.kri.common.auth.jwt;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Builder;
import lombok.Value;
@Schema(
name = "JwtUserClaimsDto",
description = "JWT에 포함되는 사용자 정보"
)
@Value
@Builder
public class JwtUserClaimsDto {
@Schema(description = "사용자 ID")
String userId;
@Schema(description = "팀 코드")
String userTeam;
@Schema(description = "사용자 이름")
String userName;
@Schema(description = "권한 코드")
Integer role;
}

View File

@@ -0,0 +1,18 @@
package com.kri.common.autoconfigure.auth.apikey;
import com.kri.common.endpoint.auth.apikey.ApiKeyAdminController;
import com.kri.common.runtime.auth.apikey.PreloadedApiKeyUserClaimsProvider;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Import;
@AutoConfiguration(after = ApiKeyPreloadAutoConfiguration.class)
@ConditionalOnClass(ApiKeyAdminController.class)
@ConditionalOnBean(PreloadedApiKeyUserClaimsProvider.class)
@ConditionalOnProperty(prefix = "kri.auth.apikey", name = "admin-api-enabled", havingValue = "true")
@Import(ApiKeyAdminController.class) // 컴포넌트 스캔 없이도 Bean 등록
public class ApiKeyAdminAutoConfiguration {
}

View File

@@ -0,0 +1,114 @@
package com.kri.common.autoconfigure.auth.apikey;
import com.zaxxer.hikari.HikariDataSource;
import jakarta.persistence.EntityManagerFactory;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.jpa.repository.config.JpaMetamodelMappingContextFactoryBean;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.persistenceunit.PersistenceUnitManager;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
/*
* @Primary 절대 금지
* 메인 JPA와 완전히 분리
*/
@AutoConfiguration(
afterName = {
// 메인 JPA가 있는 서비스에서는 메인 auto-config 이후에 올라와도 되고,
// 메인 JPA를 exclude한 서비스에서는 afterName이 무시되어도 동작해야 함.
"org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration",
"org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration"
}
)
@ConditionalOnClass(name = {
"org.springframework.data.jpa.repository.JpaRepository",
"jakarta.persistence.EntityManagerFactory",
"com.zaxxer.hikari.HikariDataSource"
})
@ConditionalOnProperty(prefix = "kri.auth.apikey", name = "enabled", havingValue = "true")
@EnableJpaRepositories(
basePackages = "com.kri.common.runtime.auth.apikey.persistence.repository",
entityManagerFactoryRef = "apiKeyEntityManagerFactory",
transactionManagerRef = "apiKeyTransactionManager"
)
@EnableConfigurationProperties(ApiKeyProperties.class)
public class ApiKeyJpaAutoConfiguration {
@Bean(name = "apiKeyDataSource")
public DataSource apiKeyDataSource(ApiKeyProperties props) {
var db = props.getDb();
HikariDataSource ds = new HikariDataSource();
ds.setJdbcUrl(db.getUrl());
ds.setUsername(db.getUsername());
ds.setPassword(db.getPassword());
ds.setDriverClassName(db.getDriverClassName());
return ds;
}
/**
* ✅ EntityManagerFactoryBuilder에 의존하지 않는 방식 - intranet-extension처럼 HibernateJpaAutoConfiguration을
* exclude 해도 동작
*/
@Bean(name = "apiKeyEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean apiKeyEntityManagerFactory(
@Qualifier("apiKeyDataSource") DataSource ds,
ObjectProvider<PersistenceUnitManager> pumProvider,
ApiKeyProperties props
) {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setShowSql(props.getJpa().isShowSql());
vendorAdapter.setGenerateDdl(false);
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(ds);
emf.setJpaVendorAdapter(vendorAdapter);
emf.setPackagesToScan("com.kri.common.runtime.auth.apikey.persistence.entity");
emf.setPersistenceUnitName("apikey");
PersistenceUnitManager pum = pumProvider.getIfAvailable();
if (pum != null) {
emf.setPersistenceUnitManager(pum);
}
// 최소 JPA 속성들 (원하면 yml로 확장 가능)
Map<String, Object> jpaProps = new HashMap<>();
jpaProps.put("hibernate.show_sql", Boolean.toString(props.getJpa().isShowSql()));
jpaProps.put("hibernate.format_sql", Boolean.toString(props.getJpa().isFormatSql()));
emf.setJpaPropertyMap(jpaProps);
return emf;
}
@Bean(name = "apiKeyTransactionManager")
public PlatformTransactionManager apiKeyTransactionManager(
@Qualifier("apiKeyEntityManagerFactory") EntityManagerFactory emf
) {
return new JpaTransactionManager(emf);
}
/**
* ✅ intranet-extension처럼 메인 JPA auto-config를 exclude해서 'jpaMappingContext'가 없을 때만 보완해준다.
* <p>
* 메인 JPA가 있는 서비스에서는 이미 jpaMappingContext가 있으므로 이 빈은 생성되지 않아 영향이 없다.
*/
@Bean(name = "jpaMappingContext")
@ConditionalOnMissingBean(name = "jpaMappingContext")
public JpaMetamodelMappingContextFactoryBean jpaMappingContext(ApplicationContext ctx) {
// FactoryBean으로 등록하면 내부에서 EntityManagerFactory들을 찾아 Metamodel을 구성함
return new JpaMetamodelMappingContextFactoryBean();
}
}

View File

@@ -0,0 +1,29 @@
package com.kri.common.autoconfigure.auth.apikey;
import com.kri.common.feature.auth.apikey.ApiKeyUserClaimsProvider;
import com.kri.common.runtime.auth.apikey.PreloadedApiKeyUserClaimsProvider;
import com.kri.common.runtime.auth.apikey.persistence.repository.ApiKeyRepository;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
@AutoConfiguration(after = ApiKeyJpaAutoConfiguration.class)
@EnableConfigurationProperties(ApiKeyProperties.class)
@ConditionalOnClass(name = "org.springframework.data.jpa.repository.JpaRepository")
@ConditionalOnProperty(prefix = "kri.auth.apikey", name = "enabled", havingValue = "true")
public class ApiKeyPreloadAutoConfiguration {
@Bean
@ConditionalOnBean(ApiKeyRepository.class)
@ConditionalOnMissingBean(ApiKeyUserClaimsProvider.class)
public PreloadedApiKeyUserClaimsProvider apiKeyUserClaimsProvider(
ApiKeyProperties props,
ApiKeyRepository repo
) {
return new PreloadedApiKeyUserClaimsProvider(props, repo);
}
}

View File

@@ -0,0 +1,96 @@
package com.kri.common.autoconfigure.auth.apikey;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Getter
@Setter
@ConfigurationProperties(prefix = "kri.auth.apikey")
public class ApiKeyProperties {
public static final List<String> DEFAULT_ADMIN_ALLOW_IPS = List.of(
"127.0.0.1/32",
"localhost",
"0:0:0:0:0:0:0:1"
);
/**
* API Key 인증 허용 여부
*/
private boolean enabled = false;
/**
* API Key 를 읽어올 헤더 이름 예: X-API-Key, X-EXTERNAL-KEY 등
*/
private String headerName = "X-API-Key";
/**
* API Key 인증을 시도할 URL 패턴. 미설정, null 또는 빈 목록이면 모든 요청에서 인증을 시도한다.
*/
private List<String> allowedPaths = List.of();
/**
* API Key 인증에서 제외할 URL 패턴. 허용 패턴보다 우선한다.
*/
private List<String> excludedPaths = List.of();
/**
* 이 서비스의 코드 (서비스별 preload 범위 결정)
*/
private String serviceCode;
/**
* 기동 시 preload 할지
*/
private boolean preloadOnStartup = false;
/**
* 내부 관리 API(리로드/조회) 노출 여부
*/
private boolean adminApiEnabled = false;
/**
* 내부 관리 API 접근 허용 IP(CIDR)
*/
private List<String> adminAllowIps = DEFAULT_ADMIN_ALLOW_IPS;
/**
* apikey 전용 DB 설정(기본값 포함)
*/
private Db db = new Db();
/**
* apikey 전용 JPA 옵션
*/
private Jpa jpa = new Jpa();
@Getter
@Setter
public static class Jpa {
/**
* hibernate.show_sql
*/
private boolean showSql = false;
/**
* hibernate.format_sql
*/
private boolean formatSql = false;
}
@Getter
@Setter
public static class Db {
//내부 통신용 url
private String url =
"jdbc:mysql://db-md87m-kr.vpc-pub-cdb.ntruss.com:3306/kri_common?characterEncoding=UTF-8";
private String username = "kriit";
private String password = "it#51304";
private String driverClassName = "com.mysql.cj.jdbc.Driver";
}
}

View File

@@ -0,0 +1,33 @@
package com.kri.common.autoconfigure.auth.jwt;
import com.kri.common.runtime.auth.apikey.ApiKeyAuthFilter;
import com.kri.common.autoconfigure.auth.apikey.ApiKeyProperties;
import com.kri.common.feature.auth.apikey.ApiKeyUserClaimsProvider;
import com.kri.common.feature.auth.jwt.JwtService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties({JwtProperties.class, ApiKeyProperties.class})
public class JwtAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public JwtService jwtService(JwtProperties properties) {
return new JwtService(properties);
}
@Bean
@ConditionalOnBean(ApiKeyUserClaimsProvider.class)
@ConditionalOnMissingBean
public ApiKeyAuthFilter apiKeyAuthFilter(
ApiKeyProperties apiKeyProperties,
ApiKeyUserClaimsProvider provider,
JwtService jwtService
) {
return new ApiKeyAuthFilter(apiKeyProperties, provider, jwtService);
}
}

View File

@@ -0,0 +1,35 @@
package com.kri.common.autoconfigure.auth.jwt;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ConfigurationProperties(prefix = "kri.auth.jwt")
public class JwtProperties {
/**
* HMAC 서명에 사용할 시크릿 키 (최소 32자 이상 권장)
*/
private String secret = "K0r2@#R2s2@rch#!nt2rn@t!0n@l#!T$T2@M";
/**
* 토큰 발급자(issuer)
*/
private String issuer = "kri-it";
/**
* Access Token 유효 시간(초 단위)
*/
private long accessTokenValiditySeconds = 24 * 3600; // 기본 24시간
/**
* (선택) Refresh Token 유효 시간(초 단위)
*/
private long refreshTokenValiditySeconds = 7 * 24 * 3600; // 기본 7일
}

View File

@@ -0,0 +1,38 @@
package com.kri.common.autoconfigure.crypto;
import com.kri.common.feature.crypto.aes.AesCryptoService;
import com.kri.common.feature.crypto.hash.AdaptiveHashService;
import com.kri.common.feature.crypto.hash.DigestService;
import com.kri.common.runtime.crypto.aes.DefaultAesCryptoService;
import com.kri.common.runtime.crypto.hash.BCryptAdaptiveHashService;
import com.kri.common.runtime.crypto.hash.JdkDigestService;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@AutoConfiguration
@EnableConfigurationProperties(CryptoProperties.class)
public class CryptoAutoConfiguration {
@Bean
@ConditionalOnMissingBean(AesCryptoService.class)
public AesCryptoService aesCryptoService(CryptoProperties properties) {
return new DefaultAesCryptoService(properties);
}
@Bean
@ConditionalOnMissingBean(DigestService.class)
public DigestService digestService() {
return new JdkDigestService();
}
@Bean
@ConditionalOnClass(BCryptPasswordEncoder.class)
@ConditionalOnMissingBean(AdaptiveHashService.class)
public AdaptiveHashService adaptiveHashService(CryptoProperties properties) {
return new BCryptAdaptiveHashService(properties.getHash().getBcrypt().getStrength());
}
}

View File

@@ -0,0 +1,54 @@
package com.kri.common.autoconfigure.crypto;
import com.kri.common.feature.crypto.aes.AesAlgorithm;
import com.kri.common.feature.crypto.aes.TagLayout;
import java.util.LinkedHashMap;
import java.util.Map;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Getter
@Setter
@ConfigurationProperties(prefix = "kri.crypto")
public class CryptoProperties {
private Aes aes = new Aes();
private Hash hash = new Hash();
@Getter
@Setter
public static class Aes {
/** 직접 master key를 전달하지 않았을 때 사용할 key ID입니다. */
private String activeKeyId;
/** key ID별 master key입니다. 실제 값은 로그나 소스 관리에 노출하지 않아야 합니다. */
private Map<String, String> keys = new LinkedHashMap<>();
/** 기본 AES 알고리즘입니다. */
private AesAlgorithm algorithm = AesAlgorithm.AES_256_GCM;
/** AES-GCM 인증 태그의 기본 저장 형태입니다. */
private TagLayout tagLayout = TagLayout.APPENDED;
private Kdf kdf = new Kdf();
}
@Getter
@Setter
public static class Kdf {
/** PBKDF2-HMAC-SHA256 반복 횟수입니다. */
private int iterations = 600_000;
/** 자동 생성하는 salt 길이(byte)입니다. 최소 16입니다. */
private int saltLength = 16;
}
@Getter
@Setter
public static class Hash {
private Bcrypt bcrypt = new Bcrypt();
}
@Getter
@Setter
public static class Bcrypt {
/** BCrypt cost입니다. 허용 범위는 4부터 31까지입니다. */
private int strength = 12;
}
}

View File

@@ -0,0 +1,23 @@
package com.kri.common.autoconfigure.http;
import com.kri.common.runtime.web.ExternalApiResponseAdvice;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
@AutoConfiguration
@ConditionalOnClass(name = {
"jakarta.servlet.http.HttpServletRequest",
"org.springframework.web.servlet.DispatcherServlet"
})
@ConditionalOnProperty(prefix = "kri.web", name = "enabled", havingValue = "true", matchIfMissing = true)
public class ExternalApiErrorAutoConfiguration {
@Bean
@ConditionalOnMissingBean(value = ExternalApiResponseAdvice.class, name = "externalApiResponseAdvice")
public ExternalApiResponseAdvice externalApiResponseAdvice() {
return new ExternalApiResponseAdvice();
}
}

View File

@@ -0,0 +1,37 @@
package com.kri.common.autoconfigure.http.bypass;
import com.kri.common.feature.http.bypass.BypassClient;
import com.kri.common.feature.http.bypass.BypassRequestCustomizer;
import com.kri.common.feature.http.bypass.BypassResponseCustomizer;
import com.kri.common.runtime.http.bypass.DefaultBypassClient;
import jakarta.servlet.http.HttpServletRequest;
import java.net.http.HttpClient;
import java.util.Map;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
@AutoConfiguration
@ConditionalOnClass({HttpServletRequest.class, HttpClient.class})
@ConditionalOnExpression("${kri.http.bypass.enabled:false}")
@EnableConfigurationProperties(BypassProperties.class)
public class BypassAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public BypassClient bypassClient(
BypassProperties properties,
ListableBeanFactory beanFactory
) {
Map<String, BypassRequestCustomizer> requestCustomizers =
beanFactory.getBeansOfType(BypassRequestCustomizer.class);
Map<String, BypassResponseCustomizer> responseCustomizers =
beanFactory.getBeansOfType(BypassResponseCustomizer.class);
return new DefaultBypassClient(properties, requestCustomizers, responseCustomizers);
}
}

View File

@@ -0,0 +1,34 @@
package com.kri.common.autoconfigure.http.bypass;
import java.time.Duration;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Getter
@Setter
@ConfigurationProperties(prefix = "kri.http.bypass")
public class BypassProperties {
private boolean enabled = false;
private Duration connectTimeout = Duration.ofSeconds(10);
private Duration requestTimeout = Duration.ofSeconds(30);
private Map<String, Target> targets = new LinkedHashMap<>();
@Getter
@Setter
public static class Target {
private String baseUrl;
private String stripPrefix;
private List<String> allowedPaths = new ArrayList<>();
private Duration requestTimeout;
private boolean throwOnError = false;
private List<String> requestCustomizers = new ArrayList<>();
private List<String> responseCustomizers = new ArrayList<>();
}
}

View File

@@ -0,0 +1,32 @@
package com.kri.common.autoconfigure.redis;
import com.kri.common.feature.redis.RedisQueueHelper;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
@AutoConfiguration
@ConditionalOnClass(RedisTemplate.class)
@ConditionalOnExpression("${kri.redis.enabled:false}")
@ConditionalOnBean(RedisConnectionFactory.class)
public class CommonRedisAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public StringRedisTemplate stringRedisTemplate(
org.springframework.data.redis.connection.RedisConnectionFactory cf) {
return new StringRedisTemplate(cf);
}
@Bean
@ConditionalOnMissingBean
public RedisQueueHelper redisQueueHelper(StringRedisTemplate rt) {
return new RedisQueueHelper(rt);
}
}

View File

@@ -1,10 +1,12 @@
package com.kri.common.scheduling; package com.kri.common.autoconfigure.scheduling;
import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.EnableScheduling;
@AutoConfiguration @AutoConfiguration
@EnableScheduling @EnableScheduling
@ConditionalOnProperty(prefix = "common.scheduling", name = "enabled", havingValue = "true", matchIfMissing = false) @ConditionalOnExpression("${kri.scheduling.enabled:false}")
public class CommonSchedulingAutoConfiguration { } public class CommonSchedulingAutoConfiguration {
}

View File

@@ -0,0 +1,102 @@
package com.kri.common.autoconfigure.security;
import com.kri.common.runtime.auth.apikey.ApiKeyAuthFilter;
import com.kri.common.feature.auth.jwt.JwtService;
import com.kri.common.runtime.security.IpAllowlistAuthorizationManager;
import com.kri.common.runtime.security.JwtAuthenticationFilter;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authorization.AuthenticatedAuthorizationManager;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@AutoConfiguration(before = SecurityAutoConfiguration.class)
@EnableConfigurationProperties(KriSecurityProperties.class)
@ConditionalOnProperty(prefix = "kri.security", name = "enabled", havingValue = "true", matchIfMissing = true)
@EnableMethodSecurity(
jsr250Enabled = true,
prePostEnabled = true
)
@RequiredArgsConstructor
public class KriSecurityAutoConfiguration {
private final KriSecurityProperties securityProperties;
@Bean
@ConditionalOnMissingBean
public JwtAuthenticationFilter jwtAuthenticationFilter(JwtService jwtService) {
return new JwtAuthenticationFilter(jwtService);
}
/**
* 서비스에서 SecurityFilterChain 을 따로 정의하지 않으면 이 기본 Security 구성이 적용된다.
*/
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Bean
@ConditionalOnMissingBean(SecurityFilterChain.class)
public SecurityFilterChain kriSecurityFilterChain(
HttpSecurity http,
ObjectProvider<ApiKeyAuthFilter> apiKeyAuthFilterProvider,
JwtAuthenticationFilter jwtAuthenticationFilter
) throws Exception {
IpAllowlistAuthorizationManager ipAllowlist =
new IpAllowlistAuthorizationManager(securityProperties.getAllowedIps());
http
.httpBasic(AbstractHttpConfigurer::disable)
.csrf(AbstractHttpConfigurer::disable)
.cors(Customizer.withDefaults())
.sessionManagement(session ->
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
)
.authorizeHttpRequests(auth -> {
// ✅ yaml에서 정의한 public-paths 전부 permitAll
if (securityProperties.getPublicPaths() != null && !securityProperties.getPublicPaths()
.isEmpty()) {
if (ipAllowlist.isConfigured()) {
auth.requestMatchers(securityProperties.getPublicPaths().toArray(String[]::new))
.access(ipAllowlist);
} else {
auth.requestMatchers(securityProperties.getPublicPaths().toArray(String[]::new))
.permitAll();
}
}
// ✅ 나머지는 전부 인증 필요
if (ipAllowlist.isConfigured()) {
auth.anyRequest().access((authentication, context) -> {
AuthorizationDecision ipDecision = ipAllowlist.check(authentication, context);
if (ipDecision == null || !ipDecision.isGranted()) {
return new AuthorizationDecision(false);
}
return AuthenticatedAuthorizationManager.<RequestAuthorizationContext>authenticated()
.check(authentication, context);
});
} else {
auth.anyRequest().authenticated();
}
});
// ✅ API Key 필터가 존재하면 먼저 태움
apiKeyAuthFilterProvider.ifAvailable(filter ->
http.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class)
);
// ✅ 그 다음 JWT 필터
http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
}

View File

@@ -0,0 +1,31 @@
package com.kri.common.autoconfigure.security;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Getter
@Setter
@ConfigurationProperties(prefix = "kri.security")
public class KriSecurityProperties {
/**
* 이 자동구성 사용 여부
*/
private boolean enabled = true;
/**
* 인증 없이 허용할 URL 패턴들 서비스에서 application.yml로 오버라이드
*/
private List<String> publicPaths = List.of(
"/v3/api-docs/**",
"/swagger-ui.html",
"/swagger-ui/**"
);
/**
* IP allowlist applied by the default SecurityFilterChain. Empty means no IP restriction.
*/
private List<String> allowedIps = List.of();
}

View File

@@ -0,0 +1,150 @@
package com.kri.common.autoconfigure.swagger;
import com.kri.common.autoconfigure.auth.apikey.ApiKeyProperties;
import com.kri.common.feature.web.RequestUserContext;
import com.kri.common.runtime.swagger.CodeEnumOpenApiCustomizer;
import com.kri.common.runtime.swagger.CodeEnumModelConverter;
import com.kri.common.runtime.swagger.CodeEnumSwaggerSupport;
import com.kri.common.runtime.swagger.SwaggerIpFilter;
import io.swagger.v3.core.converter.AnnotatedType;
import io.swagger.v3.core.converter.ModelConverter;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import jakarta.annotation.PostConstruct;
import java.util.LinkedHashSet;
import java.util.Set;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.customizers.GlobalOpenApiCustomizer;
import org.springdoc.core.customizers.ParameterCustomizer;
import org.springdoc.core.customizers.PropertyCustomizer;
import org.springdoc.core.models.GroupedOpenApi;
import org.springdoc.core.utils.SpringDocUtils;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.MethodParameter;
@AutoConfiguration(beforeName = "org.springdoc.core.configuration.SpringDocConfiguration")
@EnableConfigurationProperties(KriSwaggerProperties.class)
@ConditionalOnClass({OpenAPI.class, GroupedOpenApi.class})
@ConditionalOnProperty(prefix = "kri.swagger", name = "enabled", havingValue = "true", matchIfMissing = true)
@RequiredArgsConstructor
public class KriSwaggerAutoConfiguration {
private static final String API_KEY_ADMIN_PACKAGE = "com.kri.common.endpoint.auth.apikey";
private final KriSwaggerProperties properties;
private final ApiKeyProperties apiKeyProperties; // apikey.header-name 읽기용
@PostConstruct
void hideRequestUserContext() {
SpringDocUtils.getConfig().addRequestWrapperToIgnore(RequestUserContext.class);
}
@Bean
@ConditionalOnMissingBean
public OpenAPI kriOpenAPI() {
// JWT Bearer + API Key 스키마 정의
Components components = new Components()
.addSecuritySchemes("BearerAuth",
new SecurityScheme()
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT"))
.addSecuritySchemes("ApiKeyAuth",
new SecurityScheme()
.type(SecurityScheme.Type.APIKEY)
.in(SecurityScheme.In.HEADER)
.name(apiKeyProperties.getHeaderName())); // 예: X-API-Key
// 두 보안 스키마를 기본 보안 요구사항으로 등록
SecurityRequirement bearerRequirement = new SecurityRequirement()
.addList("BearerAuth");
SecurityRequirement apiKeyRequirement = new SecurityRequirement()
.addList("ApiKeyAuth");
return new OpenAPI()
.components(components)
.addSecurityItem(bearerRequirement)
.addSecurityItem(apiKeyRequirement)
.info(new Info()
.title(properties.getTitle())
.description(properties.getDescription())
.version(properties.getVersion()));
}
@Bean(name = "kriGroupedOpenApi")
@ConditionalOnMissingBean(name = "kriGroupedOpenApi")
public GroupedOpenApi kriGroupedOpenApi() {
GroupedOpenApi.Builder builder = GroupedOpenApi.builder()
.group("kri-api")
.pathsToMatch("/api/**", "/internal/**");
Set<String> packagesToScan = new LinkedHashSet<>(properties.getBasePackage());
if (apiKeyProperties.isAdminApiEnabled()) {
packagesToScan.add(API_KEY_ADMIN_PACKAGE);
}
packagesToScan.removeIf(pack -> pack == null || pack.isBlank());
if (!packagesToScan.isEmpty()) {
builder.packagesToScan(packagesToScan.toArray(String[]::new));
}
return builder.build();
}
@Bean
@ConditionalOnMissingBean(name = "codeEnumModelConverter")
public ModelConverter codeEnumModelConverter() {
return new CodeEnumModelConverter();
}
@Bean
@ConditionalOnMissingBean(name = "codeEnumPropertyCustomizer")
public PropertyCustomizer codeEnumPropertyCustomizer() {
return (Schema property, AnnotatedType type) -> {
CodeEnumSwaggerSupport.resolveCodeEnumClass(type)
.ifPresent(enumClass -> CodeEnumSwaggerSupport.applyEnumMetadata(property, enumClass));
return property;
};
}
@Bean
@ConditionalOnMissingBean(name = "codeEnumParameterCustomizer")
public ParameterCustomizer codeEnumParameterCustomizer() {
return (Parameter parameterModel, MethodParameter methodParameter) -> {
CodeEnumSwaggerSupport.resolveCodeEnumClass(methodParameter.getParameterType())
.ifPresent(enumClass -> {
CodeEnumSwaggerSupport.applyEnumMetadata(parameterModel.getSchema(), enumClass);
parameterModel.description(
CodeEnumSwaggerSupport.mergeEnumDescription(parameterModel.getDescription(), enumClass));
});
return parameterModel;
};
}
@Bean
@ConditionalOnMissingBean(name = "codeEnumOpenApiCustomizer")
public GlobalOpenApiCustomizer codeEnumOpenApiCustomizer() {
return new CodeEnumOpenApiCustomizer(properties.getBasePackage());
}
@Bean
@ConditionalOnMissingBean(name = "swaggerIpFilter")
public FilterRegistrationBean<SwaggerIpFilter> swaggerIpFilter() {
FilterRegistrationBean<SwaggerIpFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new SwaggerIpFilter(properties.getAllowedIps()));
registrationBean.addUrlPatterns("/swagger-ui/*", "/v3/api-docs/*", "/swagger-ui.html");
registrationBean.setName("swaggerIpFilter");
registrationBean.setOrder(1);
return registrationBean;
}
}

View File

@@ -0,0 +1,30 @@
package com.kri.common.autoconfigure.swagger;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.ArrayList;
import java.util.List;
@Getter
@Setter
@ConfigurationProperties(prefix = "kri.swagger")
public class KriSwaggerProperties {
private boolean enabled = true;
private String title = "KRI API";
private String description = "KRI Common API Docs";
private String version = "v1";
/**
* 臾몄꽌?뷀븷 base package (null ?대㈃ ?꾩껜)
*/
private List<String> basePackage = new ArrayList<>();
/**
* Swagger ?묎렐 ?덉슜 IP 紐⑸줉 (127.0.0.1, localhost, 0:0:0:0:0:0:0:1?€ 湲곕낯 ?덉슜)
*/
private List<String> allowedIps = new ArrayList<>();
}

View File

@@ -0,0 +1,130 @@
package com.kri.common.autoconfigure.web;
import com.kri.common.feature.auth.jwt.JwtService;
import com.kri.common.feature.web.RequestUserContextProvider;
import com.kri.common.runtime.web.DefaultRequestUserContextProvider;
import com.kri.common.runtime.web.CodeEnumConverter;
import com.kri.common.runtime.web.ErrorAdvice;
import com.kri.common.runtime.web.ServiceMdcAspect;
import com.kri.common.runtime.web.TraceFilter;
import com.kri.common.runtime.web.RequestUserContextArgumentResolver;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.slf4j.MDC;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@AutoConfiguration
@ConditionalOnExpression("${kri.web.enabled:true}")
public class CommonWebAutoConfiguration {
@Bean
public ErrorAdvice errorAdvice() {
return new ErrorAdvice();
}
@Bean
public FilterRegistrationBean<TraceFilter> traceFilter() {
var reg = new FilterRegistrationBean<>(new TraceFilter());
reg.setOrder(Ordered.HIGHEST_PRECEDENCE);
return reg;
}
@Bean
@ConditionalOnClass(Aspect.class)
@ConditionalOnExpression("${kri.web.mdc.enabled:true}")
public ServiceMdcAspect serviceMdcAspect() {
return new ServiceMdcAspect();
}
@Bean
@ConditionalOnExpression("${kri.web.mdc.enabled:true}")
public WebMvcConfigurer mdcWebMvcConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new org.springframework.web.servlet.HandlerInterceptor() {
@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) {
if (handler instanceof HandlerMethod hm) {
String ctrl = hm.getBeanType().getSimpleName();
String method = hm.getMethod().getName();
MDC.put("handler", ctrl + "#" + method);
}
return true;
}
@Override
public void afterCompletion(
HttpServletRequest req,
HttpServletResponse res,
Object handler,
Exception ex
) {
MDC.remove("handler");
}
});
}
};
}
@Bean
@ConditionalOnClass(HttpServletRequest.class)
@ConditionalOnBean(JwtService.class)
@ConditionalOnMissingBean(RequestUserContextProvider.class)
public RequestUserContextProvider requestUserContextProvider(JwtService jwtService) {
return new DefaultRequestUserContextProvider(jwtService);
}
@Bean
@ConditionalOnBean(JwtService.class)
@ConditionalOnMissingBean
public RequestUserContextArgumentResolver requestUserContextArgumentResolver(
RequestUserContextProvider requestUserContextProvider
) {
return new RequestUserContextArgumentResolver(requestUserContextProvider);
}
@Bean
public WebMvcConfigurer kriCommonWebMvcConfigurer(
ObjectProvider<RequestUserContextArgumentResolver> requestUserContextArgumentResolverProvider
) {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedMethods("*")
.allowedHeaders("*")
.allowCredentials(true);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
}
@Override
public void addArgumentResolvers(
java.util.List<org.springframework.web.method.support.HandlerMethodArgumentResolver> resolvers) {
requestUserContextArgumentResolverProvider.ifAvailable(resolvers::add);
}
@Override
public void addFormatters(org.springframework.format.FormatterRegistry registry) {
registry.addConverterFactory(new CodeEnumConverter());
}
};
}
}

View File

@@ -0,0 +1,98 @@
package com.kri.common.endpoint.auth.apikey;
import com.kri.common.autoconfigure.auth.apikey.ApiKeyProperties;
import com.kri.common.feature.auth.dto.JwtUserClaimsDto;
import com.kri.common.runtime.auth.apikey.PreloadedApiKeyUserClaimsProvider;
import com.kri.common.runtime.web.IpUtil;
import jakarta.servlet.http.HttpServletRequest;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.util.matcher.IpAddressMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
@RestController
@RequestMapping("/internal/apikey")
public class ApiKeyAdminController {
private final ApiKeyProperties props;
private final PreloadedApiKeyUserClaimsProvider provider;
private final List<String> allow;
public ApiKeyAdminController(ApiKeyProperties props, PreloadedApiKeyUserClaimsProvider provider) {
this.props = props;
this.provider = provider;
Set<String> allowIps = new LinkedHashSet<>(ApiKeyProperties.DEFAULT_ADMIN_ALLOW_IPS);
if (props.getAdminAllowIps() != null) {
allowIps.addAll(props.getAdminAllowIps());
}
this.allow = allowIps.stream()
.filter(StringUtils::hasText)
.toList();
}
@PostMapping("/reload")
public ReloadResult reload(HttpServletRequest req) {
assertAllowed(req);
int count = provider.reloadFromDb();
return new ReloadResult(count);
}
/**
* 현재 메모리에 적재된 API Key 캐시를 확인합니다.
*/
@GetMapping("/cache")
public List<CachedKeyView> cache(HttpServletRequest req) {
assertAllowed(req);
Map<String, JwtUserClaimsDto> snap = provider.snapshot();
return snap.entrySet().stream()
.map(e -> new CachedKeyView(mask(e.getKey()), e.getValue()))
.toList();
}
private void assertAllowed(HttpServletRequest req) {
if (!props.isAdminApiEnabled()) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
}
String remote = IpUtil.getClientIp(req);
boolean ok = allow.stream().anyMatch(allowed -> matches(remote, allowed));
if (!ok) {
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "IP not allowed: " + remote);
}
}
private boolean matches(String remote, String allowed) {
if ("localhost".equalsIgnoreCase(allowed)) {
return "localhost".equalsIgnoreCase(remote)
|| "127.0.0.1".equals(remote)
|| "0:0:0:0:0:0:0:1".equals(remote);
}
return new IpAddressMatcher(allowed).matches(remote);
}
private String mask(String raw) {
if (raw == null) {
return "";
}
int n = raw.length();
if (n <= 8) {
return raw.charAt(0) + "****";
}
return raw.substring(0, 4) + "****" + raw.substring(n - 4);
}
public record ReloadResult(int cachedKeyCount) {
}
public record CachedKeyView(String maskedApiKey, JwtUserClaimsDto claims) {
}
}

View File

@@ -0,0 +1,19 @@
package com.kri.common.feature.auth.apikey;
import com.kri.common.feature.auth.dto.JwtUserClaimsDto;
import java.util.Optional;
/**
* 외부에서 들어온 API Key를 우리 시스템의 유저 정보(JwtUserClaimsDto)로 매핑하는 인터페이스. 각 서비스에서 이 인터페이스 구현체를 Bean으로 등록하면
* 된다.
*/
public interface ApiKeyUserClaimsProvider {
/**
* API Key 로 사용자 정보를 조회한다.
*
* @param apiKey 요청 헤더에서 받은 API Key
* @return 유효한 키면 JwtUserClaimsDto, 아니면 Optional.empty()
*/
Optional<JwtUserClaimsDto> findUserByApiKey(String apiKey);
}

View File

@@ -0,0 +1,29 @@
package com.kri.common.feature.auth.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Builder;
import lombok.Value;
@Schema(
name = "JwtUserClaimsDto",
description = "JWT에 포함되는 사용자 정보"
)
@Value
@Builder
public class JwtUserClaimsDto {
@Schema(description = "사용자 ID")
String userId;
@Schema(description = "사용자 소속 회사")
String userCmpn;
@Schema(description = "팀 코드")
String userTeam;
@Schema(description = "사용자 이름")
String userName;
@Schema(description = "권한 코드")
Integer userRole;
}

View File

@@ -0,0 +1,136 @@
package com.kri.common.feature.auth.jwt;
import com.kri.common.autoconfigure.auth.jwt.JwtProperties;
import com.kri.common.feature.auth.dto.JwtUserClaimsDto;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import jakarta.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.crypto.SecretKey;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
/**
* 공통 JWT 유틸 서비스 - DTO: JwtUserClaimsDto 기준으로 토큰 생성/파싱 - 일반 JWT + 내부 고정 토큰 둘 다 지원
*/
@RequiredArgsConstructor
public class JwtService {
private final JwtProperties properties;
private SecretKey key;
@PostConstruct
public void init() {
// 시크릿 검증: HS256 권장 최소 길이(32바이트 이상)
String secret = properties.getSecret();
if (secret == null || secret.getBytes(StandardCharsets.UTF_8).length < 32) {
throw new IllegalStateException(
"kri.auth.jwt.secret must be at least 32 bytes (UTF-8) for HS256");
}
// secret 문자열을 HMAC 키로 전환
this.key = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
}
private String buildToken(Map<String, Object> claims, String subject, long validitySeconds) {
Date now = new Date();
Date expiry = new Date(now.getTime() + validitySeconds * 1000);
return Jwts.builder()
.setClaims(claims)
.setSubject(subject)
.setIssuer(properties.getIssuer())
.setIssuedAt(now)
.setExpiration(expiry)
.signWith(key, SignatureAlgorithm.HS256)
.compact();
}
private Map<String, Object> buildClaims(JwtUserClaimsDto dto) {
Map<String, Object> claims = new HashMap<>();
claims.put("userId", dto.getUserId());
claims.put("userCmpn", dto.getUserCmpn());
claims.put("userTeam", dto.getUserTeam());
claims.put("userName", dto.getUserName());
claims.put("role", dto.getUserRole());
return claims;
}
public String generateAccessToken(JwtUserClaimsDto userClaims) {
Map<String, Object> claims = buildClaims(userClaims);
return buildToken(claims, userClaims.getUserId(), properties.getAccessTokenValiditySeconds());
}
public String generateRefreshToken(String userId) {
return buildToken(Collections.emptyMap(), userId, properties.getRefreshTokenValiditySeconds());
}
public Jws<Claims> parseToken(String token) throws JwtException {
return Jwts.parser()
.requireIssuer(properties.getIssuer())
.verifyWith(key)
.build()
.parseSignedClaims(token);
}
public Claims getClaims(String token) throws JwtException {
return parseToken(token).getBody();
}
public JwtUserClaimsDto toUserClaimsDto(Claims claims) {
String userId = claims.get("userId", String.class);
if (userId == null) {
userId = claims.getSubject();
}
String userCmpn = claims.get("userCmpn", String.class);
String userTeam = claims.get("userTeam", String.class);
String userName = claims.get("userName", String.class);
Number roleNumber = claims.get("role", Number.class);
Integer userRole = roleNumber != null ? roleNumber.intValue() : null;
return JwtUserClaimsDto.builder()
.userId(userId)
.userCmpn(userCmpn)
.userTeam(userTeam)
.userName(userName)
.userRole(userRole)
.build();
}
public JwtUserClaimsDto toUserClaimsDto(String token) throws JwtException {
Claims claims = getClaims(token);
return toUserClaimsDto(claims);
}
public Authentication toAuthentication(JwtUserClaimsDto dto) {
String principal = dto.getUserId();
List<GrantedAuthority> authorities = new ArrayList<>();
if (dto.getUserRole() != null) {
authorities.add(new SimpleGrantedAuthority("ROLE_" + dto.getUserRole()));
}
UsernamePasswordAuthenticationToken auth =
new UsernamePasswordAuthenticationToken(principal, null, authorities);
auth.setDetails(dto);
return auth;
}
public Authentication toAuthentication(String token) throws JwtException {
return toAuthentication(toUserClaimsDto(token));
}
}

View File

@@ -0,0 +1,120 @@
package com.kri.common.feature.cache;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.transaction.annotation.Transactional;
public abstract class AbstractListCache<T> {
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private List<T> list = List.of();
@EventListener(ApplicationReadyEvent.class)
@Transactional(readOnly = true)
public void loadOnStartup() {
List<T> tempList = loadFromDb();
if (tempList != null) {
setList(tempList);
}
}
public List<T> getList() {
lock.readLock().lock();
try {
return list;
} finally {
lock.readLock().unlock();
}
}
public void setList(List<T> next) {
lock.writeLock().lock();
try {
this.list = List.copyOf(next == null ? List.of() : next);
} finally {
lock.writeLock().unlock();
}
}
@Transactional(readOnly = true)
public List<T> reload() {
List<T> tempList = loadFromDb();
if (tempList == null) {
throw new UnsupportedOperationException("This cache does not support reload().");
}
setList(tempList);
return getList();
}
public List<T> clear() {
lock.writeLock().lock();
try {
return list = List.of();
} finally {
lock.writeLock().unlock();
}
}
public void addAll(List<T> items) {
if (items == null || items.isEmpty()) {
return;
}
lock.writeLock().lock();
try {
List<T> merged = new java.util.ArrayList<>(this.list);
merged.addAll(items);
this.list = List.copyOf(merged);
} finally {
lock.writeLock().unlock();
}
}
public void addAll(int index, Collection<? extends T> items) {
if (items == null || items.isEmpty()) {
return;
}
lock.writeLock().lock();
try {
ArrayList<T> next = new ArrayList<>(this.list);
int i = Math.max(0, Math.min(index, next.size())); // 0 ~ size濡?蹂댁젙
next.addAll(i, new ArrayList<>(items));
this.list = List.copyOf(next);
} finally {
lock.writeLock().unlock();
}
}
public void add(T item) {
lock.writeLock().lock();
try {
List<T> merged = new java.util.ArrayList<>(this.list);
merged.add(item);
this.list = List.copyOf(merged);
} finally {
lock.writeLock().unlock();
}
}
public void add(int index, T item) {
lock.writeLock().lock();
try {
ArrayList<T> next = new ArrayList<>(this.list);
int i = Math.max(0, Math.min(index, next.size())); // 0 ~ size濡?蹂댁젙
next.add(i, item);
this.list = List.copyOf(next);
} finally {
lock.writeLock().unlock();
}
}
protected List<T> loadFromDb() {
return null;
}
}

View File

@@ -0,0 +1,118 @@
package com.kri.common.feature.cache;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.transaction.annotation.Transactional;
public abstract class AbstractMapCache<K, V> {
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private Map<K, V> map = Map.of();
@EventListener(ApplicationReadyEvent.class)
@Transactional(readOnly = true)
public void loadOnStartup() {
Map<K, V> tempMap = loadFromDb();
if (tempMap != null) {
setMap(tempMap);
}
}
public Map<K, V> getMap() {
lock.readLock().lock();
try {
return map;
} finally {
lock.readLock().unlock();
}
}
/**
* 수동: 전체 교체(불변 스냅샷으로 보관)
*/
public void setMap(Map<K, V> next) {
lock.writeLock().lock();
try {
this.map = Map.copyOf(next == null ? Map.of() : next);
} finally {
lock.writeLock().unlock();
}
}
public V get(K key) {
lock.readLock().lock();
try {
return map.get(key);
} finally {
lock.readLock().unlock();
}
}
public boolean containsKey(K key) {
lock.readLock().lock();
try {
return map.containsKey(key);
} finally {
lock.readLock().unlock();
}
}
@Transactional(readOnly = true)
public Map<K, V> reload() {
Map<K, V> tempMap = loadFromDb();
if (tempMap == null) {
throw new UnsupportedOperationException("This cache does not support reload().");
}
setMap(tempMap);
return getMap();
}
public void put(K key, V value) {
lock.writeLock().lock();
try {
Map<K, V> merged = new HashMap<>(this.map);
merged.put(key, value);
this.map = Map.copyOf(merged);
} finally {
lock.writeLock().unlock();
}
}
/**
* 수동: 부분 적재(기존 + entries 합쳐서 스냅샷 교체)
*/
public void putAll(Map<K, V> entries) {
if (entries == null || entries.isEmpty()) {
return;
}
lock.writeLock().lock();
try {
Map<K, V> merged = new HashMap<>(this.map);
merged.putAll(entries);
this.map = Map.copyOf(merged);
} finally {
lock.writeLock().unlock();
}
}
/**
* clear: 완전 비우기
*/
public void clear() {
lock.writeLock().lock();
try {
this.map = Map.of();
} finally {
lock.writeLock().unlock();
}
}
// 서브클래스가 "DB에서 어떤 Map을 만들지"만 구현
protected Map<K, V> loadFromDb() {
return null;
}
}

View File

@@ -0,0 +1,11 @@
package com.kri.common.feature.crypto;
/**
* 암호문 인증 실패, 잘못된 키 또는 잘못된 AAD로 복호화할 수 없을 때 발생합니다.
*/
public class CryptoAuthenticationException extends CryptoException {
public CryptoAuthenticationException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@@ -0,0 +1,15 @@
package com.kri.common.feature.crypto;
/**
* 암호화, 복호화 또는 해시 처리 중 발생하는 공통 예외입니다.
*/
public class CryptoException extends RuntimeException {
public CryptoException(String message) {
super(message);
}
public CryptoException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@@ -0,0 +1,11 @@
package com.kri.common.feature.crypto;
/**
* 요청한 암호화 키를 찾을 수 없을 때 발생합니다.
*/
public class CryptoKeyNotFoundException extends CryptoException {
public CryptoKeyNotFoundException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,36 @@
package com.kri.common.feature.crypto.aes;
/**
* 지원하는 AES 알고리즘입니다.
*/
public enum AesAlgorithm {
/** 인증 암호화 기본값입니다. */
AES_256_GCM("AES/GCM/NoPadding", 12, true),
/**
* 인증 태그가 없는 레거시 호환 모드입니다. 신규 데이터에는 {@link #AES_256_GCM}을 사용하십시오.
*/
AES_256_CBC_PKCS5("AES/CBC/PKCS5Padding", 16, false);
private final String transformation;
private final int ivLength;
private final boolean authenticated;
AesAlgorithm(String transformation, int ivLength, boolean authenticated) {
this.transformation = transformation;
this.ivLength = ivLength;
this.authenticated = authenticated;
}
public String getTransformation() {
return transformation;
}
public int getIvLength() {
return ivLength;
}
public boolean isAuthenticated() {
return authenticated;
}
}

View File

@@ -0,0 +1,28 @@
package com.kri.common.feature.crypto.aes;
import java.nio.charset.StandardCharsets;
/**
* AES 양방향 암호화 공개 API입니다.
*/
public interface AesCryptoService {
AesEncryptedValue encrypt(byte[] plaintext);
AesEncryptedValue encrypt(AesEncryptRequest request);
byte[] decrypt(AesEncryptedValue encryptedValue);
byte[] decrypt(AesDecryptRequest request);
default AesEncryptedValue encryptUtf8(String plaintext) {
if (plaintext == null) {
throw new IllegalArgumentException("plaintext must not be null");
}
return encrypt(plaintext.getBytes(StandardCharsets.UTF_8));
}
default String decryptUtf8(AesEncryptedValue encryptedValue) {
return new String(decrypt(encryptedValue), StandardCharsets.UTF_8);
}
}

View File

@@ -0,0 +1,65 @@
package com.kri.common.feature.crypto.aes;
import java.util.Arrays;
/**
* AES 복호화 요청입니다. masterKey를 생략하면 암호문의 keyId에 해당하는 설정 키를 사용합니다.
*/
public final class AesDecryptRequest {
private final AesEncryptedValue encryptedValue;
private final char[] masterKey;
private final byte[] aad;
private AesDecryptRequest(Builder builder) {
this.encryptedValue = builder.encryptedValue;
this.masterKey = builder.masterKey == null
? null : Arrays.copyOf(builder.masterKey, builder.masterKey.length);
this.aad = builder.aad == null ? null : Arrays.copyOf(builder.aad, builder.aad.length);
}
public static Builder builder(AesEncryptedValue encryptedValue) {
return new Builder(encryptedValue);
}
public AesEncryptedValue getEncryptedValue() {
return encryptedValue;
}
public char[] getMasterKey() {
return masterKey == null ? null : Arrays.copyOf(masterKey, masterKey.length);
}
public byte[] getAad() {
return aad == null ? null : Arrays.copyOf(aad, aad.length);
}
public static final class Builder {
private final AesEncryptedValue encryptedValue;
private char[] masterKey;
private byte[] aad;
private Builder(AesEncryptedValue encryptedValue) {
this.encryptedValue = encryptedValue;
}
public Builder masterKey(char[] masterKey) {
this.masterKey = masterKey == null ? null : Arrays.copyOf(masterKey, masterKey.length);
return this;
}
public Builder masterKey(String masterKey) {
this.masterKey = masterKey == null ? null : masterKey.toCharArray();
return this;
}
public Builder aad(byte[] aad) {
this.aad = aad == null ? null : Arrays.copyOf(aad, aad.length);
return this;
}
public AesDecryptRequest build() {
return new AesDecryptRequest(this);
}
}
}

View File

@@ -0,0 +1,144 @@
package com.kri.common.feature.crypto.aes;
import java.util.Arrays;
/**
* AES 암호화 요청입니다. masterKey, salt, IV를 직접 전달하지 않으면 설정값 또는 안전한 난수를 사용합니다.
*/
public final class AesEncryptRequest {
private final byte[] plaintext;
private final char[] masterKey;
private final byte[] salt;
private final byte[] iv;
private final byte[] aad;
private final String keyId;
private final AesAlgorithm algorithm;
private final TagLayout tagLayout;
private final Integer kdfIterations;
private AesEncryptRequest(Builder builder) {
this.plaintext = copy(builder.plaintext);
this.masterKey = copy(builder.masterKey);
this.salt = copy(builder.salt);
this.iv = copy(builder.iv);
this.aad = copy(builder.aad);
this.keyId = builder.keyId;
this.algorithm = builder.algorithm;
this.tagLayout = builder.tagLayout;
this.kdfIterations = builder.kdfIterations;
}
public static Builder builder(byte[] plaintext) {
return new Builder(plaintext);
}
public byte[] getPlaintext() {
return copy(plaintext);
}
public char[] getMasterKey() {
return copy(masterKey);
}
public byte[] getSalt() {
return copy(salt);
}
public byte[] getIv() {
return copy(iv);
}
public byte[] getAad() {
return copy(aad);
}
public String getKeyId() {
return keyId;
}
public AesAlgorithm getAlgorithm() {
return algorithm;
}
public TagLayout getTagLayout() {
return tagLayout;
}
public Integer getKdfIterations() {
return kdfIterations;
}
private static byte[] copy(byte[] value) {
return value == null ? null : Arrays.copyOf(value, value.length);
}
private static char[] copy(char[] value) {
return value == null ? null : Arrays.copyOf(value, value.length);
}
public static final class Builder {
private final byte[] plaintext;
private char[] masterKey;
private byte[] salt;
private byte[] iv;
private byte[] aad;
private String keyId;
private AesAlgorithm algorithm;
private TagLayout tagLayout;
private Integer kdfIterations;
private Builder(byte[] plaintext) {
this.plaintext = copy(plaintext);
}
public Builder masterKey(char[] masterKey) {
this.masterKey = copy(masterKey);
return this;
}
public Builder masterKey(String masterKey) {
this.masterKey = masterKey == null ? null : masterKey.toCharArray();
return this;
}
public Builder salt(byte[] salt) {
this.salt = copy(salt);
return this;
}
public Builder iv(byte[] iv) {
this.iv = copy(iv);
return this;
}
public Builder aad(byte[] aad) {
this.aad = copy(aad);
return this;
}
public Builder keyId(String keyId) {
this.keyId = keyId;
return this;
}
public Builder algorithm(AesAlgorithm algorithm) {
this.algorithm = algorithm;
return this;
}
public Builder tagLayout(TagLayout tagLayout) {
this.tagLayout = tagLayout;
return this;
}
public Builder kdfIterations(int kdfIterations) {
this.kdfIterations = kdfIterations;
return this;
}
public AesEncryptRequest build() {
return new AesEncryptRequest(this);
}
}
}

View File

@@ -0,0 +1,88 @@
package com.kri.common.feature.crypto.aes;
import java.util.Arrays;
/**
* 복호화와 키 교체에 필요한 메타데이터를 포함한 AES 암호화 결과입니다.
*/
public final class AesEncryptedValue {
public static final String CURRENT_FORMAT_VERSION = "v1";
public static final String KDF_ALGORITHM = "PBKDF2_WITH_HMAC_SHA256";
private final String formatVersion;
private final AesAlgorithm algorithm;
private final String keyId;
private final int kdfIterations;
private final byte[] salt;
private final byte[] iv;
private final byte[] ciphertext;
private final byte[] tag;
private final TagLayout tagLayout;
public AesEncryptedValue(
String formatVersion,
AesAlgorithm algorithm,
String keyId,
int kdfIterations,
byte[] salt,
byte[] iv,
byte[] ciphertext,
byte[] tag,
TagLayout tagLayout
) {
this.formatVersion = formatVersion;
this.algorithm = algorithm;
this.keyId = keyId;
this.kdfIterations = kdfIterations;
this.salt = copy(salt);
this.iv = copy(iv);
this.ciphertext = copy(ciphertext);
this.tag = copy(tag);
this.tagLayout = tagLayout;
}
public String getFormatVersion() {
return formatVersion;
}
public AesAlgorithm getAlgorithm() {
return algorithm;
}
public String getKeyId() {
return keyId;
}
public String getKdfAlgorithm() {
return KDF_ALGORITHM;
}
public int getKdfIterations() {
return kdfIterations;
}
public byte[] getSalt() {
return copy(salt);
}
public byte[] getIv() {
return copy(iv);
}
public byte[] getCiphertext() {
return copy(ciphertext);
}
public byte[] getTag() {
return copy(tag);
}
public TagLayout getTagLayout() {
return tagLayout;
}
private static byte[] copy(byte[] value) {
return value == null ? null : Arrays.copyOf(value, value.length);
}
}

View File

@@ -0,0 +1,79 @@
package com.kri.common.feature.crypto.aes;
import com.kri.common.feature.crypto.CryptoException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
/**
* {@link AesEncryptedValue}를 단일 저장 문자열로 변환합니다.
*/
public final class AesEncryptedValueCodec {
private static final String PREFIX = "kri";
private static final Base64.Encoder ENCODER = Base64.getUrlEncoder().withoutPadding();
private static final Base64.Decoder DECODER = Base64.getUrlDecoder();
private AesEncryptedValueCodec() {
}
public static String encode(AesEncryptedValue value) {
requireValue(value);
return String.join(":",
PREFIX,
value.getFormatVersion(),
value.getAlgorithm().name(),
Integer.toString(value.getKdfIterations()),
encodeText(value.getKeyId()),
value.getTagLayout().name(),
encodeBytes(value.getSalt()),
encodeBytes(value.getIv()),
encodeBytes(value.getCiphertext()),
encodeBytes(value.getTag()));
}
public static AesEncryptedValue decode(String encoded) {
try {
String[] parts = encoded == null ? new String[0] : encoded.split(":", -1);
if (parts.length != 10 || !PREFIX.equals(parts[0])) {
throw new IllegalArgumentException("invalid field count or prefix");
}
if (!AesEncryptedValue.CURRENT_FORMAT_VERSION.equals(parts[1])) {
throw new IllegalArgumentException("unsupported format version");
}
return new AesEncryptedValue(
parts[1],
AesAlgorithm.valueOf(parts[2]),
decodeText(parts[4]),
Integer.parseInt(parts[3]),
decodeBytes(parts[6]),
decodeBytes(parts[7]),
decodeBytes(parts[8]),
decodeBytes(parts[9]),
TagLayout.valueOf(parts[5]));
} catch (RuntimeException e) {
throw new CryptoException("Invalid encrypted value format", e);
}
}
private static void requireValue(AesEncryptedValue value) {
if (value == null) {
throw new CryptoException("Encrypted value must not be null");
}
}
private static String encodeText(String value) {
return value == null ? "" : encodeBytes(value.getBytes(StandardCharsets.UTF_8));
}
private static String decodeText(String value) {
return value.isEmpty() ? null : new String(decodeBytes(value), StandardCharsets.UTF_8);
}
private static String encodeBytes(byte[] value) {
return value == null || value.length == 0 ? "" : ENCODER.encodeToString(value);
}
private static byte[] decodeBytes(String value) {
return value.isEmpty() ? new byte[0] : DECODER.decode(value);
}
}

View File

@@ -0,0 +1,13 @@
package com.kri.common.feature.crypto.aes;
/**
* 인증 태그의 저장 형태입니다.
*/
public enum TagLayout {
/** GCM 태그가 ciphertext 마지막에 포함됩니다. */
APPENDED,
/** GCM 태그가 별도 필드에 저장됩니다. */
DETACHED,
/** 인증 태그가 없는 CBC 호환 모드입니다. */
NONE
}

View File

@@ -0,0 +1,13 @@
package com.kri.common.feature.crypto.hash;
/**
* 비밀번호, PIN, 복구 코드, API Secret 등 짧은 비밀값을 위한 adaptive hash API입니다.
*/
public interface AdaptiveHashService {
String hash(CharSequence value);
String hash(CharSequence value, int strength);
boolean matches(CharSequence value, String encodedHash);
}

View File

@@ -0,0 +1,29 @@
package com.kri.common.feature.crypto.hash;
/**
* 일반 메시지 다이제스트 알고리즘입니다.
*/
public enum DigestAlgorithm {
/** 레거시 검증 전용입니다. 신규 보안 기능에 사용하지 마십시오. */
MD5_LEGACY("MD5", true),
/** 레거시 검증 전용입니다. 신규 보안 기능에 사용하지 마십시오. */
SHA_1_LEGACY("SHA-1", true),
SHA_256("SHA-256", false),
SHA_512("SHA-512", false);
private final String jcaName;
private final boolean legacy;
DigestAlgorithm(String jcaName, boolean legacy) {
this.jcaName = jcaName;
this.legacy = legacy;
}
public String getJcaName() {
return jcaName;
}
public boolean isLegacy() {
return legacy;
}
}

View File

@@ -0,0 +1,10 @@
package com.kri.common.feature.crypto.hash;
/**
* 다이제스트 출력 인코딩입니다.
*/
public enum DigestEncoding {
HEX_LOWER,
HEX_UPPER,
BASE64
}

View File

@@ -0,0 +1,61 @@
package com.kri.common.feature.crypto.hash;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* 알고리즘과 출력 형식을 함께 전달하는 일반 digest 요청입니다.
*/
public final class DigestRequest {
private final byte[] value;
private final DigestAlgorithm algorithm;
private final DigestEncoding encoding;
private DigestRequest(byte[] value, DigestAlgorithm algorithm, DigestEncoding encoding) {
this.value = value == null ? null : Arrays.copyOf(value, value.length);
this.algorithm = algorithm;
this.encoding = encoding;
}
public static DigestRequest of(
byte[] value,
DigestAlgorithm algorithm,
DigestEncoding encoding
) {
return new DigestRequest(value, algorithm, encoding);
}
public static DigestRequest of(
String value,
Charset charset,
DigestAlgorithm algorithm,
DigestEncoding encoding
) {
if (value == null || charset == null) {
throw new IllegalArgumentException("value and charset must not be null");
}
return new DigestRequest(value.getBytes(charset), algorithm, encoding);
}
public static DigestRequest utf8(
String value,
DigestAlgorithm algorithm,
DigestEncoding encoding
) {
return of(value, StandardCharsets.UTF_8, algorithm, encoding);
}
public byte[] getValue() {
return value == null ? null : Arrays.copyOf(value, value.length);
}
public DigestAlgorithm getAlgorithm() {
return algorithm;
}
public DigestEncoding getEncoding() {
return encoding;
}
}

View File

@@ -0,0 +1,45 @@
package com.kri.common.feature.crypto.hash;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
/**
* 파일 무결성, 식별값 및 레거시 연동을 위한 일반 해시 API입니다.
*/
public interface DigestService {
String digest(byte[] value, DigestAlgorithm algorithm, DigestEncoding encoding);
default String digest(DigestRequest request) {
if (request == null) {
throw new IllegalArgumentException("request must not be null");
}
return digest(request.getValue(), request.getAlgorithm(), request.getEncoding());
}
boolean matches(
byte[] value,
String expectedDigest,
DigestAlgorithm algorithm,
DigestEncoding encoding
);
default String digest(String value, DigestAlgorithm algorithm, DigestEncoding encoding) {
return digest(value, StandardCharsets.UTF_8, algorithm, encoding);
}
default String digest(
String value,
Charset charset,
DigestAlgorithm algorithm,
DigestEncoding encoding
) {
if (value == null) {
throw new IllegalArgumentException("value must not be null");
}
if (charset == null) {
throw new IllegalArgumentException("charset must not be null");
}
return digest(value.getBytes(charset), algorithm, encoding);
}
}

View File

@@ -0,0 +1,273 @@
package com.kri.common.feature.datetime;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Objects;
public final class DateTimeUtil {
public static final ZoneId KST = ZoneId.of("Asia/Seoul");
public static final ZoneId UTC = ZoneOffset.UTC;
/**
* 날짜+시간: 2025-11-28 15:00:14
*/
public static final DateTimeFormatter DATETIME_FMT =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
/**
* 날짜: 2025-11-28
*/
public static final DateTimeFormatter DATE_FMT =
DateTimeFormatter.ofPattern("yyyy-MM-dd");
private DateTimeUtil() {
}
/* =======================
* Now (KST)
* ======================= */
/**
* 현재 KST 날짜+시간 문자열
*/
public static String nowKstDateTime() {
return formatKst(Instant.now(), DATETIME_FMT);
}
/**
* 현재 KST 날짜 문자열
*/
public static String nowKstDate() {
return nowKstZoned().format(DATE_FMT);
}
/**
* 현재 KST ZonedDateTime
*/
public static ZonedDateTime nowKstZoned() {
return Instant.now().atZone(KST);
}
/**
* 현재 KST LocalDateTime
*/
public static LocalDateTime nowKstLocalDateTime() {
return nowKstZoned().toLocalDateTime();
}
/**
* 현재 KST LocalDate
*/
public static LocalDate nowKstLocalDate() {
return nowKstZoned().toLocalDate();
}
/* =======================
* Format (Instant -> String)
* ======================= */
/**
* Instant -> KST 날짜+시간 문자열
*/
public static String formatKstDateTime(Instant instant) {
return formatKst(instant, DATETIME_FMT);
}
/**
* Instant -> KST 날짜 문자열
*/
public static String formatKstDate(Instant instant) {
return formatKst(instant, DATE_FMT);
}
/**
* Instant -> KST 문자열 (커스텀 포맷)
*/
public static String formatKst(Instant instant, DateTimeFormatter formatter) {
if (instant == null) {
return null;
}
final DateTimeFormatter fmt = (formatter != null) ? formatter : DATETIME_FMT;
return instant.atZone(KST).format(fmt);
}
/* =======================
* Validate
* ======================= */
/**
* "yyyy-MM-dd" 형태인지
*/
public static boolean isDate(String text) {
return tryParseLocalDate(text, DATE_FMT) != null;
}
/**
* "yyyy-MM-dd HH:mm:ss" 형태인지
*/
public static boolean isDateTime(String text) {
return tryParseLocalDateTime(text, DATETIME_FMT) != null;
}
/**
* ISO Instant / ISO OffsetDateTime / ISO ZonedDateTime 중 하나인지
*/
public static boolean isIsoDateTime(String text) {
if (text == null || text.isBlank()) {
return false;
}
final String s = text.trim();
try {
Instant.parse(s);
return true;
} catch (DateTimeParseException ignored) {
}
try {
OffsetDateTime.parse(s);
return true;
} catch (DateTimeParseException ignored) {
}
try {
ZonedDateTime.parse(s);
return true;
} catch (DateTimeParseException ignored) {
}
return false;
}
/* =======================
* Parse (String -> Instant)
* ======================= */
/**
* ISO 계열 문자열을 Instant로 파싱 (Instant/OffsetDateTime/ZonedDateTime 순으로 시도)
*/
public static Instant parseToInstant(String text) {
if (text == null || text.isBlank()) {
return null;
}
final String s = text.trim();
try {
return Instant.parse(s);
} catch (DateTimeParseException ignored) {
}
try {
return OffsetDateTime.parse(s).toInstant();
} catch (DateTimeParseException ignored) {
}
try {
return ZonedDateTime.parse(s).toInstant();
} catch (DateTimeParseException ignored) {
}
throw new DateTimeParseException("Unsupported datetime format", s, 0);
}
/**
* 커스텀 포맷 문자열을 KST 기준으로 해석해서 Instant로 변환 예) "2025-11-28 15:00:14", formatter=DATETIME_FMT
*/
public static Instant parseKstToInstant(String text, DateTimeFormatter formatter) {
if (text == null || text.isBlank()) {
return null;
}
Objects.requireNonNull(formatter, "formatter");
LocalDateTime ldt = LocalDateTime.parse(text.trim(), formatter);
return ldt.atZone(KST).toInstant();
}
/**
* "yyyy-MM-dd HH:mm:ss" 포맷을 KST로 해석
*/
public static Instant parseKstDateTimeToInstant(String text) {
return parseKstToInstant(text, DATETIME_FMT);
}
/**
* "yyyy-MM-dd" 포맷을 KST 자정(00:00:00)으로 해석
*/
public static Instant parseKstDateToInstant(String text) {
if (text == null || text.isBlank()) {
return null;
}
LocalDate ld = LocalDate.parse(text.trim(), DATE_FMT);
return ld.atStartOfDay(KST).toInstant();
}
/* =======================
* Convert / Helpers
* ======================= */
/**
* Instant -> KST ZonedDateTime
*/
public static ZonedDateTime toKstZoned(Instant instant) {
return instant == null ? null : instant.atZone(KST);
}
/**
* Instant -> KST LocalDateTime
*/
public static LocalDateTime toKstLocalDateTime(Instant instant) {
ZonedDateTime zdt = toKstZoned(instant);
return zdt == null ? null : zdt.toLocalDateTime();
}
/**
* Instant -> KST LocalDate
*/
public static LocalDate toKstLocalDate(Instant instant) {
ZonedDateTime zdt = toKstZoned(instant);
return zdt == null ? null : zdt.toLocalDate();
}
/**
* null/blank 안전 trim
*/
public static String trimToNull(String s) {
if (s == null) {
return null;
}
String t = s.trim();
return t.isEmpty() ? null : t;
}
public static LocalDate parseLocalDate(String text) {
return tryParseLocalDate(text, DATE_FMT);
}
public static LocalDateTime parseLocalDateTime(String text) {
return tryParseLocalDateTime(text, DATETIME_FMT);
}
private static LocalDate tryParseLocalDate(String text, DateTimeFormatter fmt) {
if (text == null || text.isBlank()) {
return null;
}
try {
return LocalDate.parse(text.trim(), fmt);
} catch (DateTimeParseException e) {
return null;
}
}
private static LocalDateTime tryParseLocalDateTime(String text, DateTimeFormatter fmt) {
if (text == null || text.isBlank()) {
return null;
}
try {
return LocalDateTime.parse(text.trim(), fmt);
} catch (DateTimeParseException e) {
return null;
}
}
}

View File

@@ -0,0 +1,26 @@
package com.kri.common.feature.datetime;
import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@JacksonAnnotationsInside
@JsonDeserialize(using = LenientLocalDateTimeDeserializer.class)
public @interface LenientLocalDateTime {
String[] patterns() default {
"yyyy-MM-dd",
"yyyy-MM-dd HH",
"yyyy-MM-dd HH:mm",
"yyyy-MM-dd HH:mm:ss",
"yyyy-MM-dd'T'HH:mm",
"yyyy-MM-dd'T'HH:mm:ss"
};
}

View File

@@ -0,0 +1,93 @@
package com.kri.common.feature.datetime;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoField;
import java.util.Arrays;
public class LenientLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime>
implements ContextualDeserializer {
private final DateTimeFormatter[] formatters;
public LenientLocalDateTimeDeserializer() {
this(new String[]{
"yyyy-MM-dd",
"yyyy-MM-dd HH",
"yyyy-MM-dd HH:mm",
"yyyy-MM-dd HH:mm:ss",
"yyyy-MM-dd'T'HH:mm",
"yyyy-MM-dd'T'HH:mm:ss"
});
}
private LenientLocalDateTimeDeserializer(String[] patterns) {
this.formatters = Arrays.stream(patterns)
.map(LenientLocalDateTimeDeserializer::withDefaultTimeParts)
.toArray(DateTimeFormatter[]::new);
}
private static DateTimeFormatter withDefaultTimeParts(String pattern) {
DateTimeFormatterBuilder b = new DateTimeFormatterBuilder()
.appendPattern(pattern);
// 초(ss)가 있는 패턴이면 ".밀리초(1~3자리)"를 옵션으로 허용
// 예: 2025-12-19T14:50:12.1 / .12 / .123
// (pattern 자체에 S가 들어간 경우는 중복 추가 방지)
if (pattern.contains("ss") && !pattern.contains("S")) {
b.optionalStart()
.appendFraction(ChronoField.NANO_OF_SECOND, 1, 3, true) // true => '.' 포함
.optionalEnd();
}
// 패턴에 분/초가 없으면 0으로 채움 (날짜만 와도 LocalDateTime으로 만들 수 있게)
return b
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.parseDefaulting(ChronoField.NANO_OF_SECOND, 0)
.toFormatter();
}
@Override
public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String s = DateTimeUtil.trimToNull(p.getText());
if (s == null) {
return null;
}
for (DateTimeFormatter f : formatters) {
try {
return LocalDateTime.parse(s, f);
} catch (DateTimeParseException ignored) {
}
}
throw ctxt.weirdStringException(s, LocalDateTime.class,
"Unsupported datetime format. Expected one of patterns defined in @LenientLocalDateTime");
}
@Override
public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property)
throws JsonMappingException {
if (property == null) {
return this;
}
LenientLocalDateTime ann = property.getAnnotation(LenientLocalDateTime.class);
if (ann == null) {
ann = property.getContextAnnotation(LenientLocalDateTime.class);
}
return (ann == null) ? this : new LenientLocalDateTimeDeserializer(ann.patterns());
}
}

View File

@@ -0,0 +1,6 @@
package com.kri.common.feature.enums;
public interface CodeEnum<T> {
T getCode();
}

View File

@@ -0,0 +1,23 @@
package com.kri.common.feature.enums;
public final class CodeEnumUtils {
private CodeEnumUtils() {
}
public static <E extends Enum<E> & CodeEnum<V>, V> E fromCode(Class<E> enumClass, V code) {
if (code == null) {
return null;
}
for (E e : enumClass.getEnumConstants()) {
if (e.getCode().equals(code)) {
return e;
}
}
throw new IllegalArgumentException(
"Unknown code [" + code + "] for enum class " + enumClass.getName()
);
}
}

View File

@@ -0,0 +1,17 @@
package com.kri.common.feature.excel;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ExcelColumn {
String header(); // 엑셀 헤더 이름
int order() default 0; // 컬럼 순서
int width() default -1; // 문자 수 기준, -1이면 autoSize 그대로
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,95 @@
package com.kri.common.feature.excel;
import java.text.SimpleDateFormat;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.util.NumberToTextConverter;
public final class ExcelUtil {
private static final double TIME_FRACTION_EPSILON = 0.0000001;
private static final String DATE_FORMAT = "yyyy-MM-dd";
private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
private ExcelUtil() {
}
public static String getStringCell(Cell cell) {
return getStringCell(cell, null, new DataFormatter());
}
public static String getStringCell(Cell cell, FormulaEvaluator evaluator) {
return getStringCell(cell, evaluator, new DataFormatter());
}
public static String getStringCell(Cell cell, FormulaEvaluator evaluator, DataFormatter formatter) {
if (cell == null) {
return null;
}
DataFormatter cellFormatter = formatter != null ? formatter : new DataFormatter();
return switch (cell.getCellType()) {
case NUMERIC -> formatNumericCell(cell, cell.getNumericCellValue(), cellFormatter);
case FORMULA -> formatFormulaCell(cell, evaluator, cellFormatter);
case STRING, BOOLEAN, BLANK -> cellFormatter.formatCellValue(cell);
default -> null;
};
}
private static String formatFormulaCell(
Cell cell,
FormulaEvaluator evaluator,
DataFormatter formatter
) {
try {
if (evaluator != null) {
CellValue evaluated = evaluator.evaluate(cell);
if (evaluated != null) {
return switch (evaluated.getCellType()) {
case STRING -> evaluated.getStringValue();
case NUMERIC -> formatNumericCell(cell, evaluated.getNumberValue(), formatter);
case BOOLEAN -> String.valueOf(evaluated.getBooleanValue());
case BLANK -> "";
default -> null;
};
}
}
} catch (RuntimeException ignored) {
// Fall back to the cached value stored in the workbook.
}
return formatCachedFormulaCell(cell, formatter);
}
private static String formatCachedFormulaCell(Cell cell, DataFormatter formatter) {
if (cell.getCellType() != CellType.FORMULA) {
return formatter.formatCellValue(cell);
}
return switch (cell.getCachedFormulaResultType()) {
case STRING -> cell.getStringCellValue();
case NUMERIC -> formatNumericCell(cell, cell.getNumericCellValue(), formatter);
case BOOLEAN -> String.valueOf(cell.getBooleanCellValue());
case BLANK -> "";
default -> null;
};
}
private static String formatNumericCell(Cell cell, double value, DataFormatter formatter) {
if (DateUtil.isCellDateFormatted(cell)) {
String pattern = hasTimeFraction(value) ? DATE_TIME_FORMAT : DATE_FORMAT;
return new SimpleDateFormat(pattern).format(DateUtil.getJavaDate(value));
}
return NumberToTextConverter.toText(value);
}
private static boolean hasTimeFraction(double value) {
double fraction = value - Math.floor(value);
return fraction > TIME_FRACTION_EPSILON && (1 - fraction) > TIME_FRACTION_EPSILON;
}
}

View File

@@ -0,0 +1,27 @@
package com.kri.common.feature.excel;
import java.util.Objects;
import java.util.function.UnaryOperator;
public record StreamingReadOptions(
String sheetName,
int sheetIndex,
int headerRowIndex,
UnaryOperator<String> headerNormalizer
) {
private static final int DEFAULT_SHEET_INDEX = 0;
private static final int DEFAULT_HEADER_ROW_INDEX = 1;
public static final StreamingReadOptions DEFAULT =
new StreamingReadOptions(
null,
DEFAULT_SHEET_INDEX,
DEFAULT_HEADER_ROW_INDEX,
UnaryOperator.identity()
);
public StreamingReadOptions {
headerNormalizer = Objects.requireNonNullElseGet(headerNormalizer, UnaryOperator::identity);
}
}

View File

@@ -0,0 +1,59 @@
package com.kri.common.feature.file;
import java.util.regex.Pattern;
public final class FileUtil {
private static final Pattern FILENAME_SANITIZE = Pattern.compile("[^a-zA-Z0-9._-]");
/**
* 파일명에서 위험한 문자 제거
*/
public static String sanitizeFileName(String original) {
if (original == null || original.isBlank()) {
return "file";
}
String name = original.trim().replace("\\", "/");
int idx = name.lastIndexOf('/');
if (idx >= 0 && idx < name.length() - 1) {
name = name.substring(idx + 1);
}
name = FILENAME_SANITIZE.matcher(name).replaceAll("_");
// 너무 짧으면 기본값
if (name.isBlank()) {
return "file";
}
return name;
}
public static String getExtension(String fileName) {
if (fileName == null) {
return "";
}
int dot = fileName.lastIndexOf('.');
if (dot < 0 || dot == fileName.length() - 1) {
return "";
}
return fileName.substring(dot + 1);
}
public static String extractFileNameFromPath(String pathLike) {
if (pathLike == null || pathLike.isBlank()) {
return "";
}
String s = pathLike;
int q = s.indexOf('?');
if (q >= 0) {
s = s.substring(0, q);
}
int hash = s.indexOf('#');
if (hash >= 0) {
s = s.substring(0, hash);
}
int slash = s.lastIndexOf('/');
if (slash >= 0 && slash < s.length() - 1) {
return s.substring(slash + 1);
}
return s;
}
}

View File

@@ -0,0 +1,184 @@
package com.kri.common.feature.http;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* Lightweight HTTP client based on JDK HttpClient.
*/
public class ExternalApiClient {
private static final String CRLF = "\r\n";
private final HttpClient httpClient;
private final Duration requestTimeout;
public ExternalApiClient() {
this(HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.build(), Duration.ofSeconds(30));
}
public ExternalApiClient(HttpClient httpClient, Duration requestTimeout) {
this.httpClient = httpClient;
this.requestTimeout = requestTimeout == null ? Duration.ofSeconds(30) : requestTimeout;
}
private static HttpRequest.BodyPublisher buildBodyPublisher(String method, String body) {
if (body == null || body.isEmpty()) {
return switch (method) {
case "POST", "PUT", "PATCH" -> HttpRequest.BodyPublishers.ofString("");
default -> HttpRequest.BodyPublishers.noBody();
};
}
return HttpRequest.BodyPublishers.ofString(body);
}
public ExternalApiResponse get(String url, Map<String, String> headers) {
return send("GET", url, headers, null);
}
public ExternalApiResponse delete(String url, Map<String, String> headers) {
return send("DELETE", url, headers, null);
}
public ExternalApiResponse post(String url, Map<String, String> headers, String body) {
return send("POST", url, headers, body);
}
public ExternalApiResponse put(String url, Map<String, String> headers, String body) {
return send("PUT", url, headers, body);
}
public ExternalApiResponse patch(String url, Map<String, String> headers, String body) {
return send("PATCH", url, headers, body);
}
public ExternalApiResponse postMultipart(String url, Map<String, String> headers,
List<ExternalApiMultipartPart> parts) {
return sendMultipart("POST", url, headers, parts);
}
public ExternalApiResponse putMultipart(String url, Map<String, String> headers,
List<ExternalApiMultipartPart> parts) {
return sendMultipart("PUT", url, headers, parts);
}
private ExternalApiResponse send(String method, String url, Map<String, String> headers,
String body) {
try {
HttpRequest.Builder builder = HttpRequest.newBuilder()
.uri(URI.create(url))
.timeout(requestTimeout)
.method(method, buildBodyPublisher(method, body));
applyHeaders(builder, headers, false);
if (body != null && (headers == null || !headers.keySet().stream()
.map(String::toLowerCase).anyMatch("content-type"::equals))) {
builder.header("Content-Type", "application/json; charset=utf-8");
}
HttpRequest request = builder.build();
HttpResponse<byte[]> resp = httpClient.send(request, HttpResponse.BodyHandlers.ofByteArray());
return ExternalApiResponse.ofBytes(resp.statusCode(), resp.headers(), resp.body());
} catch (IOException | InterruptedException e) {
if (e instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
throw new RuntimeException("External API call failed: " + e.getMessage(), e);
}
}
private ExternalApiResponse sendMultipart(String method, String url, Map<String, String> headers,
List<ExternalApiMultipartPart> parts) {
try {
String boundary = "----KriCommonBoundary" + UUID.randomUUID().toString().replace("-", "");
byte[] body = buildMultipartBody(parts, boundary);
HttpRequest.Builder builder = HttpRequest.newBuilder()
.uri(URI.create(url))
.timeout(requestTimeout)
.method(method, HttpRequest.BodyPublishers.ofByteArray(body));
applyHeaders(builder, headers, true);
builder.header("Content-Type", "multipart/form-data; boundary=" + boundary);
HttpRequest request = builder.build();
HttpResponse<byte[]> resp = httpClient.send(request, HttpResponse.BodyHandlers.ofByteArray());
return ExternalApiResponse.ofBytes(resp.statusCode(), resp.headers(), resp.body());
} catch (IOException | InterruptedException e) {
if (e instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
throw new RuntimeException("External API call failed: " + e.getMessage(), e);
}
}
private static byte[] buildMultipartBody(List<ExternalApiMultipartPart> parts, String boundary)
throws IOException {
if (parts == null || parts.isEmpty()) {
throw new IllegalArgumentException("parts must not be empty");
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
for (ExternalApiMultipartPart part : parts) {
if (part == null) {
throw new IllegalArgumentException("parts must not contain null");
}
writeUtf8(out, "--" + boundary + CRLF);
writeUtf8(out, "Content-Disposition: form-data; name=\"" + headerValue(part.getName()) + "\"");
if (part.getFilename() != null) {
writeUtf8(out, "; filename=\"" + headerValue(part.getFilename()) + "\"");
}
writeUtf8(out, CRLF);
if (part.getContentType() != null && !part.getContentType().isBlank()) {
writeUtf8(out, "Content-Type: " + safeHeader(part.getContentType()) + CRLF);
}
writeUtf8(out, CRLF);
out.write(part.content());
writeUtf8(out, CRLF);
}
writeUtf8(out, "--" + boundary + "--" + CRLF);
return out.toByteArray();
}
private static void applyHeaders(HttpRequest.Builder builder, Map<String, String> headers,
boolean ignoreContentType) {
if (headers == null) {
return;
}
headers.forEach((k, v) -> {
if (k != null && v != null && !(ignoreContentType && "content-type".equalsIgnoreCase(k))) {
builder.header(k, v);
}
});
}
private static void writeUtf8(ByteArrayOutputStream out, String value) throws IOException {
// Multipart delimiters remain byte-identical because UTF-8 is ASCII-compatible, while
// user-visible field names and filenames retain non-ASCII characters.
out.write(value.getBytes(StandardCharsets.UTF_8));
}
private static String headerValue(String value) {
return safeHeader(value).replace("\\", "\\\\").replace("\"", "\\\"");
}
private static String safeHeader(String value) {
if (value.indexOf('\r') >= 0 || value.indexOf('\n') >= 0) {
throw new IllegalArgumentException("multipart header values must not contain CR/LF");
}
return value;
}
}

View File

@@ -0,0 +1,66 @@
package com.kri.common.feature.http;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Objects;
/**
* Part descriptor for {@link ExternalApiClient} multipart/form-data requests.
*/
public final class ExternalApiMultipartPart {
private final String name;
private final String filename;
private final String contentType;
private final byte[] content;
private ExternalApiMultipartPart(String name, String filename, String contentType,
byte[] content) {
this.name = requireText(name, "name");
this.filename = filename;
this.contentType = contentType;
this.content = content == null ? new byte[0] : Arrays.copyOf(content, content.length);
}
public static ExternalApiMultipartPart formField(String name, String value) {
byte[] content = value == null ? new byte[0] : value.getBytes(StandardCharsets.UTF_8);
return new ExternalApiMultipartPart(name, null, null, content);
}
public static ExternalApiMultipartPart file(String name, String filename, String contentType,
byte[] content) {
return new ExternalApiMultipartPart(
name,
requireText(filename, "filename"),
contentType == null || contentType.isBlank() ? "application/octet-stream" : contentType,
content);
}
public String getName() {
return name;
}
public String getFilename() {
return filename;
}
public String getContentType() {
return contentType;
}
public byte[] getContent() {
return Arrays.copyOf(content, content.length);
}
byte[] content() {
return content;
}
private static String requireText(String value, String fieldName) {
Objects.requireNonNull(value, fieldName + " must not be null");
if (value.isBlank()) {
throw new IllegalArgumentException(fieldName + " must not be blank");
}
return value;
}
}

View File

@@ -0,0 +1,98 @@
package com.kri.common.feature.http;
import java.net.http.HttpHeaders;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 외부 API 호출 결과를 단순하게 담는 DTO.
*/
public class ExternalApiResponse {
private static final Pattern CONTENT_TYPE_PARAMETER =
Pattern.compile("(?:^|;)\\s*([^;=\\s]+)\\s*=\\s*(?:\"((?:\\\\.|[^\"\\\\])*+)\"|([^;\"\\s]+))\\s*(?=;|$)");
private final int statusCode;
private final Map<String, List<String>> headers;
private final String body;
private final byte[] bodyBytes;
public ExternalApiResponse(int statusCode, Map<String, List<String>> headers, String body) {
this(statusCode, headers, body,
body == null ? new byte[0] : body.getBytes(resolveCharset(headers)));
}
private ExternalApiResponse(int statusCode, Map<String, List<String>> headers,
String body, byte[] bodyBytes) {
this.statusCode = statusCode;
this.headers = headers;
this.body = body;
this.bodyBytes = bodyBytes.clone();
}
public static ExternalApiResponse of(int status, HttpHeaders headers, String body) {
return new ExternalApiResponse(status, headers.map(), body);
}
/** Preserve the received bytes while keeping the existing decoded string API. */
public static ExternalApiResponse ofBytes(int status, HttpHeaders headers, byte[] body) {
byte[] bytes = body == null ? new byte[0] : body;
return new ExternalApiResponse(status, headers.map(),
new String(bytes, resolveCharset(headers.map())), bytes);
}
/** Return this response for 2xx, or throw with the original upstream response. */
public ExternalApiResponse requireSuccess() {
if (statusCode < 200 || statusCode >= 300) {
throw new ExternalApiResponseException(statusCode, headers, bodyBytes);
}
return this;
}
public byte[] getBodyBytes() {
return bodyBytes.clone();
}
private static Charset resolveCharset(Map<String, List<String>> headers) {
if (headers != null) {
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
if (entry.getKey() != null && entry.getKey().equalsIgnoreCase("Content-Type")
&& entry.getValue() != null && !entry.getValue().isEmpty() && entry.getValue().get(0) != null) {
// Consume each complete parameter so quoted values cannot introduce a fake charset.
Matcher matcher = CONTENT_TYPE_PARAMETER.matcher(entry.getValue().get(0));
while (matcher.find()) {
if (!matcher.group(1).equalsIgnoreCase("charset")) {
continue;
}
String charset = matcher.group(2) == null ? matcher.group(3)
: matcher.group(2).replaceAll("\\\\(.)", "$1");
try {
return Charset.forName(charset);
} catch (IllegalArgumentException ignored) {
// Match the JDK string body handler's UTF-8 fallback for an unknown charset.
return StandardCharsets.UTF_8;
}
}
break;
}
}
}
return StandardCharsets.UTF_8;
}
public int getStatusCode() {
return statusCode;
}
public Map<String, List<String>> getHeaders() {
return headers;
}
public String getBody() {
return body;
}
}

View File

@@ -0,0 +1,41 @@
package com.kri.common.feature.http;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/** An upstream HTTP error whose response can be relayed without rewriting its body. */
public class ExternalApiResponseException extends RuntimeException {
private final int statusCode;
private final Map<String, List<String>> headers;
private final byte[] body;
public ExternalApiResponseException(int statusCode, Map<String, List<String>> headers, byte[] body) {
super("External API returned HTTP " + statusCode);
this.statusCode = statusCode;
Map<String, List<String>> copy = new LinkedHashMap<>();
if (headers != null) {
headers.forEach((name, values) -> {
if (name != null && values != null) {
copy.put(name, List.copyOf(values));
}
});
}
this.headers = Collections.unmodifiableMap(copy);
this.body = body == null ? new byte[0] : body.clone();
}
public int getStatusCode() {
return statusCode;
}
public Map<String, List<String>> getHeaders() {
return headers;
}
public byte[] getBody() {
return body.clone();
}
}

View File

@@ -0,0 +1,15 @@
package com.kri.common.feature.http.bypass;
import jakarta.servlet.http.HttpServletRequest;
public interface BypassClient {
BypassResponse forward(String targetName, HttpServletRequest servletRequest, byte[] body);
BypassResponse forward(
String targetName,
HttpServletRequest servletRequest,
byte[] body,
BypassForwardOptions options
);
}

View File

@@ -0,0 +1,56 @@
package com.kri.common.feature.http.bypass;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class BypassContext {
private final String targetName;
private final BypassTarget target;
private final HttpServletRequest servletRequest;
private final Map<String, Object> attributes;
public BypassContext(
String targetName,
BypassTarget target,
HttpServletRequest servletRequest,
Map<String, Object> attributes
) {
this.targetName = targetName;
this.target = target;
this.servletRequest = servletRequest;
this.attributes = attributes == null
? Collections.emptyMap()
: Collections.unmodifiableMap(new HashMap<>(attributes));
}
public String targetName() {
return targetName;
}
public BypassTarget target() {
return target;
}
public HttpServletRequest servletRequest() {
return servletRequest;
}
public Map<String, Object> attributes() {
return attributes;
}
public Object attribute(String name) {
return attributes.get(name);
}
public <T> T attribute(String name, Class<T> type) {
Object value = attributes.get(name);
if (value == null) {
return null;
}
return type.cast(value);
}
}

View File

@@ -0,0 +1,107 @@
package com.kri.common.feature.http.bypass;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BypassForwardOptions {
private static final BypassForwardOptions EMPTY = builder().build();
private final List<BypassRequestCustomizer> requestCustomizers;
private final List<BypassResponseCustomizer> responseCustomizers;
private final Map<String, Object> attributes;
private final String stripPrefix;
private BypassForwardOptions(Builder builder) {
this.requestCustomizers = List.copyOf(builder.requestCustomizers);
this.responseCustomizers = List.copyOf(builder.responseCustomizers);
this.attributes = Collections.unmodifiableMap(new HashMap<>(builder.attributes));
this.stripPrefix = builder.stripPrefix;
}
public static BypassForwardOptions empty() {
return EMPTY;
}
public static Builder builder() {
return new Builder();
}
public List<BypassRequestCustomizer> requestCustomizers() {
return requestCustomizers;
}
public List<BypassResponseCustomizer> responseCustomizers() {
return responseCustomizers;
}
public Map<String, Object> attributes() {
return attributes;
}
public String stripPrefix() {
return stripPrefix;
}
public static class Builder {
private final List<BypassRequestCustomizer> requestCustomizers = new ArrayList<>();
private final List<BypassResponseCustomizer> responseCustomizers = new ArrayList<>();
private final Map<String, Object> attributes = new HashMap<>();
private String stripPrefix;
public Builder requestCustomizer(BypassRequestCustomizer customizer) {
if (customizer != null) {
this.requestCustomizers.add(customizer);
}
return this;
}
public Builder requestCustomizers(List<BypassRequestCustomizer> customizers) {
if (customizers != null) {
customizers.forEach(this::requestCustomizer);
}
return this;
}
public Builder responseCustomizer(BypassResponseCustomizer customizer) {
if (customizer != null) {
this.responseCustomizers.add(customizer);
}
return this;
}
public Builder responseCustomizers(List<BypassResponseCustomizer> customizers) {
if (customizers != null) {
customizers.forEach(this::responseCustomizer);
}
return this;
}
public Builder attribute(String name, Object value) {
if (name != null && !name.isBlank()) {
this.attributes.put(name, value);
}
return this;
}
public Builder attributes(Map<String, Object> attributes) {
if (attributes != null) {
attributes.forEach(this::attribute);
}
return this;
}
public Builder stripPrefix(String stripPrefix) {
this.stripPrefix = stripPrefix;
return this;
}
public BypassForwardOptions build() {
return new BypassForwardOptions(this);
}
}
}

View File

@@ -0,0 +1,171 @@
package com.kri.common.feature.http.bypass;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
public class BypassRequest {
private final String method;
private final String path;
private final Map<String, List<String>> queryParams;
private final Map<String, List<String>> headers;
private final byte[] body;
private BypassRequest(Builder builder) {
this.method = builder.method;
this.path = builder.path;
this.queryParams = immutableMultiValueMap(builder.queryParams);
this.headers = immutableMultiValueMap(builder.headers);
this.body = builder.body == null ? new byte[0] : builder.body.clone();
}
private static Map<String, List<String>> immutableMultiValueMap(Map<String, List<String>> source) {
Map<String, List<String>> copy = new LinkedHashMap<>();
source.forEach((key, values) -> copy.put(key, List.copyOf(values)));
return Collections.unmodifiableMap(copy);
}
public static Builder builder() {
return new Builder();
}
public Builder toBuilder() {
return builder()
.method(method)
.path(path)
.queryParams(queryParams)
.headers(headers)
.body(body);
}
public String method() {
return method;
}
public String path() {
return path;
}
public Map<String, List<String>> queryParams() {
return queryParams;
}
public Map<String, List<String>> headers() {
return headers;
}
public byte[] body() {
return body.clone();
}
public String bodyAsUtf8String() {
return new String(body, StandardCharsets.UTF_8);
}
public Optional<String> firstHeader(String name) {
if (name == null) {
return Optional.empty();
}
return headers.entrySet().stream()
.filter(entry -> entry.getKey().equalsIgnoreCase(name))
.flatMap(entry -> entry.getValue().stream())
.findFirst();
}
public boolean isJsonBody() {
return firstHeader("Content-Type")
.map(value -> value.toLowerCase(Locale.ROOT).contains("application/json"))
.orElse(false);
}
public static class Builder {
private String method;
private String path = "/";
private final Map<String, List<String>> queryParams = new LinkedHashMap<>();
private final Map<String, List<String>> headers = new LinkedHashMap<>();
private byte[] body = new byte[0];
public Builder method(String method) {
this.method = method;
return this;
}
public Builder path(String path) {
this.path = path == null || path.isBlank() ? "/" : path;
return this;
}
public Builder queryParam(String name, String value) {
add(queryParams, name, value);
return this;
}
public Builder queryParams(Map<String, List<String>> queryParams) {
if (queryParams != null) {
queryParams.forEach((key, values) -> {
if (values != null) {
values.forEach(value -> queryParam(key, value));
}
});
}
return this;
}
public Builder header(String name, String value) {
add(headers, name, value);
return this;
}
public Builder headers(Map<String, List<String>> headers) {
if (headers != null) {
headers.forEach((key, values) -> {
if (values != null) {
values.forEach(value -> header(key, value));
}
});
}
return this;
}
public Builder replaceHeader(String name, String value) {
if (name != null && !name.isBlank()) {
headers.keySet().removeIf(key -> key.equalsIgnoreCase(name));
header(name, value);
}
return this;
}
public Builder removeHeader(String name) {
if (name != null) {
headers.keySet().removeIf(key -> key.equalsIgnoreCase(name));
}
return this;
}
public Builder body(byte[] body) {
this.body = body == null ? new byte[0] : body.clone();
return this;
}
public BypassRequest build() {
if (method == null || method.isBlank()) {
throw new IllegalArgumentException("method must not be blank");
}
return new BypassRequest(this);
}
private static void add(Map<String, List<String>> map, String name, String value) {
if (name == null || name.isBlank() || value == null) {
return;
}
map.computeIfAbsent(name, ignored -> new ArrayList<>()).add(value);
}
}
}

View File

@@ -0,0 +1,7 @@
package com.kri.common.feature.http.bypass;
@FunctionalInterface
public interface BypassRequestCustomizer {
BypassRequest customize(BypassRequest request, BypassContext context) throws Exception;
}

View File

@@ -0,0 +1,147 @@
package com.kri.common.feature.http.bypass;
import com.kri.common.feature.http.ExternalApiResponseException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import org.springframework.http.HttpHeaders;
public class BypassResponse {
private final int statusCode;
private final Map<String, List<String>> headers;
private final byte[] body;
private BypassResponse(Builder builder) {
this.statusCode = builder.statusCode;
this.headers = immutableMultiValueMap(builder.headers);
this.body = builder.body == null ? new byte[0] : builder.body.clone();
}
private static Map<String, List<String>> immutableMultiValueMap(Map<String, List<String>> source) {
Map<String, List<String>> copy = new LinkedHashMap<>();
source.forEach((key, values) -> copy.put(key, List.copyOf(values)));
return Collections.unmodifiableMap(copy);
}
public static Builder builder() {
return new Builder();
}
public Builder toBuilder() {
return builder()
.statusCode(statusCode)
.headers(headers)
.body(body);
}
public int statusCode() {
return statusCode;
}
/** Return this response for 2xx, or throw with the original upstream response. */
public BypassResponse requireSuccess() {
if (statusCode < 200 || statusCode >= 300) {
throw new ExternalApiResponseException(statusCode, headers, body);
}
return this;
}
public Map<String, List<String>> headers() {
return headers;
}
public HttpHeaders httpHeaders() {
HttpHeaders httpHeaders = new HttpHeaders();
headers.forEach(httpHeaders::put);
return httpHeaders;
}
public byte[] body() {
return body.clone();
}
public String bodyAsUtf8String() {
return new String(body, StandardCharsets.UTF_8);
}
public Optional<String> firstHeader(String name) {
if (name == null) {
return Optional.empty();
}
return headers.entrySet().stream()
.filter(entry -> entry.getKey().equalsIgnoreCase(name))
.flatMap(entry -> entry.getValue().stream())
.findFirst();
}
public boolean isJsonBody() {
return firstHeader("Content-Type")
.map(value -> value.toLowerCase(Locale.ROOT).contains("application/json"))
.orElse(false);
}
public static class Builder {
private int statusCode = 200;
private final Map<String, List<String>> headers = new LinkedHashMap<>();
private byte[] body = new byte[0];
public Builder statusCode(int statusCode) {
this.statusCode = statusCode;
return this;
}
public Builder header(String name, String value) {
add(headers, name, value);
return this;
}
public Builder headers(Map<String, List<String>> headers) {
if (headers != null) {
headers.forEach((key, values) -> {
if (values != null) {
values.forEach(value -> header(key, value));
}
});
}
return this;
}
public Builder replaceHeader(String name, String value) {
if (name != null && !name.isBlank()) {
headers.keySet().removeIf(key -> key.equalsIgnoreCase(name));
header(name, value);
}
return this;
}
public Builder removeHeader(String name) {
if (name != null) {
headers.keySet().removeIf(key -> key.equalsIgnoreCase(name));
}
return this;
}
public Builder body(byte[] body) {
this.body = body == null ? new byte[0] : body.clone();
return this;
}
public BypassResponse build() {
return new BypassResponse(this);
}
private static void add(Map<String, List<String>> map, String name, String value) {
if (name == null || name.isBlank() || value == null) {
return;
}
map.computeIfAbsent(name, ignored -> new ArrayList<>()).add(value);
}
}
}

View File

@@ -0,0 +1,7 @@
package com.kri.common.feature.http.bypass;
@FunctionalInterface
public interface BypassResponseCustomizer {
BypassResponse customize(BypassResponse response, BypassContext context) throws Exception;
}

View File

@@ -0,0 +1,47 @@
package com.kri.common.feature.http.bypass;
import java.time.Duration;
import java.util.List;
public class BypassTarget {
private final String name;
private final String baseUrl;
private final String stripPrefix;
private final List<String> allowedPaths;
private final Duration timeout;
public BypassTarget(
String name,
String baseUrl,
String stripPrefix,
List<String> allowedPaths,
Duration timeout
) {
this.name = name;
this.baseUrl = baseUrl;
this.stripPrefix = stripPrefix;
this.allowedPaths = allowedPaths == null ? List.of() : List.copyOf(allowedPaths);
this.timeout = timeout;
}
public String getName() {
return name;
}
public String getBaseUrl() {
return baseUrl;
}
public String getStripPrefix() {
return stripPrefix;
}
public List<String> getAllowedPaths() {
return allowedPaths;
}
public Duration getTimeout() {
return timeout;
}
}

View File

@@ -0,0 +1,27 @@
package com.kri.common.feature.jpa;
import com.kri.common.feature.enums.CodeEnum;
import com.kri.common.feature.enums.CodeEnumUtils;
import jakarta.persistence.AttributeConverter;
public abstract class AbstractCodeEnumConverter<
E extends Enum<E> & CodeEnum<V>,
V
> implements AttributeConverter<E, V> {
private final Class<E> enumClass;
protected AbstractCodeEnumConverter(Class<E> enumClass) {
this.enumClass = enumClass;
}
@Override
public V convertToDatabaseColumn(E attribute) {
return attribute == null ? null : attribute.getCode();
}
@Override
public E convertToEntityAttribute(V dbData) {
return CodeEnumUtils.fromCode(enumClass, dbData);
}
}

View File

@@ -0,0 +1,42 @@
package com.kri.common.feature.jpa;
import jakarta.persistence.MappedSuperclass;
import jakarta.persistence.PrePersist;
import java.util.UUID;
@MappedSuperclass
public abstract class BaseUuidEntity {
private static String generateId(int length) {
String base = UUID.randomUUID().toString().replace("-", ""); // 32 chars
if (length <= 32) {
return base.substring(0, length);
}
StringBuilder sb = new StringBuilder(length);
sb.append(base);
while (sb.length() < length) {
sb.append(UUID.randomUUID().toString().replace("-", ""));
}
return sb.substring(0, length);
}
protected abstract String getId();
protected abstract void setId(String id);
/**
* 엔티티마다 컬럼 길이에 맞춰 오버라이드
*/
protected int idLength() {
return 32;
}
@PrePersist
protected void prePersistId() {
if (getId() == null || getId().isBlank()) {
setId(generateId(idLength()));
}
}
}

Some files were not shown because too many files have changed in this diff Show More