Files
common-library/Agents.md

248 lines
10 KiB
Markdown

# 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`.
### 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.