feat!: 남은 리뷰 발견을 고치고 개발 매뉴얼과 기능 생성 명령을 더한다

문제: High·P1을 고친 뒤에도 P2·P3 약 90건이 남았다. 연결·구독·메시지
크기 상한이 없는 전송(WebSocket·gRPC·GraphQL deadline), 낙관적 충돌의
500, upsert 경쟁, Mongo 무제한 timeout, 샘플 목록 N+1, 갈라진 복사본
(TenantId 3벌, 이벤트 ID 문법 5곳, SQLState 표 2벌), 문서를 읽는 PR
테스트와 캐시를 막는 lane 설정 등이다. 새 기능을 어디에 어떤 순서로
만드는지 알려 주는 문서와 도구가 없었다. MinIO 공식 이미지가 사라져
객체 저장소 lane이 돌지 않았다.

방법: 영역별 묶음으로 실패 테스트를 먼저 쓰고 고쳤다. 고치는 중에 찾은
결함도 함께 고쳤다(durable operation id가 UUIDv4라 이벤트가 전부 DEAD,
S3 어댑터 생성·작은 chunk 읽기 실패, Redis 조건부 기록의 EVALSHA 권한).
MinIO는 pgsty/minio를 digest로 고정했다(Chainguard는 태그·실행 사용자·
mc 이미지 문제로 버림). docs/manual/에 작업 순서와 판단 지점을 쓰고,
scripts/new-feature.sh가 5개 leaf에 뼈대를 만든다. 생성→빌드→통과
왕복을 verifyFeatureScaffold가 mainCheck에서 본다. 묶음별 결과와
결정은 리뷰 README 14절에 있다.

위험·한계: 파생 서비스 동작이 바뀐다. JDBC batch 50 기본, 운영 jar에서
H2 제거, 트랜잭션 30초 제한, 격리 수준을 Hikari에서 고정, gRPC·
WebSocket·GraphQL 새 한도, correlation ID 규칙 밖이면 서버가 교체,
샘플 키 오류 코드 IDEMPOTENCY_KEY_INVALID. 새 leaf 두 개
(composition:durable-operation, adapter:inbound:messaging)와 새
마이그레이션(postgresql V20·V21, notification V11·V12, sample V8_1,
grpc-ledger V002)이 생긴다. V21 유일 인덱스는 기존 중복이 있으면
실패한다(runbook에 확인 쿼리).

검증: ci, mainCheck(생성 명령 왕복 포함), integrationCheck(MinIO 포함
전 컨테이너 lane), -p optional-platforms ci integrationCheck 통과.

