Compare commits

..

16 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
63 changed files with 2562 additions and 330 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

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.

256
Agents.md
View File

@@ -1,256 +0,0 @@
# Agents.md
This file is for AI agents modifying or consuming this repository. Keep it concise, factual, and synchronized with source code.
## Repository Identity
- Project: `KriCommon`
- Type: Java 17 Spring Boot starter/library
- Build: Gradle `java-library` + `maven-publish`
- Maven coordinates: `com.kri.common:starter:<commonVer>`
- Version source: `build.gradle` variable `commonVer`
- Main source root: `src/main/java`
- Auto-configuration registration: `src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`
## Package Contract
- `com.kri.common.autoconfigure`: Spring Boot auto-configurations and configuration property classes.
- `com.kri.common.feature`: Public API intended for service code to import directly.
- `com.kri.common.runtime`: Runtime implementation assembled by auto-configuration. Treat as internal unless there is no public feature API.
- `com.kri.common.endpoint`: Optional common controllers exposed by configuration.
When adding features, prefer exposing stable service-facing types under `feature` and wiring implementation under `autoconfigure`/`runtime`.
## Build Commands
```bash
./gradlew compileJava
./gradlew publishReleasePublicationToGiteaRepository
```
On Windows PowerShell, use:
```powershell
.\gradlew.bat compileJava
.\gradlew.bat publishReleasePublicationToGiteaRepository
```
Publishing requires `giteaUser`/`giteaToken` Gradle properties or `GITEA_USER`/`GITEA_TOKEN` environment variables. The publish task depends on `checkGiteaPackageVersionNotExists`.
## Dependency Model
The library intentionally uses many `compileOnly` Spring dependencies. Do not assume a class is present at runtime unless the consuming service has the matching starter.
Important dependency categories:
- Spring Boot BOM: `org.springframework.boot:spring-boot-dependencies:3.5.7`
- Java: 17
- JWT: JJWT `0.12.6`
- JSON: Jackson Databind `2.17.0`
- Excel: Apache POI `5.5.1`
- Spring Web/Security/JPA/Redis/AOP/Swagger dependencies are mostly `compileOnly`
When adding auto-configuration, use `@ConditionalOnClass`, `@ConditionalOnBean`, `@ConditionalOnMissingBean`, and property conditions to avoid breaking consumers that do not include optional starters.
## Configuration Prefixes
Only use `kri.*` prefixes.
Known prefixes:
- `kri.auth.jwt`
- `kri.auth.apikey`
- `kri.security`
- `kri.swagger`
- `kri.web`
- `kri.web.mdc`
- `kri.http.bypass`
- `kri.redis`
- `kri.scheduling`
- `kri.error.expose`
## Auto-Configurations
Declared imports:
- `com.kri.common.autoconfigure.auth.jwt.JwtAutoConfiguration`
- `com.kri.common.autoconfigure.auth.apikey.ApiKeyJpaAutoConfiguration`
- `com.kri.common.autoconfigure.auth.apikey.ApiKeyPreloadAutoConfiguration`
- `com.kri.common.autoconfigure.auth.apikey.ApiKeyAdminAutoConfiguration`
- `com.kri.common.autoconfigure.security.KriSecurityAutoConfiguration`
- `com.kri.common.autoconfigure.web.CommonWebAutoConfiguration`
- `com.kri.common.autoconfigure.swagger.KriSwaggerAutoConfiguration`
- `com.kri.common.autoconfigure.redis.CommonRedisAutoConfiguration`
- `com.kri.common.autoconfigure.scheduling.CommonSchedulingAutoConfiguration`
- `com.kri.common.autoconfigure.http.bypass.BypassAutoConfiguration`
If a new auto-configuration must be active for consumers, add it to `AutoConfiguration.imports`.
## Feature Map
### JWT
- Public classes: `JwtService`, `JwtUserClaimsDto`
- Config: `kri.auth.jwt`
- Auto-config: `JwtAutoConfiguration`
- Main operations: generate access/refresh tokens, parse token, convert claims to `JwtUserClaimsDto`, convert token/DTO to Spring Security `Authentication`
- Claims DTO fields: `userId`, `userCmpn`, `userTeam`, `userName`, `userRole`
Security note: default secrets in source are not production-safe. Documentation and examples should instruct consumers to override secrets.
### API Key Authentication
- Public extension point: `ApiKeyUserClaimsProvider`
- Runtime filter: `ApiKeyAuthFilter`
- Runtime preload provider: `PreloadedApiKeyUserClaimsProvider`
- Config: `kri.auth.apikey`
- Optional endpoint: `ApiKeyAdminController`
- Admin endpoints:
- `POST /internal/apikey/reload`
- `GET /internal/apikey/cache`
Behavior:
- API key is read from `kri.auth.apikey.header-name`, default `X-API-Key`.
- If authentication already exists in `SecurityContextHolder`, API key filter does nothing.
- If provider resolves a key, the result is converted to `Authentication` using `JwtService.toAuthentication`.
- Preloaded provider returns empty cache when `service-code` is blank.
- Admin endpoint is exposed only when `admin-api-enabled=true` and the preload provider exists.
- Admin endpoint has IP allowlist enforcement.
### Security
- Auto-config: `KriSecurityAutoConfiguration`
- Config: `kri.security`
- Default enabled: `true`
- Registers `JwtAuthenticationFilter` and default `SecurityFilterChain` only when consumer has no `SecurityFilterChain` bean.
- Filter order inside the default chain: optional `ApiKeyAuthFilter`, then `JwtAuthenticationFilter`, both before `UsernamePasswordAuthenticationFilter`.
- Default chain disables HTTP Basic and CSRF, uses stateless sessions, optionally enforces `allowed-ips`, permits `public-paths`, authenticates all other requests.
- When `kri.security.allowed-ips` is non-empty, `public-paths` require an allowed client IP but no authentication; all other paths require both allowed IP and authentication.
- Method security is enabled with JSR-250 and pre/post annotations.
### Web
- Auto-config: `CommonWebAutoConfiguration`
- Config: `kri.web.enabled`, default `true`
- MDC config: `kri.web.mdc.enabled`, default `true`
- Registers:
- `ErrorAdvice`
- `TraceFilter`
- `ServiceMdcAspect` when AspectJ is present and MDC is enabled
- MVC interceptor for handler MDC when MDC is enabled
- `RequestUserContextArgumentResolver` when `JwtService` bean exists
- `CodeEnumConverter`
- global CORS mapping
### Swagger/OpenAPI
- Auto-config: `KriSwaggerAutoConfiguration`
- Config: `kri.swagger`
- Default enabled: `true`
- Requires OpenAPI/springdoc classes on classpath.
- Defines security schemes `BearerAuth` and `ApiKeyAuth`.
- Creates `GroupedOpenApi` named `kriGroupedOpenApi`, group `kri-api`, paths `/api/**` and `/internal/**`.
- Uses `kri.swagger.base-package` for package scanning.
- Adds API key admin package when `kri.auth.apikey.admin-api-enabled=true`.
- Registers `SwaggerIpFilter` for `/swagger-ui/*`, `/v3/api-docs/*`, `/swagger-ui.html`.
- Adds CodeEnum model/property/parameter OpenAPI support.
### Redis
- Auto-config: `CommonRedisAutoConfiguration`
- Config: `kri.redis.enabled`
- Default enabled: `false`
- Requires `RedisTemplate` class and `RedisConnectionFactory` bean.
- Registers `RedisQueueHelper`.
### External API Client
- Public classes: `ExternalApiClient`, `ExternalApiResponse`, `ExternalApiMultipartPart`
- JDK `HttpClient` based lightweight HTTP client.
- Supports `GET`, `DELETE`, `POST`, `PUT`, `PATCH` with `String` request bodies.
- Supports multipart uploads through `postMultipart` and `putMultipart`.
- Multipart requests ignore caller-supplied `Content-Type` and generate `multipart/form-data` with the required boundary.
- Responses are returned as `String` body via `ExternalApiResponse`.
### HTTP Bypass
- Public classes: `BypassClient`, `BypassRequest`, `BypassResponse`, `BypassContext`, `BypassForwardOptions`, `BypassRequestCustomizer`, `BypassResponseCustomizer`
- Runtime implementation: `DefaultBypassClient`
- Auto-config: `BypassAutoConfiguration`
- Config: `kri.http.bypass`
- Default enabled: `false`
- Requires servlet web classes.
- Consumer services define bypass controllers explicitly and call `BypassClient.forward(targetName, request, body)`.
- Targets are configured under `kri.http.bypass.targets.<targetName>` with `base-url`, optional `strip-prefix`, `allowed-paths`, `request-customizers`, `response-customizers`, and timeout.
- Target customizers are referenced by Spring bean name and run before per-request customizers from `BypassForwardOptions`.
- Response bodies are returned as `byte[]`; preserve target `Content-Type` so frontends can parse JSON/text/blob correctly.
- Do not allow frontends to pass arbitrary full target URLs. Keep target base URLs server-side and use `allowed-paths`.
- Do not forward hop-by-hop headers such as `Host`, `Content-Length`, `Transfer-Encoding`, `Connection`, `Keep-Alive`, `Upgrade`, `Proxy-Authenticate`, `Proxy-Authorization`, `TE`, and `Trailer`.
### Scheduling
- Auto-config: `CommonSchedulingAutoConfiguration`
- Config: `kri.scheduling.enabled`
- Default enabled: `false`
- Enables Spring scheduling.
### Excel
- Public classes: `ExcelMapper`, `ExcelUtil`, `ExcelColumn`, `StreamingReadOptions`
- Supports DTO workbook read/write, map workbook read/write, SXSSF streaming write, SAX streaming read.
- `ExcelColumn` fields: `header`, `order`, `width`.
- `StreamingReadOptions.DEFAULT`: sheet index `0`, header row index `1`, identity header normalizer.
### JSON
- Public class: `JsonUtil`
- All methods require an explicit `ObjectMapper`.
- Do not introduce hidden global ObjectMapper state without a deliberate API decision.
### Date/Time
- Public classes: `DateTimeUtil`, `LenientLocalDateTime`, `LenientLocalDateTimeDeserializer`
- KST zone constant: `Asia/Seoul`
- UTC constant: `ZoneOffset.UTC`
### Enum
- Public classes: `CodeEnum`, `CodeEnumUtils`
- Runtime MVC converter: `CodeEnumConverter`
- JPA base converter: `AbstractCodeEnumConverter`
- Swagger metadata support exists in `runtime.swagger`.
### JPA
- Public classes: `BaseUuidEntity`, `AbstractCodeEnumConverter`, `EntityColumnAccessor`
- API key JPA runtime entities/repository are internal to `runtime.auth.apikey.persistence`.
### Utilities
- `FileUtil`: filename sanitizing, extension extraction, path-like filename extraction
- `StringUtil`: null/blank checks, normalization, basic validation, escaping
- `NumericUtil`: numeric checks and safe parsing
- `CollectionUtil`: empty checks
- `CommonUtil`: UUID helpers
## Coding Rules For Agents
- Do not move public APIs out of `feature` without a compatibility plan.
- Do not make optional Spring integrations unconditional.
- Do not add new configuration prefixes outside `kri.*`.
- Do not hard-code service-specific secrets or credentials in new code or docs.
- Do not directly expose raw API keys in endpoints or logs.
- Prefer `@ConditionalOnMissingBean` for beans consumers may override.
- Prefer explicit examples in README that use placeholder secrets and local URLs.
- Keep README human-readable and keep this file agent-readable.
- If changing behavior, update README and this file in the same change.
- Run `.\gradlew.bat compileJava` before finalizing when possible.
## Verification Checklist
- `.\gradlew.bat compileJava`
- Confirm any new auto-config is listed in `AutoConfiguration.imports`.
- Confirm property names in docs match `@ConfigurationProperties` fields.
- Confirm optional integrations have classpath/bean/property conditions.
- Confirm public examples import from `com.kri.common.feature.*` unless intentionally documenting internals.

