diff --git a/.agent/consumer.md b/.agent/consumer.md new file mode 100644 index 0000000..a6a62c8 --- /dev/null +++ b/.agent/consumer.md @@ -0,0 +1,35 @@ +## KriCommon Consumer Contract + +### Dependency and API Boundary + +- Consume KriCommon as `com.kri.common:starter:` using the consumer repository's established Gradle dependency and version-management conventions. +- Import service-facing APIs from `com.kri.common.feature.*`. Treat `com.kri.common.runtime.*` as internal and do not bind application code to it unless no public API exists and the exception is explicitly documented. +- 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. +- Prefer the shared feature or an approved extension point over duplicating authentication, HTTP, error, enum, Excel, Redis, JSON, date/time, JPA, or utility behavior locally. + +### Configuration and Overrides + +- KriCommon configuration uses only `kri.*`. Established groups include `kri.auth.jwt`, `kri.auth.apikey`, `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. + +### Major 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. +- 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`. +- `ExternalApiClient` multipart requests generate their own boundary and ignore a caller-supplied `Content-Type`. Multipart boundaries and part headers use US-ASCII, `formField` values use UTF-8, and file bodies preserve the supplied bytes. +- ASCII multipart filenames are sent unchanged in `filename`. Non-ASCII filenames use a collision-free ASCII `filename` fallback plus the original name in UTF-8 percent-encoded `filename*`; spaces are encoded as `%20`, not `+`. +- `JsonUtil` requires the consumer's explicit `ObjectMapper`; shared date/time helpers define KST as `Asia/Seoul` and also expose UTC semantics. + +### 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. +- Do not modify KriCommon or another consumer repository unless it is explicitly included in the approved task scope. diff --git a/.agent/profile.yml b/.agent/profile.yml new file mode 100644 index 0000000..a9ee931 --- /dev/null +++ b/.agent/profile.yml @@ -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 diff --git a/.agent/project.md b/.agent/project.md new file mode 100644 index 0000000..74e0910 --- /dev/null +++ b/.agent/project.md @@ -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:` 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. diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..35750b0 --- /dev/null +++ b/.gitattributes @@ -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 diff --git a/Agents.md b/Agents.md index b55a902..bb499f4 100644 --- a/Agents.md +++ b/Agents.md @@ -1,262 +1,292 @@ -# Agents.md + -This file is for AI agents modifying or consuming this repository. Keep it concise, factual, and synchronized with source code. +# KRI Development Base Instructions -## Repository Identity +This document defines the shared working rules for KRI development repositories. +Keep project-specific facts and commands in the project profile and project rules. -- Project: `KriCommon` -- Type: Java 17 Spring Boot starter/library -- Build: Gradle `java-library` + `maven-publish` -- Maven coordinates: `com.kri.common:starter:` -- 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` +## Instruction Resolution -## Package Contract +Apply repository instructions in this order: -- `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. +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 -When adding features, prefer exposing stable service-facing types under `feature` and wiring implementation under `autoconfigure`/`runtime`. +Later and more specific instructions may override earlier general instructions only within their stated scope. -## Build Commands +- 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. -```bash -./gradlew compileJava -./gradlew publishReleasePublicationToGiteaRepository -``` +## Communication -On Windows PowerShell, use: +- 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. -```powershell -.\gradlew.bat compileJava -.\gradlew.bat publishReleasePublicationToGiteaRepository -``` +## Work Authorization -Publishing requires `giteaUser`/`giteaToken` Gradle properties or `GITEA_USER`/`GITEA_TOKEN` environment variables. The publish task depends on `checkGiteaPackageVersionNotExists`. +- 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. -## Dependency Model +## Local Development Environment -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. +- 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. -Important dependency categories: +Preferred human-facing tools: -- 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` +- 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 -When adding auto-configuration, use `@ConditionalOnClass`, `@ConditionalOnBean`, `@ConditionalOnMissingBean`, and property conditions to avoid breaking consumers that do not include optional starters. +- 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. -## Configuration Prefixes +## PowerShell and Path Safety -Only use `kri.*` prefixes. +- 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. -Known prefixes: +## Change Discipline -- `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` +- 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. -## Auto-Configurations +## Text Encoding and Korean Content Safety -Declared imports: +- 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 (`�`), 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. -- `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` +## Git Safety -If a new auto-configuration must be active for consumers, add it to `AutoConfiguration.imports`. +- 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. -## Feature Map +## Dependencies and External Actions -### JWT +- 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. -- 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` +## Database Safety -Security note: default secrets in source are not production-safe. Documentation and examples should instruct consumers to override secrets. +- 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. -### API Key Authentication +## Secrets and Sensitive Data -- 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` +- 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. -Behavior: +## Validation -- API key is read from `kri.auth.apikey.header-name`, default `X-API-Key`. -- `kri.auth.apikey.allowed-paths` limits where API key authentication is attempted. Unset, `null`, empty, or blank-only lists preserve the legacy all-request behavior; one or more valid patterns restrict authentication to matching paths. -- `kri.auth.apikey.excluded-paths` skips API key authentication on matching paths. Exclusions take precedence when a request matches both an allowed and an excluded pattern. -- API key path matching uses Spring `PathPatternRequestMatcher`, ignores HTTP method and query strings, and matches the path within the application after removing the context path. -- `allowed-paths` and `excluded-paths` do not grant access or alter `kri.security.public-paths`; they only scope the API key authentication filter. -- 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`. -- DB preload auto-configuration requires Spring Data JPA on the classpath; a consumer-provided `ApiKeyUserClaimsProvider` remains usable without JPA. -- 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. +- 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. -### Security +## Artifacts and Session Records -- 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. +- 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. -### Web +## Completion Report -- 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 +When implementation is complete, report in Korean: -### Swagger/OpenAPI +- 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. -- 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. +- 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. -### Redis +## Library Project Rules -- Auto-config: `CommonRedisAutoConfiguration` -- Config: `kri.redis.enabled` -- Default enabled: `false` -- Requires `RedisTemplate` class and `RedisConnectionFactory` bean. -- Registers `RedisQueueHelper`. +- 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`. -### External API Client +## Java and Spring Boot -- 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. -- Multipart part headers are encoded as UTF-8 so non-ASCII field names and filenames are preserved. -- Responses are returned as `String` body via `ExternalApiResponse`. +- 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. -### HTTP Bypass +## KriCommon Consumer Contract -- 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.` 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`. +### Dependency and API Boundary -### Scheduling +- Consume KriCommon as `com.kri.common:starter:` using the consumer repository's established Gradle dependency and version-management conventions. +- Import service-facing APIs from `com.kri.common.feature.*`. Treat `com.kri.common.runtime.*` as internal and do not bind application code to it unless no public API exists and the exception is explicitly documented. +- 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. +- Prefer the shared feature or an approved extension point over duplicating authentication, HTTP, error, enum, Excel, Redis, JSON, date/time, JPA, or utility behavior locally. -- Auto-config: `CommonSchedulingAutoConfiguration` -- Config: `kri.scheduling.enabled` -- Default enabled: `false` -- Enables Spring scheduling. +### Configuration and Overrides -### Excel +- KriCommon configuration uses only `kri.*`. Established groups include `kri.auth.jwt`, `kri.auth.apikey`, `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. -- 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. +### Major Optional Capabilities -### JSON +- 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. +- 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`. +- `ExternalApiClient` multipart requests generate their own boundary and ignore a caller-supplied `Content-Type`. Multipart boundaries and part headers use US-ASCII, `formField` values use UTF-8, and file bodies preserve the supplied bytes. +- ASCII multipart filenames are sent unchanged in `filename`. Non-ASCII filenames use a collision-free ASCII `filename` fallback plus the original name in UTF-8 percent-encoded `filename*`; spaces are encoded as `%20`, not `+`. +- `JsonUtil` requires the consumer's explicit `ObjectMapper`; shared date/time helpers define KST as `Asia/Seoul` and also expose UTC semantics. -- Public class: `JsonUtil` -- All methods require an explicit `ObjectMapper`. -- Do not introduce hidden global ObjectMapper state without a deliberate API decision. +### Upgrade and Verification -### Date/Time +- 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. +- Do not modify KriCommon or another consumer repository unless it is explicitly included in the approved task scope. -- Public classes: `DateTimeUtil`, `LenientLocalDateTime`, `LenientLocalDateTimeDeserializer` -- KST zone constant: `Asia/Seoul` -- UTC constant: `ZoneOffset.UTC` +## KriCommon Repository Rules -### Enum +### Repository Role and Package Boundaries -- Public classes: `CodeEnum`, `CodeEnumUtils` -- Runtime MVC converter: `CodeEnumConverter` -- JPA base converter: `AbstractCodeEnumConverter` -- Swagger metadata support exists in `runtime.swagger`. +- This repository is the Java 17 Spring Boot starter/library `com.kri.common:starter:` 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`. -### JPA +### Dependency and Auto-Configuration Safety -- Public classes: `BaseUuidEntity`, `AbstractCodeEnumConverter`, `EntityColumnAccessor` -- API key JPA runtime entities/repository are internal to `runtime.auth.apikey.persistence`. +- 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. -### Utilities +### Feature Invariants -- `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 +- 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. -## Coding Rules For Agents +### Documentation and Verification -- 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. +- `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. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..43c994c --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/README.md b/README.md index ba1bab1..de01b67 100644 --- a/README.md +++ b/README.md @@ -186,8 +186,16 @@ ExternalApiResponse res = client.postMultipart(url, headers, parts); multipart 요청에서는 전달한 headers의 `Content-Type` 값을 무시하고, 필요한 boundary를 포함한 `Content-Type: multipart/form-data; boundary=...` 값을 자동 생성합니다. -multipart 파트 헤더와 텍스트 필드는 UTF-8로 인코딩하므로 한글 등 non-ASCII -파일명을 `filename="한글-파일.txt"` 형태로 손실 없이 전송합니다. +boundary와 multipart 파트 헤더는 US-ASCII로 생성하고, 텍스트 필드 내용은 +UTF-8, 파일 내용은 원본 `byte[]`로 전송합니다. ASCII 파일명은 기존 `filename`을 +그대로 사용합니다. non-ASCII 파일명은 서버 호환성을 위해 충돌하지 않는 ASCII +fallback을 `filename`에 넣고, UTF-8 퍼센트 인코딩한 원본 파일명을 `filename*`에 +함께 전송합니다. 공백은 `+`가 아닌 `%20`으로 인코딩됩니다. + +```http +Content-Disposition: form-data; name="file"; filename="attachment.txt"; + filename*=UTF-8''%ED%95%9C%EA%B8%80-%ED%8C%8C%EC%9D%BC.txt +``` 지원 메서드: @@ -765,5 +773,5 @@ Endpoint: ## 변경 이력 -- 2026-08-06: multipart 파트 헤더를 UTF-8로 인코딩하여 한글 등 non-ASCII 파일명 전송을 지원합니다. +- 2026-08-06: 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 인증 동작을 유지하며, 제외 패턴은 허용 패턴보다 우선합니다. diff --git a/build.gradle b/build.gradle index 022b1c2..5b8ac6c 100644 --- a/build.gradle +++ b/build.gradle @@ -4,7 +4,7 @@ plugins { } // 버전 변경은 여기서 -def commonVer = "beta.1.6.0" +def commonVer = "beta.1.6.1" group = 'com.kri.common' version = commonVer diff --git a/src/main/java/com/kri/common/feature/http/ExternalApiClient.java b/src/main/java/com/kri/common/feature/http/ExternalApiClient.java index 210a08a..1249762 100644 --- a/src/main/java/com/kri/common/feature/http/ExternalApiClient.java +++ b/src/main/java/com/kri/common/feature/http/ExternalApiClient.java @@ -10,6 +10,8 @@ import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.List; import java.util.Map; +import java.util.Set; +import java.util.TreeSet; import java.util.UUID; /** @@ -131,25 +133,33 @@ public class ExternalApiClient { } ByteArrayOutputStream out = new ByteArrayOutputStream(); + Set usedAsciiFilenames = collectAsciiFilenames(parts); for (ExternalApiMultipartPart part : parts) { if (part == null) { throw new IllegalArgumentException("parts must not contain null"); } - writeUtf8(out, "--" + boundary + CRLF); - writeUtf8(out, "Content-Disposition: form-data; name=\"" + headerValue(part.getName()) + "\""); + writeAscii(out, "--" + boundary + CRLF); + writeAscii(out, "Content-Disposition: form-data; name=\"" + headerValue(part.getName()) + "\""); if (part.getFilename() != null) { - writeUtf8(out, "; filename=\"" + headerValue(part.getFilename()) + "\""); + String filename = safeHeader(part.getFilename()); + if (isAscii(filename)) { + writeAscii(out, "; filename=\"" + headerValue(filename) + "\""); + } else { + String fallbackFilename = uniqueAsciiFallback(filename, usedAsciiFilenames); + writeAscii(out, "; filename=\"" + headerValue(fallbackFilename) + "\""); + writeAscii(out, "; filename*=UTF-8''" + percentEncodeUtf8(filename)); + } } - writeUtf8(out, CRLF); + writeAscii(out, CRLF); if (part.getContentType() != null && !part.getContentType().isBlank()) { - writeUtf8(out, "Content-Type: " + safeHeader(part.getContentType()) + CRLF); + writeAscii(out, "Content-Type: " + safeHeader(part.getContentType()) + CRLF); } - writeUtf8(out, CRLF); + writeAscii(out, CRLF); out.write(part.content()); - writeUtf8(out, CRLF); + writeAscii(out, CRLF); } - writeUtf8(out, "--" + boundary + "--" + CRLF); + writeAscii(out, "--" + boundary + "--" + CRLF); return out.toByteArray(); } @@ -165,10 +175,85 @@ public class ExternalApiClient { }); } - 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 void writeAscii(ByteArrayOutputStream out, String value) throws IOException { + out.write(value.getBytes(StandardCharsets.US_ASCII)); + } + + private static Set collectAsciiFilenames(List parts) { + Set filenames = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); + for (ExternalApiMultipartPart part : parts) { + if (part != null && part.getFilename() != null) { + String filename = safeHeader(part.getFilename()); + if (isAscii(filename)) { + filenames.add(filename); + } + } + } + return filenames; + } + + private static String uniqueAsciiFallback(String filename, Set usedFilenames) { + String extension = asciiExtension(filename); + String candidate = "attachment" + extension; + int sequence = 2; + while (!usedFilenames.add(candidate)) { + candidate = "attachment-" + sequence++ + extension; + } + return candidate; + } + + private static String asciiExtension(String filename) { + int lastSeparator = Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\')); + int lastDot = filename.lastIndexOf('.'); + if (lastDot <= lastSeparator || lastDot == filename.length() - 1) { + return ""; + } + + String extension = filename.substring(lastDot + 1); + if (extension.length() > 16 || !extension.chars().allMatch(Character::isLetterOrDigit) + || !isAscii(extension)) { + return ""; + } + return "." + extension; + } + + private static boolean isAscii(String value) { + return value.chars().allMatch(ch -> ch <= 0x7F); + } + + private static String percentEncodeUtf8(String value) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + StringBuilder encoded = new StringBuilder(bytes.length * 3); + char[] hex = "0123456789ABCDEF".toCharArray(); + for (byte current : bytes) { + int unsigned = current & 0xFF; + if (isRfc5987AttrChar(unsigned)) { + encoded.append((char) unsigned); + } else { + encoded.append('%') + .append(hex[unsigned >>> 4]) + .append(hex[unsigned & 0x0F]); + } + } + return encoded.toString(); + } + + private static boolean isRfc5987AttrChar(int value) { + return value >= 'A' && value <= 'Z' + || value >= 'a' && value <= 'z' + || value >= '0' && value <= '9' + || value == '!' + || value == '#' + || value == '$' + || value == '&' + || value == '+' + || value == '-' + || value == '.' + || value == '^' + || value == '_' + || value == '`' + || value == '|' + || value == '~'; } private static String headerValue(String value) {