Refs: docs/reviews/2026-11-01-maturity-review/README.md 14절
BREAKING CHANGE: JDBC batch 기본 켜짐, H2 운영 의존 제거, 트랜잭션
기본 제한 30초, gRPC·WebSocket·GraphQL 서버 한도 기본값 추가,
샘플 Idempotency-Key 오류 코드 변경.
This commit is contained in:
DongHyeonka
2026-11-03 19:52:06 +09:00
parent 34565130e0
commit 1400dc1506
768 changed files with 26982 additions and 3348 deletions
+10 -7
View File
@@ -62,17 +62,20 @@ configurations, Redis as one 376-line class.
switch registry, no cross-capability dependency validator, no activation endpoint. Component scan
covers `dev.caskeleton.bootstrap` only; web (`WebAdapterAutoConfiguration`, `WebSecurityAutoConfiguration`, `WebMethodSecurityAutoConfiguration`) and support
(`OutboundSupportConfig`) arrive through their own `AutoConfiguration.imports`. What stays in `autoconfigure/<name>/` is application
composition over application-core ports that names no module type: `operation` (the durable
operation use cases and their `/operations` endpoints, on only when the operation store and the
outbox append port exist), `common`. The outbox relay and the idempotency executor are
`composition:outbox-relay` and `composition:idempotency`, selected by one `runtimeOnly` line each
(the sample takes the idempotency one too). The runtime wiring both composition roots need —
composition every application needs: `common` (the clock). The outbox relay, the idempotency
executor and the durable operations (use cases and `/operations` endpoints, 07-08) are
`composition:outbox-relay`, `composition:idempotency` and `composition:durable-operation`, selected
by one `runtimeOnly` line each and building nothing until their ports exist (the sample takes the
idempotency one too). A capability's role→permission mapping ships in its own
`config/module-defaults` file, not in `config/security.yml`. The runtime wiring both composition roots need —
tracing, the metrics contract filters, domain-context propagation, user-principal pseudonymization
(`PrivacySettings`) and the actuator chain — is `composition:service-runtime`, which the sample
takes by the same line instead of carrying copies.
- **`<Capability>Settings` lives beside its capability**, not in `settings/`. The `settings/` package
holds only settings that belong to no capability — `BootstrapSettings`, `LoggingSettings`,
`RuntimeSafetySettings`.
holds only settings that belong to no capability — `BootstrapSettings`, `RuntimeSafetySettings` —
bound strictly with `StrictSettingsBinder`, never scanned. Logging has no settings record:
`logback-spring.xml` reads `app.logging.*` itself and `LoggingConfigurationRule` refuses values
Logback cannot use.
- **`runtime/` holds guards about the application itself** — secrets, numeric bounds, error-detail
exposure, multi-instance coordination, the runtime-profile check (`RuntimeEnvironmentProfileValidator`).
A guard about a capability's settings (the JPA OSIV/DDL/pool/TLS/vendor guards, the Mongo
+40 -25
View File
@@ -131,11 +131,12 @@ README의 "startup" 절에 있다.
`prod_default: null`로 분류된 모든 키는 prod 에서 비어 있지 않게 주입돼야 한다 — 빈 시크릿으로
부팅하는 것은 금지다. dev/local 프로파일은 두 검사를 건너뛴다(`__LOCAL_DEV_*`가 의도된 로컬
폴백이므로).
- **`SmartInitializingSingleton` 타이밍을 의도적으로 받아들였다.** 이 콜백은 모든 싱글톤 생성 *후*
context refresh 완료 *전*에 한 번 실행된다. 따라서 eager `DataSource`가 이 가드보다 먼저
`__LOCAL_DEV_` 자격증명으로 연결을 시도할 가능성은 있다. 그러나 prod 에서 `__LOCAL_DEV_` 값에
도달하는 것 자체가 예외적 오적재이고, 트래픽을 받기 전에 context 가 중단되므로 이 타이밍으로
충분하다고 판단했다. 더 이른 차단이 필요해지면 `EnvironmentPostProcessor`로 승격한다.
- **다른 싱글톤을 만들기 전에 판정한다(`StartupRule`, 07-02).** 예전에는 `SmartInitializingSingleton`
이라 모든 싱글톤 생성 *후*에 돌았다. 그래서 비밀값이 빠진 prod 배포도 DataSource가 연결을 열고
Flyway가 마이그레이션한 *뒤*에야 거부됐다. 지금은 support의 `StartupRuleRunner`가 bean factory
post-processor 단계에서 부른다. 이를 위해 `SecretSourcePort` bean을 받지 않고 같은 선택 규칙
(`SecretSourceFactory.fromEnvironment`)으로 백엔드를 직접 만든다. 모듈 기여(`RequiredProductionSecrets`)는
규칙이 돌 때 읽으므로, 기여하는 bean은 `static` `@Bean`으로 선언한다(설정 클래스를 일찍 만들지 않게).
- **필수 시크릿 검사는 Spring 환경이 아니라 `SecretSource` 백엔드를 통해 한다.** 존재 검사를
백엔드(`secretSource.resolve(key)`) 경유로 하기 때문에, env → Vault/AWS 백엔드 교체 시에도 검사가
자동으로 따라간다. 검사를 Spring `Environment`에 고정했다면 백엔드를 바꿀 때 검증 로직이 함께
@@ -158,10 +159,12 @@ README의 "startup" 절에 있다.
persistence-jpa의 datasource·Flyway·OSIV·TLS·vendor·Hikari 검사)는 `StartupRule`이다: 위반 목록만
돌려주고, `adapter:outbound:support`의 `StartupRuleRunner` 하나가 다른 싱글톤을 만들기 전에(bean factory
post-processor 단계) 규칙마다 그 phase의 종료 코드로 실패시킨다. 그래서 prod 금지 값은 DataSource가
연결을 열거나 Flyway가 마이그레이션하기 전에 거부된다. 규칙은 그만큼 일찍 만들어지므로 매개변수 없는
`static` `@Bean` 메서드로 선언한다. 다른 bean이 필요한 검사(`SecretSourceValidator`의 `SecretSourcePort`,
`StartupSafetyValidator`의 bean factory, persistence-jpa의 datasource 검사)는 계속 bean이고, 부팅 전에
돌아야 하는 profile 규칙(`RuntimeEnvironmentProfileValidator`)은 `EnvironmentPostProcessor`로 남는다.
연결을 열거나 Flyway가 마이그레이션하기 전에 거부된다. 규칙은 그만큼 일찍 만들어지므로 `static` `@Bean` 메서드로 선언한다. 같은 단계에서 도는 것은 이제 셋이 더 있다.
`SecretSourceValidator`(모듈이 기여한 비밀값 이름을 규칙이 돌 때 읽는다), `StartupSafetyValidator`(bean
*정의*만 보고 bean은 만들지 않는다), `LoggingConfigurationRule`(Logback이 쓸 수 없는 `app.logging.*` 값).
DB 연결이 꼭 필요한 persistence-jpa의 datasource 버전 검사는 bean으로 남되, 모든 Flyway initializer가
그 검사에 `dependsOn` 하도록 묶어 마이그레이션보다 먼저 돈다. 부팅 전에 돌아야 하는 profile 규칙
(`RuntimeEnvironmentProfileValidator`)은 `EnvironmentPostProcessor`로 남는다.
관계형 설정 가드(`HikariPoolConstraintValidator`, `OpenInViewSafetyValidator`,
`JpaDangerousConfigurationGuard`, `PostgreSqlTransportSecurityValidator`,
@@ -182,11 +185,11 @@ post-processor 단계) 규칙마다 그 phase의 종료 코드로 실패시킨
금지").
### StartupSafetyValidator
- **`SmartInitializingSingleton` 타이밍을 고른 이유가 핵심이다.** 검사는 모든 싱글톤 생성 후 context
refresh 완료 전에 한 번 돈다. `EnvironmentPostProcessor`는 bean 정의가 생기기 전에 실행돼 bean
*존재 여부*(multi-instance 검사에 필요)를 검사할 수 없고, `ApplicationReadyEvent` 리스너는 트래픽
직전에야 발동해 잘못된 부팅을 거부하기엔 너무 늦다. 그래서 이 중간 타이밍을 택했고, 위반 시
throw 하여 context 가 시작을 거부한다.
- **bean 정의가 다 모인 뒤, 싱글톤을 만들기 전에 판정한다(`StartupRule`, 07-02).** `EnvironmentPostProcessor`는
bean 정의가 생기기 전이라 bean *존재 여부*를 볼 수 없다. 예전의 `SmartInitializingSingleton`은 모든
싱글톤 생성 후라, lock 없는 multi-instance 배포가 저장소에 연결하고 마이그레이션한 뒤에야 거부됐다.
bean factory post-processor 단계는 둘 사이다: 이름·타입 검사(`containsBean`, `isTypeMatch`)는 정의만으로
답하므로 아무 bean도 만들지 않는다.
- **prod 에러 상세 노출은 `ErrorDetailExposureSafetyValidator`가 막는다(이 클래스가 아니다).** prod에서
`spring.web.error.include-stacktrace`·`include-message`·`include-binding-errors`가 `never`가 아니거나
`include-exception=true`면 PROFILE_MISMATCH(exit 71)로 부팅을 중단한다. env override로 들어온 값도
@@ -362,26 +365,29 @@ relay 조립(`OutboxRelayAutoConfiguration`, 스케줄러·metrics·leader token
## settings — @ConfigurationProperties 검증 정책
이 모듈의 설정 record 들은 대체로 두 가지 검증 전략 중 하나를 고른다: **fail-fast**(잘못되면 기동
이 모듈의 설정 record(`BootstrapSettings`, `RuntimeSafetySettings`, `AsyncExecutorSettings`,
`SecretSourceSettings`)는 모듈들과 같이 `StrictSettingsBinder`로 묶는다: prefix 아래 모르는 키는 기본값으로
조용히 넘어가지 않고 기동을 실패시킨다(07-10). 그래서 `@ConfigurationPropertiesScan`은 쓰지 않는다.
설정 record 들은 대체로 두 가지 검증 전략 중 하나를 고른다: **fail-fast**(잘못되면 기동
중단)와 **warn-and-default**(경고만 남기고 안전한 기본값으로 진행). 어느 쪽을 쓰는지가 각 record 의
핵심 결정이다.
### BootstrapSettings
- **`appName`은 비어 있으면 시작을 실패시킨다(fail-fast).** `app.bootstrap.*` 바인딩이며,
앱 이름은 운영자가 직접 제공해야 하고 합리적인 기본값이 존재하지 않으므로, 비어 있거나 blank 면
`@NotBlank`로 막는다(Spring Boot 가 `BindValidationException`을 띄우고 컨텍스트 기동을 거부).
compact constructor가 ENV_VALIDATION으로 막는다.
다른 settings 의 "warn-and-default"와 달리 여기서 fail-fast 를 택한 이유는, 잘못된 앱 이름으로
조용히 기동되는 것보다 즉시 멈추는 편이 안전하기 때문이다.
### LoggingSettings
- **모든 항목이 "warn-and-default" 정책이다.** `app.logging.*` 바인딩(원천은 .env). 잘못된
값은 경고 로그를 남기고 안전한 기본값으로 진행할 뿐 시작을 실패시키지 않는다.
- **fail-fast 대신 warn-and-default 를 택한 이유.** Logback 은 이 record 가 바인딩되기 전에 자기
초기화 단계에서 `<springProperty>` 바인딩으로 이미 같은 값들을 자체 기본값과 함께 소비했다. 따라서
이 record 의 역할은 로깅을 다시 강제하는 것이 아니라, 입력이 잘못됐을 때 운영자에게 명확한 경고를
표면화하는 것이다.
- **size 문자열(`maxSize`, `totalSizeCap`)은 검증하지 않는다.** 이 값들의 파싱 계약은 logback 이
소유하므로 logback 에게 맡긴다.
### 로깅 설정 (`app.logging.*`)
- **읽는 곳은 `logback-spring.xml` 하나다.** `<springProperty source="app.logging.…">`로 Spring
Environment를 읽으므로 env(`APP_LOG_*`, `config/observability.yml`이 매핑), profile 파일, 명령행 인자가 모두
같은 길로 들어간다. 예전에는 env 이름을 직접 읽어 `app.logging.*`를 yml로 바꿔도 반영되지 않았고,
`LoggingSettings`가 같은 키를 따로 바인딩해 Logback이 쓰지 않는 대체값을 경고했다(07-06). 그 record는 지웠다.
- **Logback이 쓸 수 없는 값은 기동을 멈춘다.** `LoggingConfigurationRule`(`StartupRule`)이 파일 경로 공백,
보관 일수·큐 크기 하한, 시간대, 샘플링 비율 범위를 env 키 이름으로 보고한다. size 문자열은 Logback이 파싱한다.
- **한계:** Logback은 `src/.env`가 환경에 들어오기 전에 초기화된다(dotenv run listener가 Boot의 이벤트
발행보다 늦다). `.env`에만 있는 로깅 값은 반영되지 않으므로 export하거나 프로세스에 넘긴다. 예전 방식도 같았다.
### RuntimeSafetySettings
- **시작 시 `StartupSafetyValidator`가 강제하는 운영 안전 설정이다.** 현재 구현된 runtime
@@ -427,6 +433,15 @@ app-bootstrap 은 합성 루트라 "왜 이 의존성이, 왜 이 scope 로" 결
로그 인코더는 런타임에만 있으면 되지만, `StartupFailures`가 `StructuredArguments`를 **compile
time**에 호출해 `startup.phase`/`error.code`/`error.category` JSON 필드를 방출하므로 compile
classpath 에 있어야 한다.
- **기본 jar에 Jackson 2와 3이 함께 실린다 — 의도한 것이다(09-11).** 애플리케이션 JSON은 Boot 4의
Jackson 3이다. Jackson 2(`jackson-databind`·`jackson-core`·`jackson-dataformat-yaml`·
`jackson-datatype-jsr310` 2.21.x)는 두 의존성이 요구한다: `logstash-logback-encoder` 8.0(JSON 로그)과
web 어댑터의 springdoc → `swagger-core-jakarta`(OpenAPI 문서). 둘 다 Jackson 3 판이 없어 뺄 수 없다
(`./gradlew :app-bootstrap:dependencyInsight --configuration productionRuntimeClasspath --dependency
com.fasterxml.jackson.core:jackson-databind`로 확인). 그래서 보안 패치는 두 계열을 따로 본다.
- **OTLP exporter는 JDK HttpClient sender를 쓴다(09-11).** 기본 sender(`opentelemetry-exporter-sender-okhttp`)는
okhttp·okio·kotlin-stdlib(약 3 MB)를 모든 이미지에 실었다. `composition:service-runtime`이 그 sender를
빼고 `opentelemetry-exporter-sender-jdk`를 싣는다. export 동작은 `TracingExportSystemTest`가 확인한다.
### 테스트 의존성 (transitive 로 안 새서 명시 선언)
- **`testImplementation project(':adapter-persistence-postgresql')`** — vendor 클래스
+92 -19
View File
@@ -66,7 +66,6 @@ strictTestLanes {
description = 'Runs the whole-repository ArchUnit and architecture contract source set.'
sourceSet = 'architectureTest'
maxHeapSize = '2g'
jvmArgs '-Duser.timezone=UTC'
shouldRunAfter 'test'
}
lane('systemTest') {
@@ -74,7 +73,6 @@ strictTestLanes {
description = 'Runs full-application startup and shipped-profile characterization tests.'
sourceSet = 'systemTest'
maxHeapSize = '1g'
jvmArgs '-Duser.timezone=UTC'
shouldRunAfter 'test'
}
lane('conditionalTransportBuildContractTest') {
@@ -82,7 +80,6 @@ strictTestLanes {
sourceSet = 'conditionalTransportBuildContractTest'
requires 'dev.caskeleton.bootstrap.transport.ConditionalTransportBuildContractTest'
rejectSkipped = true
jvmArgs '-Duser.timezone=UTC'
shouldRunAfter 'test'
}
}
@@ -170,10 +167,11 @@ dependencies {
// runtimeOnly project(':composition:fileserver-platform') // 파일 서버
// runtimeOnly project(':composition:notification-platform') // 알림 (persistence-jpa·persistence-notification을 함께 가져온다)
// 기본 조립에 있는 application composition. 둘 다 포트만 보고, 필요한 것(outbox store, 멱등성
// 기본 조립에 있는 application composition. 셋 다 포트만 보고, 필요한 것(outbox store, 멱등성
// provider)이 없으면 아무것도 만들지 않는다. sample-portfolio도 같은 멱등성 모듈을 쓴다.
runtimeOnly project(':composition:outbox-relay') // outbox relay (store·발행 포트가 있을 때만)
runtimeOnly project(':composition:idempotency') // 요청 멱등성 executor (provider≠disabled)
runtimeOnly project(':composition:durable-operation') // /operations (operation store·outbox가 있을 때만)
// 모든 서비스가 받는 runtime 배선: tracing, metrics 계약 filter, domain context, user principal
// 가명화, actuator 보안 chain. sample-portfolio도 같은 줄을 쓴다.
runtimeOnly project(':composition:service-runtime')
@@ -202,6 +200,8 @@ dependencies {
testImplementation(testFixtures(project(':adapter:inbound:web')))
// The idempotency composition tests drive the executor over the port owner's shared fake store.
testImplementation(testFixtures(project(':application-core')))
// A feature's composition test registers the domain ports' fakes (scripts/new-feature.sh).
testImplementation(testFixtures(project(':domain-core')))
testImplementation(testFixtures(project(':shared-contract')))
// The opt-in web library is in no shipped composition. Runtime-only for the tests so the
// whole-repository ArchUnit import (architectureTest runs on the test runtime classpath) still
@@ -313,24 +313,97 @@ dependencies {
conditionalTransportBuildContractTestRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}
// The contract tests here read the repository itself — docs/registries and docs/runbooks, the
// module registry and the rest of src/config, build scripts, Dockerfiles, Compose files, workflows,
// src/.env.example, the root guidance documents. Every one of those is an input, or Gradle calls
// the lane up to date after exactly the edit the test exists to catch.
// Tests that read the repository itself — registries, runbooks, guidance documents, build scripts,
// workflows, Compose files, other leaves' sources — run in two tagged lanes, and only those lanes
// receive the repository root (`ca.repository.root`) and declare what they read as inputs. The plain
// `test` lane gets neither: a repository-reading test left untagged fails there for want of a root
// instead of turning `test` into a task that every document edit invalidates (review 2026-11-01
// 08-03; the inputs are what keeps O-4a's "the lane reruns when a file it reads changes").
//
// documentContractTest tag document-contract main stage docs/**, the guidance documents,
// and the files the same classes
// cross-check them with
// repositoryContractTest tag repository-contract pull request build, configuration, workflow and
// Compose files and leaf sources;
// no document, so a docs/** edit
// leaves it up to date
//
// The pull-request lane exists because some of those contracts are release and security
// properties — the signing job's OIDC scope, the Docker staging contract, the request-logging body
// capture ban — that must stop a merge, not be found after one.
def repositoryRootForContractTests = rootProject.projectDir.parentFile
def repositoryContractExcludes = ['**/build/**', '**/.gradle/**', '**/node_modules/**']
def repositoryContractInputs = files(
fileTree(repositoryRootForContractTests) {
include 'docs/**', '.github/**', 'infra/**', 'scripts/**', '*.md', '*.yml', '*.example'
include '.github/**', 'infra/**', 'scripts/**', '*.yml', '*.example', '.tool-versions'
exclude '**/*.md'
exclude repositoryContractExcludes
},
fileTree(rootProject.projectDir) {
include 'config/**', '**/*.gradle', 'gradle/*.toml', 'Dockerfile*', '.env*', '**/*.md'
exclude '**/build/**', '**/.gradle/**'
include 'config/**', '**/*.gradle', 'gradle/*.toml', 'Dockerfile*', '.env*', '**/src/main/**'
// SampleRuntimeDefaultsContractTest compares the sample's runtime defaults with these.
include 'sample-portfolio/src/main/resources/application.yml'
exclude '**/*.md'
exclude repositoryContractExcludes
})
tasks.withType(Test).configureEach {
systemProperty 'ca.repository.root', repositoryRootForContractTests.absolutePath
inputs.files(repositoryContractInputs)
.withPathSensitivity(PathSensitivity.RELATIVE)
.withPropertyName('repositoryContractInputs')
def documentContractInputs = files(
repositoryContractInputs,
fileTree(repositoryRootForContractTests) {
include 'docs/**', '*.md', '.github/**/*.md'
},
fileTree(rootProject.projectDir) {
include '**/*.md'
exclude repositoryContractExcludes
})
strictTestLanes {
lane('documentContractTest') {
tag = 'document-contract'
description = 'Holds the composition to the repository documents and registries it promises.'
rejectSkipped = true
mainStage()
systemProperty 'ca.repository.root', repositoryRootForContractTests.absolutePath
customize { Test task ->
task.inputs.files(documentContractInputs)
.withPathSensitivity(PathSensitivity.RELATIVE)
.withPropertyName('documentContractInputs')
}
}
lane('repositoryContractTest') {
tag = 'repository-contract'
description = 'Holds the composition to the build, configuration and workflow files it does not own.'
systemProperty 'ca.repository.root', repositoryRootForContractTests.absolutePath
customize { Test task ->
task.inputs.files(repositoryContractInputs)
.withPathSensitivity(PathSensitivity.RELATIVE)
.withPropertyName('repositoryContractInputs')
}
}
}
tasks.named('test', Test) {
useJUnitPlatform { excludeTags 'repository-contract' }
}
tasks.named('check') {
dependsOn 'repositoryContractTest'
}
// The other suites find the repository themselves and read what Gradle cannot otherwise see: the
// architecture suite scans every leaf's production sources and its own rule sources as text, the
// opt-in classpath contract reads this build script, and the Compose characterization reads the
// Compose files.
tasks.named('architectureTest', Test) {
inputs.files(fileTree(rootProject.projectDir) {
include '**/src/main/java/**/*.java', 'app-bootstrap/src/architectureTest/java/**'
exclude repositoryContractExcludes
}).withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName('scannedSources')
}
tasks.named('conditionalTransportBuildContractTest', Test) {
inputs.file('build.gradle').withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName('buildScript')
}
tasks.named('integrationTest', Test) {
inputs.files(fileTree(repositoryRootForContractTests) {
include '*.yml', 'infra/**'
exclude repositoryContractExcludes
}).withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName('composeFiles')
}
// Fast developer test lane. Whole-repository ArchUnit graphs and full composition-root boot
@@ -340,9 +413,6 @@ tasks.named('test', Test) {
// Two forks are the measured sweet spot after moving whole-repository ArchUnit and full boot
// composition tests out of the fast lane. More forks duplicate Spring contexts for little gain.
maxParallelForks = 2
// Pin UTC for the TEST JVM so timestamp tests are host-locale-independent (production UTC is
// owned elsewhere).
jvmArgs '-Duser.timezone=UTC'
}
@@ -449,6 +519,9 @@ tasks.register('stageQualificationDockerJar', Sync) {
def h2RunClasspath = compositionRuntimeClasspath('bootRunH2Classpath')
dependencies {
bootRunH2Classpath project(':adapter:outbound:persistence-jpa')
// The driver is not a runtime dependency of persistence-jpa (review 09-09), so the task that
// chose H2 brings it.
bootRunH2Classpath 'com.h2database:h2'
}
tasks.register('bootRunH2', org.springframework.boot.gradle.tasks.run.BootRun) {
group = 'application'
+3 -9
View File
@@ -20,7 +20,7 @@ com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,architectureTes
com.github.docker-java:docker-java-api:3.7.1=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath
com.github.docker-java:docker-java-transport-zerodep:3.7.1=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath
com.github.docker-java:docker-java-transport:3.7.1=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath
com.github.f4b6a3:uuid-creator:6.1.1=architectureTestRuntimeClasspath,qualificationRuntimeClasspath
com.github.f4b6a3:uuid-creator:6.1.1=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath
com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,architectureTestAnnotationProcessor,conditionalTransportBuildContractTestAnnotationProcessor,integrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor
com.github.luben:zstd-jni:1.5.6-10=architectureTestRuntimeClasspath,qualificationRuntimeClasspath
com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs
@@ -54,7 +54,7 @@ com.google.protobuf:protobuf-java:3.25.5=architectureTestRuntimeClasspath,condit
com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,architectureTestAnnotationProcessor,conditionalTransportBuildContractTestAnnotationProcessor,integrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor
com.graphql-java:graphql-java:25.0=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath
com.graphql-java:java-dataloader:6.0.0=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath
com.h2database:h2:2.4.240=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,testRuntimeClasspath
com.h2database:h2:2.4.240=bootRunH2Classpath
com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins
com.jayway.jsonpath:json-path:2.10.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
com.networknt:json-schema-validator:3.0.2=architectureTestRuntimeClasspath,qualificationRuntimeClasspath
@@ -63,10 +63,6 @@ com.nimbusds:lang-tag:1.7=architectureTestRuntimeClasspath,qualificationRuntimeC
com.nimbusds:nimbus-jose-jwt:10.4=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath
com.nimbusds:oauth2-oidc-sdk:11.26.1=architectureTestRuntimeClasspath,qualificationRuntimeClasspath
com.puppycrawl.tools:checkstyle:13.5.0=checkstyle
com.squareup.okhttp3:okhttp-jvm:5.2.1=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath
com.squareup.okhttp3:okhttp:5.2.1=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath
com.squareup.okio:okio-jvm:3.16.1=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath
com.squareup.okio:okio:3.16.1=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath
com.sun.istack:istack-commons-runtime:4.1.2=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,testRuntimeClasspath
com.tngtech.archunit:archunit-junit5-api:1.3.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath
com.tngtech.archunit:archunit-junit5-engine-api:1.3.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,testRuntimeClasspath
@@ -134,7 +130,7 @@ io.opentelemetry:opentelemetry-context:1.55.0=architectureTestCompileClasspath,a
io.opentelemetry:opentelemetry-exporter-common:1.55.0=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-exporter-otlp-common:1.55.0=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-exporter-otlp:1.55.0=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-exporter-sender-okhttp:1.55.0=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-exporter-sender-jdk:1.55.0=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-extension-trace-propagators:1.55.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-sdk-common:1.55.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-sdk-extension-autoconfigure-spi:1.55.0=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath
@@ -230,8 +226,6 @@ org.hibernate.validator:hibernate-validator:9.0.1.Final=architectureTestCompileC
org.javassist:javassist:3.28.0-GA=checkstyle
org.javassist:javassist:3.29.0-GA=architectureTestRuntimeClasspath,qualificationRuntimeClasspath
org.jboss.logging:jboss-logging:3.6.3.Final=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
org.jetbrains.kotlin:kotlin-stdlib:2.2.21=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath
org.jetbrains:annotations:13.0=bootRunH2Classpath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath
org.jetbrains:annotations:17.0.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath
org.jspecify:jspecify:1.0.1=annotationProcessor,architectureTestAnnotationProcessor,architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,checkstyle,compileClasspath,conditionalTransportBuildContractTestAnnotationProcessor,conditionalTransportBuildContractTestCompileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestAnnotationProcessor,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestAnnotationProcessor,systemTestCompileClasspath,systemTestRuntimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter-api:6.0.3=architectureTestCompileClasspath,architectureTestRuntimeClasspath,conditionalTransportBuildContractTestCompileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
@@ -21,6 +21,7 @@ import com.tngtech.archunit.lang.ConditionEvents;
import com.tngtech.archunit.lang.SimpleConditionEvent;
import dev.caskeleton.application.capability.UseCaseCapability;
import dev.caskeleton.application.security.RequiresPermission;
import dev.caskeleton.application.security.SystemInvoked;
import dev.caskeleton.application.usecase.CommandUseCase;
import dev.caskeleton.application.usecase.QueryUseCase;
import java.util.HashSet;
@@ -424,6 +425,23 @@ class ApplicationBoundaryArchitectureTest {
+ "static-analysis blind spot (D4 limit).")
.allowEmptyShould(true);
/**
* A use case only the system calls states that with {@link SystemInvoked} and declares no
* permission. Both together would be the decorative gate this marker replaces: a check that
* either never runs or refuses every scheduler tick.
*/
@ArchTest
static final ArchRule SYSTEM_INVOKED_USE_CASES_DECLARE_NO_PERMISSION =
classes()
.that()
.areAnnotatedWith(SystemInvoked.class)
.should()
.notBeAnnotatedWith(RequiresPermission.class)
.as(
"a @SystemInvoked use case declares no @RequiresPermission: the system caller has no "
+ "Authentication, so the gate would be decoration")
.allowEmptyShould(true);
@ArchTest
static final ArchRule APPLICATION_AND_DOMAIN_DO_NOT_DEPEND_ON_SPRING_SECURITY =
noClasses()
@@ -537,6 +555,9 @@ class ApplicationBoundaryArchitectureTest {
if (!writeRepository) {
return;
}
if (item.isAnnotatedWith(SystemInvoked.class.getName())) {
return;
}
if (!item.isAnnotatedWith(RequiresPermission.class.getName())) {
events.add(
SimpleConditionEvent.violated(
@@ -161,6 +161,7 @@ class ArchRuleDiscoveryContractTest {
"REQUEST_DTOS_DO_NOT_SILENCE_UNKNOWN_FIELDS",
"SHARED_CONTRACT_CONTAINS_ONLY_OPERATIONAL_CONTRACT_PACKAGES",
"STARTUP_FAILURES_ARE_RAISED_THROUGH_THE_TYPED_FACTORY",
"SYSTEM_INVOKED_USE_CASES_DECLARE_NO_PERMISSION",
"THROWABLES_ARE_NAMED_EXCEPTION",
"USE_CASE_CAPABILITY_MATCHES_TRANSACTION_PORT_BOUNDARY",
"USE_CASE_PORTS_CARRY_ONE_OPERATION",
@@ -4,12 +4,42 @@ import static org.assertj.core.api.Assertions.assertThat;
import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.core.importer.ClassFileImporter;
import com.tngtech.archunit.lang.ArchRule;
import com.tngtech.archunit.lang.EvaluationResult;
import dev.caskeleton.bootstrap.authz.RequiresPermissionProxyabilityTest;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/** Contract dry-run for adding a real domain feature against the production boundaries. */
/**
* Contract dry-run for adding a real domain feature against the production boundaries.
*
* <p>The fixture under {@code dev.caskeleton.onboarding} is test code, so every production suite
* leaves it out ({@link ProductionClassImportOption}). Left there, it drifted into a shape the
* production rules reject — a {@code final} use case carrying {@code @RequiresPermission}, which
* fails startup the moment it becomes a bean. {@link
* #onboardingSliceBreaksNoProductionArchitectureRule()} closes that gap: it holds the fixture to
* every rule the production suites declare, not to a hand-picked subset.
*/
class DomainFeatureOnboardingContractTest {
/**
* Every class whose {@code static final ArchRule} constants guard production code. A new suite is
* added here; a new rule in a listed suite is picked up without editing this test.
*/
private static final List<Class<?>> PRODUCTION_RULE_SUITES =
List.of(
DomainPurityArchitectureTest.class,
ApplicationBoundaryArchitectureTest.class,
AdapterBoundaryArchitectureTest.class,
TypeBoundaryArchitectureTest.class,
ForbiddenApiArchitectureTest.class,
NamingConventionTest.class,
RequiresPermissionProxyabilityTest.class);
private static final String ROOT = "dev.caskeleton.onboarding";
private static final JavaClasses ONBOARDING_CLASSES =
@@ -68,7 +98,7 @@ class DomainFeatureOnboardingContractTest {
ROOT + ".domain.feature.FeatureAggregateId",
ROOT + ".domain.feature.FeatureAggregateIdFactory",
ROOT + ".application.command.CreateFeatureAggregateCommand",
ROOT + ".application.port.FeatureAggregateWritePort",
ROOT + ".domain.feature.FeatureAggregateRepository",
ROOT + ".application.usecase.CreateFeatureAggregateUseCase",
ROOT + ".adapter.outbound.persistence.entity.FeatureAggregateEntity",
ROOT + ".adapter.outbound.persistence.mapper.FeatureAggregateEntityMapper",
@@ -107,6 +137,38 @@ class DomainFeatureOnboardingContractTest {
.isNotNull();
}
@Test
@DisplayName("온보딩 fixture는 production 아키텍처 규칙을 하나도 어기지 않는다")
void onboardingSliceBreaksNoProductionArchitectureRule() throws IllegalAccessException {
// given
List<ArchRule> rules = productionRules();
// when
List<String> violations = new ArrayList<>();
for (ArchRule rule : rules) {
EvaluationResult result = rule.allowEmptyShould(true).evaluate(ONBOARDING_CLASSES);
if (result.hasViolation()) {
violations.add(rule.getDescription() + System.lineSeparator() + result.getFailureReport());
}
}
// then
assertThat(violations).isEmpty();
}
private static List<ArchRule> productionRules() throws IllegalAccessException {
List<ArchRule> rules = new ArrayList<>();
for (Class<?> suite : PRODUCTION_RULE_SUITES) {
for (Field field : suite.getDeclaredFields()) {
if (Modifier.isStatic(field.getModifiers()) && ArchRule.class.equals(field.getType())) {
field.setAccessible(true);
rules.add((ArchRule) field.get(null));
}
}
}
return rules;
}
private static List<String> classNames() {
return ONBOARDING_CLASSES.stream().map(javaClass -> javaClass.getName()).sorted().toList();
}
@@ -55,13 +55,9 @@ class ForbiddenApiArchitectureTest {
"dev.caskeleton.shared.response",
"dev.caskeleton.shared.request",
"dev.caskeleton.shared.error",
"dev.caskeleton.shared.operation",
"dev.caskeleton.shared.headers",
"dev.caskeleton.shared.logging",
"dev.caskeleton.shared.tracing",
"dev.caskeleton.shared.metrics",
"dev.caskeleton.shared.registry",
"dev.caskeleton.shared.annotation",
// Not this module at all — see the defect note on the rule above. The Mongo leaf has
// a
// tenancy.shared package of its own and only began tripping this rule when that leaf
@@ -96,6 +96,7 @@ class JpaProductionArchitectureTest {
}
@Test
@DisplayName("운영 엔티티의 연관관계는 모두 한쪽에서만 매핑된다")
void everyProductionAssociationIsMappedFromOneSideOnly() {
JpaArchitectureRules.associationsAreMappedFromOneSideOnly().check(productionClasses);
}
@@ -124,6 +125,19 @@ class JpaProductionArchitectureTest {
.check(productionClasses);
}
@Test
@DisplayName("@Version 엔티티를 바꾸는 bulk UPDATE는 version을 올린다")
void bulkUpdatesOfVersionedEntitiesAdvanceTheVersion() {
// Hibernate does not touch the version for a bulk statement, so an entity read before it
// flushes over the change with no optimistic-lock conflict (review 04-07). The versioned set is
// computed from the same graph, like the audited set above.
dev.caskeleton.adapter.outbound.persistence.testkit.arch.JpaVersionedBulkUpdateRule
.bulkUpdatesOfVersionedEntitiesAdvanceVersion(
dev.caskeleton.adapter.outbound.persistence.testkit.arch.JpaVersionedBulkUpdateRule
.versionedTargets(productionClasses))
.check(productionClasses);
}
@Test
@DisplayName("no tenant-scoped repository inherits the tenant-blind CRUD surface")
void noTenantScopedRepositoryInheritsBroadCrud() {
@@ -8,14 +8,14 @@ import com.tngtech.archunit.lang.ArchRule;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Naming convention enforcement — the machine-checkable ({@code [객관]}) subset of {@code
* .agents/plugins/ca-superpowers/rules/code-conventions.md}.
* Naming convention enforcement — the machine-checkable subset of the naming table in {@code
* src/application-core/CLAUDE.md} ("Naming convention"), which is the rule book.
*
* <p>The naming/idiom SSOT is {@code code-conventions.md}. This test enforces only the rules that
* ArchUnit can decide reliably (N6, I5). {@code [판단]} naming rules (N2/N7/N8/...) and rules with
* intentional project exceptions (N3/N4 — e.g. the {@code IdFactory} domain port, the {@code
* SpringTransaction} canonical impl) stay in {@code ca-quality-reviewer} (doc+review), per the
* code-conventions enforcement matrix.
* <p>This test enforces only the rules that ArchUnit can decide reliably (N6 configuration binding,
* I5 throwables). The rest of that table — repository vs store port, id factories, use case suffix
* exceptions — is a review rule, and the review checks it against that table. (The previous rule
* book, {@code .agents/plugins/ca-superpowers/rules/code-conventions.md}, is not in the
* repository.)
*/
@AnalyzeClasses(packages = "dev.caskeleton", importOptions = ProductionClassImportOption.class)
class NamingConventionTest {
@@ -4,6 +4,7 @@ import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.methods;
import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.core.domain.JavaModifier;
import com.tngtech.archunit.core.importer.ClassFileImporter;
import com.tngtech.archunit.lang.ArchRule;
import dev.caskeleton.application.security.RequiresPermission;
@@ -33,7 +34,49 @@ import org.junit.jupiter.api.Test;
* silently does not run is indistinguishable from one that passes.
* </ul>
*/
class RequiresPermissionProxyabilityTest {
public class RequiresPermissionProxyabilityTest {
/**
* The three rules are constants so that the onboarding fixture (test classes the production
* import option leaves out) is held to the same rules — {@code
* DomainFeatureOnboardingContractTest} evaluates them against the fixture.
*/
public static final ArchRule NO_ANNOTATED_CLASS_IS_FINAL =
classes()
.that()
.areAnnotatedWith(RequiresPermission.class)
.should()
.notHaveModifier(JavaModifier.FINAL)
.because(
"CGLIB cannot subclass a final class, so registering one as a bean fails startup "
+ "with 'Cannot subclass final class' — and until it is registered the "
+ "annotation enforces nothing");
public static final ArchRule NO_ANNOTATED_METHOD_IS_FINAL =
methods()
.that()
.areAnnotatedWith(RequiresPermission.class)
.should()
.notHaveModifier(JavaModifier.FINAL)
.because(
"a CGLIB proxy inherits a final method rather than overriding it, so the "
+ "authorization check is skipped with no error anywhere — the annotation reads "
+ "as enforcement and is decoration")
.allowEmptyShould(true);
public static final ArchRule NO_METHOD_OF_AN_ANNOTATED_CLASS_IS_FINAL =
methods()
.that()
.areDeclaredInClassesThat()
.areAnnotatedWith(RequiresPermission.class)
.and()
.arePublic()
.should()
.notHaveModifier(JavaModifier.FINAL)
.because(
"the advisor's pointcut matches the class annotation, so every public method of "
+ "such a class is an enforcement point and a final one is a hole in it")
.allowEmptyShould(true);
private static JavaClasses productionClasses;
@@ -48,53 +91,18 @@ class RequiresPermissionProxyabilityTest {
@Test
@DisplayName("no class carrying @RequiresPermission is final")
void noAnnotatedClassIsFinal() {
ArchRule rule =
classes()
.that()
.areAnnotatedWith(RequiresPermission.class)
.should()
.notHaveModifier(com.tngtech.archunit.core.domain.JavaModifier.FINAL)
.because(
"CGLIB cannot subclass a final class, so registering one as a bean fails startup "
+ "with 'Cannot subclass final class' — and until it is registered the "
+ "annotation enforces nothing");
rule.check(productionClasses);
NO_ANNOTATED_CLASS_IS_FINAL.check(productionClasses);
}
@Test
@DisplayName("no method carrying @RequiresPermission is final")
void noAnnotatedMethodIsFinal() {
ArchRule rule =
methods()
.that()
.areAnnotatedWith(RequiresPermission.class)
.should()
.notHaveModifier(com.tngtech.archunit.core.domain.JavaModifier.FINAL)
.because(
"a CGLIB proxy inherits a final method rather than overriding it, so the "
+ "authorization check is skipped with no error anywhere — the annotation reads "
+ "as enforcement and is decoration");
rule.allowEmptyShould(true).check(productionClasses);
NO_ANNOTATED_METHOD_IS_FINAL.check(productionClasses);
}
@Test
@DisplayName("a method of an annotated class is not final either")
void noMethodOfAnAnnotatedClassIsFinal() {
ArchRule rule =
methods()
.that()
.areDeclaredInClassesThat()
.areAnnotatedWith(RequiresPermission.class)
.and()
.arePublic()
.should()
.notHaveModifier(com.tngtech.archunit.core.domain.JavaModifier.FINAL)
.because(
"the advisor's pointcut matches the class annotation, so every public method of "
+ "such a class is an enforcement point and a final one is a hole in it");
rule.allowEmptyShould(true).check(productionClasses);
NO_METHOD_OF_AN_ANNOTATED_CLASS_IS_FINAL.check(productionClasses);
}
}
@@ -7,7 +7,7 @@ import org.testcontainers.postgresql.PostgreSQLContainer;
*/
public final class PostgreSqlTestContainer {
public static final String IMAGE = "postgres:16-alpine";
public static final String IMAGE = System.getProperty("ca.test.image.postgres-16");
private static final String REUSE_ENV = "TESTCONTAINERS_REUSE_ENABLE";
private PostgreSqlTestContainer() {}
@@ -5,10 +5,6 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import dev.caskeleton.adapter.inbound.web.auth.AuthenticatedPrincipal;
import dev.caskeleton.adapter.inbound.web.authz.AuthorizationAdapter;
import dev.caskeleton.adapter.inbound.web.authz.MethodSecurityConfig;
import dev.caskeleton.adapter.inbound.web.authz.RolePermissionPolicy;
import dev.caskeleton.adapter.inbound.web.authz.RolePermissionRegistry;
import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler;
import dev.caskeleton.adapter.inbound.web.fileserver.mapper.RawUploadRequestMapper;
import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction;
@@ -44,7 +40,6 @@ import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.context.annotation.Bean;
@@ -500,15 +495,12 @@ class FileserverCompositionIntegrationTest {
// declarations over overlapping packages produced a duplicate uploadLeaseRepository definition —
// and, more to the point, a test that declared its own scan would keep passing if the shipped one
// were ever registered nowhere, which is exactly the failure this arrangement exists to catch.
@EnableConfigurationProperties(RolePermissionPolicy.class)
@Import({
FileserverPlatformAutoConfiguration.class,
DomainContextConfig.class,
// The permission gate the running application puts in front of every fileserver write, and
// the handler that answers its refusal. Without them a @RequiresPermission is only a marker.
MethodSecurityConfig.class,
AuthorizationAdapter.class,
RolePermissionRegistry.class,
// The handler that answers a refused permission. The permission gate itself is the web leaf's
// WebMethodSecurityAutoConfiguration, which arrives by auto-configuration as in the running
// application; importing it here as well registered it twice.
GlobalExceptionHandler.class
})
static class FileserverRuntime {
@@ -7,10 +7,6 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder
import com.jayway.jsonpath.JsonPath;
import dev.caskeleton.adapter.inbound.web.auth.AuthenticatedPrincipal;
import dev.caskeleton.adapter.inbound.web.authz.AuthorizationAdapter;
import dev.caskeleton.adapter.inbound.web.authz.MethodSecurityConfig;
import dev.caskeleton.adapter.inbound.web.authz.RolePermissionPolicy;
import dev.caskeleton.adapter.inbound.web.authz.RolePermissionRegistry;
import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeBodyAdvice;
import dev.caskeleton.bootstrap.integration.PostgreSqlTestContainer;
import dev.caskeleton.composition.runtime.context.DomainContextConfig;
@@ -22,7 +18,6 @@ import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.context.annotation.Import;
@@ -221,20 +216,17 @@ class DurableOperationCompositionIntegrationTest {
/** The shipped composition over a datasource, plus the web authorization pieces it relies on. */
@SpringBootConfiguration
// The web security root would add the JWT/session security chain, which needs an issuer; the
// permission check lives in the method-security advisor imported below.
// The web security root would add the JWT/session security chain, which needs an issuer. The
// permission check is WebMethodSecurityAutoConfiguration, kept by auto-configuration as in the
// running application.
@EnableAutoConfiguration(
excludeName = {
"dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration",
"dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebSecurityAutoConfiguration"
})
@EnableConfigurationProperties(RolePermissionPolicy.class)
@Import({
// The JPA audit port reads the domain context; the running application gets it from here.
DomainContextConfig.class,
MethodSecurityConfig.class,
AuthorizationAdapter.class,
RolePermissionRegistry.class,
EnvelopeBodyAdvice.class
})
static class OperationRuntime {}
@@ -2,7 +2,6 @@ package dev.caskeleton.bootstrap;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
/**
* Composition root.
@@ -11,19 +10,11 @@ import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
* beans and settings through its {@code AutoConfiguration.imports}, so adding a capability is one
* build line and removing it is deleting that line — nothing here names a module.
*
* <p>{@code @ConfigurationPropertiesScan} names the bootstrap packages whose settings are always
* bound. {@code bootstrap.autoconfigure} is left out on purpose: each auto-configuration there
* binds its own settings with {@code @EnableConfigurationProperties}, so a root whose condition is
* off binds nothing.
* <p>No {@code @ConfigurationPropertiesScan}: a scanned settings class binds leniently and ignores
* a misspelt key, so the root's own settings are bound strictly by the configuration that uses them
* ({@code StrictSettingsBinder}, 07-10), the way every module binds its own.
*/
@SpringBootApplication
@ConfigurationPropertiesScan(
basePackages = {
"dev.caskeleton.bootstrap.async",
"dev.caskeleton.bootstrap.runtime",
"dev.caskeleton.bootstrap.security",
"dev.caskeleton.bootstrap.settings"
})
public class CaSkeletonApplication {
public static void main(String[] args) {
@@ -3,10 +3,10 @@ package dev.caskeleton.bootstrap.async;
import dev.caskeleton.shared.concurrency.DomainContextPropagator;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.core.task.TaskDecorator;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@@ -18,14 +18,24 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
*/
@Configuration
@EnableAsync
@EnableConfigurationProperties(AsyncExecutorSettings.class)
public class AsyncExecutorConfig {
/** Spring's default {@code @Async} executor bean name (Boot's auto-config backs off). */
public static final String EXECUTOR_BEAN_NAME = "applicationTaskExecutor";
/** Shutdown await: container app-shutdown budget (20s) minus a 1s cleanup margin. */
static final int AWAIT_TERMINATION_SECONDS = 19;
/**
* How long close waits for queued async work. It is spent after the web server's graceful drain
* ({@code spring.lifecycle.timeout-per-shutdown-phase}, 30s) has finished, because Spring stops
* lifecycle beans before it destroys this executor — so the two add up. The container grace in
* the root {@code docker-compose.yml} is sized to that sum; {@code
* DeveloperExperienceContractTest} fails when it is not (07-07).
*/
public static final int AWAIT_TERMINATION_SECONDS = 19;
@Bean
AsyncExecutorSettings asyncExecutorSettings(Environment environment) {
return AsyncExecutorSettings.bind(environment);
}
@Bean
TaskDecorator asyncContextTaskDecorator(DomainContextPropagator domainContextPropagator) {
@@ -1,22 +1,23 @@
package dev.caskeleton.bootstrap.async;
import dev.caskeleton.adapter.outbound.support.StrictSettingsBinder;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailures;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;
import org.springframework.core.env.Environment;
/**
* Async executor pool sizing knobs, bound from {@code app.async.executor.*}. Rejects {@code
* Integer.MAX_VALUE} as a queue capacity so the queue stays bounded. See README for the design
* rationale.
* Integer.MAX_VALUE} as a queue capacity so the queue stays bounded. Bound strictly (07-10): a
* misspelt key such as {@code app.async.executor.core-sise} fails startup instead of leaving the
* default silently in force. See README for the design rationale.
*
* @param coreSize always-alive worker count (≥ 1)
* @param maxSize hard ceiling on workers (≥ 1 and ≥ {@code coreSize})
* @param queueCapacity bounded backlog depth (1 ≤ capacity &lt; {@code Integer.MAX_VALUE})
*/
@Validated
@ConfigurationProperties(prefix = "app.async.executor")
public record AsyncExecutorSettings(Integer coreSize, Integer maxSize, Integer queueCapacity) {
static final String PREFIX = "app.async.executor";
private static final int DEFAULT_CORE_SIZE = 10;
private static final int DEFAULT_MAX_SIZE = 50;
private static final int DEFAULT_QUEUE_CAPACITY = 200;
@@ -61,4 +62,14 @@ public record AsyncExecutorSettings(Integer coreSize, Integer maxSize, Integer q
+ ") (positive_int_ge_core)");
}
}
/**
* Binds the prefix strictly.
*
* @param environment the environment to bind from
* @return the validated settings
*/
public static AsyncExecutorSettings bind(Environment environment) {
return StrictSettingsBinder.bind(environment, PREFIX, AsyncExecutorSettings.class);
}
}
@@ -1,74 +0,0 @@
package dev.caskeleton.bootstrap.autoconfigure.operation;
import dev.caskeleton.adapter.inbound.web.operation.DurableOperationController;
import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort;
import dev.caskeleton.application.operation.CancelDurableOperationUseCase;
import dev.caskeleton.application.operation.DurableOperationStorePort;
import dev.caskeleton.application.operation.DurableOperationSubmittedContract;
import dev.caskeleton.application.operation.GetDurableOperationUseCase;
import dev.caskeleton.application.operation.SubmitDurableOperationUseCase;
import dev.caskeleton.application.outbox.OutboxAppendPort;
import dev.caskeleton.application.transaction.TransactionPort;
import java.time.Clock;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
/**
* Durable operations: the three use cases and their HTTP endpoints.
*
* <p>Application composition, like the outbox relay: it builds use cases from ports, which a driven
* adapter must not do. It names no module type, only ports, and turns itself on from what the
* selected modules provide — an operation store and an outbox to announce submissions through, both
* of which the JPA module contributes (the outbox with {@code app.outbox.enabled}). Removing that
* module's build line removes the endpoints with it.
*
* <p>The use cases are beans rather than objects built inside the controller so that the method
* security advisor proxies them: {@code @RequiresPermission} on submit and cancel is enforced by
* that proxy, and a use case constructed by hand would carry the annotation and skip the check.
*
* <p>The submission event's contract is registered here as a bean, which is how the application's
* {@link IntegrationEventEncoderPort} learns it: the encoder is built over every contract
* contribution the context holds.
*/
@AutoConfiguration(
afterName =
"dev.caskeleton.adapter.outbound.persistence.autoconfigure.PersistenceJpaAutoConfiguration")
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@ConditionalOnBean({DurableOperationStorePort.class, OutboxAppendPort.class, TransactionPort.class})
@Import(DurableOperationController.class)
public class DurableOperationConfig {
/** The {@code durable-operation.submitted} contract, so the encoder can validate the event. */
@Bean
public DurableOperationSubmittedContract durableOperationSubmittedContract() {
return new DurableOperationSubmittedContract();
}
/** Accepts work: the operation row and its outbox event in one transaction. */
@Bean
public SubmitDurableOperationUseCase submitDurableOperationUseCase(
DurableOperationStorePort operations,
OutboxAppendPort outbox,
IntegrationEventEncoderPort encoder,
TransactionPort transactions,
Clock clock) {
return new SubmitDurableOperationUseCase(operations, outbox, encoder, transactions, clock);
}
/** Reads one operation for the caller that submitted it. */
@Bean
public GetDurableOperationUseCase getDurableOperationUseCase(
DurableOperationStorePort operations, TransactionPort transactions, Clock clock) {
return new GetDurableOperationUseCase(operations, transactions, clock);
}
/** Cancels one operation for the caller that submitted it. */
@Bean
public CancelDurableOperationUseCase cancelDurableOperationUseCase(
DurableOperationStorePort operations, TransactionPort transactions, Clock clock) {
return new CancelDurableOperationUseCase(operations, transactions, clock);
}
}
@@ -0,0 +1,116 @@
package dev.caskeleton.bootstrap.logging;
import dev.caskeleton.adapter.outbound.support.startup.StartupPhase;
import dev.caskeleton.adapter.outbound.support.startup.StartupRule;
import java.time.DateTimeException;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import org.springframework.core.env.Environment;
/**
* Refuses {@code app.logging.*} values Logback cannot use.
*
* <p>Logback reads these keys itself ({@code logback-spring.xml}), before any bean exists, so they
* have exactly one reader. What used to stand beside it was {@code LoggingSettings}: a record that
* bound the same keys, replaced a bad value with a fallback and logged that it had — while Logback,
* which it never configured, went on using the bad value (07-06). The fallback it announced was not
* even Logback's ({@code logs/app.json} against {@code logs/ca-skeleton.json}). A warning about a
* correction nobody applies is worse than none, so a value Logback would reject now stops startup
* instead, with the variable that set it named.
*/
public class LoggingConfigurationRule implements StartupRule {
@Override
public StartupPhase phase() {
return StartupPhase.ENV_VALIDATION;
}
@Override
public String summary() {
return "logging configuration (app.logging.*) has values Logback cannot use";
}
@Override
public List<String> violations(Environment environment) {
List<String> violations = new ArrayList<>();
if (flag(environment, "app.logging.file.enabled", violations)) {
String path = environment.getProperty("app.logging.file.path");
if (path == null || path.isBlank()) {
violations.add(
"APP_LOG_FILE_PATH (app.logging.file.path) is blank while file logging is on");
}
atLeast(
environment, "app.logging.file.max-history", "APP_LOG_FILE_MAX_HISTORY", 1, violations);
}
if (flag(environment, "app.logging.async.enabled", violations)) {
atLeast(
environment, "app.logging.async.queue-size", "APP_LOG_ASYNC_QUEUE_SIZE", 1, violations);
atLeast(
environment,
"app.logging.async.discarding-threshold",
"APP_LOG_ASYNC_DISCARDING_THRESHOLD",
0,
violations);
}
String timezone = environment.getProperty("app.logging.json.timezone");
if (timezone != null && !"default".equalsIgnoreCase(timezone.trim())) {
try {
ZoneId.of(timezone.trim());
} catch (DateTimeException invalid) {
violations.add(
"APP_LOG_JSON_TIMEZONE (app.logging.json.timezone) is not an IANA zone: " + timezone);
}
}
atLeast(
environment,
"app.logging.json.logger-name-length",
"APP_LOG_JSON_LOGGER_NAME_LENGTH",
0,
violations);
String rate = environment.getProperty("app.logging.sampling-rate");
if (rate != null) {
try {
double value = Double.parseDouble(rate.trim());
if (!(value >= 0.0 && value <= 1.0)) {
violations.add(
"APP_LOG_SAMPLING_RATE (app.logging.sampling-rate) must be in [0.0, 1.0], was "
+ rate);
}
} catch (NumberFormatException invalid) {
violations.add(
"APP_LOG_SAMPLING_RATE (app.logging.sampling-rate) is not a number: " + rate);
}
}
return violations;
}
private static boolean flag(Environment environment, String key, List<String> violations) {
String value = environment.getProperty(key);
if (value == null) {
return false;
}
String trimmed = value.trim();
if (!"true".equalsIgnoreCase(trimmed) && !"false".equalsIgnoreCase(trimmed)) {
violations.add(key + " must be true or false, was " + value);
return false;
}
return Boolean.parseBoolean(trimmed);
}
private static void atLeast(
Environment environment, String key, String variable, int minimum, List<String> violations) {
String value = environment.getProperty(key);
if (value == null) {
return;
}
try {
int parsed = Integer.parseInt(value.trim());
if (parsed < minimum) {
violations.add(variable + " (" + key + ") must be >= " + minimum + ", was " + parsed);
}
} catch (NumberFormatException invalid) {
violations.add(variable + " (" + key + ") is not an integer: " + value);
}
}
}
@@ -3,6 +3,7 @@ package dev.caskeleton.bootstrap.runtime;
import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailures;
import dev.caskeleton.adapter.outbound.support.startup.StartupOrder;
import dev.caskeleton.bootstrap.CaSkeletonApplication;
import dev.caskeleton.shared.runtime.RuntimeEnvironment;
import java.util.List;
import org.springframework.boot.EnvironmentPostProcessor;
@@ -82,8 +83,7 @@ public class RuntimeEnvironmentProfileValidator implements EnvironmentPostProces
*/
private static boolean isDeployableArtifact(SpringApplication application) {
Class<?> mainClass = application.getMainApplicationClass();
return mainClass != null
&& "dev.caskeleton.bootstrap.CaSkeletonApplication".equals(mainClass.getName());
return mainClass != null && CaSkeletonApplication.class.getName().equals(mainClass.getName());
}
@Override
@@ -1,22 +1,22 @@
package dev.caskeleton.bootstrap.runtime;
import dev.caskeleton.bootstrap.settings.RuntimeSafetySettings;
import dev.caskeleton.bootstrap.logging.LoggingConfigurationRule;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Wires the runtime-safety startup fail-fast validators into the running application. See README
* for the design rationale. The relational guards (OSIV, DDL, pool, TLS, vendor) belong to the
* persistence-jpa module and arrive with it.
* Wires the runtime-safety startup rules into the running application. See README for the design
* rationale. The relational guards (OSIV, DDL, pool, TLS, vendor) belong to the persistence-jpa
* module and arrive with it. Every bean here is {@code static}: support's runner evaluates the
* rules before any other singleton exists, which must not create this class.
*/
@Configuration
@Configuration(proxyBeanMethods = false)
public class RuntimeSafetyConfig {
@Bean
StartupSafetyValidator startupSafetyValidator(
RuntimeSafetySettings settings, ListableBeanFactory beanFactory) {
return new StartupSafetyValidator(settings, beanFactory);
static StartupSafetyValidator startupSafetyValidator(ListableBeanFactory beanFactory) {
return new StartupSafetyValidator(beanFactory);
}
@Bean
@@ -24,6 +24,11 @@ public class RuntimeSafetyConfig {
return new RuntimeNumericBoundsValidator();
}
@Bean
static LoggingConfigurationRule loggingConfigurationRule() {
return new LoggingConfigurationRule();
}
@Bean
static ErrorDetailExposureSafetyValidator errorDetailExposureSafetyValidator() {
return new ErrorDetailExposureSafetyValidator();
@@ -3,31 +3,35 @@ package dev.caskeleton.bootstrap.runtime;
import dev.caskeleton.adapter.outbound.support.startup.RequiredProductionSecrets;
import dev.caskeleton.application.outbound.SecretSourcePort;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
/**
* Wires the secret/config-source backend and its startup fail-fast guard. See README for the design
* rationale.
*/
@Configuration
@EnableConfigurationProperties(SecretSourceSettings.class)
@Configuration(proxyBeanMethods = false)
public class SecretSourceConfig {
@Bean
SecretSourcePort secretSource(
SecretSourceSettings properties, ConfigurableEnvironment environment) {
return SecretSourceFactory.create(properties.strategy(), environment);
SecretSourcePort secretSource(Environment environment) {
return SecretSourceFactory.fromEnvironment(environment);
}
/**
* The guard, as a startup rule: it runs before any ordinary singleton exists, so a prod
* deployment missing a secret stops before a datasource opens a connection or a migration runs
* (07-02). Static, so creating it creates neither this class nor the backend bean above; the
* contributions are read when the rule runs, and each contributor declares its bean {@code
* static} too.
*
* @param contributed the secrets each selected module needs
* @return the rule
*/
@Bean
SecretSourceValidator secretSourceValidator(
ConfigurableEnvironment environment,
SecretSourcePort secretSource,
static SecretSourceValidator secretSourceValidator(
ObjectProvider<RequiredProductionSecrets> contributed) {
return new SecretSourceValidator(
environment, secretSource, contributed.orderedStream().toList());
return new SecretSourceValidator(() -> contributed.orderedStream().toList());
}
}
@@ -17,4 +17,15 @@ public final class SecretSourceFactory {
case ENVIRONMENT -> new EnvironmentSecretSource(environment);
};
}
/**
* Builds the backend {@code app.secret-source.strategy} selects. The one place the selection is
* read, for the {@code SecretSourcePort} bean and for the startup guard alike.
*
* @param environment the resolved environment
* @return the backend
*/
public static SecretSourcePort fromEnvironment(Environment environment) {
return create(SecretSourceSettings.bind(environment).strategy(), environment);
}
}
@@ -1,19 +1,31 @@
package dev.caskeleton.bootstrap.runtime;
import org.springframework.boot.context.properties.ConfigurationProperties;
import dev.caskeleton.adapter.outbound.support.StrictSettingsBinder;
import org.springframework.core.env.Environment;
/**
* Secret backend selection, bound from {@code app.secret-source.strategy}. See README for the
* design rationale.
* Secret backend selection, bound strictly from {@code app.secret-source.strategy} (07-10). See
* README for the design rationale.
*
* @param strategy the secret backend; {@code null} → {@code ENVIRONMENT}
*/
@ConfigurationProperties(prefix = "app.secret-source")
public record SecretSourceSettings(SecretSourceStrategy strategy) {
static final String PREFIX = "app.secret-source";
public SecretSourceSettings {
if (strategy == null) {
strategy = SecretSourceStrategy.ENVIRONMENT;
}
}
/**
* Binds the prefix strictly.
*
* @param environment the environment to bind from
* @return the settings
*/
public static SecretSourceSettings bind(Environment environment) {
return StrictSettingsBinder.bind(environment, PREFIX, SecretSourceSettings.class);
}
}
@@ -3,21 +3,31 @@ package dev.caskeleton.bootstrap.runtime;
import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot;
import dev.caskeleton.adapter.outbound.support.startup.RequiredProductionSecrets;
import dev.caskeleton.adapter.outbound.support.startup.StartupPhase;
import dev.caskeleton.adapter.outbound.support.startup.StartupValidationContext;
import dev.caskeleton.adapter.outbound.support.startup.StartupRule;
import dev.caskeleton.application.outbound.SecretSourcePort;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import org.springframework.beans.factory.SmartInitializingSingleton;
import java.util.function.Supplier;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertySource;
/**
* Fail-fast startup guard for the secret/config-source contract (prod-profile only; a violation
* throws so the application refuses to start). See README for the design rationale.
* Fail-fast startup rule for the secret/config-source contract (prod-profile only). See README for
* the design rationale.
*
* <p>A startup rule, not a {@code SmartInitializingSingleton} as it once was (07-02). That callback
* runs after every singleton exists — after a datasource has opened a connection with whatever
* password it had and after Flyway has migrated — so a prod deployment missing its secrets was
* refused only once it had already reached the database. As a rule it runs before any ordinary
* singleton is created. It builds the secret backend from the environment itself rather than taking
* the {@code SecretSourcePort} bean, so running early pulls no other bean forward.
*/
public class SecretSourceValidator implements SmartInitializingSingleton {
public class SecretSourceValidator implements StartupRule {
/** Prefix marking a dev/local fake credential; forbidden to reach the prod profile. */
static final String LOCAL_DEV_SENTINEL_PREFIX = "__LOCAL_DEV_";
@@ -34,38 +44,51 @@ public class SecretSourceValidator implements SmartInitializingSingleton {
public static final List<String> REQUIRED_PROD_SECRETS =
List.of("APP_PRIVACY_PSEUDONYMIZATION_SALT");
private final ConfigurableEnvironment environment;
private final SecretSourcePort secretSource;
private final List<RequiredProductionSecrets> contributed;
private final Supplier<List<RequiredProductionSecrets>> contributed;
public SecretSourceValidator(
ConfigurableEnvironment environment,
SecretSourcePort secretSource,
List<RequiredProductionSecrets> contributed) {
this.environment = environment;
this.secretSource = secretSource;
this.contributed = List.copyOf(contributed);
/**
* Creates the rule.
*
* @param contributed the secrets each selected module needs, read when the rule runs
*/
public SecretSourceValidator(Supplier<List<RequiredProductionSecrets>> contributed) {
this.contributed = Objects.requireNonNull(contributed, "contributed");
}
@Override
public void afterSingletonsInstantiated() {
if (!RuntimeProfileSnapshot.from(environment).isProduction()) {
return;
}
StartupValidationContext validation =
StartupValidationContext.forPhase(StartupPhase.ENV_VALIDATION);
collectLocalDevSentinelViolations(validation);
collectMissingSecretViolations(validation);
validation.failIfViolated(
"prod secret/config-source contract is invalid",
"inject real non-blank secrets from the secret manager / mounted environment; "
+ "local/dev sentinel credentials are forbidden in prod.");
public StartupPhase phase() {
return StartupPhase.ENV_VALIDATION;
}
private void collectLocalDevSentinelViolations(StartupValidationContext validation) {
@Override
public String summary() {
return "prod secret/config-source contract is invalid";
}
@Override
public String remedy() {
return "inject real non-blank secrets from the secret manager / mounted environment; "
+ "local/dev sentinel credentials are forbidden in prod.";
}
@Override
public List<String> violations(Environment environment) {
if (!RuntimeProfileSnapshot.from(environment).isProduction()) {
return List.of();
}
List<String> violations = new ArrayList<>();
collectLocalDevSentinelViolations(environment, violations);
collectMissingSecretViolations(environment, violations);
return violations;
}
private static void collectLocalDevSentinelViolations(
Environment environment, List<String> violations) {
if (!(environment instanceof ConfigurableEnvironment configurable)) {
return;
}
Set<String> offenders = new LinkedHashSet<>();
for (PropertySource<?> source : environment.getPropertySources()) {
for (PropertySource<?> source : configurable.getPropertySources()) {
if (source instanceof EnumerablePropertySource<?> enumerable) {
for (String name : enumerable.getPropertyNames()) {
Object value = enumerable.getProperty(name);
@@ -76,19 +99,20 @@ public class SecretSourceValidator implements SmartInitializingSingleton {
}
}
for (String offender : offenders) {
validation.reject(
violations.add(
"'" + LOCAL_DEV_SENTINEL_PREFIX + "' sentinel credential is configured for " + offender);
}
}
private void collectMissingSecretViolations(StartupValidationContext validation) {
private void collectMissingSecretViolations(Environment environment, List<String> violations) {
SecretSourcePort secretSource = SecretSourceFactory.fromEnvironment(environment);
Set<String> required = new LinkedHashSet<>(REQUIRED_PROD_SECRETS);
// Each module names the secrets its selected capabilities need. This guard does not know which
// capabilities a module has or how they are selected — it only checks the names resolve.
contributed.forEach(module -> required.addAll(module.requiredSecrets(environment)));
contributed.get().forEach(module -> required.addAll(module.requiredSecrets(environment)));
for (String key : required) {
if (secretSource.resolve(key).isEmpty()) {
validation.reject(key + " is missing/blank");
violations.add(key + " is missing/blank");
}
}
}
@@ -1,34 +1,48 @@
package dev.caskeleton.bootstrap.runtime;
import dev.caskeleton.adapter.outbound.support.startup.StartupPhase;
import dev.caskeleton.adapter.outbound.support.startup.StartupValidationContext;
import dev.caskeleton.adapter.outbound.support.startup.StartupRule;
import dev.caskeleton.application.lock.DistributedLockPort;
import dev.caskeleton.bootstrap.settings.RuntimeSafetySettings;
import java.util.List;
import java.util.Objects;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.core.env.Environment;
/**
* Fail-fast startup guard for env-combination invariants. Implemented as a {@link
* SmartInitializingSingleton} so the check runs once after every singleton is instantiated but
* before the context finishes refreshing; a violation throws so the context refuses to start. See
* README for the design rationale.
* Fail-fast startup rule for env-combination invariants. See README for the design rationale.
*
* <p>A startup rule rather than the {@code SmartInitializingSingleton} it was (07-02): that ran
* after every singleton existed, so a multi-instance deployment with no cross-instance lock had
* already connected to its stores and migrated before it was refused. The question it asks — is a
* bean of that name and type declared? — is answered by the bean definitions, which are complete
* before any singleton is created, so asking it then creates nothing.
*/
public class StartupSafetyValidator implements SmartInitializingSingleton {
public class StartupSafetyValidator implements StartupRule {
/** Shipped cross-instance lock provider selected by multi-instance mode. */
static final String DISTRIBUTED_LOCK_PROVIDER_BEAN = "distributedLockProvider";
private final RuntimeSafetySettings settings;
private final ListableBeanFactory beanFactory;
public StartupSafetyValidator(RuntimeSafetySettings settings, ListableBeanFactory beanFactory) {
this.settings = settings;
this.beanFactory = beanFactory;
/**
* Creates the rule.
*
* @param beanFactory the bean definitions the rule inspects; it creates no bean
*/
public StartupSafetyValidator(ListableBeanFactory beanFactory) {
this.beanFactory = Objects.requireNonNull(beanFactory, "beanFactory");
}
@Override
public void afterSingletonsInstantiated() {
validateMultiInstance();
public StartupPhase phase() {
// ADAPTER_ENABLEMENT (exit 72): a required adapter is missing.
return StartupPhase.ADAPTER_ENABLEMENT;
}
@Override
public String summary() {
return "APP_MULTI_INSTANCE_ENABLED=true requires the cross-instance DistributedLockPort";
}
/**
@@ -39,24 +53,21 @@ public class StartupSafetyValidator implements SmartInitializingSingleton {
* optional efficiency, rate limiting is validated by its transport/provider contract, and outbox
* coordination exists only when outbox itself is enabled.
*/
private void validateMultiInstance() {
if (!settings.multiInstanceEnabled()) {
return;
@Override
public List<String> violations(Environment environment) {
if (!RuntimeSafetySettings.bind(environment).multiInstanceEnabled()) {
return List.of();
}
StartupValidationContext invalid =
StartupValidationContext.forPhase(StartupPhase.ADAPTER_ENABLEMENT);
if (!beanFactory.containsBean(DISTRIBUTED_LOCK_PROVIDER_BEAN)) {
invalid.reject(DISTRIBUTED_LOCK_PROVIDER_BEAN + " (missing)");
} else if (!beanFactory.isTypeMatch(
DISTRIBUTED_LOCK_PROVIDER_BEAN, DistributedLockPort.class)) {
invalid.reject(
return List.of(DISTRIBUTED_LOCK_PROVIDER_BEAN + " (missing)");
}
if (!beanFactory.isTypeMatch(DISTRIBUTED_LOCK_PROVIDER_BEAN, DistributedLockPort.class)) {
return List.of(
DISTRIBUTED_LOCK_PROVIDER_BEAN
+ " (must implement "
+ DistributedLockPort.class.getName()
+ ")");
}
// ADAPTER_ENABLEMENT (exit 72) follows from the context's phase.
invalid.failIfViolated(
"APP_MULTI_INSTANCE_ENABLED=true requires the cross-instance DistributedLockPort");
return List.of();
}
}
@@ -1,16 +1,35 @@
package dev.caskeleton.bootstrap.settings;
import jakarta.validation.constraints.NotBlank;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;
import dev.caskeleton.adapter.outbound.support.StrictSettingsBinder;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailures;
import org.springframework.core.env.Environment;
/**
* Bootstrap-scope settings bound from {@code app.bootstrap.*}. {@code appName} is fail-fast
* (@NotBlank): no sensible default, so a blank value must stop startup rather than warn-and-default
* like the other settings. See README for the design rationale.
* Bootstrap-scope settings bound from {@code app.bootstrap.*}. {@code appName} is fail-fast: no
* sensible default, so a blank value must stop startup rather than warn-and-default. Bound strictly
* (07-10), so a misspelt key under {@code app.bootstrap} fails startup too. See README for the
* design rationale.
*
* @param appName the application name, required
*/
@Validated
@ConfigurationProperties(prefix = "app.bootstrap")
public record BootstrapSettings(
@NotBlank(message = "APP_NAME (app.bootstrap.app-name) is required and must not be blank")
String appName) {}
public record BootstrapSettings(String appName) {
static final String PREFIX = "app.bootstrap";
public BootstrapSettings {
if (appName == null || appName.isBlank() || appName.contains("${")) {
throw StartupFailures.envValidation(
"APP_NAME (app.bootstrap.app-name) is required and must not be blank");
}
}
/**
* Binds the prefix strictly.
*
* @param environment the environment to bind from
* @return the settings
*/
public static BootstrapSettings bind(Environment environment) {
return StrictSettingsBinder.bind(environment, PREFIX, BootstrapSettings.class);
}
}
@@ -0,0 +1,18 @@
package dev.caskeleton.bootstrap.settings;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
/**
* Binds the composition root's own identity settings strictly. A bean rather than a scanned
* {@code @ConfigurationProperties} class, because a scanned class ignores unknown keys (07-10).
*/
@Configuration(proxyBeanMethods = false)
public class BootstrapSettingsConfig {
@Bean
BootstrapSettings bootstrapSettings(Environment environment) {
return BootstrapSettings.bind(environment);
}
}
@@ -1,84 +0,0 @@
package dev.caskeleton.bootstrap.settings;
import dev.caskeleton.adapter.outbound.support.startup.RuntimeWarnings;
import java.time.ZoneId;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Logging settings bound from {@code app.logging.*}. Every knob is "warn-and-default": a bad value
* logs a warning and proceeds with a safe fallback rather than failing startup. See README for the
* design rationale.
*/
@ConfigurationProperties(prefix = "app.logging")
public record LoggingSettings(File file, Async async, Json json) {
public record File(
boolean enabled, String path, String maxSize, int maxHistory, String totalSizeCap) {
public File {
if (enabled) {
if (path == null || path.isBlank()) {
RuntimeWarnings.settingFallback(
"APP_LOG_FILE_PATH", path, "logs/app.json", "it is blank while file logging is on");
path = "logs/app.json";
}
if (maxHistory <= 0) {
RuntimeWarnings.settingFallback(
"APP_LOG_FILE_MAX_HISTORY", maxHistory, 14, "it must be >= 1");
maxHistory = 14;
}
// Size strings (maxSize, totalSizeCap) are parsed by logback; let it own that contract.
}
}
}
public record Async(boolean enabled, int queueSize, int discardingThreshold) {
public Async {
if (enabled) {
if (queueSize <= 0) {
RuntimeWarnings.settingFallback(
"APP_LOG_ASYNC_QUEUE_SIZE", queueSize, 512, "it must be >= 1");
queueSize = 512;
}
if (discardingThreshold < 0) {
RuntimeWarnings.settingFallback(
"APP_LOG_ASYNC_DISCARDING_THRESHOLD", discardingThreshold, 20, "it must be >= 0");
discardingThreshold = 20;
}
}
}
}
public record Json(
String timezone, String timestampPattern, boolean includeCallerData, int loggerNameLength) {
private static final String DEFAULT_TIMEZONE = "UTC";
private static final String DEFAULT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
public Json {
if (timezone == null || timezone.isBlank()) {
RuntimeWarnings.settingFallback(
"APP_LOG_JSON_TIMEZONE", timezone, DEFAULT_TIMEZONE, "it is blank");
timezone = DEFAULT_TIMEZONE;
} else if (!"default".equalsIgnoreCase(timezone)) {
try {
ZoneId.of(timezone);
} catch (Exception e) {
RuntimeWarnings.settingFallback(
"APP_LOG_JSON_TIMEZONE", timezone, DEFAULT_TIMEZONE, "it is not a valid IANA zone");
timezone = DEFAULT_TIMEZONE;
}
}
if (timestampPattern == null || timestampPattern.isBlank()) {
RuntimeWarnings.settingFallback(
"APP_LOG_JSON_TIMESTAMP_PATTERN", timestampPattern, DEFAULT_PATTERN, "it is blank");
timestampPattern = DEFAULT_PATTERN;
}
if (loggerNameLength < 0) {
RuntimeWarnings.settingFallback(
"APP_LOG_JSON_LOGGER_NAME_LENGTH", loggerNameLength, 0, "it must be >= 0");
loggerNameLength = 0;
}
}
}
}
@@ -1,13 +1,36 @@
package dev.caskeleton.bootstrap.settings;
import org.springframework.boot.context.properties.ConfigurationProperties;
import dev.caskeleton.adapter.outbound.support.StrictSettingsBinder;
import java.util.Set;
import org.springframework.core.env.Environment;
/**
* Operational runtime settings bound from {@code app.runtime.*}.
*
* <p>Only implemented controls belong here. Internal error-detail exposure and HTTP body logging
* have no runtime implementation and therefore no reserved configuration switch. {@code
* migration-on-startup} is read by the JPA module that runs the migration, not here.
* have no runtime implementation and therefore no reserved configuration switch.
*
* <p>Bound strictly (07-10): a misspelt key under {@code app.runtime} fails startup instead of
* leaving its default silently in force. {@code migration-on-startup} is the JPA module's — it runs
* the migration — so this binding leaves it to that module.
*
* @param multiInstanceEnabled whether several instances serve the same data
*/
@ConfigurationProperties(prefix = "app.runtime")
public record RuntimeSafetySettings(boolean multiInstanceEnabled) {}
public record RuntimeSafetySettings(boolean multiInstanceEnabled) {
static final String PREFIX = "app.runtime";
/** Keys under the prefix another module binds for itself. */
static final Set<String> FOREIGN_KEYS = Set.of("migration-on-startup");
/**
* Binds the prefix strictly.
*
* @param environment the environment to bind from
* @return the settings
*/
public static RuntimeSafetySettings bind(Environment environment) {
return StrictSettingsBinder.bindExcept(
environment, PREFIX, RuntimeSafetySettings.class, FOREIGN_KEYS);
}
}
@@ -1,2 +1 @@
dev.caskeleton.bootstrap.autoconfigure.common.BootstrapClockAutoConfiguration
dev.caskeleton.bootstrap.autoconfigure.operation.DurableOperationConfig
@@ -3,10 +3,8 @@
#
# This file is a complete standalone configuration, not a patch. application.yml resolves ~70
# values from ${APP_*} placeholders that carry no inline default, so a launcher that does not
# inject src/.env dies during property binding — and because logback-spring.xml reads the same
# unresolved app.logging.* values, the logging system fails first and swallows the console
# output that would have said so. The observable symptom is a process that exits 1 having printed
# nothing.
# inject src/.env dies during property binding. The observable symptom is a process that exits 1
# having printed little that says why.
#
# Only `./gradlew :app-bootstrap:bootRun` injects src/.env (see app-bootstrap/build.gradle). An IDE
# Run/Debug on CaSkeletonApplication, `java -jar`, and a bare container do not. Restating the
@@ -124,7 +122,10 @@ spring:
timeout-per-shutdown-phase: 30s
server:
port: 8080
# The one server value local takes from the environment (09-10): two services — or the default
# composition and the sample — on one machine need different ports, and a literal here made
# APP_SERVER_PORT=18080 still start on 8080.
port: ${APP_SERVER_PORT:8080}
shutdown: graceful
# No proxy in front of a local run, so trusting X-Forwarded-* would let a caller forge its own
# client IP. dev/prod sit behind a load balancer and set this to framework via env.
@@ -181,23 +182,7 @@ app:
allowed-headers: "*"
allow-credentials: true
max-age-seconds: 3600
logging:
file:
# Console only. A local run should not quietly grow a logs/ directory in the working
# directory, which differs between a Gradle run and an IDE run.
enabled: false
path: logs/ca-skeleton.json
max-size: 100MB
max-history: 14
total-size-cap: 3GB
async:
enabled: true
queue-size: 512
discarding-threshold: 20
json:
timezone: UTC
timestamp-pattern: "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"
include-caller-data: false
logger-name-length: 0
# Keep every log line locally; prod samples <=INFO down to 10%.
sampling-rate: 1.0
# No app.logging block: config/observability.yml already defaults every knob to what local wants
# (console only, no file, every line kept), and leaving it there keeps APP_LOG_* able to change a
# local run. Logback reads app.logging.* since 07-06, so a literal here would have been the one
# value an environment variable could not override.
@@ -8,7 +8,7 @@
# forbidden value has to fail whether it arrives from this file, an env var, or a container
# override — a YAML default only wins against the sources that are quieter than it:
#
# JpaSchemaSafetyValidator ddl-auto must be none|validate (exit 71)
# JpaDangerousConfigurationGuard ddl-auto must be none|validate (persistence-jpa)
# FlywayProdSafetyValidator baseline-on-migrate / out-of-order / clean stay disarmed
# ErrorDetailExposureSafetyValidator spring.web.error.include-* stay never/false (exit 71)
# PostgreSqlTransportSecurityValidator pgJDBC sslmode=verify-full
@@ -8,9 +8,9 @@ app:
# required, non-blank — startup fails if blank (see BootstrapSettings)
app-name: ${APP_NAME}
runtime:
# feature-env-driven-runtime-configuration D8: enforced at startup by
# the prod profile; multi-instance fails startup if its coordination beans are absent.
# true | false (requires the 5 instance-coordination beans when true)
# true | false. When true, startup fails (exit 72) unless a cross-instance DistributedLockPort
# bean named distributedLockProvider is declared (StartupSafetyValidator). The persistence-jpa
# module provides it.
multi-instance-enabled: ${APP_MULTI_INSTANCE_ENABLED:false}
presentation:
# feature-api-contract-baseline D2: API version prefix. Default is the URI
@@ -29,35 +29,14 @@ app:
path: ${APP_SESSION_COOKIE_PATH:/}
csrf-cookie-name: ${APP_SESSION_CSRF_COOKIE_NAME:XSRF-TOKEN}
csrf-header-name: ${APP_SESSION_CSRF_HEADER_NAME:X-XSRF-TOKEN}
authz:
# feature-authentication-authorization-contract D2/D3/D8: app-side role→permission
# mapping (the default source; IdP-issued permission claims are an out-of-scope
# alternative). Keys are RAW IdP role names (no ROLE_ prefix — that prefix only
# exists on Spring authorities, not on the principal's raw role set), looked up
# case-insensitively. Values are explicitly enumerated `resource:action` permissions
# (no wildcards — least-privilege, OWASP-AUTHZ-C4). The production defaults only grant
# platform-owned permissions; sample-domain permissions live in sample-portfolio fixtures.
role-permissions:
# The notification platform's own two permissions, granted to two roles rather than one.
# Publishing a template changes what every future submission renders, so a service that may
# send notifications is not thereby a service that may rewrite them; a deployment that wants
# both grants both roles.
notification-submit: notification:submit
notification-template-publish: notification-template:publish
# Durable operations (/operations, on with the JPA module and the outbox). One role for both:
# a caller that may start an operation may cancel its own, and reading one needs no
# permission beyond being the one who submitted it.
operation-submit: operation:submit,operation:cancel
# Fileserver (/v1/files, /v1/uploads, /internal/fileserver; on with the fileserver module).
# Keyed by the fileserver's own default tier roles (app.fileserver-platform.security.*-roles),
# so one role grants both halves of a fileserver write: the permission here, checked on the
# use case, and the tier FileAccessPolicyPort checks inside it along with ownership. The
# brackets keep the underscores, which unbracketed map keys lose in binding. A deployment that
# renames those roles maps its own names here too. The tiers do not inherit, and neither do
# these: a writer that also reads holds both roles.
"[ROLE_FILE_READ]": file:read
"[ROLE_FILE_WRITE]": file:upload,file:delete,file:copy,file:move
"[ROLE_FILE_ADMIN]": file:admin
# app.authz.role-permissions — no entry in this file. App-side role→permission mapping
# (feature-authentication-authorization-contract D2/D3/D8): keys are RAW IdP role names (no ROLE_
# prefix), looked up case-insensitively; values are enumerated `resource:action` permissions (no
# wildcards — least-privilege, OWASP-AUTHZ-C4). A capability's own permissions arrive with it, in
# that module's config/module-defaults file (notification, fileserver, durable-operation), and
# leave with its build line (07-08). Map entries from every source merge, so a deployment adds its
# own roles in its profile file or environment beside them. Sample-domain permissions live in
# sample-portfolio.
cors:
# true | false
enabled: ${APP_SECURITY_CORS_ENABLED:false}
@@ -12,8 +12,14 @@ server:
# Never framework — it believes every peer, so a caller can pick its own getRemoteAddr().
forward-headers-strategy: ${APP_SERVER_FORWARD_HEADERS_STRATEGY:none}
tomcat:
# With virtual threads on (spring.threads.virtual.enabled, the default in application.yml)
# Tomcat runs each request on a new virtual thread and threads.max / min-spare stop bounding
# concurrency: the number of requests in progress is bounded by max-connections below and by
# what each request waits on — the datasource pool, rate limits. Lower max-connections, or put a
# limit in front of the scarce resource, to shed load; lowering threads.max does nothing then.
# (Boot behaviour, not measured in this repository — 07-12.)
threads:
# integer >= 1
# integer >= 1. Platform-thread pool size; a concurrency bound only with virtual threads off.
max: ${APP_SERVER_TOMCAT_MAX_THREADS:200}
# integer >= 0
min-spare: ${APP_SERVER_TOMCAT_MIN_SPARE_THREADS:10}
@@ -2,7 +2,11 @@
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<!-- Early logging initializes before dotenv-backed application.yml placeholders are reliable. -->
<!--
Read when Logback initialises, which is before src/.env is added to the environment: the
dotenv run listener runs after Boot's event-publishing one. A value only in .env therefore
reaches neither this file nor anything it reads; export it or pass it to the process.
-->
<springProperty scope="context" name="APP_NAME"
source="APP_NAME" defaultValue="ca-skeleton"/>
<!--
@@ -14,37 +18,46 @@
<springProperty scope="context" name="APP_PROFILE"
source="SPRING_PROFILES_ACTIVE" defaultValue="unresolved"/>
<!--
The logging knobs are read from app.logging.*, the settings tree config/observability.yml
declares and maps onto the APP_LOG_* variables. springProperty reads the Spring Environment,
so a value set in YAML, a profile file or on the command line takes effect the same way the
variable does. They used to name the variables themselves, which made the variable the only
way in: app.logging.* in a profile file changed nothing (07-06). The defaultValue attributes
repeat the YAML defaults only for a context without that file. Values Logback would reject
are refused at startup by LoggingConfigurationRule.
-->
<springProperty scope="context" name="FILE_ENABLED"
source="APP_LOG_FILE_ENABLED" defaultValue="false"/>
source="app.logging.file.enabled" defaultValue="false"/>
<springProperty scope="context" name="FILE_PATH"
source="APP_LOG_FILE_PATH" defaultValue="logs/ca-skeleton.json"/>
source="app.logging.file.path" defaultValue="logs/ca-skeleton.json"/>
<springProperty scope="context" name="FILE_MAX_SIZE"
source="APP_LOG_FILE_MAX_SIZE" defaultValue="100MB"/>
source="app.logging.file.max-size" defaultValue="100MB"/>
<springProperty scope="context" name="FILE_MAX_HISTORY"
source="APP_LOG_FILE_MAX_HISTORY" defaultValue="14"/>
source="app.logging.file.max-history" defaultValue="14"/>
<springProperty scope="context" name="FILE_TOTAL_SIZE_CAP"
source="APP_LOG_FILE_TOTAL_SIZE_CAP" defaultValue="3GB"/>
source="app.logging.file.total-size-cap" defaultValue="3GB"/>
<springProperty scope="context" name="ASYNC_ENABLED"
source="APP_LOG_ASYNC_ENABLED" defaultValue="true"/>
source="app.logging.async.enabled" defaultValue="true"/>
<springProperty scope="context" name="ASYNC_QUEUE_SIZE"
source="APP_LOG_ASYNC_QUEUE_SIZE" defaultValue="512"/>
source="app.logging.async.queue-size" defaultValue="512"/>
<springProperty scope="context" name="ASYNC_DISCARDING_THRESHOLD"
source="APP_LOG_ASYNC_DISCARDING_THRESHOLD" defaultValue="20"/>
source="app.logging.async.discarding-threshold" defaultValue="20"/>
<springProperty scope="context" name="JSON_TIMEZONE"
source="APP_LOG_JSON_TIMEZONE" defaultValue="UTC"/>
source="app.logging.json.timezone" defaultValue="UTC"/>
<springProperty scope="context" name="JSON_TIMESTAMP_PATTERN"
source="APP_LOG_JSON_TIMESTAMP_PATTERN"
source="app.logging.json.timestamp-pattern"
defaultValue="yyyy-MM-dd'T'HH:mm:ss.SSSXXX"/>
<springProperty scope="context" name="JSON_INCLUDE_CALLER_DATA"
source="APP_LOG_JSON_INCLUDE_CALLER_DATA" defaultValue="false"/>
source="app.logging.json.include-caller-data" defaultValue="false"/>
<springProperty scope="context" name="JSON_LOGGER_NAME_LENGTH"
source="APP_LOG_JSON_LOGGER_NAME_LENGTH" defaultValue="0"/>
source="app.logging.json.logger-name-length" defaultValue="0"/>
<!-- D5/D8: ≤INFO sampling rate (prod 0.1 = 10%); WARN/ERROR always kept. -->
<springProperty scope="context" name="LOG_SAMPLING_RATE"
source="APP_LOG_SAMPLING_RATE" defaultValue="1.0"/>
source="app.logging.sampling-rate" defaultValue="1.0"/>
<!-- Redaction Layer 1 (DRIFT-2): %maskedMsg masks secrets in the human-readable pattern,
the SAME catalog (LogMaskingPatterns) the JSON decorator uses. -->
@@ -45,11 +45,12 @@ class DefaultCompositionBootTest {
"dev.caskeleton.adapter.inbound.websocket",
"dev.caskeleton.adapter.inbound.grpc",
// composition:service-runtime (`composition.runtime`) is part of the default composition;
// the outbox relay and idempotency modules are selected but build nothing until their
// store or provider is there.
// the outbox relay, durable-operation and idempotency modules are selected but build
// nothing until their store or provider is there.
"dev.caskeleton.composition.fileserver",
"dev.caskeleton.composition.notification",
"dev.caskeleton.composition.outbox",
"dev.caskeleton.composition.operation",
"dev.caskeleton.composition.idempotency");
/** Infrastructure a capability connects to; a bean of any of these would open a connection. */
@@ -0,0 +1,64 @@
package dev.caskeleton.bootstrap.logging;
import static org.assertj.core.api.Assertions.assertThat;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.Appender;
import dev.caskeleton.bootstrap.composition.ShippedCompositionHarness;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.slf4j.LoggerFactory;
import org.springframework.context.ConfigurableApplicationContext;
/**
* Logback reads {@code app.logging.*} from the Spring environment, so a value set in YAML, a
* profile file or on the command line takes effect — not only the {@code APP_LOG_*} variable the
* shipped YAML maps onto it (07-06).
*/
class LoggingSettingsSourceSystemTest {
@Test
@DisplayName("app.logging.file.enabled를 환경 변수가 아닌 설정으로 켜도 파일 appender가 붙는다")
void fileLoggingTurnedOnThroughTheSettingAttachesTheFileAppender(@TempDir Path directory) {
// given
Path logFile = directory.resolve("app.json");
String[] arguments =
Stream.concat(
Stream.of(ShippedCompositionHarness.requiredOperatorInputs()),
Stream.of(
"--server.port=0",
"--management.server.port=0",
"--app.logging.file.enabled=true",
"--app.logging.file.path=" + logFile))
.toArray(String[]::new);
// when
try (ConfigurableApplicationContext context =
ShippedCompositionHarness.shippedComposition("dev").run(arguments)) {
// then
assertThat(rootAppenderNames()).contains("ASYNC_FILE");
assertThat(Files.exists(logFile)).isTrue();
}
}
private static List<String> rootAppenderNames() {
Logger root =
((LoggerContext) LoggerFactory.getILoggerFactory()).getLogger(Logger.ROOT_LOGGER_NAME);
List<String> names = new ArrayList<>();
for (Iterator<Appender<ch.qos.logback.classic.spi.ILoggingEvent>> it =
root.iteratorForAppenders();
it.hasNext(); ) {
names.add(it.next().getName());
}
return names;
}
}
@@ -2,14 +2,17 @@ package dev.caskeleton.bootstrap.async;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException;
import java.util.Map;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.source.ConfigurationPropertySource;
import org.springframework.boot.context.properties.source.MapConfigurationPropertySource;
import org.springframework.mock.env.MockEnvironment;
/**
* Contract test for {@link AsyncExecutorSettings} (feature-background-job-async-contract D7 — pool
@@ -45,6 +48,20 @@ class AsyncExecutorSettingsTest {
assertThat(settings.queueCapacity()).isEqualTo(64);
}
@Test
@DisplayName("app.async.executor 아래 오타 키는 기본값으로 넘어가지 않고 기동을 실패시킨다")
void aMisspelledKeyFailsInsteadOfFallingBackToTheDefault() {
// given
MockEnvironment environment =
new MockEnvironment().withProperty("app.async.executor.core-sise", "4");
// when
Throwable thrown = catchThrowable(() -> AsyncExecutorSettings.bind(environment));
// then
assertThat(thrown).hasStackTraceContaining("core-sise");
}
// ---- positive_int (core) -------------------------------------------------
@Test
@@ -2,11 +2,13 @@ package dev.caskeleton.bootstrap.autoconfigure.jpa;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
@@ -32,6 +34,7 @@ import org.springframework.mock.env.MockEnvironment;
* available as {@code :app-bootstrap:bootRunH2}. What changed is that choosing it is now visible in
* the command somebody typed, rather than being what {@code local} quietly meant.
*/
@Tag("repository-contract")
class LocalJpaVendorParityTest {
/**
@@ -136,14 +139,9 @@ class LocalJpaVendorParityTest {
}
private static Path repositoryRoot() {
Path candidate = Path.of("").toAbsolutePath();
while (candidate != null
&& !Files.isRegularFile(candidate.resolve("src/config/architecture/modules.json"))) {
candidate = candidate.getParent();
}
if (candidate == null) {
throw new IllegalStateException("could not locate the repository root from the test cwd");
}
return candidate;
// Gradle hands the root only to the lanes that declare the repository files as inputs; the
// plain `test` lane gets none, so a test that reads the repository without a lane tag fails
// here instead of going stale behind an up-to-date check (review 2026-11-01 08-03).
return RepositoryContractResources.fromSystemProperty().repositoryRoot();
}
}
@@ -2,6 +2,7 @@ package dev.caskeleton.bootstrap.composition;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
@@ -14,6 +15,7 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
/**
@@ -38,6 +40,7 @@ import org.junit.jupiter.api.Test;
* multi-instance-enabled} is false or absent, the JDBC-backed one when it is true. Those cannot
* coexist, so nothing is being preferred — one of them simply is not there.
*/
@Tag("repository-contract")
class PortResolutionContractTest {
/** `@Bean` methods, with the annotations that precede them. */
@@ -151,15 +154,10 @@ class PortResolutionContractTest {
}
private static Path repositoryRoot() {
Path candidate = Path.of("").toAbsolutePath();
while (candidate != null
&& !Files.isRegularFile(candidate.resolve("src/config/architecture/modules.json"))) {
candidate = candidate.getParent();
}
if (candidate == null) {
throw new IllegalStateException("could not locate the repository root from the test cwd");
}
return candidate;
// Gradle hands the root only to the lanes that declare the repository files as inputs; the
// plain `test` lane gets none, so a test that reads the repository without a lane tag fails
// here instead of going stale behind an up-to-date check (review 2026-11-01 08-03).
return RepositoryContractResources.fromSystemProperty().repositoryRoot();
}
private record ProductionSource(Path path, String text) {}
@@ -11,6 +11,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.yaml.snakeyaml.Yaml;
@@ -27,6 +28,7 @@ import org.yaml.snakeyaml.Yaml;
* <p>The registry SSOT and linked runbooks are checked-in resources. A missing resource or a
* mismatched row is a hard FAIL.
*/
@Tag("document-contract")
class BackgroundJobErrorCodeContractTest {
private static Path registry;
@@ -26,7 +26,9 @@ class BootstrapCapabilityAutoConfigurationReachabilityTest {
// idempotency executor: `composition:outbox-relay` and `composition:idempotency`, which
// the sample composes too. Tracing, metrics, domain context, pseudonymization and the
// actuator chain are `composition:service-runtime`, which proves its own registration.
"dev.caskeleton.bootstrap.autoconfigure.operation.DurableOperationConfig");
// Durable operations moved out last (07-08): `composition:durable-operation`. What is
// left is the clock every composition needs.
"dev.caskeleton.bootstrap.autoconfigure.common.BootstrapClockAutoConfiguration");
@Test
void everyBootstrapOwnedCapabilityRootIsDiscoverableByBoot() {
@@ -12,7 +12,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.yaml.snakeyaml.Yaml;
@@ -41,7 +41,6 @@ class BusinessRuleValidationContractTest {
private static List<Map<String, Object>> registryRows;
@BeforeAll
static void loadRegistry() throws Exception {
Path registry =
RepositoryContractResources.fromSystemProperty()
@@ -75,8 +74,10 @@ class BusinessRuleValidationContractTest {
assertThat(OperationalError.PRECONDITION_FAILED.category()).isEqualTo(Category.CONFLICT);
}
@Tag("document-contract")
@Test
void persistenceIntegrityCodesMapToDataIntegrityOrConflictCategory() {
void persistenceIntegrityCodesMapToDataIntegrityOrConflictCategory() throws Exception {
loadRegistry();
// C3/C4: the SQLState integrity matrix (owned by feature-persistence-failure-baseline)
// must land in DATA_INTEGRITY or CONFLICT — never INTERNAL (which would hide a client-
// correctable conflict as a server fault) and never VALIDATION.
@@ -105,8 +106,10 @@ class BusinessRuleValidationContractTest {
// ---- C5: category × retryable consistency (registry, every row) ----
@Tag("document-contract")
@Test
void deterministicClientErrorRowsAreNeverRetryable() {
void deterministicClientErrorRowsAreNeverRetryable() throws Exception {
loadRegistry();
// C5: VALIDATION / AUTHZ / NOT_FOUND are deterministic client errors — the same request
// can never succeed, so retryable=true would be a busy-loop trap. AUTH is excluded: it is
// context-dependent (e.g. AUTH_KID_UNKNOWN is retryable=true once the JWKS key set
@@ -125,8 +128,10 @@ class BusinessRuleValidationContractTest {
}
}
@Tag("document-contract")
@Test
void registryCategoriesAreAllMembersOfTheSharedEnum() {
void registryCategoriesAreAllMembersOfTheSharedEnum() throws Exception {
loadRegistry();
// The registry's category column may not drift from the 10-value Category SSOT.
for (Map<String, Object> row : registryRows) {
String category = (String) row.get("category");
@@ -140,8 +145,10 @@ class BusinessRuleValidationContractTest {
// ---- C7 / D9: client_safe_message leak scan (registry, every row) ----
@Tag("document-contract")
@Test
void noClientSafeMessageLeaksSqlConstraintOrInternals() {
void noClientSafeMessageLeaksSqlConstraintOrInternals() throws Exception {
loadRegistry();
// D9: "safe field errors only" — a client-facing message must never carry a raw SQL
// fragment, a DB constraint/index name, a SQLState code, an exception class name, or an
// internal package path. This is the registry-wide DLP gate complementing the runtime
@@ -2,11 +2,13 @@ package dev.caskeleton.bootstrap.contract;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
/**
@@ -20,6 +22,7 @@ import org.junit.jupiter.api.Test;
* the source of truth for a judgement, which is the shape of verification this repository's own
* review says to stop adding.
*/
@Tag("document-contract")
class CapabilityStatusDocumentTest {
private static final String DOCUMENT = "docs/capability-status.md";
@@ -46,12 +49,9 @@ class CapabilityStatusDocumentTest {
}
private static Path repositoryRoot() {
for (Path path = Path.of("").toAbsolutePath(); path != null; path = path.getParent()) {
if (Files.isRegularFile(path.resolve("AGENTS.md"))
&& Files.isRegularFile(path.resolve("src/settings.gradle"))) {
return path;
}
}
throw new IllegalStateException("repository root not found");
// Gradle hands the root only to the lanes that declare the repository files as inputs; the
// plain `test` lane gets none, so a test that reads the repository without a lane tag fails
// here instead of going stale behind an up-to-date check (review 2026-11-01 08-03).
return RepositoryContractResources.fromSystemProperty().repositoryRoot();
}
}
@@ -2,6 +2,7 @@ package dev.caskeleton.bootstrap.contract;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources;
import dev.caskeleton.bootstrap.contract.support.ShippedConfiguration;
import java.io.IOException;
import java.nio.file.Files;
@@ -15,6 +16,7 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
/**
@@ -97,6 +99,7 @@ class ConfigurationNamespaceContractTest {
.contains("app", "spring");
}
@Tag("repository-contract")
@Test
@DisplayName("app-bootstrap이 선언한 설정 prefix는 모두 이 계약에 기록돼 있다")
void everyBootstrapPrefixIsRecorded() throws IOException {
@@ -110,6 +113,7 @@ class ConfigurationNamespaceContractTest {
.isSubsetOf(BOOTSTRAP_PREFIXES);
}
@Tag("repository-contract")
@Test
@DisplayName("모든 leaf의 설정 prefix는 app 아래에 있다")
void everyLeafPrefixSitsUnderTheApplicationRoot() throws IOException {
@@ -148,14 +152,9 @@ class ConfigurationNamespaceContractTest {
}
private static Path repositoryRoot() {
Path candidate = Path.of("").toAbsolutePath();
while (candidate != null
&& !Files.isRegularFile(candidate.resolve("src/config/architecture/modules.json"))) {
candidate = candidate.getParent();
}
if (candidate == null) {
throw new IllegalStateException("could not locate the repository root from the test cwd");
}
return candidate;
// Gradle hands the root only to the lanes that declare the repository files as inputs; the
// plain `test` lane gets none, so a test that reads the repository without a lane tag fails
// here instead of going stale behind an up-to-date check (review 2026-11-01 08-03).
return RepositoryContractResources.fromSystemProperty().repositoryRoot();
}
}
@@ -11,7 +11,7 @@ import java.nio.file.Path;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.yaml.snakeyaml.Yaml;
@@ -34,7 +34,6 @@ class ContainerRuntimeOomContractTest {
private static Map<String, Map<String, Object>> rowsByCode;
@BeforeAll
static void loadRegistry() throws Exception {
Path registry =
RepositoryContractResources.fromSystemProperty()
@@ -70,8 +69,10 @@ class ContainerRuntimeOomContractTest {
// ---- registry-row leg ------------------------------------------------------
@Tag("document-contract")
@Test
void registryRowMatchesJvmOomEnum() {
void registryRowMatchesJvmOomEnum() throws Exception {
loadRegistry();
Map<String, Object> row = rowsByCode.get("JVM_OOM");
assertThat(row)
.as("error-codes.yaml must contain a JVM_OOM row (feature-container-runtime-contract §5)")
@@ -93,8 +94,10 @@ class ContainerRuntimeOomContractTest {
assertThat(code.retryable()).isEqualTo((boolean) row.get("retryable"));
}
@Tag("document-contract")
@Test
void registryRowHasCorrectRunbookLinkFormat() {
void registryRowHasCorrectRunbookLinkFormat() throws Exception {
loadRegistry();
Map<String, Object> row = rowsByCode.get("JVM_OOM");
assertThat(row).as("JVM_OOM row must exist").isNotNull();
@@ -103,8 +106,10 @@ class ContainerRuntimeOomContractTest {
.isEqualTo(EXPECTED_RUNBOOK_LINK);
}
@Tag("document-contract")
@Test
void runbookFileExistsWhenPresentOnDisk() {
void runbookFileExistsWhenPresentOnDisk() throws Exception {
loadRegistry();
Path runbookFile =
RepositoryContractResources.fromSystemProperty()
.requireTrackedFile("docs/runbooks/runtime-jvm-oom.md");
@@ -8,6 +8,7 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Set;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -19,6 +20,7 @@ import org.junit.jupiter.api.io.TempDir;
* leaf test. This gate owns the exact artifact catalog, strict YAML envelope, unique identities,
* and truthful repository/semantic owner provenance.
*/
@Tag("document-contract")
class ContractRegistrySchemaGovernanceTest {
private static final Set<String> EXACT_REGISTRY_FILES =
@@ -3,21 +3,30 @@ package dev.caskeleton.bootstrap.contract;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import dev.caskeleton.bootstrap.async.AsyncExecutorConfig;
import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
/** Pins the executable local-developer entrypoint and its documentation/CI guardrails. */
/**
* Pins the executable local-developer entrypoint and its documentation/CI guardrails.
*
* <p>Every test here reads the repository, so each one names its lane: workflow, Docker and Compose
* structure is {@code repository-contract} and blocks the pull request, because a release or
* signing regression must not merge; a sentence in a guidance document is {@code document-contract}
* and runs in the main stage (review 2026-11-01 08-03).
*/
class DeveloperExperienceContractTest {
private static final Path REPOSITORY_ROOT = repositoryRoot();
@@ -29,11 +38,13 @@ class DeveloperExperienceContractTest {
// spelling — a YAML parser written in bash, tested from a Java application's test suite.
@Test
@Tag("repository-contract")
void toolVersionsPinTemurin21() throws IOException {
assertThat(read(".tool-versions")).containsPattern("(?m)^java temurin-21\\.[^\\s]+$");
}
@Test
@Tag("repository-contract")
@DisplayName("로컬 기동 진입점은 네 단계를 순서대로 밟는 scripts/bootstrap-local.sh 하나다")
void theLocalBootstrapEntrypointIsOneScriptWithFourOrderedStages() throws IOException {
// given
@@ -57,6 +68,7 @@ class DeveloperExperienceContractTest {
}
@Test
@Tag("repository-contract")
void localComposeSupportsDatabaseMigrationAndPublicHealthSmoke() throws IOException {
String base = read("docker-compose.yml");
String local = read("docker-compose.local.yml");
@@ -80,6 +92,7 @@ class DeveloperExperienceContractTest {
* contract this asserts is unchanged; only the file that owns it is.
*/
@Test
@Tag("repository-contract")
void localComposePublishesTheHostPortTheCommittedDatasourceUrlTargets() throws IOException {
String datasourceUrl = envValue("APP_DATASOURCE_URL");
Matcher target = Pattern.compile("^jdbc:postgresql://([^:/]+):(\\d+)/").matcher(datasourceUrl);
@@ -106,6 +119,7 @@ class DeveloperExperienceContractTest {
}
@Test
@Tag("document-contract")
void readmeDocumentsOneFirstRunEntrypoint() throws IOException {
// The `verifyReadmeCommands` half of this is gone with the task. That gate parsed the README's
// ```bash blocks and resolved every `./gradlew`, `docker compose` and `make` token against the
@@ -123,6 +137,7 @@ class DeveloperExperienceContractTest {
}
@Test
@Tag("repository-contract")
void linkCheckIsBlockingAndUsesThePinnedLycheeAction() throws IOException {
String workflow = read(".github/workflows/link-check.yml");
@@ -130,6 +145,7 @@ class DeveloperExperienceContractTest {
}
@Test
@Tag("repository-contract")
void linkCheckTriggersAndScansTheExactDocumentationScope() throws IOException {
List<String> expectedPaths =
List.of(
@@ -179,6 +195,7 @@ class DeveloperExperienceContractTest {
}
@Test
@Tag("repository-contract")
void testcontainersReuseIsLocalOptInAndExplicitlyDisabledInCi() throws IOException {
assertThat(read("testcontainers.properties.example"))
.contains("testcontainers.reuse.enable=true");
@@ -187,6 +204,7 @@ class DeveloperExperienceContractTest {
}
@Test
@Tag("repository-contract")
void gradleWrapperIsCheckedInAndValidatedByTheOfficialAction() throws IOException {
// Twenty-four tests stood here, and every one of them tested .github/scripts/
// verify-gradle-wrapper.sh — an 799-line shell script that this suite exercised by writing
@@ -225,11 +243,13 @@ class DeveloperExperienceContractTest {
}
@Test
@Tag("repository-contract")
void dockerDependencyCacheStagesDeclareTheCompleteConfigurationRegistry() throws IOException {
assertDockerDependencyCacheContract("src/Dockerfile", read("src/Dockerfile"));
}
@Test
@Tag("repository-contract")
void dockerDependencyCacheStagesEveryIncludedBuildBeforeGradle() throws IOException {
String settings = read("src/settings.gradle");
String dockerfile = read("src/Dockerfile");
@@ -258,6 +278,7 @@ class DeveloperExperienceContractTest {
}
@Test
@Tag("repository-contract")
void architectureWorkflowSelectorsUseTheArchitectureSourceSetTask() throws IOException {
String staleSelector = ":app-bootstrap:test --tests 'dev.caskeleton.bootstrap.architecture.*'";
@@ -276,8 +297,17 @@ class DeveloperExperienceContractTest {
.as("the release workflow runs the tag-only checks through releaseCheck")
.contains("./gradlew :releaseCheck")
.doesNotContain(staleSelector);
}
assertThat(read("CLAUDE.md"))
@Test
@Tag("document-contract")
@DisplayName("루트 안내 문서는 아키텍처 suite를 그 source set의 태스크 이름으로 안내한다")
void guidanceNamesTheArchitectureSourceSetTask() throws IOException {
// when
String guidance = read("CLAUDE.md");
// then
assertThat(guidance)
.as("the operator/developer command must match the shipped architecture source set")
.contains("./gradlew :app-bootstrap:architectureTest")
.doesNotContain(
@@ -285,6 +315,7 @@ class DeveloperExperienceContractTest {
}
@Test
@Tag("repository-contract")
@DisplayName("릴리스 이미지는 서명 job 하나만 OIDC 토큰을 받아 digest를 keyless 서명하고 검증한다")
void onlyTheSigningJobHoldsAnOidcTokenAndItSignsAndVerifiesTheDigest() throws IOException {
// given
@@ -327,6 +358,7 @@ class DeveloperExperienceContractTest {
}
@Test
@Tag("repository-contract")
void everyOptionalPlatformIntegrationLaneHasAnExecutingWorkflowCaller() throws IOException {
// `grpc-operation-ledger-jpa` declares a Testcontainers PostgreSQL lane that certifies the
// atomic claim durable mutation idempotency rests on. It was registered in `strictTestLanes`,
@@ -350,6 +382,114 @@ class DeveloperExperienceContractTest {
}
@Test
@Tag("repository-contract")
@DisplayName("샘플 이미지의 의존성 단계는 릴리스 이미지와 같은 파일을 같은 순서로 복사한다")
void theSampleImageDependencyStageCopiesWhatTheReleaseImageCopies() throws IOException {
// given
String release = read("src/Dockerfile");
String sample = read("src/Dockerfile.sample");
// when
List<String> releaseCopies = dependencyStageCopies(release);
List<String> sampleCopies = dependencyStageCopies(sample);
// then
// The sample's copy of this stage once missed gradle.properties and build-logic/, so settings
// could not resolve the convention plugins and the image did not build at all (07-04).
assertThat(sampleCopies).isNotEmpty().isEqualTo(releaseCopies);
assertDockerDependencyCacheContract("src/Dockerfile.sample", sample);
}
@Test
@Tag("repository-contract")
@DisplayName("compose 종료 유예 시간은 웹 drain, async 대기, preStop, 여유를 모두 더한 값 이상이다")
void theComposeStopGraceCoversEveryShutdownWaitInSequence() throws IOException {
// given
Map<?, ?> app =
requireMap(requireMap(parseYamlMap(read("docker-compose.yml")), "services"), "app");
int webDrainSeconds = 30;
int preStopSeconds = 5;
int marginSeconds = 5;
// when
String grace = requireString(app, "stop_grace_period");
// then
// Spring finishes the lifecycle phase (the web server's graceful drain) before it destroys the
// async executor, which then waits for its queue: the two run one after the other (07-07).
assertThat(Integer.parseInt(grace.replace("s", "")))
.isGreaterThanOrEqualTo(
webDrainSeconds
+ AsyncExecutorConfig.AWAIT_TERMINATION_SECONDS
+ preStopSeconds
+ marginSeconds);
}
@Test
@Tag("repository-contract")
@DisplayName("compose는 관리 포트 9001을 호스트의 loopback에만 연다")
void composePublishesTheManagementPortOnLoopbackOnly() throws IOException {
// given
List<String> composeFiles =
List.of("docker-compose.yml", "docker-compose.dev.yml", "docker-compose.local.yml");
// when
List<String> exposed =
composeFiles.stream()
.flatMap(
file -> {
try {
return portMappings(read(file)).stream().map(port -> file + ": " + port);
} catch (IOException unreadable) {
throw new java.io.UncheckedIOException(unreadable);
}
})
.filter(mapping -> mapping.endsWith(":9001"))
.filter(mapping -> !mapping.contains(" 127.0.0.1:"))
.toList();
// then
// health, info (with build revision and capability list) and prometheus answer without
// authentication on that port; published on every interface they reach the whole LAN (07-13).
assertThat(exposed).isEmpty();
}
/**
* The port mappings of a Compose file, read as list items under a {@code ports:} key. Read as
* text because the override files use Compose's {@code !override} tag, which a plain YAML parser
* refuses.
*/
private static List<String> portMappings(String compose) {
List<String> mappings = new java.util.ArrayList<>();
boolean inPorts = false;
int portsIndent = -1;
for (String line : compose.lines().toList()) {
String trimmed = line.strip();
int indent = line.length() - line.stripLeading().length();
if (trimmed.startsWith("ports:")) {
inPorts = true;
portsIndent = indent;
continue;
}
if (inPorts && !trimmed.isEmpty() && !trimmed.startsWith("#")) {
if (indent <= portsIndent || !trimmed.startsWith("- ")) {
inPorts = false;
continue;
}
String item = trimmed.substring(2).replaceAll("\\s+#.*$", "").replace("\"", "").strip();
mappings.add(item);
}
}
return mappings;
}
private static List<String> dependencyStageCopies(String dockerfile) {
String prefix = dockerfile.substring(0, dockerfile.indexOf("./gradlew"));
return prefix.lines().filter(line -> line.startsWith("COPY ")).toList();
}
@Test
@Tag("repository-contract")
void dockerBuildConsumesOnlyTheGradleStagedExecutableJar() throws IOException {
String dockerfile = "src/Dockerfile";
String module = "app-bootstrap";
@@ -364,6 +504,7 @@ class DeveloperExperienceContractTest {
}
@Test
@Tag("repository-contract")
void dockerContractRejectsAWorkdirOverrideBeforeTheFirstGradleInvocation() throws IOException {
String dockerfile = "src/Dockerfile";
String content = read(dockerfile);
@@ -380,6 +521,7 @@ class DeveloperExperienceContractTest {
}
@Test
@Tag("repository-contract")
void dockerContractRejectsJarSelectorsRegardlessOfRunCommandPrefix() throws IOException {
String dockerfile = "src/Dockerfile";
String content = read(dockerfile);
@@ -499,13 +641,9 @@ class DeveloperExperienceContractTest {
}
private static Path repositoryRoot() {
for (Path path = Paths.get("").toAbsolutePath(); path != null; path = path.getParent()) {
if (Files.isRegularFile(path.resolve("AGENTS.md"))
&& Files.isRegularFile(path.resolve("src/settings.gradle"))) {
return path;
}
}
throw new IllegalStateException(
"repository root not found from " + Paths.get("").toAbsolutePath());
// Gradle hands the root only to the lanes that declare the repository files as inputs; the
// plain `test` lane gets none, so a test that reads the repository without a lane tag fails
// here instead of going stale behind an up-to-date check (review 2026-11-01 08-03).
return RepositoryContractResources.fromSystemProperty().repositoryRoot();
}
}
@@ -23,7 +23,7 @@ import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.slf4j.MDC;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
@@ -55,7 +55,6 @@ class DistributedTracingContractTest {
private static Map<String, Object> metricsRoot;
private static Map<String, Object> mdcRoot;
@BeforeAll
static void loadRegistries() throws Exception {
RepositoryContractResources resources = RepositoryContractResources.fromSystemProperty();
Path headersPath = resources.requireTrackedFile("docs/registries/headers.yaml");
@@ -135,8 +134,10 @@ class DistributedTracingContractTest {
* tracestate} row exists with {@code generated_if_missing: false}; AND that code agrees: {@code
* MdcKeys.TRACE_ID == "trace_id"} and {@link ResponseMeta} has a {@code traceId} component.
*/
@Tag("document-contract")
@Test
void traceparentHeaderRowMatchesCodeContract() {
void traceparentHeaderRowMatchesCodeContract() throws Exception {
loadRegistries();
@SuppressWarnings("unchecked")
List<Map<String, Object>> headers = (List<Map<String, Object>>) headersRoot.get("headers");
@@ -189,8 +190,10 @@ class DistributedTracingContractTest {
* local]}; AND registers {@link TracingSamplingRateGauge} against a {@link SimpleMeterRegistry}
* and asserts exactly one {@code tracing.sampling.rate} series exists (cardinality 1 ≤ 4).
*/
@Tag("document-contract")
@Test
void tracingSamplingRateGaugeRegistryContract() {
void tracingSamplingRateGaugeRegistryContract() throws Exception {
loadRegistries();
@SuppressWarnings("unchecked")
List<Map<String, Object>> metrics = (List<Map<String, Object>>) metricsRoot.get("metrics");
@@ -267,8 +270,10 @@ class DistributedTracingContractTest {
assertThat(MdcKeys.SPAN_ID).isEqualTo("span_id");
}
@Tag("document-contract")
@Test
void mdcKeysYamlListsTraceIdAndSpanId() {
void mdcKeysYamlListsTraceIdAndSpanId() throws Exception {
loadRegistries();
@SuppressWarnings("unchecked")
List<Map<String, Object>> keys = (List<Map<String, Object>>) mdcRoot.get("mdc_keys");
Set<String> keyNames =
@@ -8,6 +8,7 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
/**
@@ -16,6 +17,7 @@ import org.junit.jupiter.api.Test;
* <p>Reserved switches for unimplemented error-detail exposure and body logging are intentionally
* absent; profile-matrix tests must not treat nonexistent features as safety controls.
*/
@Tag("document-contract")
class EnvProfileMatrixContractTest {
@Test
@@ -12,6 +12,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.yaml.snakeyaml.Yaml;
@@ -26,6 +27,7 @@ import org.yaml.snakeyaml.Yaml;
* (405/406/412/413/414/415) are actually present in the registry — a missing row is a FAIL, never a
* silent SKIP (design record §Edge).
*/
@Tag("document-contract")
class ErrorCodeRegistryMappingTest {
private static Map<String, Integer> registryHttpStatusByCode;
@@ -10,10 +10,12 @@ import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.yaml.snakeyaml.Yaml;
@Tag("document-contract")
class HeaderRegistryRuntimeAlignmentTest {
private static List<Map<String, Object>> headers;
@@ -13,7 +13,7 @@ import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.yaml.snakeyaml.Yaml;
@@ -32,7 +32,6 @@ class LockAcquisitionTimeoutClassificationContractTest {
private static Map<String, Map<String, Object>> errorRegistryByCode;
private static List<Map<String, Object>> metricsRows;
@BeforeAll
static void loadRegistries() throws Exception {
RepositoryContractResources resources = RepositoryContractResources.fromSystemProperty();
Path errorRegistry = resources.requireTrackedFile("docs/registries/error-codes.yaml");
@@ -93,8 +92,10 @@ class LockAcquisitionTimeoutClassificationContractTest {
// ---- registry-row leg -----------------------------------------------------
@Tag("document-contract")
@Test
void registryRowAgreesWithTheEnumClassification() {
void registryRowAgreesWithTheEnumClassification() throws Exception {
loadRegistries();
Map<String, Object> row = errorRegistryByCode.get("LOCK_ACQUISITION_TIMEOUT");
assertThat(row)
.as("registry must define LOCK_ACQUISITION_TIMEOUT (feature-distributed-lock-contract D7)")
@@ -112,8 +113,10 @@ class LockAcquisitionTimeoutClassificationContractTest {
// ---- metrics-row leg ------------------------------------------------------
@Tag("document-contract")
@Test
void metricsRegistryContainsLockAcquisitionWithBoundedOutcomeTag() {
void metricsRegistryContainsLockAcquisitionWithBoundedOutcomeTag() throws Exception {
loadRegistries();
Map<String, Object> lockAcquisitionRow =
metricsRows.stream()
.filter(row -> "lock.acquisition".equals(row.get("name")))
@@ -12,7 +12,7 @@ import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.yaml.snakeyaml.Yaml;
@@ -61,7 +61,6 @@ class LockFailureClassificationContractTest {
private static Map<String, Map<String, Object>> registryByCode;
@BeforeAll
static void loadRegistry() throws Exception {
Path registry =
RepositoryContractResources.fromSystemProperty()
@@ -155,8 +154,10 @@ class LockFailureClassificationContractTest {
// ---- required registry rows agree with the classified policy (fail-closed) ----
@Tag("document-contract")
@Test
void registryRowsAgreeWithTheLockClassificationPolicy() {
void registryRowsAgreeWithTheLockClassificationPolicy() throws Exception {
loadRegistry();
RETRYABLE_LOCK_CONFLICTS.forEach(code -> assertRegistryRow(code, "CONFLICT", 409, true));
assertRegistryRow(NON_RETRYABLE_CONFLICT, "CONFLICT", 409, false);
assertRegistryRow(OPTIMISTIC_CONFLICT, "CONFLICT", 409, false);
@@ -14,7 +14,7 @@ import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
import org.springframework.boot.actuate.autoconfigure.web.server.ManagementServerProperties;
@@ -48,16 +48,16 @@ import org.yaml.snakeyaml.Yaml;
class ManagementActuatorSecurityContractTest {
// ---- Required registry cross-check ----
// Only the registry row comparison reads the repository, so only it carries the
// document-contract tag and runs in the main stage; the actuator exposure contracts below stay in
// the pull request's `test` (review 2026-11-01 08-03).
private static RepositoryContractResources repositoryResources;
private static Path registry;
private static Map<String, Map<String, Object>> rowsByCode;
@BeforeAll
static void loadRegistry() throws Exception {
private static Map<String, Map<String, Object>> loadRegistry() throws Exception {
repositoryResources = RepositoryContractResources.fromSystemProperty();
registry = repositoryResources.requireTrackedFile("docs/registries/error-codes.yaml");
rowsByCode = new LinkedHashMap<>();
Path registry = repositoryResources.requireTrackedFile("docs/registries/error-codes.yaml");
Map<String, Map<String, Object>> rowsByCode = new LinkedHashMap<>();
try (InputStream in = Files.newInputStream(registry)) {
Map<String, Object> root = new Yaml().load(in);
@SuppressWarnings("unchecked")
@@ -66,6 +66,7 @@ class ManagementActuatorSecurityContractTest {
rowsByCode.put((String) row.get("code"), row);
}
}
return rowsByCode;
}
// ---- contract-verification:management-actuator
@@ -81,8 +82,9 @@ class ManagementActuatorSecurityContractTest {
}
@Test
void actuatorForbiddenMatchesRegistryRow() {
Map<String, Object> row = rowsByCode.get("ACTUATOR_FORBIDDEN");
@Tag("document-contract")
void actuatorForbiddenMatchesRegistryRow() throws Exception {
Map<String, Object> row = loadRegistry().get("ACTUATOR_FORBIDDEN");
assertThat(row).as("error-codes.yaml must contain row ACTUATOR_FORBIDDEN").isNotNull();
assertThat(row.get("category")).as("ACTUATOR_FORBIDDEN category").isEqualTo("AUTHZ");
assertThat(((Number) row.get("http_status")).intValue())
@@ -18,8 +18,8 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.yaml.snakeyaml.Yaml;
@@ -39,7 +39,6 @@ class MetricsAlertingContractTest {
private static Map<String, Object> metricsRoot;
private static List<Map<String, Object>> metrics;
@BeforeAll
@SuppressWarnings(
"unchecked") // SnakeYAML returns untyped Object; the registry shape is fixed by the
// metrics.yaml contract
@@ -57,9 +56,11 @@ class MetricsAlertingContractTest {
// Global checks — every row
// ================================================================
@Tag("document-contract")
@Test
@DisplayName("D2: every metric name passes MetricNaming.isValidName()")
void everyMetricNameIsValidDotCase() {
void everyMetricNameIsValidDotCase() throws Exception {
loadRegistry();
for (Map<String, Object> row : metrics) {
String name = (String) row.get("name");
assertThat(MetricNaming.isValidName(name))
@@ -68,9 +69,11 @@ class MetricsAlertingContractTest {
}
}
@Tag("document-contract")
@Test
@DisplayName("D2: every metric unit is in {seconds, bytes, total}")
void everyMetricUnitIsAllowed() {
void everyMetricUnitIsAllowed() throws Exception {
loadRegistry();
for (Map<String, Object> row : metrics) {
String name = (String) row.get("name");
String unit = (String) row.get("unit");
@@ -80,12 +83,14 @@ class MetricsAlertingContractTest {
}
}
@Tag("document-contract")
@Test
@DisplayName("D8: no row has a tag whose name is in ForbiddenMetricTags.FORBIDDEN")
@SuppressWarnings(
"unchecked") // SnakeYAML returns untyped Object; the registry shape is fixed by the
// metrics.yaml contract
void noRowHasForbiddenTag() {
void noRowHasForbiddenTag() throws Exception {
loadRegistry();
for (Map<String, Object> row : metrics) {
String metricName = (String) row.get("name");
List<Map<String, Object>> tags = (List<Map<String, Object>>) row.get("tags");
@@ -102,9 +107,11 @@ class MetricsAlertingContractTest {
}
}
@Tag("document-contract")
@Test
@DisplayName("every row's required_test equals 'contract-verification:metrics-cardinality'")
void everyRowHasCorrectRequiredTest() {
void everyRowHasCorrectRequiredTest() throws Exception {
loadRegistry();
for (Map<String, Object> row : metrics) {
String name = (String) row.get("name");
assertThat(row.get("required_test"))
@@ -113,13 +120,15 @@ class MetricsAlertingContractTest {
}
}
@Tag("document-contract")
@Test
@DisplayName(
"§Cardinality Bounds: tag cardinality_limit <= CardinalityBounds.limitFor() where defined")
@SuppressWarnings(
"unchecked") // SnakeYAML returns untyped Object; the registry shape is fixed by the
// metrics.yaml contract
void tagCardinalityLimitsRespectBounds() {
void tagCardinalityLimitsRespectBounds() throws Exception {
loadRegistry();
for (Map<String, Object> row : metrics) {
String metricName = (String) row.get("name");
List<Map<String, Object>> tags = (List<Map<String, Object>>) row.get("tags");
@@ -145,12 +154,14 @@ class MetricsAlertingContractTest {
}
}
@Tag("document-contract")
@Test
@DisplayName("§P1/P2/P3: alert_severity_thresholds keys must parse via AlertSeverity.fromKey()")
@SuppressWarnings(
"unchecked") // SnakeYAML returns untyped Object; the registry shape is fixed by the
// metrics.yaml contract
void alertSeverityThresholdKeysAreValid() {
void alertSeverityThresholdKeysAreValid() throws Exception {
loadRegistry();
for (Map<String, Object> row : metrics) {
String metricName = (String) row.get("name");
Map<String, Object> thresholds = (Map<String, Object>) row.get("alert_severity_thresholds");
@@ -173,13 +184,15 @@ class MetricsAlertingContractTest {
}
}
@Tag("document-contract")
@Test
@DisplayName(
"D9: every row with histogram_buckets='slo_driven' also declares non-empty percentiles")
@SuppressWarnings(
"unchecked") // SnakeYAML returns untyped Object; the registry shape is fixed by the
// metrics.yaml contract
void sloDrivenTimersDeclarePercentiles() {
void sloDrivenTimersDeclarePercentiles() throws Exception {
loadRegistry();
for (Map<String, Object> row : metrics) {
String metricName = (String) row.get("name");
Object histBuckets = row.get("histogram_buckets");
@@ -200,9 +213,11 @@ class MetricsAlertingContractTest {
// Row-specific checks — §테스트 계약 explicit bullets
// ================================================================
@Tag("document-contract")
@Test
@DisplayName("§테스트 계약 #1: http.server.requests row exists with method/status/uri_template tags")
void httpServerRequestsRowExistsWithRequiredTags() {
void httpServerRequestsRowExistsWithRequiredTags() throws Exception {
loadRegistry();
Map<String, Object> row = findRow("http.server.requests");
assertThat(row).as("metrics.yaml must contain an 'http.server.requests' row").isNotNull();
@@ -212,13 +227,15 @@ class MetricsAlertingContractTest {
.contains("method", "status", "uri_template");
}
@Tag("document-contract")
@Test
@DisplayName(
"§테스트 계약 #2: dependency.client.requests row exists with dependency_name/dependency_type tags and P1 alert")
@SuppressWarnings(
"unchecked") // SnakeYAML returns untyped Object; the registry shape is fixed by the
// metrics.yaml contract
void dependencyClientRequestsRowExistsWithRequiredTagsAndP1Alert() {
void dependencyClientRequestsRowExistsWithRequiredTagsAndP1Alert() throws Exception {
loadRegistry();
Map<String, Object> row = findRow("dependency.client.requests");
assertThat(row).as("metrics.yaml must contain a 'dependency.client.requests' row").isNotNull();
@@ -239,13 +256,15 @@ class MetricsAlertingContractTest {
.containsKey("p1");
}
@Tag("document-contract")
@Test
@DisplayName(
"§테스트 계약 #3: hikaricp.connections.acquire row exists with outcome tag containing TIMEOUT and non-empty alerts")
@SuppressWarnings(
"unchecked") // SnakeYAML returns untyped Object; the registry shape is fixed by the
// metrics.yaml contract
void hikaricpConnectionsAcquireRowExistsWithTimeoutOutcome() {
void hikaricpConnectionsAcquireRowExistsWithTimeoutOutcome() throws Exception {
loadRegistry();
Map<String, Object> row = findRow("hikaricp.connections.acquire");
assertThat(row)
.as(
@@ -274,12 +293,14 @@ class MetricsAlertingContractTest {
.isNotEmpty();
}
@Tag("document-contract")
@Test
@DisplayName("every row owned by this branch has non-empty alert_severity_thresholds")
@SuppressWarnings(
"unchecked") // SnakeYAML returns untyped Object; the registry shape is fixed by the
// metrics.yaml contract
void everyBranchOwnedRowHasAlertSeverityThresholds() {
void everyBranchOwnedRowHasAlertSeverityThresholds() throws Exception {
loadRegistry();
for (Map<String, Object> row : metrics) {
if (!"feature-metrics-alerting-contract".equals(row.get("owner_branch"))) {
continue;
@@ -354,10 +375,12 @@ class MetricsAlertingContractTest {
.isNull();
}
@Tag("document-contract")
@Test
@DisplayName(
"registry↔filter coverage: every owned slo_driven timer in metrics.yaml is configured by MetricsDistributionMeterFilter")
void everyOwnedSloDrivenTimerIsConfiguredByDistributionFilter() {
void everyOwnedSloDrivenTimerIsConfiguredByDistributionFilter() throws Exception {
loadRegistry();
var filter = new MetricsDistributionMeterFilter();
for (Map<String, Object> row : metrics) {
@@ -2,6 +2,7 @@ package dev.caskeleton.bootstrap.contract;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources;
import dev.caskeleton.shared.error.Category;
import dev.caskeleton.shared.error.ClientErrorMessages;
import java.io.IOException;
@@ -16,6 +17,7 @@ import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
@@ -35,6 +37,7 @@ import org.yaml.snakeyaml.constructor.SafeConstructor;
* shared-contract} is Java-stdlib-only by policy and this repository already parses the same
* registry here for the runbook coverage contract.
*/
@Tag("document-contract")
class OperationalErrorRegistryContractTest {
private static final String REGISTRY = "docs/registries/error-codes.yaml";
@@ -161,12 +164,9 @@ class OperationalErrorRegistryContractTest {
}
private static Path repositoryRoot() {
for (Path path = Path.of("").toAbsolutePath(); path != null; path = path.getParent()) {
if (Files.isRegularFile(path.resolve("AGENTS.md"))
&& Files.isRegularFile(path.resolve("src/settings.gradle"))) {
return path;
}
}
throw new IllegalStateException("repository root not found");
// Gradle hands the root only to the lanes that declare the repository files as inputs; the
// plain `test` lane gets none, so a test that reads the repository without a lane tag fails
// here instead of going stale behind an up-to-date check (review 2026-11-01 08-03).
return RepositoryContractResources.fromSystemProperty().repositoryRoot();
}
}
@@ -18,7 +18,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
@@ -65,7 +65,6 @@ class PersistenceFailureMappingContractTest {
private static Map<String, Map<String, Object>> registryByCode;
@BeforeAll
static void loadRegistry() throws Exception {
Path registry =
RepositoryContractResources.fromSystemProperty()
@@ -102,8 +101,10 @@ class PersistenceFailureMappingContractTest {
// ---- each classified code agrees with the required registry row ----
@Tag("document-contract")
@Test
void everyClassifiedCodeAgreesWithTheRegistryRow() {
void everyClassifiedCodeAgreesWithTheRegistryRow() throws Exception {
loadRegistry();
MATRIX.forEach(
(sqlState, expected) -> {
Map<String, Object> row = registryByCode.get(expected.code());
@@ -12,6 +12,7 @@ import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.regex.Pattern;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
@@ -108,6 +109,7 @@ class PiiTokenBodyForbiddenContractTest {
.doesNotContain("eyJhbGciOiJIUzI1NiInPayload");
}
@Tag("repository-contract")
@Test
void requestLoggingHasNoBodyCapturePath() throws IOException {
Path filter =
@@ -2,11 +2,11 @@ package dev.caskeleton.bootstrap.contract;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources;
import dev.caskeleton.bootstrap.contract.support.ShippedConfiguration;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
@@ -17,6 +17,7 @@ import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
@@ -40,6 +41,7 @@ import org.yaml.snakeyaml.constructor.SafeConstructor;
* test guards, is the wiring between them drifting — a profile quietly changing vendor, or local
* regaining a migration expectation it cannot satisfy.
*/
@Tag("repository-contract")
class ProfileSeparationContractTest {
private static final Path REPOSITORY_ROOT = repositoryRoot();
@@ -177,14 +179,10 @@ class ProfileSeparationContractTest {
}
private static Path repositoryRoot() {
for (Path path = Paths.get("").toAbsolutePath(); path != null; path = path.getParent()) {
if (Files.isRegularFile(path.resolve("AGENTS.md"))
&& Files.isRegularFile(path.resolve("src/settings.gradle"))) {
return path;
}
}
throw new IllegalStateException(
"repository root not found from " + Paths.get("").toAbsolutePath());
// Gradle hands the root only to the lanes that declare the repository files as inputs; the
// plain `test` lane gets none, so a test that reads the repository without a lane tag fails
// here instead of going stale behind an up-to-date check (review 2026-11-01 08-03).
return RepositoryContractResources.fromSystemProperty().repositoryRoot();
}
/**
@@ -12,7 +12,7 @@ import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.yaml.snakeyaml.Yaml;
@@ -45,7 +45,6 @@ class RepositoryAccessCapabilityRegistryTest {
private static Set<String> registryCapabilityNames;
@BeforeAll
static void loadRegistry() throws Exception {
Path registry =
RepositoryContractResources.fromSystemProperty()
@@ -75,8 +74,10 @@ class RepositoryAccessCapabilityRegistryTest {
}
}
@Tag("document-contract")
@Test
void registryCapabilityNamesMatchTheAsBuiltModelOneToOne() {
void registryCapabilityNamesMatchTheAsBuiltModelOneToOne() throws Exception {
loadRegistry();
Set<String> expected = asBuiltVocabulary();
assertThat(registryCapabilityNames)
@@ -15,6 +15,7 @@ import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.yaml.snakeyaml.Yaml;
@@ -45,6 +46,7 @@ import org.yaml.snakeyaml.Yaml;
* <p>{@code template.md} is excluded from coverage and stub enforcement — it is the canonical
* runbook template, not a real runbook.
*/
@Tag("document-contract")
class RunbookCoverageContractTest {
/**
@@ -0,0 +1,108 @@
package dev.caskeleton.bootstrap.contract;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
/**
* The sample keeps the default composition's runtime defaults, so a number measured on the sample —
* thread count, pool wait — says something about the composition a service ships (09-08). It reads
* two configuration files, so it runs in the pull-request {@code repository-contract} lane (08-03).
*/
@Tag("repository-contract")
class SampleRuntimeDefaultsContractTest {
private static final Path REPOSITORY_ROOT = repositoryRoot();
private static final Pattern DEFAULT = Pattern.compile("^\\$\\{[A-Z0-9_]+:(.*)}$");
@Test
@DisplayName("샘플은 가상 스레드와 앱 로그 레벨 기본값을 기본 조합과 같게 둔다")
void theSampleKeepsTheDefaultCompositionRuntimeDefaults() throws IOException {
// given
Map<String, Object> bootstrap = new LinkedHashMap<>();
flatten("", load("src/app-bootstrap/src/main/resources/application.yml"), bootstrap);
flatten("", load("src/app-bootstrap/src/main/resources/config/observability.yml"), bootstrap);
Map<String, Object> sample = new LinkedHashMap<>();
flatten("", load("src/sample-portfolio/src/main/resources/application.yml"), sample);
// when
Map<String, String> differing = new LinkedHashMap<>();
for (String key :
new String[] {"spring.threads.virtual.enabled", "logging.level.dev.caskeleton"}) {
String expected = defaultOf(bootstrap.get(key));
String actual = defaultOf(sample.get(key));
if (actual != null && !actual.equals(expected)) {
differing.put(key, actual + " (default composition: " + expected + ")");
}
}
// then
assertThat(differing).isEmpty();
}
@Test
@DisplayName("샘플은 persistence-jpa 모듈의 풀 대기 시간 기본값을 덮어쓰지 않는다")
void theSampleDoesNotOverrideTheModulePoolWait() throws IOException {
// given
Map<String, Object> sample = new LinkedHashMap<>();
flatten("", load("src/sample-portfolio/src/main/resources/application.yml"), sample);
// when
Object connectionTimeout = sample.get("spring.datasource.hikari.connection-timeout");
// then
// The module's 5000 ms is a fail-fast decision; the sample's 30000 made a dry pool wait six
// times longer there than in the default composition.
assertThat(connectionTimeout).isNull();
}
private static String defaultOf(Object value) {
if (value == null) {
return null;
}
String text = String.valueOf(value).trim();
Matcher matcher = DEFAULT.matcher(text);
return matcher.matches() ? matcher.group(1) : text;
}
private static Map<?, ?> load(String relative) throws IOException {
LoaderOptions options = new LoaderOptions();
options.setMaxAliasesForCollections(0);
Object first =
new Yaml(new SafeConstructor(options))
.loadAll(Files.readString(REPOSITORY_ROOT.resolve(relative)))
.iterator()
.next();
assertThat(first).as(relative).isInstanceOf(Map.class);
return (Map<?, ?>) first;
}
private static void flatten(String prefix, Map<?, ?> map, Map<String, Object> into) {
map.forEach(
(key, value) -> {
String name = prefix.isEmpty() ? String.valueOf(key) : prefix + "." + key;
if (value instanceof Map<?, ?> child) {
flatten(name, child, into);
} else {
into.put(name, value);
}
});
}
private static Path repositoryRoot() {
return RepositoryContractResources.fromSystemProperty().repositoryRoot();
}
}
@@ -12,6 +12,7 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.yaml.snakeyaml.Yaml;
@@ -28,6 +29,7 @@ import org.yaml.snakeyaml.Yaml;
* Mirrors the {@code RepositoryAccessCapabilityRegistryTest} / {@code ErrorCodeRegistryMappingTest}
* registry-drift pattern.
*/
@Tag("document-contract")
class SecretsClassificationRegistryTest {
private static final Set<String> VALID_TIERS =
@@ -7,6 +7,7 @@ import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
/**
@@ -19,6 +20,7 @@ import org.junit.jupiter.api.Test;
* <p>{@code src/.env} is the committed runtime defaults file. Missing or unreadable defaults are a
* hard contract failure.
*/
@Tag("repository-contract")
class SqlLoggingForbiddenContractTest {
private Properties loadEnv() throws Exception {
@@ -12,6 +12,8 @@ import java.util.LinkedHashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
/**
@@ -41,6 +43,7 @@ class StructuredLogFieldContractTest {
private static final Set<String> REQUIRED_CORRELATION_FIELDS =
Set.of("request_id", "trace_id", "correlation_id");
@Tag("document-contract")
@Test
void structuredAppenderEmitsOnlyRegisteredSnakeCaseFields() throws IOException {
Set<String> emittedFields = includeMdcKeyNames();
@@ -70,18 +73,31 @@ class StructuredLogFieldContractTest {
}
@Test
void logbackEarlyPropertiesDoNotResolveApplicationYamlPlaceholders() throws IOException {
@DisplayName("Logback은 로깅 설정을 app.logging.* 한 곳에서 읽고, 프로필·앱 이름은 env 이름으로 읽는다")
void logbackReadsLoggingKnobsFromTheSettingsTreeAndIdentityFromTheEnvironment()
throws IOException {
// given
String logback = logbackText();
// when
boolean readsLoggingVariablesDirectly = logback.contains("source=\"APP_LOG_");
// then
// The logging knobs are springProperty reads of the Spring Environment, so app.logging.* in a
// profile file or on the command line reaches Logback the same way APP_LOG_* does through the
// YAML mapping (07-06). Both spellings are read at the same moment, so neither sees a value
// that arrives later than Logback's initialisation.
assertThat(readsLoggingVariablesDirectly).isFalse();
assertThat(logback)
.contains("source=\"app.logging.file.enabled\"")
.contains("source=\"app.logging.sampling-rate\"");
// The profile is corrected after resolution by ResolvedProfileLoggingContextListener, and the
// early value must not be read from spring.profiles.active, which is empty at that point.
assertThat(logback)
.as("Logback initializes before dotenv-backed application.yml placeholders are reliable")
.doesNotContain("source=\"spring.application.name\"")
.doesNotContain("source=\"spring.profiles.active\"")
.doesNotContain("source=\"app.logging.");
assertThat(logback)
.contains("source=\"APP_NAME\"")
.contains("source=\"SPRING_PROFILES_ACTIVE\"")
.contains("source=\"APP_LOG_FILE_ENABLED\"");
.contains("source=\"SPRING_PROFILES_ACTIVE\"");
}
/** Distinct {@code <includeMdcKeyName>} values from the structured JSON appenders. */
@@ -2,11 +2,13 @@ package dev.caskeleton.bootstrap.contract.graphql;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
/**
@@ -28,6 +30,7 @@ import org.junit.jupiter.api.Test;
* /graphql} and reads the body rather than the status, because a failed resolution is a {@code 200}
* carrying an {@code errors} array.
*/
@Tag("repository-contract")
class GraphQlResolverReachabilityTest {
@Test
@@ -77,14 +80,9 @@ class GraphQlResolverReachabilityTest {
}
private static Path repositoryRoot() {
Path candidate = Path.of("").toAbsolutePath();
while (candidate != null
&& !Files.isRegularFile(candidate.resolve("src/config/architecture/modules.json"))) {
candidate = candidate.getParent();
}
if (candidate == null) {
throw new IllegalStateException("could not locate the repository root from the test cwd");
}
return candidate;
// Gradle hands the root only to the lanes that declare the repository files as inputs; the
// plain `test` lane gets none, so a test that reads the repository without a lane tag fails
// here instead of going stale behind an up-to-date check (review 2026-11-01 08-03).
return RepositoryContractResources.fromSystemProperty().repositoryRoot();
}
}
@@ -2,6 +2,7 @@ package dev.caskeleton.bootstrap.contract.messaging;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
@@ -10,6 +11,7 @@ import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
/**
@@ -35,6 +37,7 @@ import org.junit.jupiter.api.Test;
* and the starter, which is the boundary working. A test that could see both would be evidence the
* boundary had gone.
*/
@Tag("repository-contract")
class MessagingAuthorityContractTest {
private static final Pattern MESSAGING_PREFIX =
@@ -143,15 +146,10 @@ class MessagingAuthorityContractTest {
}
private static Path repositoryRoot() {
Path candidate = Path.of("").toAbsolutePath();
while (candidate != null
&& !Files.isRegularFile(candidate.resolve("src/config/architecture/modules.json"))) {
candidate = candidate.getParent();
}
if (candidate == null) {
throw new IllegalStateException("could not locate the repository root from the test cwd");
}
return candidate;
// Gradle hands the root only to the lanes that declare the repository files as inputs; the
// plain `test` lane gets none, so a test that reads the repository without a lane tag fails
// here instead of going stale behind an up-to-date check (review 2026-11-01 08-03).
return RepositoryContractResources.fromSystemProperty().repositoryRoot();
}
private record ProductionSource(Path path, String text) {}
@@ -2,6 +2,7 @@ package dev.caskeleton.bootstrap.contract.messaging;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
@@ -16,6 +17,7 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
/**
@@ -41,6 +43,7 @@ import org.junit.jupiter.api.Test;
* composition boundary, where the container constructs the types rather than an adopter naming
* them, and that boundary is where the family policy already confines them.
*/
@Tag("repository-contract")
class MessagingPublicSurfaceContractTest {
/**
@@ -375,14 +378,9 @@ class MessagingPublicSurfaceContractTest {
}
private static Path repositoryRoot() {
Path candidate = Path.of("").toAbsolutePath();
while (candidate != null
&& !Files.isRegularFile(candidate.resolve("src/config/architecture/modules.json"))) {
candidate = candidate.getParent();
}
if (candidate == null) {
throw new IllegalStateException("the repository root is not above the working directory");
}
return candidate;
// Gradle hands the root only to the lanes that declare the repository files as inputs; the
// plain `test` lane gets none, so a test that reads the repository without a lane tag fails
// here instead of going stale behind an up-to-date check (review 2026-11-01 08-03).
return RepositoryContractResources.fromSystemProperty().repositoryRoot();
}
}
@@ -13,6 +13,7 @@ import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.yaml.snakeyaml.Yaml;
@@ -21,6 +22,7 @@ import org.yaml.snakeyaml.Yaml;
* outbox.pending.size} allowed_values, and {@code OUTBOX_*} 2 error codes ↔ {@code
* error-codes.yaml} category/retryable.
*/
@Tag("document-contract")
class OutboxStatusRegistryContractTest {
private static Map<String, Object> metricsRoot;
@@ -7,7 +7,15 @@ import java.nio.file.Path;
import java.util.List;
import java.util.Objects;
/** Resolves checked-in repository resources for fail-closed contract tests. */
/**
* Resolves checked-in repository resources for fail-closed contract tests.
*
* <p>Gradle passes the root only to the two lanes that declare the files they read as inputs:
* {@code documentContractTest} (tag {@code document-contract}, main stage) and {@code
* repositoryContractTest} (tag {@code repository-contract}, pull request). The plain {@code test}
* lane gets no root, so an untagged test that reads the repository fails here rather than passing
* on a stale up-to-date result (review 2026-11-01 08-03).
*/
public final class RepositoryContractResources {
public static final String ROOT_PROPERTY = "ca.repository.root";
@@ -36,7 +44,10 @@ public final class RepositoryContractResources {
String configuredRoot = System.getProperty(ROOT_PROPERTY);
if (configuredRoot == null || configuredRoot.isBlank()) {
throw new IllegalStateException(
"Required system property '" + ROOT_PROPERTY + "' is missing or blank");
"Required system property '"
+ ROOT_PROPERTY
+ "' is missing or blank. Only the document-contract and repository-contract lanes"
+ " receive it: tag a test that reads the repository with one of the two.");
}
try {
return new RepositoryContractResources(Path.of(configuredRoot));
@@ -6,6 +6,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -25,6 +26,7 @@ class RepositoryContractResourcesTest {
}
@Test
@Tag("repository-contract")
void gradleInjectsTheCanonicalRepositoryRoot() {
RepositoryContractResources resources = RepositoryContractResources.fromSystemProperty();
@@ -0,0 +1,91 @@
package dev.caskeleton.bootstrap.logging;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.mock.env.MockEnvironment;
class LoggingConfigurationRuleTest {
private final LoggingConfigurationRule rule = new LoggingConfigurationRule();
@Test
@DisplayName("기본값 그대로면 위반이 없다")
void theShippedDefaultsHaveNoViolation() {
// given
MockEnvironment environment =
new MockEnvironment()
.withProperty("app.logging.file.enabled", "false")
.withProperty("app.logging.async.enabled", "true")
.withProperty("app.logging.async.queue-size", "512")
.withProperty("app.logging.async.discarding-threshold", "20")
.withProperty("app.logging.json.timezone", "UTC")
.withProperty("app.logging.json.logger-name-length", "0")
.withProperty("app.logging.sampling-rate", "1.0");
// when
List<String> violations = rule.violations(environment);
// then
assertThat(violations).isEmpty();
}
@Test
@DisplayName("파일 로그를 켰는데 경로가 비고 보관 일수가 0이면 둘 다 env 키 이름으로 보고한다")
void fileLoggingWithABlankPathAndZeroHistoryReportsBoth() {
// given
MockEnvironment environment =
new MockEnvironment()
.withProperty("app.logging.file.enabled", "true")
.withProperty("app.logging.file.path", " ")
.withProperty("app.logging.file.max-history", "0");
// when
List<String> violations = rule.violations(environment);
// then
assertThat(violations)
.anyMatch(violation -> violation.startsWith("APP_LOG_FILE_PATH"))
.anyMatch(violation -> violation.startsWith("APP_LOG_FILE_MAX_HISTORY"));
}
@Test
@DisplayName("파일 로그가 꺼져 있으면 파일 설정 값은 보지 않는다")
void fileSettingsAreIgnoredWhileFileLoggingIsOff() {
// given
MockEnvironment environment =
new MockEnvironment()
.withProperty("app.logging.file.enabled", "false")
.withProperty("app.logging.file.max-history", "0");
// when
List<String> violations = rule.violations(environment);
// then
assertThat(violations).isEmpty();
}
@Test
@DisplayName("비동기 큐 크기 0, 잘못된 시간대, 범위 밖 샘플링 비율을 모두 한 번에 보고한다")
void everyInvalidValueIsReportedAtOnce() {
// given
MockEnvironment environment =
new MockEnvironment()
.withProperty("app.logging.async.enabled", "true")
.withProperty("app.logging.async.queue-size", "0")
.withProperty("app.logging.json.timezone", "Mars/Base")
.withProperty("app.logging.sampling-rate", "1.5");
// when
List<String> violations = rule.violations(environment);
// then
assertThat(violations)
.hasSize(3)
.anyMatch(violation -> violation.startsWith("APP_LOG_ASYNC_QUEUE_SIZE"))
.anyMatch(violation -> violation.startsWith("APP_LOG_JSON_TIMEZONE"))
.anyMatch(violation -> violation.startsWith("APP_LOG_SAMPLING_RATE"));
}
}
@@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -14,6 +15,7 @@ import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
/**
@@ -30,6 +32,7 @@ import org.junit.jupiter.api.Test;
* widens both the build and the registry in the same change, which is the review this exists to
* force; freezing the list at zero would only move the argument to this file.
*/
@Tag("repository-contract")
class MongoRegistryPermissionParityTest {
private static final String MODULE_ID = "adapter-outbound-persistence-mongo";
@@ -108,15 +111,9 @@ class MongoRegistryPermissionParityTest {
}
private static Path repositoryRoot() {
Path directory = Path.of("").toAbsolutePath();
while (directory != null
&& !Files.isRegularFile(directory.resolve(Path.of("src", "settings.gradle")))) {
directory = directory.getParent();
}
if (directory == null) {
throw new AssertionError(
"cannot locate the repository root from " + Path.of("").toAbsolutePath());
}
return directory;
// Gradle hands the root only to the lanes that declare the repository files as inputs; the
// plain `test` lane gets none, so a test that reads the repository without a lane tag fails
// here instead of going stale behind an up-to-date check (review 2026-11-01 08-03).
return RepositoryContractResources.fromSystemProperty().repositoryRoot();
}
}
@@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -12,6 +13,7 @@ import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
/**
@@ -27,6 +29,7 @@ import org.junit.jupiter.api.Test;
* tail wagging the dog. They now sit under {@code experimental_contracts}, which this test does not
* read, and {@code contracts} means "blocking, and therefore must exist".
*/
@Tag("repository-contract")
class ReleaseManifestTaskExistenceTest {
private static final Pattern REGISTERED_TASK =
@@ -114,14 +117,9 @@ class ReleaseManifestTaskExistenceTest {
}
private static Path repositoryRoot() {
Path candidate = Path.of("").toAbsolutePath();
while (candidate != null
&& !Files.isRegularFile(candidate.resolve("src/config/architecture/modules.json"))) {
candidate = candidate.getParent();
}
if (candidate == null) {
throw new IllegalStateException("could not locate the repository root from the test cwd");
}
return candidate;
// Gradle hands the root only to the lanes that declare the repository files as inputs; the
// plain `test` lane gets none, so a test that reads the repository without a lane tag fails
// here instead of going stale behind an up-to-date check (review 2026-11-01 08-03).
return RepositoryContractResources.fromSystemProperty().repositoryRoot();
}
}
@@ -5,27 +5,30 @@ import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.support.startup.RequiredProductionSecrets;
import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException;
import dev.caskeleton.adapter.outbound.support.startup.StartupRuleAutoConfiguration;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
/**
* Contract test for the secret/config-source startup fail-fast guard
* (feature-secrets-config-source-contract §2 / C1). Pairs with the {@link SecretSourceValidator}
* runtime mechanism so a regression in either the {@code __LOCAL_DEV_} sentinel check (D9) or the
* required-secret-presence check (§테스트 계약) fails the build. Mirrors the {@code
* StartupSafetyValidatorTest} {@code ApplicationContextRunner} pattern.
* required-secret-presence check (§테스트 계약) fails the build. Runs the production wiring ({@link
* SecretSourceConfig}) under support's startup-rule runner, as the application does.
*/
class SecretSourceValidatorTest {
private final ApplicationContextRunner runner =
new ApplicationContextRunner().withUserConfiguration(ValidatorConfig.class);
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(StartupRuleAutoConfiguration.class))
.withUserConfiguration(SecretSourceConfig.class);
/** All required prod secrets set to real (non-sentinel) values. */
private static String[] allRequiredSecretsPresent() {
@@ -191,17 +194,55 @@ class SecretSourceValidatorTest {
.run(context -> assertThat(context).hasNotFailed());
}
@Configuration
static class ValidatorConfig {
// ---- timing: before any other singleton exists (07-02) -----------------------------------
@Test
@DisplayName("prod에서 비밀값이 비어 있으면 다른 싱글턴을 만들기 전에 기동이 실패한다")
void aMissingProdSecretFailsTheBootBeforeAnyOtherSingletonIsCreated() {
// given
AtomicInteger otherSingletons = new AtomicInteger();
// when
runner
.withBean("databaseClient", Object.class, () -> otherSingletons.incrementAndGet())
.withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("prod"))
.run(
context -> {
// then
assertThat(context.getStartupFailure())
.isInstanceOf(StartupFailureException.class)
.hasMessageContaining("APP_PRIVACY_PSEUDONYMIZATION_SALT is missing/blank");
assertThat(otherSingletons).hasValue(0);
});
}
@Test
@DisplayName("prod에서 모듈이 기여한 비밀값이 비어 있으면 다른 싱글턴을 만들기 전에 기동이 실패한다")
void aMissingContributedSecretFailsTheBootBeforeAnyOtherSingletonIsCreated() {
// given
AtomicInteger otherSingletons = new AtomicInteger();
// when
runner
.withUserConfiguration(ModuleSecretConfig.class)
.withBean("databaseClient", Object.class, () -> otherSingletons.incrementAndGet())
.withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("prod"))
.withPropertyValues(allRequiredSecretsPresent())
.run(
context -> {
// then
assertThat(context.getStartupFailure())
.isInstanceOf(StartupFailureException.class)
.hasMessageContaining("APP_MODULE_KEY is missing/blank");
assertThat(otherSingletons).hasValue(0);
});
}
@Configuration(proxyBeanMethods = false)
static class ModuleSecretConfig {
@Bean
SecretSourceValidator secretSourceValidator(
ConfigurableEnvironment environment,
ObjectProvider<RequiredProductionSecrets> contributed) {
// Default backend (ENVIRONMENT) — the presence check resolves through the port.
return new SecretSourceValidator(
environment,
SecretSourceFactory.create(SecretSourceStrategy.ENVIRONMENT, environment),
contributed.orderedStream().toList());
static RequiredProductionSecrets moduleSecrets() {
return environment -> List.of("APP_MODULE_KEY");
}
}
}
@@ -4,11 +4,13 @@ import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException;
import dev.caskeleton.adapter.outbound.support.startup.StartupRuleAutoConfiguration;
import dev.caskeleton.application.lock.DistributedLockPort;
import dev.caskeleton.bootstrap.settings.RuntimeSafetySettings;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.assertj.AssertableApplicationContext;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
@@ -23,7 +25,9 @@ import org.springframework.context.annotation.Configuration;
class StartupSafetyValidatorTest {
private final ApplicationContextRunner runner =
new ApplicationContextRunner().withUserConfiguration(ValidatorConfig.class);
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(StartupRuleAutoConfiguration.class))
.withUserConfiguration(ValidatorConfig.class);
@Test
void multiInstanceEnabledWithMissingDistributedLockProviderFailsStartup() {
@@ -62,11 +66,44 @@ class StartupSafetyValidatorTest {
});
}
@Test
@DisplayName("app.runtime 아래 오타 키는 무시되지 않고 기동을 실패시킨다")
void aMisspelledRuntimeKeyFailsStartup() {
// when
runner
.withPropertyValues("app.runtime.multi-instance-enabeld=true")
.run(
context -> {
// then
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.hasStackTraceContaining("multi-instance-enabeld");
});
}
@Test
void multiInstanceDisabledIsAllowed() {
runner.run(context -> assertThat(context).hasNotFailed());
}
@Test
@DisplayName("다중 인스턴스인데 분산 락이 없으면 다른 싱글턴을 만들기 전에 종료 코드 72로 기동이 실패한다")
void aMissingLockProviderFailsTheBootBeforeAnyOtherSingletonIsCreated() {
// given
AtomicInteger otherSingletons = new AtomicInteger();
// when
runner
.withBean("databaseClient", Object.class, () -> otherSingletons.incrementAndGet())
.withPropertyValues("app.runtime.multi-instance-enabled=true")
.run(
context -> {
// then
assertThat(startupFailure(context).getExitCode()).isEqualTo(72);
assertThat(otherSingletons).hasValue(0);
});
}
private static StartupFailureException startupFailure(AssertableApplicationContext context) {
Throwable failure = context.getStartupFailure();
while (failure != null && !(failure instanceof StartupFailureException)) {
@@ -76,13 +113,11 @@ class StartupSafetyValidatorTest {
return (StartupFailureException) failure;
}
@Configuration
@EnableConfigurationProperties(RuntimeSafetySettings.class)
@Configuration(proxyBeanMethods = false)
static class ValidatorConfig {
@Bean
StartupSafetyValidator startupSafetyValidator(
RuntimeSafetySettings settings, ListableBeanFactory beanFactory) {
return new StartupSafetyValidator(settings, beanFactory);
static StartupSafetyValidator startupSafetyValidator(ListableBeanFactory beanFactory) {
return new StartupSafetyValidator(beanFactory);
}
}
@@ -49,8 +49,9 @@ class StartupOrderContractTest {
@Test
void validationAndDefaultingBandIsStrictlyOrdered() {
assertThat(StartupOrder.RUNTIME_ENVIRONMENT_PROFILE).isLessThan(StartupOrder.TRACING_SAMPLING);
assertThat(StartupOrder.TRACING_SAMPLING).isEqualTo(Ordered.LOWEST_PRECEDENCE);
assertThat(StartupOrder.RUNTIME_ENVIRONMENT_PROFILE)
.isLessThan(StartupOrder.TRACING_PROPERTIES);
assertThat(StartupOrder.TRACING_PROPERTIES).isEqualTo(Ordered.LOWEST_PRECEDENCE);
}
private static Map<String, Integer> registeredEnvironmentPostProcessorOrders() throws Exception {
@@ -2,12 +2,13 @@ package dev.caskeleton.bootstrap.security;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources;
import dev.caskeleton.bootstrap.contract.support.ShippedConfiguration;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
@@ -27,6 +28,7 @@ import org.springframework.mock.env.MockEnvironment;
* which is the failure arriving in the least useful place. The allowlist is derived from the base
* path now; this holds it derived.
*/
@Tag("repository-contract")
class PublicHealthPathAgreementTest {
@Test
@@ -92,14 +94,9 @@ class PublicHealthPathAgreementTest {
}
private static Path repositoryRoot() {
Path candidate = Path.of("").toAbsolutePath();
while (candidate != null
&& !Files.isRegularFile(candidate.resolve("src/config/architecture/modules.json"))) {
candidate = candidate.getParent();
}
if (candidate == null) {
throw new IllegalStateException("could not locate the repository root from the test cwd");
}
return candidate;
// Gradle hands the root only to the lanes that declare the repository files as inputs; the
// plain `test` lane gets none, so a test that reads the repository without a lane tag fails
// here instead of going stale behind an up-to-date check (review 2026-11-01 08-03).
return RepositoryContractResources.fromSystemProperty().repositoryRoot();
}
}
@@ -2,19 +2,14 @@ package dev.caskeleton.bootstrap.settings;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.boot.validation.autoconfigure.ValidationAutoConfiguration;
import org.springframework.context.annotation.Configuration;
class BootstrapSettingsTest {
private final ApplicationContextRunner runner =
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class))
.withUserConfiguration(EnableProperties.class);
new ApplicationContextRunner().withUserConfiguration(BootstrapSettingsConfig.class);
@Test
void appNameValidBinds() {
@@ -48,7 +43,17 @@ class BootstrapSettingsTest {
});
}
@Configuration
@EnableConfigurationProperties(BootstrapSettings.class)
static class EnableProperties {}
@Test
@DisplayName("app.bootstrap 아래 오타 키는 무시되지 않고 기동을 실패시킨다")
void aMisspelledKeyFailsStartup() {
// when
runner
.withPropertyValues("app.bootstrap.app-name=ca-skeleton", "app.bootstrap.app-nmae=typo")
.run(
context -> {
// then
assertThat(context).hasFailed();
assertThat(context.getStartupFailure()).hasStackTraceContaining("app-nmae");
});
}
}
@@ -1,132 +0,0 @@
package dev.caskeleton.bootstrap.settings;
import static org.assertj.core.api.Assertions.assertThat;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Configuration;
/**
* Verifies the warn-and-default validation policy of {@link LoggingSettings}.
*
* <p>Warnings are asserted via a logback {@link ListAppender} attached directly to the settings
* package logger rather than Spring's {@code CapturedOutput}. Reason: {@code LoggingSettings} emits
* warnings through SLF4J, and when the full app-bootstrap suite has already initialised logback
* with the async console appender ({@code ASYNC_CONSOLE} in {@code logback-spring.xml}), the
* warning is written to stdout by the async worker thread. A synchronous {@code
* CapturedOutput.getOut()} read right after {@code .run(...)} then races that flush and fails
* intermittently (passes in isolation, fails inside the full suite). A {@code ListAppender} bound
* to the logger receives each event synchronously on the logging thread, independent of appender
* topology, so the assertion is deterministic. This unit boundary also matches the record's real
* responsibility — "did it warn?" — not "did logback route it to a console".
*/
class LoggingSettingsTest {
private static final String SETTINGS_LOGGER = "dev.caskeleton.bootstrap.runtime";
private final ApplicationContextRunner runner =
new ApplicationContextRunner().withUserConfiguration(EnableProperties.class);
private Logger settingsLogger;
private ListAppender<ILoggingEvent> warnings;
@BeforeEach
void attachWarningCapture() {
settingsLogger = (Logger) LoggerFactory.getLogger(SETTINGS_LOGGER);
warnings = new ListAppender<>();
warnings.start();
settingsLogger.addAppender(warnings);
// Ensure WARN passes regardless of the level logback was left at by prior tests.
settingsLogger.setLevel(Level.WARN);
}
@AfterEach
void detachWarningCapture() {
settingsLogger.detachAppender(warnings);
warnings.stop();
}
@Test
void badTimezoneWarnsAndFallsBack() {
runner
.withPropertyValues(
"app.logging.json.timezone=Mars/Olympus_Mons",
"app.logging.json.timestamp-pattern=yyyy-MM-dd'T'HH:mm:ss.SSSXXX",
"app.logging.json.include-caller-data=false",
"app.logging.json.logger-name-length=0",
"app.logging.async.enabled=false",
"app.logging.file.enabled=false")
.run(
context -> {
assertThat(context).hasNotFailed();
LoggingSettings settings = context.getBean(LoggingSettings.class);
assertThat(settings.json().timezone()).isEqualTo("UTC");
assertThat(warningMessages())
.anyMatch(
m ->
m.contains("APP_LOG_JSON_TIMEZONE") && m.contains("'Mars/Olympus_Mons'"));
});
}
@Test
void badAsyncQueueSizeWarnsAndFallsBack() {
runner
.withPropertyValues(
"app.logging.async.enabled=true",
"app.logging.async.queue-size=-1",
"app.logging.async.discarding-threshold=20",
"app.logging.file.enabled=false",
"app.logging.json.timezone=UTC",
"app.logging.json.timestamp-pattern=yyyy-MM-dd'T'HH:mm:ss.SSSXXX",
"app.logging.json.include-caller-data=false",
"app.logging.json.logger-name-length=0")
.run(
context -> {
assertThat(context).hasNotFailed();
LoggingSettings settings = context.getBean(LoggingSettings.class);
assertThat(settings.async().queueSize()).isEqualTo(512);
assertThat(warningMessages()).anyMatch(m -> m.contains("APP_LOG_ASYNC_QUEUE_SIZE"));
});
}
@Test
void validValuesNoWarning() {
runner
.withPropertyValues(
"app.logging.async.enabled=true",
"app.logging.async.queue-size=1024",
"app.logging.async.discarding-threshold=10",
"app.logging.file.enabled=false",
"app.logging.json.timezone=Asia/Seoul",
"app.logging.json.timestamp-pattern=yyyy-MM-dd'T'HH:mm:ss.SSSXXX",
"app.logging.json.include-caller-data=false",
"app.logging.json.logger-name-length=0")
.run(
context -> {
assertThat(context).hasNotFailed();
LoggingSettings settings = context.getBean(LoggingSettings.class);
assertThat(settings.async().queueSize()).isEqualTo(1024);
assertThat(settings.json().timezone()).isEqualTo("Asia/Seoul");
assertThat(warningMessages())
.noneMatch(m -> m.contains("APP_LOG_JSON_TIMEZONE"))
.noneMatch(m -> m.contains("APP_LOG_ASYNC_QUEUE_SIZE"));
});
}
private List<String> warningMessages() {
return warnings.list.stream().map(ILoggingEvent::getFormattedMessage).toList();
}
@Configuration
@EnableConfigurationProperties(LoggingSettings.class)
static class EnableProperties {}
}
@@ -2,10 +2,10 @@ package dev.caskeleton.onboarding.adapter.outbound.persistence.repository;
import dev.caskeleton.onboarding.adapter.outbound.persistence.entity.FeatureAggregateEntity;
import dev.caskeleton.onboarding.adapter.outbound.persistence.mapper.FeatureAggregateEntityMapper;
import dev.caskeleton.onboarding.application.port.FeatureAggregateWritePort;
import dev.caskeleton.onboarding.domain.feature.FeatureAggregate;
import dev.caskeleton.onboarding.domain.feature.FeatureAggregateRepository;
public final class FeatureAggregateRepositoryAdapter implements FeatureAggregateWritePort {
public final class FeatureAggregateRepositoryAdapter implements FeatureAggregateRepository {
private final FeatureAggregateEntityMapper mapper;
@@ -1,8 +0,0 @@
package dev.caskeleton.onboarding.application.port;
import dev.caskeleton.onboarding.domain.feature.FeatureAggregate;
public interface FeatureAggregateWritePort {
FeatureAggregate save(FeatureAggregate featureAggregate);
}
@@ -8,27 +8,27 @@ import dev.caskeleton.application.transaction.TransactionMode;
import dev.caskeleton.application.transaction.TransactionPort;
import dev.caskeleton.application.usecase.CommandUseCase;
import dev.caskeleton.onboarding.application.command.CreateFeatureAggregateCommand;
import dev.caskeleton.onboarding.application.port.FeatureAggregateWritePort;
import dev.caskeleton.onboarding.domain.feature.FeatureAggregate;
import dev.caskeleton.onboarding.domain.feature.FeatureAggregateIdFactory;
import dev.caskeleton.onboarding.domain.feature.FeatureAggregateRepository;
@RequiresPermission("feature-aggregate:write")
@UseCaseCapability(
transactionMode = TransactionMode.WRITE,
idempotency = Idempotency.NOT_IDEMPOTENT,
repositoryAccess = RepositoryAccess.WRITE_REPOSITORY)
public final class CreateFeatureAggregateUseCase
public class CreateFeatureAggregateUseCase
implements CommandUseCase<CreateFeatureAggregateCommand, FeatureAggregate> {
private final FeatureAggregateWritePort writePort;
private final FeatureAggregateRepository repository;
private final FeatureAggregateIdFactory idFactory;
private final TransactionPort tx;
public CreateFeatureAggregateUseCase(
FeatureAggregateWritePort writePort,
FeatureAggregateRepository repository,
FeatureAggregateIdFactory idFactory,
TransactionPort tx) {
this.writePort = writePort;
this.repository = repository;
this.idFactory = idFactory;
this.tx = tx;
}
@@ -36,6 +36,6 @@ public final class CreateFeatureAggregateUseCase
@Override
public FeatureAggregate handle(CreateFeatureAggregateCommand command) {
return tx.inWrite(
() -> writePort.save(FeatureAggregate.create(idFactory.newId(), command.name())));
() -> repository.save(FeatureAggregate.create(idFactory.newId(), command.name())));
}
}
@@ -1,9 +1,10 @@
package dev.caskeleton.onboarding.domain.feature;
import dev.caskeleton.domain.identifier.ResourceId;
import dev.caskeleton.domain.stereotype.ValueObject;
@ValueObject
public record FeatureAggregateId(String value) {
public record FeatureAggregateId(String value) implements ResourceId<FeatureAggregateId> {
public FeatureAggregateId {
if (value == null || value.isBlank()) {
throw new IllegalArgumentException("feature aggregate id must not be blank");
@@ -1,6 +1,8 @@
package dev.caskeleton.onboarding.domain.feature;
public interface FeatureAggregateIdFactory {
import dev.caskeleton.domain.identifier.IdFactory;
FeatureAggregateId newId();
}
/**
* Server-assigned id generation for {@link FeatureAggregate}; an identifier adapter implements it.
*/
public interface FeatureAggregateIdFactory extends IdFactory<FeatureAggregateId> {}
@@ -0,0 +1,11 @@
package dev.caskeleton.onboarding.domain.feature;
/**
* Aggregate-level persistence for {@link FeatureAggregate}. The domain owns it because it stores
* and returns whole aggregates — the {@code *Repository} side of the naming rule in {@code
* application-core/CLAUDE.md}; a technical store the application owns is a {@code *StorePort}.
*/
public interface FeatureAggregateRepository {
FeatureAggregate save(FeatureAggregate featureAggregate);
}