1
CLAUDE.md Normal file
View File

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

238
README.md
View File

@@ -99,6 +99,22 @@ import com.kri.common.feature.web.RequestUserContext;
컨트롤러 파라미터로 선언하면 현재 인증 사용자와 client IP를 받을 수 있습니다. `JwtService` Bean이 있을 때 `RequestUserContextArgumentResolver`가 자동 등록됩니다.
`beta.1.7.1`부터 인터셉터 등에서도 공개 API인 `RequestUserContextProvider`를 주입받아 동일한 컨텍스트를 조회할 수 있습니다.
```java
import com.kri.common.feature.web.RequestUserContext;
import com.kri.common.feature.web.RequestUserContextProvider;
// 생성자로 주입받은 Provider를 요청 처리 중 호출합니다.
RequestUserContext ctx = requestUserContextProvider.resolve(request);
```
기본 Provider는 기존 Resolver의 principal → details → 검증된 Bearer 토큰 순서와 IP 해석을 유지합니다. 인증 정보를 찾지 못하면 사용자 필드가 비어 있는 컨텍스트를 반환합니다. 요청 파라미터에서 사용자 정보를 가져오지 않으며, 인증 필수 여부나 업무 권한은 호출 서비스에서 검사해야 합니다. 요청 간 컨텍스트를 캐시하지 않습니다.
기본 Provider는 `kri.web.enabled=true`와 `JwtService` Bean이 있을 때 등록되며, 서비스가 `RequestUserContextProvider` Bean을 제공하면 이를 사용합니다. 기존 컨트롤러 주입 방식과 Resolver 교체 지점, `JwtService`를 받는 기존 Resolver 생성자는 유지됩니다. Provider도 기존 Web 통합과 마찬가지로 Servlet/Spring Web classpath가 필요합니다.
Swagger 자동 구성이 활성화되면 `RequestUserContext`는 요청 입력 문서에서 제외됩니다. `authenticated`, `clientIp`, `userRole` 등의 입력 항목은 표시되지 않으며, 실제 요청의 인증 정보와 IP 주입 동작은 유지됩니다.
```java
@GetMapping("/me")
public Object me(RequestUserContext user) {
@@ -178,7 +194,7 @@ ExternalApiResponse res = client.post(url, headers, jsonBody);
```java
List<ExternalApiMultipartPart> parts = List.of(
ExternalApiMultipartPart.formField("serviceCode", "demo"),
ExternalApiMultipartPart.file("file", "sample.txt", "text/plain", fileBytes)
ExternalApiMultipartPart.file("file", "한글-파일.txt", "text/plain", fileBytes)
);
ExternalApiResponse res = client.postMultipart(url, headers, parts);
@@ -186,6 +202,13 @@ ExternalApiResponse res = client.postMultipart(url, headers, parts);
multipart 요청에서는 전달한 headers의 `Content-Type` 값을 무시하고, 필요한 boundary를 포함한
`Content-Type: multipart/form-data; boundary=...` 값을 자동 생성합니다.
multipart 파트 헤더와 텍스트 필드는 UTF-8로 인코딩하고, 파일 내용은 원본
`byte[]`로 전송합니다. ASCII와 non-ASCII 파일명 모두 원본 값을 quoted `filename`에
UTF-8 바이트로 전송하며, ASCII fallback이나 `filename*`는 추가하지 않습니다.
```http
Content-Disposition: form-data; name="file"; filename="한글-파일.txt"
```
지원 메서드:
@@ -199,6 +222,20 @@ multipart 요청에서는 전달한 headers의 `Content-Type` 값을 무시하
응답은 `statusCode`, `headers`, `body`를 제공합니다.
`getBody()`는 기존처럼 `Content-Type`의 charset(없거나 알 수 없으면 UTF-8)으로
해석한 문자열을 반환하며, `getBodyBytes()`는 수신한 원본 바이트의 복사본을 반환합니다.
charset 추출 시 다른 매개변수의 따옴표 내부 문자열은 charset 선언으로 취급하지 않습니다.
직접 호출도 오류에서 후속 작업을 중단하려면 `requireSuccess()`를 사용합니다.
```java
ExternalApiResponse response = client.put(url, headers, json).requireSuccess();
String bulkSendKey = response.getBody();
```
`requireSuccess()`는 2xx에서 같은 응답을 반환하고, 그 외 상태에서는
`com.kri.common.feature.http.ExternalApiResponseException`을 던집니다.
기존 호출은 명시적으로 검증하지 않으면 오류 상태도 응답 객체로 반환합니다.
#### `BypassClient`
Front에서 들어온 요청을 target API로 bypass하는 HTTP client입니다. 원본 method, query param,
@@ -308,6 +345,118 @@ BypassResponse response = bypassClient.forward(
`Host`, `Content-Length`, `Transfer-Encoding`, `Connection` 같은 hop-by-hop header는
전달하지 않습니다.
HTTP/2 전용 `:status` 등 `:`로 시작하는 헤더도 전달하지 않습니다. 상태값은
`BypassResponse.statusCode()`를 사용하며 일반 응답 헤더와 원본 바디는 유지합니다.
#### 원본 오류 응답 전달
대상별 `throw-on-error`의 기본값은 `false`이며, 기존처럼 비정상 HTTP 상태도
`BypassResponse`로 반환합니다. 내부 서비스 처리에서 오류 이후 실행을 중단하려면
해당 대상에만 활성화할 수 있습니다.
```yaml
kri:
http:
bypass:
enabled: true
targets:
nice:
base-url: https://api.nice.example
allowed-paths:
- /v1/**
throw-on-error: true
```
활성화하면 응답 customizer 적용 후 최종 상태가 2xx가 아닐 때
`ExternalApiResponseException`을 던집니다. 호출별 명시적 검증은
`bypassClient.forward(...).requireSuccess()`로도 가능합니다. 연결 실패는 기존
`BYPASS_CALL_FAILED` 처리이며, 원본 HTTP 응답이 없는 경우와 구분합니다.
response customizer 안에서 `requireSuccess()`를 호출하거나 `ExternalApiResponseException`을
던지면 그 예외를 그대로 전파합니다. 일반 customizer 실패는 기존 오류 처리를 유지합니다.
Spring MVC와 Servlet API가 있고 `kri.web.enabled=true`(기본값)이면
`ExternalApiErrorAutoConfiguration`이 원본 응답 처리기를 자동 등록합니다.
원본 HTTP 상태와 바디 바이트, `Content-Type`, `Content-Encoding`을 그대로 반환하므로
상위 서비스의 오류 필드와 압축된 바디를 유지합니다. 쿠키·인증·전송 헤더는 오류
처리기가 전달하지 않습니다. 오류 바디가 비어 있으면 빈 바디를 그대로 반환합니다.
공통 처리기는 이 전용 예외만 처리하며 일반 공통 오류 처리보다 먼저 적용됩니다.
소비 서비스가 `externalApiResponseAdvice`라는 이름으로 자체 오류 처리기 Bean을
제공하면 기본 등록을 대체할 수 있으며 runtime 구현에 의존할 필요가 없습니다.
예외를 컨트롤러에서 명시적으로 처리할 수도 있습니다. Web이 비활성화되었거나 없는 환경에서는
직접 예외를 처리해야 합니다. 원본 오류 바디의 외부 노출이 적절한 대상에만 활성화하세요.
### 암호화와 해시
공개 API는 `com.kri.common.feature.crypto.*`에 있습니다. 중앙 키 DB를 사용하지 않으며,
AES master key는 `kri.crypto.aes.keys` 설정 또는 각 호출의 `masterKey`로 전달합니다.
#### AES-256
기본 알고리즘은 인증 암호화인 `AES_256_GCM`입니다. `masterKey`와 salt를
`PBKDF2WithHmacSHA256`으로 처리해 256-bit AES key를 만들며, salt와 IV를 생략하면
안전한 난수로 자동 생성합니다. 기존 시스템 연동을 위해 salt와 IV를 직접 전달할 수도 있습니다.
```java
import com.kri.common.feature.crypto.aes.AesCryptoService;
import com.kri.common.feature.crypto.aes.AesDecryptRequest;
import com.kri.common.feature.crypto.aes.AesEncryptRequest;
import com.kri.common.feature.crypto.aes.AesEncryptedValue;
import com.kri.common.feature.crypto.aes.AesEncryptedValueCodec;
import com.kri.common.feature.crypto.aes.TagLayout;
AesEncryptedValue encrypted = aesCryptoService.encrypt(
AesEncryptRequest.builder(plainBytes)
.masterKey(masterKey)
.salt(salt)
.iv(iv)
.aad(aad)
.tagLayout(TagLayout.DETACHED)
.build()
);
String storedValue = AesEncryptedValueCodec.encode(encrypted);
AesEncryptedValue decoded = AesEncryptedValueCodec.decode(storedValue);
byte[] restored = aesCryptoService.decrypt(
AesDecryptRequest.builder(decoded)
.masterKey(masterKey)
.aad(aad)
.build()
);
```
- GCM tag는 ciphertext 결합형 `APPENDED` 또는 별도 필드형 `DETACHED`를 지원합니다.
- GCM tag는 생략할 수 없습니다. tag가 없는 기존 데이터는 명시적으로
`AES_256_CBC_PKCS5`를 선택해야 하며, CBC는 변조를 감지하지 못하므로 신규 데이터에 권장하지 않습니다.
- GCM IV는 12바이트, CBC IV는 16바이트이고 salt는 최소 16바이트입니다.
- 호출자가 IV를 직접 전달하면 동일한 key에서 IV가 중복되지 않도록 호출 서비스가 보장해야 합니다.
- AAD는 GCM에서만 지원하며 복호화할 때 암호화 시점과 동일한 값을 전달해야 합니다.
- 암호화 결과는 format version, algorithm, key ID, KDF iteration, salt, IV, ciphertext 및 tag 정보를 포함합니다.
#### 일반 digest와 BCrypt
```java
import com.kri.common.feature.crypto.hash.AdaptiveHashService;
import com.kri.common.feature.crypto.hash.DigestAlgorithm;
import com.kri.common.feature.crypto.hash.DigestEncoding;
import com.kri.common.feature.crypto.hash.DigestService;
String checksum = digestService.digest(
bytes,
DigestAlgorithm.SHA_256,
DigestEncoding.HEX_LOWER
);
String encodedSecret = adaptiveHashService.hash("secret-value");
boolean matched = adaptiveHashService.matches("secret-value", encodedSecret);
```
`DigestService`는 MD5, SHA-1, SHA-256, SHA-512와 HEX 소문자/대문자, Base64 출력을 지원합니다.
MD5와 SHA-1 enum 이름은 각각 `MD5_LEGACY`, `SHA_1_LEGACY`이며 기존 데이터 검증과
연동에만 사용해야 합니다. `AdaptiveHashService`는 BCrypt 기반이며 비밀번호뿐 아니라 PIN,
복구 코드, API Secret 같은 짧은 비밀값 검증에 사용할 수 있습니다. BCrypt 결과에는 salt가
포함되며 일반적인 구현의 72바이트 입력 제한을 고려해야 합니다.
### JSON
#### `JsonUtil`
@@ -351,6 +500,8 @@ Apache POI 기반 Excel 읽기/쓰기 helper입니다.
- SAX 기반 대용량 스트리밍 읽기
- streaming writer를 열어 row를 점진적으로 append
`Path`를 받는 `readStreaming`과 `readHeaderStreaming`은 `PackageAccess.READ`로 파일을 열어 원본의 SHA-256, 크기, 수정 시각을 유지합니다. 읽기 전용 파일도 처리하며, 콜백에서 예외가 발생해도 원본을 저장하지 않고 파일 핸들을 해제합니다. 기존 옵션 검증, 예외 처리, SAX 스트리밍 방식은 유지합니다.
#### `StreamingReadOptions`
스트리밍 읽기 옵션입니다.
@@ -473,6 +624,8 @@ kri:
apikey:
enabled: false
header-name: "X-API-Key"
allowed-paths: []
excluded-paths: []
service-code: "example-service"
preload-on-startup: false
admin-api-enabled: false
@@ -488,6 +641,19 @@ kri:
jpa:
show-sql: false
format-sql: false
crypto:
aes:
active-key-id: "key-2026"
keys:
key-2026: "replace-with-a-service-master-key"
algorithm: AES_256_GCM
tag-layout: APPENDED
kdf:
iterations: 600000
salt-length: 16
hash:
bcrypt:
strength: 12
security:
enabled: true
allowed-ips:
@@ -523,6 +689,20 @@ kri:
운영 서비스에서는 JWT secret, API Key DB 접속 정보, Swagger/API Key admin 허용 IP를 반드시 서비스 환경에 맞게 override해야 합니다.
### `kri.crypto`
- `aes.active-key-id`: 직접 master key를 전달하지 않았을 때 사용할 key ID
- `aes.keys`: key ID별 master key. 복호화 호환을 위해 교체 전 key도 필요한 기간 동안 유지
- `aes.algorithm`: 기본값 `AES_256_GCM`
- `aes.tag-layout`: 기본값 `APPENDED`
- `aes.kdf.iterations`: PBKDF2 반복 횟수, 기본값 `600000`
- `aes.kdf.salt-length`: 자동 생성 salt 길이, 기본값 `16`
- `hash.bcrypt.strength`: 기본 BCrypt cost, 기본값 `12`, 허용 범위 `4..31`
`kri.crypto.enabled` 설정은 없습니다. Crypto API Bean은 항상 자동 구성되며, YML 키가 없어도
호출 시 master key를 직접 전달할 수 있습니다. 설정과 호출 양쪽에 키가 있으면 직접 전달한 키가
우선합니다. master key를 소스에 커밋하거나 로그와 예외에 출력하지 마십시오.
### `kri.auth.jwt`
관련 클래스:
@@ -554,13 +734,52 @@ kri:
- `enabled=true`일 때 API Key 인증 기능 활성화
- `header-name`으로 API Key를 읽을 HTTP header 지정
- `allowed-paths`가 한 개 이상이면 일치하는 요청에서만 API Key 인증 시도
- `excluded-paths`와 일치하는 요청은 허용 여부와 관계없이 API Key 인증에서 제외
- JPA repository를 통해 서비스별 활성 API Key를 preload cache로 적재
- `ApiKeyAuthFilter`가 API Key를 `Authentication`으로 변환
- `admin-api-enabled=true`일 때 내부 reload/cache endpoint 노출
API Key를 일부 API에서만 인증 수단으로 허용하려면 다음처럼 설정합니다.
```yaml
kri:
auth:
apikey:
enabled: true
header-name: X-API-Key
service-code: kric-contact-service
allowed-paths:
- /api/v1/list/update/**
- /api/v1/external/**
excluded-paths:
- /api/v1/external/admin/**
```
경로 설정의 동작은 다음과 같습니다. 두 설정이 겹치면 `excluded-paths`가 우선합니다.
| `allowed-paths` | `excluded-paths` | API Key 인증 대상 |
|---|---|---|
| 비어 있음 | 비어 있음 | 기존처럼 모든 요청 |
| 비어 있음 | 설정됨 | 제외 패턴과 일치하지 않는 요청 |
| 설정됨 | 비어 있음 | 허용 패턴과 일치하는 요청 |
| 설정됨 | 설정됨 | 허용 패턴과 일치하면서 제외 패턴과 일치하지 않는 요청 |
하위 호환 규칙과 매칭 방식은 다음과 같습니다.
- 각 속성의 미설정, `null`, 빈 목록 또는 공백 패턴만 있는 목록은 해당 경로 제한을 적용하지 않습니다.
- `allowed-paths`에 유효한 패턴이 하나 이상이면 그중 하나와 일치하는 요청만 인증 대상이 됩니다.
- `excluded-paths`에 유효한 패턴이 하나 이상이면 그중 하나와 일치하는 요청은 항상 인증 대상에서 제외됩니다.
- Spring 경로 패턴을 사용하며 `*`는 한 경로 구간, `**`는 하위 경로 전체와 매칭합니다.
- HTTP method는 구분하지 않고, context path와 query string은 매칭 대상에서 제외합니다.
- 패턴은 `/`로 시작해야 하며 잘못된 패턴은 애플리케이션 기동 시 오류로 처리됩니다.
- 두 설정은 API Key 인증 필터의 적용 범위만 제한합니다. 경로를 공개하거나 접근 권한을 직접 부여하지 않습니다.
- 공개 경로는 별도 설정인 `kri.security.public-paths`로 관리합니다.
주의:
- DB preload 방식은 JPA와 DataSource 관련 classpath가 필요합니다.
- JPA classpath가 없으면 DB preload 자동 구성만 건너뛰며, 서비스가 직접 등록한 `ApiKeyUserClaimsProvider`는 사용할 수 있습니다.
- `service-code`가 비어 있으면 preload cache는 비어 있게 됩니다.
- admin API는 IP allowlist를 통과해야 합니다.
@@ -611,6 +830,7 @@ other paths require both an allowed client IP and authentication. Exact IPs, CID
- API Key admin API가 활성화되면 내부 admin endpoint package도 scan
- Swagger UI/API docs 접근 IP 제한
- `CodeEnum` 구현 enum의 schema/parameter 설명 보강
- 서버가 주입하는 `RequestUserContext`를 요청 입력 문서에서 제외
### `kri.web`
@@ -618,6 +838,8 @@ other paths require both an allowed client IP and authentication. Exact IPs, CID
- `CommonWebAutoConfiguration`
- `ErrorAdvice`
- `ExternalApiErrorAutoConfiguration`
- `ExternalApiResponseAdvice`
- `TraceFilter`
- `ServiceMdcAspect`
- `RequestUserContextArgumentResolver`
@@ -705,6 +927,7 @@ Endpoint:
- `com.kri.common.autoconfigure.swagger.KriSwaggerAutoConfiguration`
- `com.kri.common.autoconfigure.redis.CommonRedisAutoConfiguration`
- `com.kri.common.autoconfigure.scheduling.CommonSchedulingAutoConfiguration`
- `com.kri.common.autoconfigure.crypto.CryptoAutoConfiguration`
---
@@ -713,7 +936,20 @@ Endpoint:
- 서비스 코드에서는 가능한 한 `feature` 패키지의 타입만 직접 사용합니다.
- `runtime` 패키지는 자동 구성으로 조립되는 내부 구현으로 보고 직접 의존을 피합니다.
- 운영 환경에서는 기본 JWT secret과 API Key DB 설정을 사용하지 않습니다.
- AES 신규 데이터는 GCM을 사용하고, MD5·SHA-1·AES-CBC는 레거시 호환 범위로 제한합니다.
- 자체 보안 정책이 필요한 서비스는 직접 `SecurityFilterChain` Bean을 등록해 기본 구성을 대체합니다.
- Swagger 접근 제한은 운영망/관리망 정책에 맞춰 `allowed-ips`를 명시합니다.
- 대용량 Excel은 일반 `Workbook` 변환보다 streaming API를 우선 검토합니다.
- 배포 전 `./gradlew compileJava`로 컴파일을 확인합니다.
---
## 변경 이력
- 2026-11-02: `beta.1.7.1`에서 공개 `RequestUserContextProvider`를 추가하고 기존 컨트롤러 인자 해석을 위임하도록 정리했습니다. 인증 정보와 IP 해석, 기존 Resolver 생성자 및 자동 등록 조건을 유지합니다.
- 2026-08-06: `beta.1.6.3`에서 non-ASCII multipart 파일명을 ASCII fallback/
`filename*` 없이 원본 `filename`의 UTF-8 바이트로 전송하도록 복원했습니다.
- 2026-08-06: `beta.1.6.2`에서 non-ASCII multipart 파일명에 ASCII `filename`
fallback과 UTF-8 `filename*`를 추가했습니다.
- 2026-08-04: `kri.auth.apikey.allowed-paths`와 `kri.auth.apikey.excluded-paths`를 추가했습니다. 미설정·`null`·빈 목록은 기존 전역 API Key 인증 동작을 유지하며, 제외 패턴은 허용 패턴보다 우선합니다.

View File

@@ -4,7 +4,7 @@ plugins {
}
// 버전 변경은 여기서
def commonVer = "beta.1.3.0"
def commonVer = "beta.1.7.1"
group = 'com.kri.common'
version = commonVer
@@ -176,4 +176,4 @@ tasks.register('checkGiteaPackageVersionNotExists') {
tasks.named('publishReleasePublicationToGiteaRepository') {
dependsOn 'checkGiteaPackageVersionNotExists'
}
}

View File

@@ -5,6 +5,7 @@ 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;
@@ -12,6 +13,7 @@ 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 {

View File

@@ -26,6 +26,16 @@ public class ApiKeyProperties {
*/
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 범위 결정)
*/

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

@@ -27,6 +27,7 @@ public class BypassProperties {
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

@@ -1,6 +1,7 @@
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;
@@ -14,6 +15,7 @@ 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;
@@ -21,6 +23,7 @@ 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;
@@ -42,6 +45,11 @@ public class KriSwaggerAutoConfiguration {
private final KriSwaggerProperties properties;
private final ApiKeyProperties apiKeyProperties; // apikey.header-name 읽기용
@PostConstruct
void hideRequestUserContext() {
SpringDocUtils.getConfig().addRequestWrapperToIgnore(RequestUserContext.class);
}
@Bean
@ConditionalOnMissingBean
public OpenAPI kriOpenAPI() {

View File

@@ -1,6 +1,8 @@
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;
@@ -78,13 +80,21 @@ public class CommonWebAutoConfiguration {
};
}
@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(
JwtService jwtService
RequestUserContextProvider requestUserContextProvider
) {
return new RequestUserContextArgumentResolver(jwtService);
return new RequestUserContextArgumentResolver(requestUserContextProvider);
}
@Bean

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

@@ -19,6 +19,7 @@ import java.util.Objects;
import java.util.Set;
import java.util.function.UnaryOperator;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
@@ -651,7 +652,7 @@ public final class ExcelMapper {
) {
StreamingReadOptions validatedOptions = validateStreamingReadOptions(options);
try (OPCPackage pkg = OPCPackage.open(path.toFile())) {
try (OPCPackage pkg = OPCPackage.open(path.toFile(), PackageAccess.READ)) {
readStreaming(pkg, validatedOptions, handler);
} catch (Exception e) {
throw new RuntimeException("Streaming 엑셀 읽기 중 오류", e);
@@ -746,7 +747,7 @@ public final class ExcelMapper {
public static List<String> readHeaderStreaming(Path path, StreamingReadOptions options) {
StreamingReadOptions validatedOptions = validateStreamingReadOptions(options);
try (OPCPackage pkg = OPCPackage.open(path.toFile())) {
try (OPCPackage pkg = OPCPackage.open(path.toFile(), PackageAccess.READ)) {
return readHeaderStreaming(pkg, validatedOptions);
} catch (Exception e) {
throw new RuntimeException("Streaming 엑셀 헤더 읽기 중 오류", e);

View File

@@ -89,8 +89,8 @@ public class ExternalApiClient {
}
HttpRequest request = builder.build();
HttpResponse<String> resp = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
return ExternalApiResponse.of(resp.statusCode(), resp.headers(), resp.body());
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();
@@ -114,8 +114,8 @@ public class ExternalApiClient {
builder.header("Content-Type", "multipart/form-data; boundary=" + boundary);
HttpRequest request = builder.build();
HttpResponse<String> resp = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
return ExternalApiResponse.of(resp.statusCode(), resp.headers(), resp.body());
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();
@@ -136,20 +136,20 @@ public class ExternalApiClient {
throw new IllegalArgumentException("parts must not contain null");
}
writeAscii(out, "--" + boundary + CRLF);
writeAscii(out, "Content-Disposition: form-data; name=\"" + headerValue(part.getName()) + "\"");
writeUtf8(out, "--" + boundary + CRLF);
writeUtf8(out, "Content-Disposition: form-data; name=\"" + headerValue(part.getName()) + "\"");
if (part.getFilename() != null) {
writeAscii(out, "; filename=\"" + headerValue(part.getFilename()) + "\"");
writeUtf8(out, "; filename=\"" + headerValue(part.getFilename()) + "\"");
}
writeAscii(out, CRLF);
writeUtf8(out, CRLF);
if (part.getContentType() != null && !part.getContentType().isBlank()) {
writeAscii(out, "Content-Type: " + safeHeader(part.getContentType()) + CRLF);
writeUtf8(out, "Content-Type: " + safeHeader(part.getContentType()) + CRLF);
}
writeAscii(out, CRLF);
writeUtf8(out, CRLF);
out.write(part.content());
writeAscii(out, CRLF);
writeUtf8(out, CRLF);
}
writeAscii(out, "--" + boundary + "--" + CRLF);
writeUtf8(out, "--" + boundary + "--" + CRLF);
return out.toByteArray();
}
@@ -165,8 +165,10 @@ public class ExternalApiClient {
});
}
private static void writeAscii(ByteArrayOutputStream out, String value) throws IOException {
out.write(value.getBytes(StandardCharsets.US_ASCII));
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) {

View File

@@ -1,28 +1,89 @@
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;
}

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

@@ -1,5 +1,6 @@
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;
@@ -43,6 +44,14 @@ public class BypassResponse {
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;
}

View File

@@ -0,0 +1,11 @@
package com.kri.common.feature.web;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.lang.Nullable;
/** Provides the same user context used by controller argument resolution. */
public interface RequestUserContextProvider {
/** Resolves existing authentication or a verified Bearer token; otherwise returns an empty context. */
RequestUserContext resolve(@Nullable HttpServletRequest request);
}

View File

@@ -6,7 +6,10 @@ import java.beans.PropertyDescriptor;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
@@ -18,14 +21,23 @@ public final class Pageables {
}
public static Pageable of(PageRequestDto req, Class<?> sortType) {
return of(req, sortType, Function.identity());
}
public static Pageable of(PageRequestDto req, Class<?> sortType, Map<String, String> sortAliases) {
Map<String, String> aliases = (sortAliases == null) ? Map.of() : sortAliases;
return of(req, sortType, sortKey -> aliases.getOrDefault(sortKey, sortKey));
}
public static Pageable of(PageRequestDto req, Class<?> sortType, Function<String, String> sortMapper) {
int page = Math.max(req.getPageIndex(), 0);
int size = Math.max(req.getPageSize(), 1);
Sort sort = buildSort(req, sortType);
Sort sort = buildSort(req, sortType, sortMapper);
return (sort == null) ? PageRequest.of(page, size) : PageRequest.of(page, size, sort);
}
private static Sort buildSort(PageRequestDto req, Class<?> sortType) {
private static Sort buildSort(PageRequestDto req, Class<?> sortType, Function<String, String> sortMapper) {
String sortBy = req.getSortBy();
if (sortBy == null || sortBy.isBlank()) {
return null;
@@ -36,8 +48,13 @@ public final class Pageables {
: Sort.Direction.DESC;
Set<String> allowed = allowedProperties(sortType);
Function<String, String> mapper = (sortMapper == null) ? Function.identity() : sortMapper;
List<String> props = Arrays.stream(sortBy.split(","))
.map(String::trim)
.filter(s -> !s.isBlank())
.map(mapper)
.filter(Objects::nonNull)
.map(String::trim)
.filter(s -> !s.isBlank())
.collect(Collectors.toList());
@@ -74,4 +91,4 @@ public final class Pageables {
throw new IllegalStateException("Failed to introspect sortType=" + sortType.getName(), e);
}
}
}
}

View File

@@ -8,18 +8,62 @@ import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import lombok.RequiredArgsConstructor;
import java.util.List;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
@RequiredArgsConstructor
public class ApiKeyAuthFilter extends OncePerRequestFilter {
private final ApiKeyProperties apiKeyProperties;
private final ApiKeyUserClaimsProvider apiKeyUserClaimsProvider;
private final JwtService jwtService;
private final List<RequestMatcher> allowedPathMatchers;
private final List<RequestMatcher> excludedPathMatchers;
public ApiKeyAuthFilter(
ApiKeyProperties apiKeyProperties,
ApiKeyUserClaimsProvider apiKeyUserClaimsProvider,
JwtService jwtService
) {
this.apiKeyProperties = apiKeyProperties;
this.apiKeyUserClaimsProvider = apiKeyUserClaimsProvider;
this.jwtService = jwtService;
this.allowedPathMatchers = createPathMatchers(apiKeyProperties.getAllowedPaths());
this.excludedPathMatchers = createPathMatchers(apiKeyProperties.getExcludedPaths());
}
private static List<RequestMatcher> createPathMatchers(List<String> paths) {
if (paths == null || paths.isEmpty()) {
return List.of();
}
PathPatternRequestMatcher.Builder matcherBuilder = PathPatternRequestMatcher.withDefaults();
return paths.stream()
.filter(StringUtils::hasText)
.map(String::trim)
.map(matcherBuilder::matcher)
.map(RequestMatcher.class::cast)
.toList();
}
@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
if (matchesAny(excludedPathMatchers, request)) {
return true;
}
return !allowedPathMatchers.isEmpty() && !matchesAny(allowedPathMatchers, request);
}
private static boolean matchesAny(
List<RequestMatcher> matchers,
HttpServletRequest request
) {
return matchers.stream().anyMatch(matcher -> matcher.matches(request));
}
@Override
protected void doFilterInternal(

View File

@@ -0,0 +1,321 @@
package com.kri.common.runtime.crypto.aes;
import com.kri.common.autoconfigure.crypto.CryptoProperties;
import com.kri.common.feature.crypto.CryptoAuthenticationException;
import com.kri.common.feature.crypto.CryptoException;
import com.kri.common.feature.crypto.CryptoKeyNotFoundException;
import com.kri.common.feature.crypto.aes.AesAlgorithm;
import com.kri.common.feature.crypto.aes.AesCryptoService;
import com.kri.common.feature.crypto.aes.AesDecryptRequest;
import com.kri.common.feature.crypto.aes.AesEncryptRequest;
import com.kri.common.feature.crypto.aes.AesEncryptedValue;
import com.kri.common.feature.crypto.aes.TagLayout;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.util.Arrays;
import javax.crypto.AEADBadTagException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
public class DefaultAesCryptoService implements AesCryptoService {
private static final int AES_KEY_BITS = 256;
private static final int GCM_TAG_BITS = 128;
private static final int GCM_TAG_BYTES = GCM_TAG_BITS / 8;
private static final int MIN_SALT_BYTES = 16;
private static final int MIN_KDF_ITERATIONS = 1;
private static final int MAX_KDF_ITERATIONS = 5_000_000;
private final CryptoProperties properties;
private final SecureRandom secureRandom;
public DefaultAesCryptoService(CryptoProperties properties) {
this(properties, new SecureRandom());
}
DefaultAesCryptoService(CryptoProperties properties, SecureRandom secureRandom) {
this.properties = properties;
this.secureRandom = secureRandom;
}
@Override
public AesEncryptedValue encrypt(byte[] plaintext) {
return encrypt(AesEncryptRequest.builder(plaintext).build());
}
@Override
public AesEncryptedValue encrypt(AesEncryptRequest request) {
validateRequest(request);
byte[] plaintext = request.getPlaintext();
AesAlgorithm algorithm = defaultIfNull(request.getAlgorithm(), properties.getAes().getAlgorithm());
TagLayout tagLayout = resolveTagLayout(algorithm, request.getTagLayout());
int iterations = defaultIfNull(request.getKdfIterations(), properties.getAes().getKdf().getIterations());
validateIterations(iterations);
String keyId = request.getKeyId();
char[] masterKey = request.getMasterKey();
if (masterKey == null || masterKey.length == 0) {
keyId = isBlank(keyId) ? properties.getAes().getActiveKeyId() : keyId;
masterKey = configuredKey(keyId);
}
byte[] salt = request.getSalt();
if (salt == null) {
salt = randomBytes(properties.getAes().getKdf().getSaltLength());
}
validateSalt(salt);
byte[] iv = request.getIv();
if (iv == null) {
iv = randomBytes(algorithm.getIvLength());
}
validateIv(iv, algorithm);
validateAad(request.getAad(), algorithm);
try {
SecretKey key = deriveKey(masterKey, salt, iterations);
Cipher cipher = initCipher(Cipher.ENCRYPT_MODE, algorithm, key, iv);
updateAad(cipher, request.getAad(), algorithm);
byte[] encrypted = cipher.doFinal(plaintext);
return toEncryptedValue(algorithm, keyId, iterations, salt, iv, encrypted, tagLayout);
} catch (GeneralSecurityException e) {
throw new CryptoException("AES encryption failed", e);
} finally {
Arrays.fill(masterKey, '\0');
}
}
@Override
public byte[] decrypt(AesEncryptedValue encryptedValue) {
return decrypt(AesDecryptRequest.builder(encryptedValue).build());
}
@Override
public byte[] decrypt(AesDecryptRequest request) {
if (request == null || request.getEncryptedValue() == null) {
throw new IllegalArgumentException("encryptedValue must not be null");
}
AesEncryptedValue value = request.getEncryptedValue();
validateEncryptedValue(value);
char[] masterKey = request.getMasterKey();
if (masterKey == null || masterKey.length == 0) {
masterKey = configuredKey(value.getKeyId());
}
try {
SecretKey key = deriveKey(masterKey, value.getSalt(), value.getKdfIterations());
Cipher cipher = initCipher(
Cipher.DECRYPT_MODE, value.getAlgorithm(), key, value.getIv());
updateAad(cipher, request.getAad(), value.getAlgorithm());
return cipher.doFinal(ciphertextWithTag(value));
} catch (AEADBadTagException e) {
throw new CryptoAuthenticationException(
"AES-GCM authentication failed: ciphertext, key, IV, tag or AAD is invalid", e);
} catch (GeneralSecurityException e) {
throw new CryptoException("AES decryption failed", e);
} finally {
Arrays.fill(masterKey, '\0');
}
}
private AesEncryptedValue toEncryptedValue(
AesAlgorithm algorithm,
String keyId,
int iterations,
byte[] salt,
byte[] iv,
byte[] encrypted,
TagLayout tagLayout
) {
byte[] ciphertext = encrypted;
byte[] tag = new byte[0];
if (algorithm == AesAlgorithm.AES_256_GCM && tagLayout == TagLayout.DETACHED) {
if (encrypted.length < GCM_TAG_BYTES) {
throw new CryptoException("AES-GCM result is shorter than its authentication tag");
}
int ciphertextLength = encrypted.length - GCM_TAG_BYTES;
ciphertext = Arrays.copyOf(encrypted, ciphertextLength);
tag = Arrays.copyOfRange(encrypted, ciphertextLength, encrypted.length);
}
return new AesEncryptedValue(
AesEncryptedValue.CURRENT_FORMAT_VERSION,
algorithm,
keyId,
iterations,
salt,
iv,
ciphertext,
tag,
tagLayout);
}
private byte[] ciphertextWithTag(AesEncryptedValue value) {
byte[] ciphertext = value.getCiphertext();
if (value.getAlgorithm() != AesAlgorithm.AES_256_GCM
|| value.getTagLayout() == TagLayout.APPENDED) {
return ciphertext;
}
byte[] tag = value.getTag();
byte[] combined = Arrays.copyOf(ciphertext, ciphertext.length + tag.length);
System.arraycopy(tag, 0, combined, ciphertext.length, tag.length);
return combined;
}
private SecretKey deriveKey(char[] masterKey, byte[] salt, int iterations)
throws GeneralSecurityException {
if (masterKey == null || masterKey.length == 0) {
throw new CryptoKeyNotFoundException("AES master key is missing");
}
PBEKeySpec spec = new PBEKeySpec(masterKey, salt, iterations, AES_KEY_BITS);
try {
byte[] encoded = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
.generateSecret(spec)
.getEncoded();
try {
return new SecretKeySpec(encoded, "AES");
} finally {
Arrays.fill(encoded, (byte) 0);
}
} finally {
spec.clearPassword();
}
}
private Cipher initCipher(
int mode,
AesAlgorithm algorithm,
SecretKey key,
byte[] iv
) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance(algorithm.getTransformation());
if (algorithm == AesAlgorithm.AES_256_GCM) {
cipher.init(mode, key, new GCMParameterSpec(GCM_TAG_BITS, iv));
} else {
cipher.init(mode, key, new IvParameterSpec(iv));
}
return cipher;
}
private void updateAad(Cipher cipher, byte[] aad, AesAlgorithm algorithm) {
if (aad != null && aad.length > 0 && algorithm == AesAlgorithm.AES_256_GCM) {
cipher.updateAAD(aad);
}
}
private char[] configuredKey(String keyId) {
if (isBlank(keyId)) {
throw new CryptoKeyNotFoundException(
"AES master key was not provided and kri.crypto.aes.active-key-id is empty");
}
if (properties.getAes().getKeys() == null) {
throw new CryptoKeyNotFoundException("AES master key map is empty");
}
String configured = properties.getAes().getKeys().get(keyId);
if (configured == null || configured.isEmpty()) {
throw new CryptoKeyNotFoundException("AES master key was not found for keyId=" + keyId);
}
return configured.toCharArray();
}
private void validateRequest(AesEncryptRequest request) {
if (request == null || request.getPlaintext() == null) {
throw new IllegalArgumentException("plaintext must not be null");
}
}
private void validateEncryptedValue(AesEncryptedValue value) {
if (!AesEncryptedValue.CURRENT_FORMAT_VERSION.equals(value.getFormatVersion())) {
throw new CryptoException("Unsupported encrypted value format version");
}
if (value.getAlgorithm() == null || value.getTagLayout() == null) {
throw new CryptoException("Encrypted value algorithm and tag layout are required");
}
validateIterations(value.getKdfIterations());
validateSalt(value.getSalt());
validateIv(value.getIv(), value.getAlgorithm());
if (value.getCiphertext() == null) {
throw new CryptoException("Encrypted value ciphertext is required");
}
if (value.getAlgorithm() == AesAlgorithm.AES_256_GCM) {
if (value.getTagLayout() == TagLayout.NONE) {
throw new CryptoException("AES-GCM authentication tag is required");
}
if (value.getTagLayout() == TagLayout.DETACHED
&& (value.getTag() == null || value.getTag().length != GCM_TAG_BYTES)) {
throw new CryptoException("Detached AES-GCM tag must be 16 bytes");
}
if (value.getTagLayout() == TagLayout.APPENDED
&& value.getCiphertext().length < GCM_TAG_BYTES) {
throw new CryptoException("Appended AES-GCM ciphertext does not contain a tag");
}
} else if (value.getTagLayout() != TagLayout.NONE) {
throw new CryptoException("AES-CBC does not use a GCM tag layout");
}
}
private TagLayout resolveTagLayout(AesAlgorithm algorithm, TagLayout requested) {
if (algorithm == AesAlgorithm.AES_256_CBC_PKCS5) {
if (requested != null && requested != TagLayout.NONE) {
throw new IllegalArgumentException("AES-CBC tag layout must be NONE");
}
return TagLayout.NONE;
}
TagLayout resolved = defaultIfNull(requested, properties.getAes().getTagLayout());
if (resolved == TagLayout.NONE) {
throw new IllegalArgumentException("AES-GCM authentication tag cannot be omitted");
}
return resolved;
}
private void validateSalt(byte[] salt) {
if (salt == null || salt.length < MIN_SALT_BYTES) {
throw new IllegalArgumentException("salt must be at least 16 bytes");
}
}
private void validateIv(byte[] iv, AesAlgorithm algorithm) {
if (iv == null || iv.length != algorithm.getIvLength()) {
throw new IllegalArgumentException(
algorithm + " IV must be exactly " + algorithm.getIvLength() + " bytes");
}
}
private void validateAad(byte[] aad, AesAlgorithm algorithm) {
if (aad != null && aad.length > 0 && algorithm != AesAlgorithm.AES_256_GCM) {
throw new IllegalArgumentException("AAD is supported only by AES-GCM");
}
}
private void validateIterations(int iterations) {
if (iterations < MIN_KDF_ITERATIONS || iterations > MAX_KDF_ITERATIONS) {
throw new IllegalArgumentException(
"PBKDF2 iterations must be between 1 and " + MAX_KDF_ITERATIONS);
}
}
private byte[] randomBytes(int length) {
if (length < MIN_SALT_BYTES && length != 12) {
throw new IllegalArgumentException("random byte length is invalid");
}
byte[] value = new byte[length];
secureRandom.nextBytes(value);
return value;
}
private boolean isBlank(String value) {
return value == null || value.isBlank();
}
private <T> T defaultIfNull(T value, T defaultValue) {
return value == null ? defaultValue : value;
}
private int defaultIfNull(Integer value, int defaultValue) {
return value == null ? defaultValue : value;
}
}

View File

@@ -0,0 +1,53 @@
package com.kri.common.runtime.crypto.hash;
import com.kri.common.feature.crypto.hash.AdaptiveHashService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
public class BCryptAdaptiveHashService implements AdaptiveHashService {
private final int defaultStrength;
private final BCryptPasswordEncoder defaultEncoder;
public BCryptAdaptiveHashService(int defaultStrength) {
validateStrength(defaultStrength);
this.defaultStrength = defaultStrength;
this.defaultEncoder = new BCryptPasswordEncoder(defaultStrength);
}
@Override
public String hash(CharSequence value) {
validateValue(value);
return defaultEncoder.encode(value);
}
@Override
public String hash(CharSequence value, int strength) {
validateValue(value);
validateStrength(strength);
if (strength == defaultStrength) {
return defaultEncoder.encode(value);
}
return new BCryptPasswordEncoder(strength).encode(value);
}
@Override
public boolean matches(CharSequence value, String encodedHash) {
validateValue(value);
if (encodedHash == null || encodedHash.isBlank()) {
return false;
}
return defaultEncoder.matches(value, encodedHash);
}
private void validateValue(CharSequence value) {
if (value == null) {
throw new IllegalArgumentException("value must not be null");
}
}
private void validateStrength(int strength) {
if (strength < 4 || strength > 31) {
throw new IllegalArgumentException("BCrypt strength must be between 4 and 31");
}
}
}

View File

@@ -0,0 +1,59 @@
package com.kri.common.runtime.crypto.hash;
import com.kri.common.feature.crypto.CryptoException;
import com.kri.common.feature.crypto.hash.DigestAlgorithm;
import com.kri.common.feature.crypto.hash.DigestEncoding;
import com.kri.common.feature.crypto.hash.DigestService;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
public class JdkDigestService implements DigestService {
private static final char[] LOWER_HEX = "0123456789abcdef".toCharArray();
private static final char[] UPPER_HEX = "0123456789ABCDEF".toCharArray();
@Override
public String digest(byte[] value, DigestAlgorithm algorithm, DigestEncoding encoding) {
if (value == null || algorithm == null || encoding == null) {
throw new IllegalArgumentException("value, algorithm and encoding must not be null");
}
try {
byte[] digest = MessageDigest.getInstance(algorithm.getJcaName()).digest(value);
return encode(digest, encoding);
} catch (NoSuchAlgorithmException e) {
throw new CryptoException("Digest algorithm is not available: " + algorithm, e);
}
}
@Override
public boolean matches(
byte[] value,
String expectedDigest,
DigestAlgorithm algorithm,
DigestEncoding encoding
) {
if (expectedDigest == null) {
return false;
}
String actual = digest(value, algorithm, encoding);
return MessageDigest.isEqual(
actual.getBytes(StandardCharsets.US_ASCII),
expectedDigest.getBytes(StandardCharsets.US_ASCII));
}
private String encode(byte[] value, DigestEncoding encoding) {
if (encoding == DigestEncoding.BASE64) {
return Base64.getEncoder().encodeToString(value);
}
char[] alphabet = encoding == DigestEncoding.HEX_UPPER ? UPPER_HEX : LOWER_HEX;
char[] output = new char[value.length * 2];
for (int i = 0; i < value.length; i++) {
int current = value[i] & 0xff;
output[i * 2] = alphabet[current >>> 4];
output[i * 2 + 1] = alphabet[current & 0x0f];
}
return new String(output);
}
}

View File

@@ -1,6 +1,7 @@
package com.kri.common.runtime.http.bypass;
import com.kri.common.autoconfigure.http.bypass.BypassProperties;
import com.kri.common.feature.http.ExternalApiResponseException;
import com.kri.common.feature.http.bypass.BypassClient;
import com.kri.common.feature.http.bypass.BypassContext;
import com.kri.common.feature.http.bypass.BypassForwardOptions;
@@ -94,7 +95,11 @@ public class DefaultBypassClient implements BypassClient {
bypassRequest = applyRequestCustomizers(bypassRequest, context, targetProperties, effectiveOptions);
BypassResponse bypassResponse = send(target, targetProperties, bypassRequest);
return applyResponseCustomizers(bypassResponse, context, targetProperties, effectiveOptions);
bypassResponse = applyResponseCustomizers(bypassResponse, context, targetProperties, effectiveOptions);
if (targetProperties.isThrowOnError()) {
bypassResponse.requireSuccess();
}
return bypassResponse;
}
private BypassProperties.Target resolveTargetProperties(String targetName) {
@@ -253,6 +258,8 @@ public class DefaultBypassClient implements BypassClient {
try {
BypassResponse result = customizer.customize(response, context);
return result == null ? response : result;
} catch (ExternalApiResponseException e) {
throw e;
} catch (Exception e) {
throw BusinessException.internalError("BYPASS_RESPONSE_CUSTOMIZE_FAILED",
"Bypass response customize failed.").with("target", context.targetName());
@@ -385,7 +392,8 @@ public class DefaultBypassClient implements BypassClient {
}
private static boolean isHopByHopHeader(String name) {
return name != null && HOP_BY_HOP_HEADERS.contains(name.toLowerCase(Locale.ROOT));
return name != null && (name.startsWith(":")
|| HOP_BY_HOP_HEADERS.contains(name.toLowerCase(Locale.ROOT)));
}
private static List<String> nullToEmpty(List<String> values) {

View File

@@ -0,0 +1,60 @@
package com.kri.common.runtime.web;
import com.kri.common.feature.auth.dto.JwtUserClaimsDto;
import com.kri.common.feature.auth.jwt.JwtService;
import com.kri.common.feature.web.RequestUserContext;
import com.kri.common.feature.web.RequestUserContextProvider;
import io.jsonwebtoken.JwtException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.lang.Nullable;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
@RequiredArgsConstructor
public class DefaultRequestUserContextProvider implements RequestUserContextProvider {
private final JwtService jwtService;
@Override
public RequestUserContext resolve(@Nullable HttpServletRequest request) {
String clientIp = request != null ? IpUtil.getClientIp(request) : null;
JwtUserClaimsDto claims = null;
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
Object principal = auth.getPrincipal();
if (principal instanceof JwtUserClaimsDto jwtDto) {
claims = jwtDto;
} else {
Object details = auth.getDetails();
if (details instanceof JwtUserClaimsDto jwtDto) {
claims = jwtDto;
}
}
}
if (claims == null && request != null) {
String authHeader = request.getHeader("Authorization");
if (authHeader != null && authHeader.startsWith("Bearer ")) {
try {
claims = jwtService.toUserClaimsDto(authHeader.substring(7));
} catch (JwtException ignored) {
}
}
}
if (claims == null) {
return RequestUserContext.builder().clientIp(clientIp).build();
}
return RequestUserContext.builder()
.userId(claims.getUserId())
.userCmpn(claims.getUserCmpn())
.userTeam(claims.getUserTeam())
.userName(claims.getUserName())
.userRole(claims.getUserRole())
.clientIp(clientIp)
.build();
}
}

View File

@@ -0,0 +1,30 @@
package com.kri.common.runtime.web;
import com.kri.common.feature.http.ExternalApiResponseException;
import java.util.List;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@Order(Ordered.HIGHEST_PRECEDENCE)
@RestControllerAdvice
public class ExternalApiResponseAdvice {
@ExceptionHandler(ExternalApiResponseException.class)
public ResponseEntity<byte[]> handleExternalApiResponse(ExternalApiResponseException exception) {
HttpHeaders headers = new HttpHeaders();
// Forward representation headers only; transport and authentication headers stay upstream.
for (String name : List.of(HttpHeaders.CONTENT_TYPE, HttpHeaders.CONTENT_ENCODING)) {
exception.getHeaders().entrySet().stream()
.filter(entry -> entry.getKey().equalsIgnoreCase(name))
.findFirst()
.ifPresent(entry -> headers.put(name, entry.getValue()));
}
return ResponseEntity.status(exception.getStatusCode())
.headers(headers)
.body(exception.getBody());
}
}

View File

@@ -1,24 +1,27 @@
package com.kri.common.runtime.web;
import com.kri.common.feature.auth.dto.JwtUserClaimsDto;
import com.kri.common.feature.auth.jwt.JwtService;
import com.kri.common.feature.web.RequestUserContext;
import io.jsonwebtoken.JwtException;
import com.kri.common.feature.web.RequestUserContextProvider;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.core.MethodParameter;
import org.springframework.lang.Nullable;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
@RequiredArgsConstructor
public class RequestUserContextArgumentResolver implements HandlerMethodArgumentResolver {
private final JwtService jwtService;
private final RequestUserContextProvider requestUserContextProvider;
public RequestUserContextArgumentResolver(JwtService jwtService) {
this(new DefaultRequestUserContextProvider(jwtService));
}
public RequestUserContextArgumentResolver(RequestUserContextProvider requestUserContextProvider) {
this.requestUserContextProvider = requestUserContextProvider;
}
@Override
public boolean supportsParameter(MethodParameter parameter) {
@@ -32,44 +35,7 @@ public class RequestUserContextArgumentResolver implements HandlerMethodArgument
NativeWebRequest webRequest,
@Nullable WebDataBinderFactory binderFactory
) {
HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
String clientIp = request != null ? IpUtil.getClientIp(request) : null;
JwtUserClaimsDto claims = null;
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
Object principal = auth.getPrincipal();
if (principal instanceof JwtUserClaimsDto jwtDto) {
claims = jwtDto;
} else {
Object details = auth.getDetails();
if (details instanceof JwtUserClaimsDto jwtDto) {
claims = jwtDto;
}
}
}
if (claims == null && request != null) {
String authHeader = request.getHeader("Authorization");
if (authHeader != null && authHeader.startsWith("Bearer ")) {
try {
claims = jwtService.toUserClaimsDto(authHeader.substring(7));
} catch (JwtException ignored) {
}
}
}
if (claims == null) {
return RequestUserContext.builder().clientIp(clientIp).build();
}
return RequestUserContext.builder()
.userId(claims.getUserId())
.userCmpn(claims.getUserCmpn())
.userTeam(claims.getUserTeam())
.userName(claims.getUserName())
.userRole(claims.getUserRole())
.clientIp(clientIp)
.build();
return requestUserContextProvider.resolve(
webRequest.getNativeRequest(HttpServletRequest.class));
}
}

View File

@@ -9,3 +9,5 @@ com.kri.common.autoconfigure.swagger.KriSwaggerAutoConfiguration
com.kri.common.autoconfigure.redis.CommonRedisAutoConfiguration
com.kri.common.autoconfigure.scheduling.CommonSchedulingAutoConfiguration
com.kri.common.autoconfigure.http.bypass.BypassAutoConfiguration
com.kri.common.autoconfigure.crypto.CryptoAutoConfiguration
com.kri.common.autoconfigure.http.ExternalApiErrorAutoConfiguration