diff --git a/docs/architecture/jpa-api-surface.txt b/docs/architecture/jpa-api-surface.txt index c02213ed..df856a74 100644 --- a/docs/architecture/jpa-api-surface.txt +++ b/docs/architecture/jpa-api-surface.txt @@ -163,7 +163,6 @@ dev.caskeleton.adapter.outbound.persistence.springdata.FetchPlanName dev.caskeleton.adapter.outbound.persistence.springdata.JpaKeysetQuerySupport dev.caskeleton.adapter.outbound.persistence.springdata.JpaRepositoryFragmentSupport dev.caskeleton.adapter.outbound.persistence.springdata.JpaStreamExecutor -dev.caskeleton.adapter.outbound.persistence.springdata.JpaStreamScope dev.caskeleton.adapter.outbound.persistence.springdata.KeysetPredicateBuilder dev.caskeleton.adapter.outbound.persistence.springdata.KeysetSliceAssembler dev.caskeleton.adapter.outbound.persistence.springdata.KeysetTerm @@ -172,4 +171,5 @@ dev.caskeleton.adapter.outbound.persistence.springdata.SafeSortField dev.caskeleton.adapter.outbound.persistence.springdata.SafeSortMapper dev.caskeleton.adapter.outbound.persistence.springdata.SafeSortRegistry dev.caskeleton.adapter.outbound.persistence.springdata.ScrollPolicy +dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransactionPort diff --git a/docs/capability-status.md b/docs/capability-status.md index 9df0b3c4..f9bd91f3 100644 --- a/docs/capability-status.md +++ b/docs/capability-status.md @@ -497,3 +497,14 @@ web 경로의 `W/`는 `src/adapter/inbound/web/src/main/java/dev/caskeleton/adap | `IdempotencyScriptsConcurrencyContractTest` | `src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/` | `423a29c4` | reflection으로 `digests` Map 구조를 고정하던 테스트. 슬롯이 `RegisteredLuaScript` final 필드가 되어 대상이 없음; 동작은 `RegisteredLuaScriptTest`가 검증 | | `SecretSourceValidator.REDIS_ENABLED_PROPERTY`와 Redis 역할 prefix 분기(`isRedisMaterial`, `isRedisRoleSelected`, `isRedisCacheBound`, `isSelected`), `REQUIRED_PROD_SECRETS`의 Redis 8개 | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java` | `423a29c4` | cache-redis `RedisProductionSecrets`가 기여(S6-#2c) | | shared `RateLimitBounds.MAXIMUM_CLEANUP_GRACE`·`MAXIMUM_CLOCK_REGRESSION`, `EdgeRateLimitProviderNeutralContractTest.allPortableAlgorithmsHaveBoundedProviderNeutralPolicies` | `src/shared-contract/src/{main,test}/java/dev/caskeleton/shared/ratelimit/` | `423a29c4` | 정책 타입이 cache-redis로 이동(S1-#15c). 정책 검증 테스트는 이동한 `RateLimitPolicyTest`에 있음 | +| `WebRequestContext` | `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/core/WebRequestContext.java` | `36ba0810` | store 호출 0 → 선언한 컨트롤러는 항상 500, 소비자 0 (I-1c) | +| `ExternalRequestContext` | `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/core/ExternalRequestContext.java` | `36ba0810` | `WebRequestContext` 전용 | +| `WebMvcRequestContextArgumentResolver`·`WebMvcRequestContextHolder` | `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/context/` | `36ba0810` | I-1c | +| `webMvcRequestContextConfigurer` bean | `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfiguration.java` | `36ba0810` | I-1c | +| app-core `Sha256` | `src/application-core/src/main/java/dev/caskeleton/application/messaging/contract/Sha256.java` | `36ba0810` | shared-contract `digest.Sha256`로 이동 | +| `MessageDigestPort` | `src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/MessageDigestPort.java` | `36ba0810` | stdlib 포장 포트(X1-#10b) | +| `Sha256MessageDigestAdapter`·`NotificationDigest` | `src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/template/` | `36ba0810` | 위 포트의 adapter·SHA-256 헬퍼 | +| `JpaStreamScope` | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/springdata/JpaStreamScope.java` | `36ba0810` | 읽기 전용 caller 트랜잭션 guard를 `transaction/CallerTransaction.requireReadOnly`로 합침(JPA API surface 순증 0) | +| web `MdcKeys` | `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/MdcKeys.java` | `36ba0810` | shared-contract `observability.MdcKeys`로 이동(X2-P2-5) | +| `DurableOperationJpaRepositoryShapeTest` | `src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationJpaRepositoryShapeTest.java` | `36ba0810` | `ScopedRowRepositoryShapeTest`로 흡수(테스트) | +| notification `UuidV7Generator` 비트 배치 구현 | `src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/UuidV7Generator.java` | `36ba0810` | 클래스는 남기고 구현을 uuid-creator로 교체(S1-lead-2) | diff --git a/docs/notification/api-surface-snapshot.txt b/docs/notification/api-surface-snapshot.txt index 3c45b144..99474fda 100644 --- a/docs/notification/api-surface-snapshot.txt +++ b/docs/notification/api-surface-snapshot.txt @@ -2,7 +2,7 @@ # Every top-level public type under the platform packages. Growth is a reviewed change. # Update only after review with: # ./gradlew :adapter:outbound:notification:updateNotificationApiSurface -PapproveNotificationApiSurfaceChange -# types: 365 +# types: 362 dev.caskeleton.adapter.outbound.notification.NotificationConfig dev.caskeleton.adapter.outbound.notification.NotificationRoutesSettings dev.caskeleton.adapter.outbound.notification.core.FailOpenNotificationProvider @@ -85,11 +85,9 @@ dev.caskeleton.adapter.outbound.notification.platform.template.JacksonInboxConte dev.caskeleton.adapter.outbound.notification.platform.template.JacksonNotificationVariablesCodec dev.caskeleton.adapter.outbound.notification.platform.template.JacksonTemplateContentCodec dev.caskeleton.adapter.outbound.notification.platform.template.JsonSchemaVariableValidator -dev.caskeleton.adapter.outbound.notification.platform.template.NotificationDigest dev.caskeleton.adapter.outbound.notification.platform.template.NotificationJsonMapper dev.caskeleton.adapter.outbound.notification.platform.template.NotificationTemplateEngine dev.caskeleton.adapter.outbound.notification.platform.template.PlaceholderTemplateEngine -dev.caskeleton.adapter.outbound.notification.platform.template.Sha256MessageDigestAdapter dev.caskeleton.adapter.outbound.notification.platform.template.TemplateSlotMode dev.caskeleton.adapter.outbound.notification.platform.template.TemplateSlotPolicy dev.caskeleton.adapter.outbound.notification.platform.template.ThymeleafStringTemplateEngine @@ -232,7 +230,6 @@ dev.caskeleton.application.notification.platform.dispatch.DispatchPipeline dev.caskeleton.application.notification.platform.dispatch.DuplicateIdempotencyKeyException dev.caskeleton.application.notification.platform.dispatch.GetNotificationApplicationUseCase dev.caskeleton.application.notification.platform.dispatch.LeaseRecoveryService -dev.caskeleton.application.notification.platform.dispatch.MessageDigestPort dev.caskeleton.application.notification.platform.dispatch.NotificationDispatchService dev.caskeleton.application.notification.platform.dispatch.NotificationIdGeneratorPort dev.caskeleton.application.notification.platform.dispatch.NotificationRequestInsertOutcome @@ -243,6 +240,7 @@ dev.caskeleton.application.notification.platform.dispatch.NotificationRoutePlann dev.caskeleton.application.notification.platform.dispatch.NotificationRoutingPlanCodecPort dev.caskeleton.application.notification.platform.dispatch.NotificationSubmissionService dev.caskeleton.application.notification.platform.dispatch.NotificationVariablesCodecPort +dev.caskeleton.application.notification.platform.dispatch.PlanFingerprint dev.caskeleton.application.notification.platform.dispatch.PolicyRoutePlanner dev.caskeleton.application.notification.platform.dispatch.ProviderDispatchGatewayPort dev.caskeleton.application.notification.platform.dispatch.ProviderProfileCatalogPort @@ -256,7 +254,6 @@ dev.caskeleton.application.notification.platform.dispatch.ReconciliationGatewayP dev.caskeleton.application.notification.platform.dispatch.ReconciliationJob dev.caskeleton.application.notification.platform.dispatch.ReconciliationJobStorePort dev.caskeleton.application.notification.platform.dispatch.ReconciliationService -dev.caskeleton.application.notification.platform.dispatch.RequestFingerprint dev.caskeleton.application.notification.platform.dispatch.ScheduleNotificationApplicationUseCase dev.caskeleton.application.notification.platform.dispatch.SubmitNotificationApplicationUseCase dev.caskeleton.application.notification.platform.dispatch.SyntheticEventFingerprint diff --git a/docs/reviews/2026-09-25-review-followup-results/W3-P19.md b/docs/reviews/2026-09-25-review-followup-results/W3-P19.md new file mode 100644 index 00000000..2574c061 --- /dev/null +++ b/docs/reviews/2026-09-25-review-followup-results/W3-P19.md @@ -0,0 +1,67 @@ +## 행 결과 +| ID | 결과 | 근거 | +|---|---|---| +| D-8d | 완료 | 커밋 `c3b7bacb`. `RoutingObjectMutationAdapter`의 `Instant.now()` 5곳(P24 이동 후 남은 수)과 같은 흐름의 `kernel/ManagedObjectPublicationKernel` 7곳, 합 12곳 → `clock.instant()`; 1-인자 생성자(`Clock.systemUTC()`) 삭제, kernel이 생성자로 Clock을 받음. `objectstorage/.../routing/RoutingObjectMutationAdapter.java`, `kernel/ManagedObjectPublicationKernel.java` | +| X2-P1-7 | 완료 | 커밋 `c3b7bacb`·`ccb90e82`. objectstorage 설정 5곳(`ObjectStorageCapabilityConfig` capability·handoff·binding compiler·S3 contribution, `ObjectStorageScanMaintenanceConfig`)이 `ObjectProvider`(Clock bean, 없으면 system UTC)을 주입(`ObjectStorageCapabilityConfig.clock`); `S3ObjectStorageProviderContribution(SecretSourcePort, Clock)`. 생성자 Clock: `LiveEventStompBroadcaster`(websocket), `MongoTenantClientRegistry`(mongo, `MongoTenancyContractTest.anAcquireWithoutAnInstantReadsTheInjectedClock`), `MvcStreamWriter`(web-advanced 5곳). redis-sdk `KeyOperationRequests`는 동시 묶음 P22 영역이라 손대지 않음(남은 1곳) | +| E-3b | 완료 | 커밋 `080cc6aa`. `persistence-jpa/.../transaction/CallerTransaction.java`(`require`·`requireReadOnly`·`requireReadWrite`), `CallerTransactionTest` 4건. outbox·durable operation·live-event 복사본과 `IdempotencyCapabilityGuard`의 3조건 검사가 이것을 호출 | +| X1-#4 / S2-#6b | 남음 | persistence-jpa 복사본 4벌 + 읽기 전용 변형(`JpaStreamScope`, 삭제)은 `CallerTransaction` 하나로 교체(커밋 `080cc6aa`). 남은 것: notification JPA store 9개의 guard — P23에서 `adapter:outbound:persistence-notification` leaf로 추출됐고 그 leaf의 허용 edge는 application-core·application-notification뿐이라 persistence-jpa `CallerTransaction`을 쓸 수 없다. 사유: 결정 필요 — persistence-notification에 persistence-jpa(또는 adapter:outbound:support로 guard 이동 후 support) edge를 줄지. 새 복사본을 만들지 않았다. 승인자: 저장소 소유자 결정 필요 / 결정 33(2026-09-29): edge 추가로 결정 → P30 | +| X1-#1c | 해당 없음(코드 삭제) | `CanonicalOutboxAppendAdapter`가 P18(`423a29c4`)에서 `OutboxStoreAdapter.append`로 합쳐져 삭제됨. `append` 첫 줄이 guard(`OutboxStoreAdapterTest`의 "outbox append requires an active caller transaction" 단언), 이제 `CallerTransaction.require("outbox append")` | +| X1-지도-caller 트랜잭션 guard | 남음 | X1-#4와 같음(persistence-jpa는 완료, notification store 9개는 edge 결정 필요) / 결정 33(2026-09-29): edge 추가로 결정 → P30 | +| E-6b | 완료 | 커밋 `080cc6aa`. `IdempotencyRecordJpaRepository`·`OutboxEventJpaRepository`를 `Repository` marker + 쓰는 메서드만(outbox는 `save`·`findById` + 쿼리 메서드)으로 축소. `ScopedRowRepositoryShapeTest.repositoryExposesNoUnscopedBulkReadOrDelete`(3개 리포지토리 매개변수화, 기존 `DurableOperationJpaRepositoryShapeTest` 흡수) FAIL(`Expecting empty but was: ["findAll","deleteAllInBatch","deleteAllByIdInBatch","findAllById","deleteAll","deleteAllById","count"]`, [2]·[3]) → PASS. 실제 PostgreSQL: `jpaPlatformContractTest`, `postgresqlIdempotencyIntegrationTest`, `postgresqlOutboxAppendTransactionalIntegrationTest`, `postgresqlOutboxConcurrentRelayIntegrationTest`, `postgresqlOutboxRowLifecycleIntegrationTest` 통과. (커밋 라벨은 W3로 묶였다) | +| I-1c | 완료 | 소비자 0이라 구현 대신 삭제(커밋 `d19cf5e5`): `core/WebRequestContext`, `core/ExternalRequestContext`(WebRequestContext 전용), `mvc/context/WebMvcRequestContextArgumentResolver`·`WebMvcRequestContextHolder`, `webMvcRequestContextConfigurer` bean. `WebMvcPlatformAutoConfigurationTest.aServletApplicationGetsThePlatformBeans`가 bean 부재를 단언 | +| P9-new-4 | 완료 | I-1c와 같은 커밋 `d19cf5e5`(파라미터 사용처 제거 쪽) | +| P9-new-5 | 완료 | 커밋 `b64471cb`. `AuthenticatedPrincipal`에 `Optional tenant`(검증된 JWT의 `tenant_id` claim — `JwtToAuthenticatedPrincipalConverter.TENANT_CLAIM`, 에이전트 기본값: MDC·baggage 키와 같은 이름), 형식이 틀린 claim은 "없음"이 아니라 `InvalidBearerTokenException`(401). `DurableOperationController`가 submit·get·cancel에 tenant를 넘김(전에는 null). 테스트: `DurableOperationControllerTest.theSameSubjectInAnotherTenantGetsTheSame404`·`theSubmitterReadsTheirOperationInTheTenantTheyAreSignedInTo`, `JwtToAuthenticatedPrincipalConverterTest` 3건. 한계: redis-session 인증(`PrimitiveSessionSecurityContextRepository`)은 세션 인코딩에 tenant가 없어 tenant 없는 principal을 만든다(세션 형식 변경은 하지 않음) | +| J-12 / X2-P2-6b | 보류 | J-12(production에서 익명 principal resolver 기동 거부)는 Wave 1–2 `aa5f4d90`에서 완료. X2-P2-6b 나머지 3건은 결정 필요: (1) `AuthorizationPrincipal`에 tenant — 지금 읽는 `AuthorizationPort` 구현이 없어 추가하면 소비자 0 필드가 된다(어떤 인가 결정이 tenant를 쓸지 정해야 함), (2) GraphQL에 Spring Security `Authentication` → principal 기본 resolver — graphql leaf는 spring-security를 test scope에만 두고 "서버·보안 스택은 composition이 고른다"는 규칙(`adapter/inbound/graphql/CLAUDE.md`)이라 main 의존 추가가 구조 결정, (3) 가명을 `UserPrincipalPseudonymizerPort` 하나로 — web rate-limit의 `EdgeSubjectPseudonymizer`는 키 버전·회전이 있는 rate-limit 키 전용이라 로그 가명 포트와 목적(키 분리)이 다르다. 승인자: 저장소 소유자 결정 필요 / 승인자: 소유자 결정 35(2026-09-29) | +| X1-지도-Backoff 계산식 | 완료 | X1-#9 | +| X1-#9 | 완료 | 커밋 `35e1df8a`. `shared-contract/.../retry/Backoff.java`(ceiling·fullJitter=U[0,ceiling]·decorrelatedJitter, 포화 연산), `BackoffTest` 7건. httpclient `ExponentialFullJitterBackoff`, notification `RetryBackoff`(application-notification→shared-contract edge를 이 묶음에서 추가했으므로 포함; multiplier 제거·base 하한 유지), outbox `OutboxBackoffPolicy`(ceiling 120s 상한 + 한 base짜리 full jitter). outbox를 순수 full jitter로 바꾸지 않은 이유: 0 지연이면 실패 순간 재claim되므로 기존 불변식(`nextAttemptAtIsAlwaysAfterNow`)과 registry `retry_after_seconds=30`이 깨진다 — 대신 "full jitter"라는 이름을 문서에서 바로잡음(`application-core/README.md`). mongo·messaging·grpc는 자체 유지 | +| X1-#10b | 완료 | 커밋 `bca2c682`. application-notification → shared-contract edge 추가(modules.json) 후 `MessageDigestPort`·`Sha256MessageDigestAdapter`·`NotificationDigest` 삭제 | +| X2-P1-4b | 완료 | 커밋 `35e1df8a`. `shared-contract/.../digest/HmacSha256.java`(sign/verify, 길이 먼저 확인 후 constant-time), `HmacSha256Test` 5건. 사용: graphql `HmacGraphQlCursorCodec`·`GraphQlIdentityFingerprinter`, persistence-jpa `SignedJsonCursorCodec`, notification HMAC 3곳, sample digester. 서명 codec은 유지(2026-09-25 결정). mongo `MongoKeysetCursorCodec`은 shared-contract edge 없어 유지, redis·identifier·fileserver는 동시 묶음/edge 없음으로 유지 | +| X2-P1-5 | 완료 | 커밋 `bca2c682`. `shared-contract/.../digest/Sha256.java`(of/ofUtf8/newMessageDigest/hex), `Sha256Test` 5건. `MessageDigest.getInstance` main 36곳 → 10곳(mongo 3, application-objectstorage 2 — shared-contract edge 없음; vendored messaging 2·gRPC 2; cache-redis SHA-1 1) | +| X2-P2-4 | 완료 | 수정 자체는 Wave 2 `016597ac`에서 이미 됨(`WebMvcRequestIdFilter`가 정규식 대신 `TraceParent.parse`). 이번에 회귀 테스트 추가(커밋 `ccb90e82`): `WebMvcRequestIdFilterTest.aTraceparentTheSharedParserRefusesIsReplaced`(버전 ff, 0 trace id, 0 span id). gRPC 쪽도 같은 parser(`GrpcCorrelationInterceptorTest.aTraceparentTheSharedParserRefusesIsNotAdopted`) | +| X2-P2-5 | 완료 | 커밋 `c3b7bacb`·`ccb90e82`. `shared-contract/.../observability/MdcKeys.java`(web에서 이동, 사용처 web·web-fileserver·app-bootstrap import 변경). gRPC `GrpcCorrelationInterceptor`(outermost, 콜백마다 MDC put/복원) — `GrpcCorrelationInterceptorTest` 3건; STOMP `WebSocketCorrelationInterceptor`(ExecutorChannelInterceptor) — 테스트 2건; GraphQL은 web leaf에 의존할 수 없어 `WebRequestId` 대신 filter가 MDC에 둔 `request_id`를 executionId로 사용 — `GraphQlPlatformWebInterceptorRequestBoundsTest.aRejectionNamesTheHttpRequestIdTheFilterAssigned`. registry 원본 `docs/registries/mdc-keys.yaml`은 키가 같아 변경 없음 | +| X2-P2-6a | 완료 | 커밋 `b64471cb`. `application-core/.../tenant/TenantId.java`(web 문법, `optional()`은 형식이 틀리면 거부), `TenantIdTest`. web `core/TenantContext(Optional)`, graphql `context/TenantContext`가 이것으로 검증(`tenantId()` 추가). 수정 방향 중 notification·jpa `TenantId`를 같은 타입으로 맞추는 부분은 하지 않음: notification은 100자·임의 문자로 이미 저장된 행을 새 문법으로 읽으면 기존 데이터 읽기가 실패(데이터 호환 결정 필요 → P19-new-1), persistence-jpa experimental `TenantId`는 schema 이름에 들어가 소문자만 허용하는 더 엄격한 문법이 의도(보안상 넓히면 안 됨) | +| S5-lead-3 | 완료 | X2-P2-6a와 같음(`b64471cb`): 두 전송 context가 같은 값 타입을 담는다 | +| S1-#11 | 완료 | 커밋 `bca2c682`. app-core `messaging.contract.Sha256` 값 타입을 shared-contract로 옮겨 헬퍼와 합침(같은 이름 두 타입 방지), notification `RequestFingerprint` → `PlanFingerprint` | +| S1-lead-2 | 완료 | 커밋 `19ffd755`. notification `UuidV7Generator`가 uuid-creator `TimeOrderedEpochFactory`(주입 Clock, `withIncrementPlus1`)로 생성; `UuidV7GeneratorTest` 2건(버전 7, 같은 ms 1000개 정렬·중복 없음). lockfile 3개 재생성. fileserver v4 유지 | +| S2-lead-3 | 완료 | X2-P1-4b와 같음(`35e1df8a`). 수정 방향의 "jpa·mongo codec 삭제"는 2026-09-25 라이브러리 유지 결정과 충돌해 서명 헬퍼 공유로 좁힘(프롬프트 기본값) | +| P16-new-5 | 보류 | `NotificationIdGeneratorPort`(UUID 반환)·`UploadIdentifierFactory`를 domain `IdFactory>` 기반으로 바꾸려면 application-notification·application-fileserver에 domain-core edge가 필요하고(현재 둘 다 없음), 모든 notification id를 `ResourceId` 타입으로 바꿔야 한다. fileserver 쪽은 동시 묶음 P28이 같은 파일군을 바꾸는 중. 사유: 결정 필요 — 두 application leaf에 domain-core edge를 줄지. 승인자: 저장소 소유자 결정 필요 / 승인자: 소유자 결정 34(2026-09-29) | +| ORCH-new-3 | 완료 | 커밋 `c3380270`. 원인: `WebStreamRegistry.register`가 `compute()` 안에서 `sessions.size()`를 읽음 — compute는 한 bin만 잠그고 크기 카운터는 잠금 해제 뒤 갱신되므로 다른 bin의 두 도착이 모두 999를 보고 삽입(실제 경합, 테스트 타이밍 문제 아님: 먼저 단언하는 `activeStreams()`가 1001). 수정: AtomicInteger CAS로 슬롯 선예약 + `putIfAbsent`, 중복·deregister는 슬롯 반환. 테스트 `stream/WebStreamRegistryAdmissionTest`(경쟁 도착 200라운드, 슬롯 반환 2건). FAIL 근거: P27 통합 ci의 `expected: 1000 but was: 1001` — 로컬에서는 수정 전 soak 형태 6회 + 200라운드로도 재현되지 않았다(창이 `addCount` 한 구간뿐). 수정 후 `WebStreamingSoakIT`+새 테스트 3회 반복 통과 | + +## 제거된 코드 +| 대상 | 경로 | 마지막으로 존재한 커밋 | 이유 | +|---|---|---|---| +| `WebRequestContext` | `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/core/WebRequestContext.java` | `36ba0810` | store 호출 0 → 선언한 컨트롤러는 항상 500, 소비자 0 (I-1c) | +| `ExternalRequestContext` | `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/core/ExternalRequestContext.java` | `36ba0810` | `WebRequestContext` 전용 | +| `WebMvcRequestContextArgumentResolver`·`WebMvcRequestContextHolder` | `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/context/` | `36ba0810` | I-1c | +| `webMvcRequestContextConfigurer` bean | `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfiguration.java` | `36ba0810` | I-1c | +| app-core `Sha256` | `src/application-core/src/main/java/dev/caskeleton/application/messaging/contract/Sha256.java` | `36ba0810` | shared-contract `digest.Sha256`로 이동 | +| `MessageDigestPort` | `src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/MessageDigestPort.java` | `36ba0810` | stdlib 포장 포트(X1-#10b) | +| `Sha256MessageDigestAdapter`·`NotificationDigest` | `src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/template/` | `36ba0810` | 위 포트의 adapter·SHA-256 헬퍼 | +| `JpaStreamScope` | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/springdata/JpaStreamScope.java` | `36ba0810` | 읽기 전용 caller 트랜잭션 guard를 `transaction/CallerTransaction.requireReadOnly`로 합침(JPA API surface 순증 0) | +| web `MdcKeys` | `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/MdcKeys.java` | `36ba0810` | shared-contract `observability.MdcKeys`로 이동(X2-P2-5) | +| `DurableOperationJpaRepositoryShapeTest` | `src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationJpaRepositoryShapeTest.java` | `36ba0810` | `ScopedRowRepositoryShapeTest`로 흡수(테스트) | +| notification `UuidV7Generator` 비트 배치 구현 | `src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/UuidV7Generator.java` | `36ba0810` | 클래스는 남기고 구현을 uuid-creator로 교체(S1-lead-2) | + +## 새로 발견한 결함 +- P19-new-1: notification `platform.api.TenantId`는 "비어 있지 않고 100자 이하"만 검사해 web·GraphQL이 거부하는 tenant(공백·줄바꿈·경로 문자)를 받는다(`src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/TenantId.java:4`). application-core `TenantId`로 맞추면 이미 저장된 행(`tenant_id varchar(100)`)을 읽는 `new TenantId(entity.tenantId())`가 실패할 수 있어 데이터 호환 결정이 필요 — 고치지 않음. +- P19-new-2: redis-session 인증 경로(`src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/PrimitiveSessionSecurityContextRepository.java:116`)는 세션에 tenant를 저장하지 않아, JWT 경로가 tenant를 해석해도 세션 경로 principal은 tenant가 없다. 세션 인코딩 변경이 필요 — 고치지 않음. +- P19-new-3: `docs/study/postgresql-jpa-walkthrough.ko.md:818`이 삭제된 `JpaStreamScope`를 설명한다(Wave 5 문서 갱신 대상) — 고치지 않음. + +## 커밋·검증 +- worktree `.claude/worktrees/agent-afb877fb43ed8daf5`, 브랜치 `worktree-agent-afb877fb43ed8daf5`, 기준 `36ba0810` +- 커밋: `d19cf5e5` D, `bca2c682` W3, `35e1df8a` W3, `c3380270` W2, `080cc6aa` W3, `b64471cb` W3, `c3b7bacb` W3, `ccb90e82` W3, `19ffd755` W3, `43d0c3eb` W3 +- registry: `application-notification` → `shared-contract` edge 추가(modules.json, 커밋 `bca2c682`) +- API surface 재승인: notification(`bca2c682`), JPA(`080cc6aa`, 167 유지 — `CallerTransaction` 추가·`JpaStreamScope` 삭제) +- lockfile 재생성: adapter:outbound:notification, composition:notification-platform, app-bootstrap(uuid-creator) +- migration 추가 없음, env 키 변경 없음 +- `check` 통과: shared-contract, application-core, application-notification, adapter:outbound:{notification, objectstorage, fileserver, cache-redis, persistence-jpa, support, messaging, httpclient, persistence-mongo}, adapter:inbound:{graphql, web, web-advanced, web-fileserver, web-notification, grpc, websocket}, composition:{notification-platform, outbox-relay}, sample-portfolio, app-bootstrap +- `architectureCheck` 통과(첫 실행에서 D7 `EXTERNAL_OUTBOUND_CALLS_REQUIRE_EXTERNAL_OUTBOUND_ALLOWED_CAPABILITY` 1건 → `43d0c3eb`로 수정 후 통과) +- 실제 PostgreSQL: `jpaPlatformContractTest`, `postgresqlIdempotencyIntegrationTest`, `postgresqlOutboxAppendTransactionalIntegrationTest`, `postgresqlOutboxConcurrentRelayIntegrationTest`, `postgresqlOutboxRowLifecycleIntegrationTest` 통과 +- `:app-bootstrap:integrationTest` 9/9, `:sample-portfolio:integrationTest` 51/51, `:sample-portfolio:systemTest` 3/3, `:adapter:inbound:graphql:systemTest` 25/25, `:adapter:inbound:websocket:systemTest` 18/18 (실패·skip 0) +- `verifyPublicPathSnapshot`, `:app-bootstrap:verifyEnvKeys`, `verifyDependencyLocks` 통과 +- 전 저장소 source set 컴파일(`classes testClasses postgresqlIntegrationTestClasses systemTestClasses …`) 통과 +- ORCH-new-3: `WebStreamingSoakIT`+`WebStreamRegistryAdmissionTest` `--rerun-tasks` 3회 통과 +- 돌리지 않은 것: objectstorage MinIO lane(묶음 지시에 없음; objectstorage는 Clock 주입만 바뀜), redis·messaging lane(손대지 않음) + +## 규칙 이탈 +- 소스 편집 일부를 셸 python 스크립트(scratchpad의 `repl.py`·`addimport.py`·`dropmethod.py`·`edit_*.py`, 일부 heredoc)로 했다(기계적 import 치환·동일 블록 교체). 결과는 매번 컴파일·spotless·check로 확인했다. diff --git a/docs/reviews/2026-09-25-review-followup-status.md b/docs/reviews/2026-09-25-review-followup-status.md index afffe342..4d06c60e 100644 --- a/docs/reviews/2026-09-25-review-followup-status.md +++ b/docs/reviews/2026-09-25-review-followup-status.md @@ -68,6 +68,9 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | 30 | PR `ci`를 변경 모듈만 실행 | 하지 않음 — 전체 실행 + Gradle 캐시 → 보류 | BUILD-계획-B3 | | 31 | 릴리스 이미지 서명 | 넣음 — cosign keyless, 공식 릴리스 체크섬 고정 설치, tag 릴리스에서 서명·검증 | BUILD-계획-C | | 32 | fileserver 연산을 use case로 바꿀 때 `@RequiresPermission` | 권한 추가(`file:*`) — 역할 검사(권한)와 소유자·tenant 검사(`FileAccessPolicyPort`)를 둘 다 둔다 | S1-#6b, S1-#18b | +| 33 | 분리된 persistence leaf의 caller 트랜잭션 guard | `persistence-notification`·`persistence-fileserver` → `persistence-jpa` edge 추가, `CallerTransaction` 하나를 쓴다 | X1-#4, X1-지도-caller 트랜잭션 guard | +| 34 | notification·fileserver id 포트를 domain `IdFactory`로 | 하지 않음 — 두 application leaf에 domain-core edge를 주지 않는다 → 보류 | P16-new-5 | +| 35 | X2-P2-6b 나머지(principal tenant, GraphQL Spring Security resolver, 가명화 키) | 전부 하지 않음 — 소비자 없는 필드는 만들지 않고, adopter resolver bean 방식 유지, 키 분리는 의도(문서화) → 보류 | J-12 / X2-P2-6b | 기존 원칙에서 바로 따라 나와 에이전트가 정한 것(소유자가 뒤집을 수 있음): @@ -268,7 +271,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | D-8a | Consider | managed 경로의 참조 게시(`persistPublishedReference`/`createOrRequireSame`)가 `ObjectReferencePublicationService`와 중복 | 완료 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): `806c4ca9`. managed publish의 참조 게시 사본(`persistPublishedReference`/`createOrRequireSame`) 삭제, `ObjectReferencePublicationService.publish(route, policy, provider, control, objectId, version, identity, mediaType, now)`(`kernel/ObjectReferencePublicationService.java:59`) 하나를 staged finalize와 managed publish(`kernel/ManagedObjectPublicationKernel.java:87`)가 함께 쓴다. objectstorage `test` 전부 PASS(`StagedObjectPublicationLifecycleTest`·`RoutingObjectStorageAdapterTest` 포함) | - | `RoutingObjectMutationAdapter`가 `ObjectReferencePublicationService.publish`를 호출하고 사본 삭제 | | D-8b | Consider | `objectId`/`sha256Hex` 계산 중복 | 완료 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): `806c4ca9`. `codec/ObjectIdentityCodec.objectId(operationKey, fingerprint)`(`codec/ObjectIdentityCodec.java:23`)·`sha256Hex` 하나로, `StagedObjectPublicationKernel`·`ManagedObjectPublicationKernel`·`RoutingObjectMutationAdapter.resolve`가 호출. 공용 `Sha256`은 3-D 몫이라 leaf 안에서만 모음 | - | `codec` 패키지에 identity helper 하나로 합치고 두 곳이 호출 | | D-8c | Consider | route token 파싱 `split("\\.")[1]`이 두 곳에 복사 | 완료 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): `806c4ca9`. `ObjectReferenceCodec.routeToken(..)`(`codec/ObjectReferenceCodec.java:25`), `routeOf`·`RoutingObjectMutationAdapter.retire`·`RoutingObjectReadAdapter.load`가 사용. `split("\\.")[1]` 사본 0 | - | `ObjectReferenceCodec.routeToken(..)` 추가 후 두 곳 교체 | -| D-8d | Consider | `clock`을 주입받고도 `Instant.now()`를 12번 호출 | 남음 | `src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/RoutingObjectMutationAdapter.java:60,70`(clock), `:128,152,192,201,212,223,229,283,311,329,341,349`(`Instant.now()`) | W3 | `Instant.now()`를 `clock.instant()`로 교체 | +| D-8d | Consider | `clock`을 주입받고도 `Instant.now()`를 12번 호출 | 완료 | Wave 3 W3-P19 (Wave 3 라운드 3 커밋): 커밋 `c3b7bacb`. `RoutingObjectMutationAdapter`의 `Instant.now()` 5곳(P24 이동 후 남은 수)과 같은 흐름의 `kernel/ManagedObjectPublicationKernel` 7곳, 합 12곳 → `clock.instant()`; 1-인자 생성자(`Clock.systemUTC()`) 삭제, kernel이 생성자로 Clock을 받음. `objectstorage/.../routing/RoutingObjectMutationAdapter.java`, `kernel/ManagedObjectPublicationKernel.java` | - | `Instant.now()`를 `clock.instant()`로 교체 | | D-9 | Consider | `inspect`가 scan 상태를 항상 NOT_REQUIRED로 보고(SCAN_CLEAN destination 포함) | 완료 | Wave 1–2 P2 (fcddab7e·Wave 2 커밋): `…$Inspect.scanGatedReferenceReportsItsCleanVerdict` FAIL(`Expecting actual: Optional[NOT_REQUIRED]`)→PASS. `config/RoutingObjectReadAdapter.java:53-58`. 이 보고가 참이 되려면 managed publish의 scan 우회를 막아야 해서 P2-new-1을 함께 고쳤다 | - | destination `policySnapshot().publicationRequirement()`가 SCAN_CLEAN이면 CLEAN으로 보고 | | D-10 | Nit | capability close가 역순이 아님(`Map.copyOf`는 순서 없음), 하나가 던지면 나머지 close를 건너뜀 | 완료 | Wave 1–2 P2 (fcddab7e·Wave 2 커밋): `ObjectStorageCapabilityAssemblerTest.closeReleasesProvidersInReverseCreationOrderAndKeepsEveryFailure` FAIL(`Expecting message to be: "close failed: a"`)→PASS. `config/ObjectStorageCapabilityAssembler.java:52-82,137-140`(provider를 생성 순서 `List`로 보관, 역순 close, 첫 실패에 나머지 `addSuppressed`; assemble 실패 경로도 같은 helper) | - | provider를 생성 순서 `List`로 보관, 역순 close를 try/catch + `addSuppressed`로 | | D-11a | Nit | leaf CLAUDE.md 허용 의존에서 `application-objectstorage` 누락 | 남음 | `src/adapter/outbound/objectstorage/CLAUDE.md:30` (registry: `application-core`, `shared-contract`, `application-objectstorage`) | W5 | 의존 나열을 지우고 registry 참조 한 줄만 남김 | @@ -283,7 +286,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | E-2a | Critical | 같은 요청 재제출이 unique 위반 후 같은 트랜잭션 재조회 → PostgreSQL 25P02 | 완료 | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationStoreAdapter.java:43-70`(`submitIfAbsent` 후 조회), `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationJpaRepository.java:39-59`(`ON CONFLICT … DO NOTHING`), 테스트 `DurableOperationStoreAdapterContractTest`(postgresqlIntegrationTest) ← `DurableOperationStoreContract.identicalResubmissionInsideOneTransactionReturnsTheFirstOperation`, 커밋 6d27356e | - | - | | E-2b | Required | (알려진 남은 문제) 같은 operationId 재시도 시 outbox 중복 append: `alreadyAccepted`를 operationId 불일치로만 판단 → 같은 id 재시도는 새 제출로 보고 `outbox.append` 재실행. `OutboxEventEntity`에 `Persistable`/`@Version`이 없어 `repository.save`가 merge로 기존 행을 PENDING·attempt 0으로 덮거나(reaper가 지웠으면 새 행) 재발행 | 완료 | Wave 1–2 P9 (fcddab7e·Wave 2 커밋): NEW-7a와 같은 결함·같은 수정. 아래 NEW-7a 행 참고 | - | `DurableOperationStorePort.submit`이 생성/재사용 여부를 돌려주게 하고(`submitIfAbsent` 영향 행 수 1/0) 그 값으로 append 여부 결정. `DurableOperationStoreContract`에 같은 id 재시도 케이스 추가 | | E-3a | Required | `CanonicalOutboxAppendAdapter.append`에 caller 트랜잭션 확인 없음 → 트랜잭션 밖 호출 시 조용한 dual-write | 완료 | Wave 1–2 P9 (fcddab7e·Wave 2 커밋): `CanonicalOutboxAppendAdapterTest.appendOutsideACallerTransactionIsRefusedBeforeAnyWrite` FAIL("Expecting actual not to be null")→PASS. `.../outbox/CanonicalOutboxAppendAdapter.java:40-44` 첫 줄에 caller 트랜잭션 guard(형제 `OutboxStoreAdapter`와 같은 메시지) | - | `append` 첫 줄에 caller 트랜잭션 guard 추가 | -| E-3b | Required | caller 트랜잭션 guard가 세 클래스에 복사됨 | 남음 | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxStoreAdapter.java:130-135`, `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationStoreAdapter.java:169-174`, `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/liveevent/JpaLiveEventReplayAdapter.java:163-168` | W3 | `persistence/transaction` 패키지에 공용 helper 하나를 두고 세 곳 + E-3a가 호출 | +| E-3b | Required | caller 트랜잭션 guard가 세 클래스에 복사됨 | 완료 | Wave 3 W3-P19 (Wave 3 라운드 3 커밋): 커밋 `080cc6aa`. `persistence-jpa/.../transaction/CallerTransaction.java`(`require`·`requireReadOnly`·`requireReadWrite`), `CallerTransactionTest` 4건. outbox·durable operation·live-event 복사본과 `IdempotencyCapabilityGuard`의 3조건 검사가 이것을 호출 | - | `persistence/transaction` 패키지에 공용 helper 하나를 두고 세 곳 + E-3a가 호출 | | E-3c | Required | ownership 테스트가 canonical append adapter를 검사하지 않음 | 남음 | `src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/PersistenceTransactionOwnershipTest.java:25-47`(DurableOperation·LiveEvent만) | W4 | `PersistenceTransactionOwnershipTest`에 `CanonicalOutboxAppendAdapter`의 트랜잭션 없는 호출 거부 케이스 추가 | | E-4a | Required | `markAllRead` 서브쿼리가 `read_at IS NULL`만 보고 state를 거르지 않음 → 읽지 않고 보관한 ARCHIVED 항목이 READ로 되살아남 | 완료 | Wave 1–2 P9 (fcddab7e·Wave 2 커밋): 실제 PG `PostgreSqlInboxCutoffIntegrationTest.markAllReadLeavesAnUnreadArchivedItemArchived` FAIL(`[2, READ]` ≠ `[1, ARCHIVED]`)→PASS. 서브쿼리에 `AND state NOT IN ('ARCHIVED','EXPIRED','DELETED')`: `.../notification/platform/inbox/InboxItemJpaRepository.java:91-93`. 이 테스트 클래스는 SQL 사본을 실행하고 있어서(결함이 안 보였던 이유) repository `@Query` 값을 읽어 실행하도록 바꿈 | - | 서브쿼리에 `AND state NOT IN ('ARCHIVED','EXPIRED','DELETED')` 추가 | | E-4b | Required | 엔티티 `markRead`/`markSeen`이 ARCHIVED·terminal 상태를 막지 않음 | 완료 | Wave 1–2 P9 (fcddab7e·Wave 2 커밋): `InboxItemEntityTest.markReadLeavesAnItemThatLeftTheInboxWhereItIs` / `markSeen...` (ARCHIVED·EXPIRED·DELETED 각 3건) FAIL(`[true, READ]`/`[true, SEEN]`)→PASS. `.../inbox/InboxItemEntity.java` `leftTheInbox()` 가드 | - | `markSeen`/`markRead`에서 `archivedAt != null`·terminal이면 false 반환 | @@ -292,7 +295,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | E-5b | Required | gate가 `tenant_scope`·`aggregate_type`을 안 봐 다른 tenant/type의 같은 `aggregate_id` DEAD row가 서로 영구 차단 | 완료 | Wave 1–2 P9 (fcddab7e·Wave 2 커밋): 실제 PG `aDeadCanonicalRowOfAnotherTenantOrTypeDoesNotBlockTheSameAggregateId` FAIL(`[]`)→PASS. E-5a와 같은 SQL 변경(canonical 쌍은 tenant_scope·aggregate_type까지 같아야 같은 aggregate) | - | canonical row의 gate 키를 `(tenant_scope, aggregate_type, aggregate_id)`로(E-5a와 같은 SQL 변경, PostgreSQL·H2 두 곳) | | E-5c | Required | README가 "한 배치에 aggregate 당 최대 한 row"라고 적음(같은 `occurred_at`이면 거짓) | 남음 | `src/adapter/outbound/persistence-jpa/README.md:248-249` | W5 | E-5a 수정 후 README를 실제 보장에 맞춤 | | E-6a | Required | H10 tenant 규칙이 필드 이름 `tenantId`로만 판정("Structural" Javadoc과 반대) → `tenant`, `tenantScope` 엔티티 누락 | 남음 | `src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/TenantScopedRepositoryPredicate.java:12-19,49` | W4 | `tenant*` 필드 전부(또는 marker annotation)로 판정 | -| E-6b | Required | tenant 컬럼을 가진 세 리포지토리가 `JpaRepository`를 상속해 범위 없는 `findAll`/`deleteAll` 노출 | 남음 | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationJpaRepository.java:25-26`, `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyRecordJpaRepository.java:12-13`, `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxEventJpaRepository.java:16`
Wave 3 W3-P26: 미완 — 일부 완료(커밋 `27958d6c`): `DurableOperationJpaRepository`를 `Repository` marker + 사용 메서드(`findById` 포함)만으로 축소. `DurableOperationJpaRepositoryShapeTest.repositoryExposesNoUnscopedBulkReadOrDelete` FAIL(`Expecting empty but was: ["findAll","deleteAllInBatch","deleteAllByIdInBatch","findAllById","deleteAll","deleteAllById","count"]`)→PASS. `persistence-jpa/.../operation/DurableOperationJpaRepository.java:25`. 남은 것: `IdempotencyRecordJpaRepository`·`OutboxEventJpaRepository`는 이 묶음 지시상 제외(같은 라운드의 P18이 persistence-jpa outbox·멱등성 패키지를 이동 중). P18 통합 후 같은 방식(`Repository` marker + 쓰는 메서드만, 같은 모양의 shape 테스트)으로 처리 | W3 | 세 리포지토리를 `Repository` marker + 쓰는 메서드만 선언으로 축소 | +| E-6b | Required | tenant 컬럼을 가진 세 리포지토리가 `JpaRepository`를 상속해 범위 없는 `findAll`/`deleteAll` 노출 | 완료 | Wave 3 W3-P19 (Wave 3 라운드 3 커밋): 커밋 `080cc6aa`. `IdempotencyRecordJpaRepository`·`OutboxEventJpaRepository`를 `Repository` marker + 쓰는 메서드만(outbox는 `save`·`findById` + 쿼리 메서드)으로 축소. `ScopedRowRepositoryShapeTest.repositoryExposesNoUnscopedBulkReadOrDelete`(3개 리포지토리 매개변수화, 기존 `DurableOperationJpaRepositoryShapeTest` 흡수) FAIL(`Expecting empty but was: ["findAll","deleteAllInBatch","deleteAllByIdInBatch","findAllById","deleteAll","deleteAllById","count"]`, [2]·[3]) → PASS. 실제 PostgreSQL: `jpaPlatformContractTest`, `postgresqlIdempotencyIntegrationTest`, `postgresqlOutboxAppendTransactionalIntegrationTest`, `postgresqlOutboxConcurrentRelayIntegrationTest`, `postgresqlOutboxRowLifecycleIntegrationTest` 통과. (커밋 라벨은 W3로 묶였다) | - | 세 리포지토리를 `Repository` marker + 쓰는 메서드만 선언으로 축소 | | E-7 | Consider | 잘못된 canonical row 하나가 `claimBatch` 매핑에서 예외 → claim 트랜잭션 전체 롤백 → 매 주기 같은 row 재선택으로 relay 정지 | 완료 | Wave 1–2 P9 (fcddab7e·Wave 2 커밋): `OutboxStoreAdapterTest.claimBatchMovesAnUnreadableRowToDeadAndClaimsTheRestOfTheBatch` FAIL(IllegalStateException partial canonical)→PASS, 실제 PG `anUnreadableCanonicalRowDoesNotStopTheRestOfTheBatchFromBeingClaimed`·`anUnreadableCanonicalRowIsMovedToDeadByTheClaim` FAIL(projection mismatch 예외)→PASS. `.../outbox/OutboxStoreAdapter.java:84-110` 매핑 실패 row는 DEAD·lease 해제 후 배치에서 제외(legacy로 낮추지 않으므로 fail-closed 유지) | - | 매핑 실패 row는 DEAD로 전이하고 배치의 나머지는 계속 | | E-8a | Consider | outbox 지표 쿼리가 매 poll(PT5S)마다 테이블 전체를 status별로 셈(7일치 PUBLISHED 포함) | 완료 | Wave 1–2 P9 (fcddab7e·Wave 2 커밋): 실제 PG `countByStatusLeavesPublishedRowsUncounted` FAIL(`{PENDING=1, PUBLISHED=1}`)→PASS. `countGroupedByStatus`에 `where e.status <> 'PUBLISHED'`(`.../outbox/OutboxEventJpaRepository.java`), fake `InMemoryOutboxStore.countByStatus` 동일, 포트 문서 갱신, `OutboxMetrics`는 PUBLISHED 시리즈를 내보내지 않음(0 고정 시리즈 방지). lifecycle PG 테스트의 PUBLISHED 카운트 단언 3곳은 row 상태 직접 조회로 교체 | - | `countGroupedByStatus`에 `where e.status <> 'PUBLISHED'` | | E-8b | Consider | `OutboxReaper`가 PUBLISHED 삭제를 한도 없는 단일 트랜잭션 DELETE로 실행 | 완료 | Wave 1–2 P9 (fcddab7e·Wave 2 커밋): `OutboxReaperTest` 3건 FAIL(컴파일: `deletePublishedBatch` 없음)→PASS. native `DELETE … WHERE event_id IN (SELECT … LIMIT n)`(ctid 대신 PG·H2 공통 SQL)를 repository 메서드 `@Transactional`로 배치마다 커밋, 덜 찬 배치에서 종료: `.../outbox/OutboxEventJpaRepository.java:19-35`, `.../outbox/OutboxReaper.java`(배치 1,000, `ponytail:` 주석). 실제 PG `reaperDeletesOldPublishedRowsOutsideAnyCallerTransaction`, H2 `theReaperBatchDeleteRunsOnH2AndStopsAtItsLimit` PASS | - | native `DELETE … WHERE ctid IN (SELECT … LIMIT n)`를 0건 될 때까지 배치별 트랜잭션으로 반복 | @@ -417,7 +420,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): |---|---|---|---|---|---|---| | I-1a | Critical | durable operation 조회/취소의 저장소 호출·트랜잭션·접근 판정이 web 어댑터 안에 있음(HARD-STOP 4) (= A-4) | 완료 | 유스케이스로 이동: `src/application-core/src/main/java/dev/caskeleton/application/operation/GetDurableOperationUseCase.java`, `CancelDurableOperationUseCase.java:56`(`transactions.inWrite`), `DurableOperationAccessPolicy.java:14`. 테스트 `GetDurableOperationUseCaseTest.submitterInAnotherTenantReadsNothing`, `CancelDurableOperationUseCaseTest.submitterInAnotherTenantIsAnsweredAsIfTheOperationDidNotExist`, `DurableOperationAccessPolicyTest`. web `operationasync/` 삭제(제거 표 「durable operation HTTP 투영」). 커밋 `6d27356e` | - | - | | I-1b | Critical | `OperationQueryService`가 testFixtures에서만 생성돼 켜면 기동 실패 | 해당 없음(코드 삭제) | 제거 표 「durable operation HTTP 투영 (`OperationQueryService`, `OperationHttpController` 외)」. `git ls-tree -r HEAD`에 `OperationQueryService`·`OperationFixtureSupport` 없음 | - | - | -| I-1c | Critical | `WebRequestContext` argument resolver는 등록되지만 `store` 호출이 0이라 선언한 컨트롤러는 항상 예외(500) | 남음 | 등록 `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfiguration.java:64-74`, `WebMvcRequestContextHolder.store`(`.../mvc/context/WebMvcRequestContextHolder.java:34`) 호출처 main·test 0, `WebMvcRequestContextArgumentResolver.java:40`이 `require` → `IllegalStateException`. `WebRequestContext` 소비자 0 | W3 | 소비자가 없으므로 `core/WebRequestContext`·`mvc/context/*`·`webMvcRequestContextConfigurer` bean을 삭제(쓰려면 `WebMvcRequestIdFilter`에서 `store` 호출) | +| I-1c | Critical | `WebRequestContext` argument resolver는 등록되지만 `store` 호출이 0이라 선언한 컨트롤러는 항상 예외(500) | 완료 | Wave 3 W3-P19 (Wave 3 라운드 3 커밋): 소비자 0이라 구현 대신 삭제(커밋 `d19cf5e5`): `core/WebRequestContext`, `core/ExternalRequestContext`(WebRequestContext 전용), `mvc/context/WebMvcRequestContextArgumentResolver`·`WebMvcRequestContextHolder`, `webMvcRequestContextConfigurer` bean. `WebMvcPlatformAutoConfigurationTest.aServletApplicationGetsThePlatformBeans`가 bean 부재를 단언 | - | 소비자가 없으므로 `core/WebRequestContext`·`mvc/context/*`·`webMvcRequestContextConfigurer` bean을 삭제(쓰려면 `WebMvcRequestIdFilter`에서 `store` 호출) | | I-1d | Critical | `WebResourceNotVisibleException`이 기본 envelope 계약에서 catch-all 500 | 해당 없음(코드 삭제) | `208077fd`에만 `web/error/WebResourceNotVisibleException.java` 존재, HEAD grep 0. 제거 표 「WebProblem 어휘」「durable operation HTTP 투영」 | - | - | | I-1e | Critical | 실서버 IT가 `OperationFixtureController`로 합성 context를 넣어 결함을 못 잡음 | 해당 없음(코드 삭제) | 제거 표 「WebProblem·budget·throttle·operation fixture와 lane」(`testkit/operation/`). HEAD에 `OperationFixtureController` 없음 | - | - | | I-2a | Required | 인증 없는 알림 콜백이 `@RequestBody byte[]`로 본문 전체를 읽은 뒤 크기 검사 | 완료 | Wave 1–2 P10 (fcddab7e·Wave 2 커밋): `NotificationCallbackMvcControllerTest.aDeclaredOversizeBodyIsRefusedWithoutReadingIt`, `anUndeclaredOversizeBodyIsRefusedAfterReadingOneByteOverTheCeiling` FAIL(컴파일: `method callback … cannot be applied to given types` — `@RequestBody byte[]` 시그니처)→PASS. 컨트롤러가 `HttpServletRequest`만 받아 Content-Length 초과면 읽지 않고 413, 아니면 `readNBytes(max+1)`(`src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/NotificationCallbackMvcController.java:85,91`) | - | 컨트롤러가 `HttpServletRequest`만 받아 `getContentLengthLong() > maxBodyBytes`면 413, 본문은 `getInputStream().readNBytes(maxBodyBytes + 1)`로 읽고 초과 시 413 | @@ -466,7 +469,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | J-10g | Consider | `schema/` 19개 중 16개 도달 불가 | 해당 없음(코드 삭제) | 제거 표 「schema gate·병렬 조립기 … 14개」. 남은 `schema/` 3개(`GraphQlScalar*`)는 자동 설정에서 도달 | - | - | | J-11a | Consider | CLAUDE.md가 Accept negotiation을 `wired`로 표기(`GraphQlMediaTypes` 도달 불가) | 해당 없음(코드 삭제) | 제거 표 「병렬 HTTP 전송 모델(… `GraphQlMediaTypes`, `GraphQlAcceptHeader` …)」, CLAUDE.md 등급 표에서 행 제거됨 | - | - | | J-11b | Consider | README/CLAUDE가 없는 `GraphqlExceptionResolver`와 "비-carrier는 null 반환 → Spring 기본 처리"를 설명(실제는 전부 마스킹) | 남음 | `src/adapter/inbound/graphql/README.md:64-79`, `src/adapter/inbound/graphql/CLAUDE.md:52,125` | W5 | 현재 구조(`GraphQlDataFetcherExceptionResolver` → `GraphQlWireErrorMapper`, unknown은 마스킹)로 해당 절 재작성 | -| J-12 / X2-P2-6b | Consider | prod가 익명 principal resolver로 기동한 뒤 모든 요청을 `AUTHENTICATION_REQUIRED`로 거부 | 남음 | Wave 1–2 P8 (fcddab7e·Wave 2 커밋): `autoconfigure/GraphQlDeploymentModeContractTest.aProductionModeRefusesTheAnonymousPrincipalResolver`(PRODUCTION_INTERNAL·PUBLIC) FAIL(`to have failed but context started successfully`) → PASS, `aProductionModeWithAnExplicitPolicyAndResolverStarts` PASS. 기본 `graphQlPrincipalResolver` bean이 production이면 `GraphQlPlatformConfigurationException`(mode 없으면 REQUIRED_MESSAGE). `.../autoconfigure/GraphQlPlatformAutoConfiguration.java:243`. 커밋 `aa5f4d90`
J-12 부분은 완료(production에서 principal resolver가 없으면 기동 거부). X2-P2-6b 나머지(`AuthorizationPrincipal` tenant, gRPC 인증 정책, 가명 포트 통일)는 Wave 3 3-D | W3 | `graphQlPrincipalResolver` 기본 bean도 `properties.production()`이면 `GraphQlPlatformConfigurationException`
X2-P2-6b: `AuthorizationPrincipal`에 tenant 추가해 모든 inbound가 생성, GraphQL에 Spring Security `Authentication` → principal 기본 resolver, 가명은 `UserPrincipalPseudonymizerPort` 하나로 | +| J-12 / X2-P2-6b | Consider | prod가 익명 principal resolver로 기동한 뒤 모든 요청을 `AUTHENTICATION_REQUIRED`로 거부 | 보류 | Wave 3 W3-P19 (Wave 3 라운드 3 커밋): J-12(production에서 익명 principal resolver 기동 거부)는 Wave 1–2 `aa5f4d90`에서 완료. X2-P2-6b 나머지 3건은 결정 필요: (1) `AuthorizationPrincipal`에 tenant — 지금 읽는 `AuthorizationPort` 구현이 없어 추가하면 소비자 0 필드가 된다(어떤 인가 결정이 tenant를 쓸지 정해야 함), (2) GraphQL에 Spring Security `Authentication` → principal 기본 resolver — graphql leaf는 spring-security를 test scope에만 두고 "서버·보안 스택은 composition이 고른다"는 규칙(`adapter/inbound/graphql/CLAUDE.md`)이라 main 의존 추가가 구조 결정, (3) 가명을 `UserPrincipalPseudonymizerPort` 하나로 — web rate-limit의 `EdgeSubjectPseudonymizer`는 키 버전·회전이 있는 rate-limit 키 전용이라 로그 가명 포트와 목적(키 분리)이 다르다. 승인자: 저장소 소유자 결정 필요 / 승인자: 소유자 결정 35(2026-09-29) | W3 | `graphQlPrincipalResolver` 기본 bean도 `properties.production()`이면 `GraphQlPlatformConfigurationException`
X2-P2-6b: `AuthorizationPrincipal`에 tenant 추가해 모든 inbound가 생성, GraphQL에 Spring Security `Authentication` → principal 기본 resolver, 가명은 `UserPrincipalPseudonymizerPort` 하나로 | | K-1 | Required | `HandshakeAdmissionPipeline`이 bearer/cookie 헤더 존재만으로 통과, 모든 사용자가 한 actor | 해당 없음(코드 삭제) | 제거 표 「platform catalog·정책 패키지 … `handshake` …」(K#1 명시). 현재 websocket main에 `handshake/` 없음 | - | - | | K-2a | Required | servlet 런타임에서 frame/fragment 상한(`FragmentAssembler`)이 동작하지 않음 | 해당 없음(코드 삭제) | 제거 표 「`inbound/FragmentAssembler`, … `maxFrameBytes`·`maxFragments` …」(K#2 명시) | - | - | | K-2b | Required | 실제 수신 상한이 Tomcat 기본 8 KiB이고 설정한 `maxMessageBytes`와 무관 | 완료 | handler가 whole message의 크기를 직접 검사 `src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/servlet/PlatformWebSocketHandler.java:79-86`, 컨테이너 버퍼를 `maxMessageBytes`와 맞추는 조립 예·설명 `src/adapter/inbound/websocket/README.md:108-124`. 커밋 `6d27356e` | - | - | @@ -687,8 +690,8 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | X1-지도-자연키 생성-또는-반환 | 권고 | durable operation을 notification 방식(`ON CONFLICT`)으로, upsert executor 삭제 (= E-2) | 완료 | `DurableOperationJpaRepository.java:48` `ON CONFLICT … DO NOTHING`, `DurableOperationStoreAdapter.java:46-58` 삽입 후 재조회, upsert 실행기 7종 삭제(`docs/capability-status.md:158`), 커밋 `6d27356e` | - | - | | X1-지도-Inbox / 소비자 dedup | 권고 | app-core inbox 삭제, 나머지(messaging inbox·notification ledger) 유지 | 완료 | `application/inbox/`·`PostgreSqlSameStoreInboxAdapter` 삭제(`docs/capability-status.md:155`), mongo change stream dedup 삭제(`:151`); application-core 패키지 목록에 `inbox` 없음, 커밋 `6d27356e` | - | - | | X1-지도-lock / lease / fencing | 권고 | 미사용 포트·claim executor 삭제, fencing은 contract kit로 | 완료 | Wave 3 W3-P22 (Wave 3 라운드 3 커밋): 소유자 결정 8대로 lock·lease 포트 유지. claim executor·`CacheRefreshCoordinationPort`·`LeaseWatchdog`는 이미 `208077fd`에서 삭제돼 남은 미사용 포트 없음. fencing은 contract kit로(P22 W2 `7f39bfda`): `application-core/src/testFixtures/.../lease/testkit/DistributedLeaseContract.java`(밀려난 holder의 renew·release는 NotOwner이고 후임의 lease를 건드리지 않는다, 같은 attempt 재acquire는 replay, 이중 release는 AlreadyAbsent — 7건)를 fake `InMemoryDistributedLease`(`InMemoryDistributedLeaseContractTest`), Redis 어댑터+in-memory 명령(`RedisDistributedLeaseContractTest`), 실제 Redis(`LiveRedisDistributedLeaseContractTest`, standalone lane)가 모두 통과. lock 포트의 공통 계약(JDBC 어댑터 포함)은 Wave 4 범위로 남김 | - | 결정(2026-09-25): lock·lease 유지, 쓰지 않는 claim executor만 삭제, fencing은 계약 테스트로 | -| X1-지도-caller 트랜잭션 guard | 권고 | 9벌 복사 → persistence-jpa helper 1개 (= E-3) | 남음 | persistence-jpa 복사본 4벌 + guard 없는 곳 10개(세부 X1-#4) | W3 | X1-#4 | -| X1-지도-Backoff 계산식 | 권고 | 10개, "full jitter" 뜻 3가지 → shared-contract `Backoff` | 남음 | 앱 쪽 3개 남음(`OutboxBackoffPolicy.java:63-68`, `ExponentialFullJitterBackoff.java:78`, `RetryBackoff.java:42`), JPA 2개 삭제 | W3 | X1-#9 | +| X1-지도-caller 트랜잭션 guard | 권고 | 9벌 복사 → persistence-jpa helper 1개 (= E-3) | 남음 | persistence-jpa 복사본 4벌 + guard 없는 곳 10개(세부 X1-#4)
Wave 3 W3-P19: 미완 — X1-#4와 같음(persistence-jpa는 완료, notification store 9개는 edge 결정 필요) / 결정 33(2026-09-29): edge 추가로 결정 → P30 | W3 | X1-#4 | +| X1-지도-Backoff 계산식 | 권고 | 10개, "full jitter" 뜻 3가지 → shared-contract `Backoff` | 완료 | Wave 3 W3-P19 (Wave 3 라운드 3 커밋): X1-#9 | - | X1-#9 | | X1-지도-Rate limit | 권고 | web 전용 병렬 타입 세트 삭제 (= I-8 일부) | 완료 | `WebRateLimiter`·web `RateLimitDecision`·`RateLimitFailurePolicy`·`WebMvcThrottleFilter` 삭제(`docs/capability-status.md:99`); 남은 경로 `RateLimitWebConfig.java:22` → `EdgeRateLimitTransportBridge` → shared `EdgeRateLimitPort`, 커밋 `6d27356e` | - | - | | X1-지도-Admission / in-flight | 권고 | 유지하되 gRPC check-then-increment는 `Semaphore`로 (= N-5) | 완료 | Wave 1–2 P5 (fcddab7e·Wave 2 커밋): N-5a와 같은 수정. `Semaphore` 대신 한 락: in-flight와 queued 두 카운터를 한 결정에서 함께 봐야 해서 semaphore 두 개로는 원자적으로 안 된다. `GrpcAdmissionController.java:52`, `GrpcAdmissionControllerTest` | - | X1-#10a | | X1-지도-Kafka producer | 권고 | legacy seam·platform 2개, 둘 다 TLS/SASL 없음 → outbox 정리에 포함 | 해당 없음(코드 삭제) | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): **삭제:** legacy seam producer(`KafkaSenderAutoConfiguration`·`KafkaSender`·`LegacyKafkaMessagingRootAutoConfiguration`)를 `6268c494`에서 지웠다.
**남은 producer:** platform 하나다. `KafkaSecurityConfigurer`로 TLS/SASL을 적용한다: `src/messaging/messaging-spring-boot-starter-kafka/src/main/java/dev/caskeleton/messaging/autoconfigure/KafkaMessagingAutoConfiguration.java:188` `config.putAll(producerSecurity(...))`, `:216`.
**같은 결함 없음:** `MessagingSecuredBrokerQualificationTest`가 PASS다 — `aPublishIsConfirmedByAPrivateCaBrokerThatRequiresSaslAsTheProviderUser`, `aPublishIsConfirmedByAPrivateCaBrokerThatRequiresAClientCertificate`, `:messaging:messaging-spring-boot-starter:integrationTest` 3/3. | - | X1-#1f | @@ -697,7 +700,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | X1-지도-테스트 fake / contract kit | 권고 | 같은 포트 fake가 모듈마다 따로 → 포트 소유 leaf testFixtures에 contract kit | 남음 | `TransactionPort` fake 21 → 10, kit 4개(DurableOperation·OutboxLeaseFencing·GrpcOperationLedger·sample WorkLogRepository) | W4 | X1-#3a~#3d | | X1-#1a | Required | Outbox V2 삭제 + v1 claim에 owner+token fencing 이식 | 완료 | `persistence-jpa/.../db/migration/postgresql/V17__outbox_event_lease_fencing.sql`, `OutboxStoreAdapter.java:102-123`(markPublished·markFailed·markDead가 `lease.owner()`·`lease.token()` 조건부 UPDATE), V2 코드·`jpa/outbox-storage`·`jpa/outbox-polling` 삭제(`docs/capability-status.md:175-179`), 커밋 `6d27356e` | - | - | | X1-#1b | Required | append 포트를 `OutboxAppendPort` 하나로, legacy는 cutover 후 삭제 | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): **소비자 4곳 이전:** `SubmitDurableOperationUseCase`(`src/application-core/src/main/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCase.java:72`, 계약 `DurableOperationSubmittedContract`)와 sample 3곳이 `OutboxAppendPort`를 쓴다.
**encoder:** 템플릿 encoder `JsonIntegrationEventEncoder`(`src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoder.java:47`)와 `IntegrationEventEncoderAutoConfiguration`.
**테스트:** `JsonIntegrationEventEncoderTest`, `IntegrationEventEncoderAutoConfigurationTest`, `DurableOperationSubmissionOutboxIntegrationTest`(실제 encoder) PASS. | - | 결정(2026-09-25): canonical 통일(S1-#2b와 같은 작업) | -| X1-#1c | Required | `CanonicalOutboxAppendAdapter`에 caller 트랜잭션 guard 없음 (= E-3) | 남음 | `CanonicalOutboxAppendAdapter.java:36-75` `append`가 트랜잭션 확인 없이 `repository.save` | W3 | X1-#4 helper를 `append` 첫 줄에서 호출(1곳) + 트랜잭션 없이 부르면 거부되는 테스트 | +| X1-#1c | Required | `CanonicalOutboxAppendAdapter`에 caller 트랜잭션 guard 없음 (= E-3) | 해당 없음(코드 삭제) | Wave 3 W3-P19 (Wave 3 라운드 3 커밋): `CanonicalOutboxAppendAdapter`가 P18(`423a29c4`)에서 `OutboxStoreAdapter.append`로 합쳐져 삭제됨. `append` 첫 줄이 guard(`OutboxStoreAdapterTest`의 "outbox append requires an active caller transaction" 단언), 이제 `CallerTransaction.require("outbox append")` | - | X1-#4 helper를 `append` 첫 줄에서 호출(1곳) + 트랜잭션 없이 부르면 거부되는 테스트 | | X1-#1d | Required | canonical 이벤트가 v1 claim을 타며 aggregate 순서·tenant 범위를 잃음 (= E-5) | 완료 | Wave 1–2 P9 (fcddab7e·Wave 2 커밋): E-5a·E-5b와 같은 변경 — canonical row claim 순서를 tenant·type·id + sequence·index로(PostgreSQL·H2 SQL), migration V18 index | - | X1-#1b에서 canonical 경로를 남기면: canonical row(`contract_id IS NOT NULL`) gate를 `(tenant_scope, aggregate_type, aggregate_id)` + `(aggregate_sequence, event_index)` 순서로, `H2OutboxClaimRepository`도 동일 | | X1-#1f | Required | legacy Kafka producer에 TLS/SASL 없음 (Critical #8 = M-2와 같은 문제) | 해당 없음(코드 삭제) | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): 위와 같다. 보안 블록을 추가할 대상인 `KafkaAdapterSettings`·`kafkaSeamProducer`가 `6268c494`에서 삭제됐다. canonical 경로의 producer는 `KafkaMessagingAutoConfiguration.java:188`에서 보안 profile을 적용하고, `MessagingSecuredBrokerQualificationTest` 2/2가 PASS다. | - | `KafkaAdapterSettings`에 security 블록(protocol·SASL·truststore) 추가 후 `kafkaSeamProducer` config에 반영, 또는 X1-#1b 결정으로 seam 자체 삭제 | | X1-#1g | Required | `src/messaging/CLAUDE.md`에 "앱은 `messaging_outbox`를 쓰지 않는다" 명시 | 남음 | `grep -n messaging_outbox src/messaging/CLAUDE.md` → 0건 | W5 | `src/messaging/CLAUDE.md` MSG-015 절(:60-89)에 한 줄 추가 | @@ -711,7 +714,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | X1-#3b | Required | 포트별 contract kit를 소유 leaf testFixtures에 두고 fake와 실제 adapter가 같이 실행 | 남음 | 있음: `DurableOperationStoreContract`, `OutboxLeaseFencingContract`, `GrpcOperationLedgerContract`(grpc-core-api testFixtures), sample `WorkLogRepositoryContract`. 없음: `IdempotencyStorePort`(testFixtures `InMemoryIdempotencyStore`, `RedisIdempotencyStoreAdapter`, `PostgreSqlOwnerSafeIdempotencyStore`가 공통 계약 없이 따로 테스트), `RecipientLeaseStorePort`(PG 전용 `PostgreSqlRecipientLeaseFencingIntegrationTest`만), tus upload, Redis gateway | W4 | application-core testFixtures `IdempotencyStoreContract`(구현 3개 상속), application-notification testFixtures `RecipientLeaseStoreContract`(fake + `JpaRecipientLeaseStore`)부터 추가(`AGENTS.md:218` 기준 5) | | X1-#3c | Required | `ObjectControlStore` fake 7개 → `@TempDir` 위 `LocalDevObjectControlStore` | 남음 | objectstorage 테스트 source set에 `implements ObjectControlStore` 7개 | W4 | fake 7개를 `LocalDevObjectControlStore`(`@TempDir`)로 교체 | | X1-#3d | Required | `DistributedLockPortContractTest`가 테스트 안에서 만든 fake를 검증 | 남음 | `application-core/src/test/.../lock/DistributedLockPortContractTest.java:46` `FakeDistributedLockPort` | W4 | X1-#6b 결정에 따라 테스트 삭제, 또는 testFixtures 추상 계약으로 바꿔 `LockRegistryDistributedLockAdapter`가 상속 | -| X1-#4 / S2-#6b | Required | caller 트랜잭션 guard 9벌 복사 → persistence-jpa `CallerTransaction.require` 하나 (= E-3) | 남음 | 복사본 4벌: `OutboxStoreAdapter.java:131`, `DurableOperationStoreAdapter.java:170`, `JpaLiveEventReplayAdapter.java:164`, `IdempotencyCapabilityGuard.java:93`(읽기 전용 변형 `JpaStreamScope.java:28` 별도). guard 0: `CanonicalOutboxAppendAdapter`, notification JPA store 9개(`persistence/notification/platform/*Store.java`, `@Transactional`도 0). messaging 2벌(`JdbcOutboxRepository.java:229`, `JdbcInboxRepository.java:102`)은 vendored라 유지
S2-#6b: `persistence-jpa/.../outbox/OutboxStoreAdapter.java:131`, `operation/DurableOperationStoreAdapter.java:170`, `liveevent/JpaLiveEventReplayAdapter.java:164`, `postgresql/idempotency/IdempotencyCapabilityGuard.java:93`; `outbox/CanonicalOutboxAppendAdapter.java`는 guard 0(조용한 dual-write) | W3 | persistence-jpa `transaction` 패키지에 `CallerTransaction.require(String op)` 추가, 복사본 4곳 교체 + `CanonicalOutboxAppendAdapter.append`와 notification store 9개의 쓰기 메서드에 호출 추가
S2-#6b: persistence-jpa에 `CallerTransaction.require(op)` 하나 두고 4곳 교체 + `CanonicalOutboxAppendAdapter.append`에 적용 | +| X1-#4 / S2-#6b | Required | caller 트랜잭션 guard 9벌 복사 → persistence-jpa `CallerTransaction.require` 하나 (= E-3) | 남음 | 복사본 4벌: `OutboxStoreAdapter.java:131`, `DurableOperationStoreAdapter.java:170`, `JpaLiveEventReplayAdapter.java:164`, `IdempotencyCapabilityGuard.java:93`(읽기 전용 변형 `JpaStreamScope.java:28` 별도). guard 0: `CanonicalOutboxAppendAdapter`, notification JPA store 9개(`persistence/notification/platform/*Store.java`, `@Transactional`도 0). messaging 2벌(`JdbcOutboxRepository.java:229`, `JdbcInboxRepository.java:102`)은 vendored라 유지
S2-#6b: `persistence-jpa/.../outbox/OutboxStoreAdapter.java:131`, `operation/DurableOperationStoreAdapter.java:170`, `liveevent/JpaLiveEventReplayAdapter.java:164`, `postgresql/idempotency/IdempotencyCapabilityGuard.java:93`; `outbox/CanonicalOutboxAppendAdapter.java`는 guard 0(조용한 dual-write)
Wave 3 W3-P19: 미완 — persistence-jpa 복사본 4벌 + 읽기 전용 변형(`JpaStreamScope`, 삭제)은 `CallerTransaction` 하나로 교체(커밋 `080cc6aa`). 남은 것: notification JPA store 9개의 guard — P23에서 `adapter:outbound:persistence-notification` leaf로 추출됐고 그 leaf의 허용 edge는 application-core·application-notification뿐이라 persistence-jpa `CallerTransaction`을 쓸 수 없다. 사유: 결정 필요 — persistence-notification에 persistence-jpa(또는 adapter:outbound:support로 guard 이동 후 support) edge를 줄지. 새 복사본을 만들지 않았다. 승인자: 저장소 소유자 결정 필요 / 결정 33(2026-09-29): edge 추가로 결정 → P30 | W3 | persistence-jpa `transaction` 패키지에 `CallerTransaction.require(String op)` 추가, 복사본 4곳 교체 + `CanonicalOutboxAppendAdapter.append`와 notification store 9개의 쓰기 메서드에 호출 추가
S2-#6b: persistence-jpa에 `CallerTransaction.require(op)` 하나 두고 4곳 교체 + `CanonicalOutboxAppendAdapter.append`에 적용 | | X1-#5 | Required | web 병렬 rate-limit 타입·throttle filter 삭제 (= I-8 일부) | 완료 | `docs/capability-status.md:99-100`, `WebRateLimiter`·`WebMvcThrottleFilter`·`ThrottleProblemWriter` main 참조 0, 남은 경로 `RateLimitWebConfig.java:22` → `EdgeRateLimitPort`, 커밋 `6d27356e` | - | - | | X1-#6a | Required | 범용 claim executor(`PostgreSqlWorkClaimExecutor`·`WorkQueue*`) 삭제 | 완료 | `docs/capability-status.md:157`, main 참조 0, 커밋 `6d27356e` | - | - | | X1-#6b | Required | lock과 lease 중 하나만 남김 | 남음 | `DistributedLockPort`(구현 `LockRegistryDistributedLockAdapter`, 참조는 `StartupSafetyValidator.java:51` 존재 검사뿐), `DistributedLeasePort`(구현 `RedisDistributedLeaseAdapter`, 소비자 0). `CacheRefreshCoordinationPort`는 삭제(`docs/capability-status.md:152`). `LeaseAttempt`·`IdempotencyClaimAttempt` 같은 구조 그대로 | W4 | 결정(2026-09-25): lock·lease 둘 다 유지(S1-#3b와 같은 작업) | @@ -723,9 +726,9 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | X1-#7b | Required | API-surface gate 3개 → `ca.api-surface` 하나 | 완료 | notification·persistence-jpa·persistence-mongo·graphql 모두 `id 'ca.api-surface'`(`adapter/outbound/notification/build.gradle:4`, `persistence-jpa/build.gradle:7`), `ca.notification-api-surface`·`verifyJpaAdopterApiSurface` 삭제. JPA adopter import 검사는 leaf 테스트 `JpaAdopterApiSurfaceTest`, 커밋 `6d27356e` | - | - | | X1-#7c | Required | web·graphql·websocket main의 moduleboundary 3벌 → ArchUnit | 완료 | 3벌 삭제(`docs/capability-status.md:80,93,113`), graphql 규칙 2개는 `GraphQlTransportBoundaryArchitectureTest.java`로, 커밋 `6d27356e` | - | - | | X1-#8a | Consider | 소비자 0인 `FilePublicationPort` plane 삭제, parser 3→1, 경계 결정 문서화 | 완료 | `docs/capability-status.md:76-77`, fileserver `FileserverControlRecordCodec`·`LocalPublicationJournalCodec` 삭제, 남은 파서 `CanonicalJsonReader.java` 1개, `docs/storage-capability-boundary.md` "Decision rule" 절, 커밋 `6d27356e` | - | - | -| X1-#9 | Consider | Backoff 계산식 10개, "full jitter" 뜻 3가지 → shared-contract `Backoff` | 남음 | JPA `BackoffCalculator`·`TransactionRetryBackoff`, httpclient `BackoffStrategy` 삭제. 앱 쪽 3개: `OutboxBackoffPolicy.java:63-68`(이름은 full jitter인데 `base·2ⁿ + U(0,base)`, 상한 없음), `ExponentialFullJitterBackoff.java:78`(`U(0,capped]`), notification `RetryBackoff.java:42`. mongo·messaging·grpc는 자체 유지 대상 | W3 | shared-contract에 `Backoff(base, max, Jitter)`(stdlib만) 추가, 사용처 2곳(`OutboxBackoffPolicy`, `ExponentialFullJitterBackoff`) 교체; notification은 application-notification→shared-contract edge를 registry에 추가할 때만 | +| X1-#9 | Consider | Backoff 계산식 10개, "full jitter" 뜻 3가지 → shared-contract `Backoff` | 완료 | Wave 3 W3-P19 (Wave 3 라운드 3 커밋): 커밋 `35e1df8a`. `shared-contract/.../retry/Backoff.java`(ceiling·fullJitter=U[0,ceiling]·decorrelatedJitter, 포화 연산), `BackoffTest` 7건. httpclient `ExponentialFullJitterBackoff`, notification `RetryBackoff`(application-notification→shared-contract edge를 이 묶음에서 추가했으므로 포함; multiplier 제거·base 하한 유지), outbox `OutboxBackoffPolicy`(ceiling 120s 상한 + 한 base짜리 full jitter). outbox를 순수 full jitter로 바꾸지 않은 이유: 0 지연이면 실패 순간 재claim되므로 기존 불변식(`nextAttemptAtIsAlwaysAfterNow`)과 registry `retry_after_seconds=30`이 깨진다 — 대신 "full jitter"라는 이름을 문서에서 바로잡음(`application-core/README.md`). mongo·messaging·grpc는 자체 유지 | - | shared-contract에 `Backoff(base, max, Jitter)`(stdlib만) 추가, 사용처 2곳(`OutboxBackoffPolicy`, `ExponentialFullJitterBackoff`) 교체; notification은 application-notification→shared-contract edge를 registry에 추가할 때만 | | X1-#10a | FYI | `GrpcAdmissionController` check-then-increment → `Semaphore.tryAcquire` (= N-5) | 완료 | Wave 1–2 P5 (fcddab7e·Wave 2 커밋): 위와 같음(동시 호출 수 > 한도 테스트 `GrpcAdmissionControllerTest.racingCallersNeverGetPastTheConcurrencyAndQueueBounds`, optional build) | - | `inFlight`·`queued`를 `Semaphore` 또는 `updateAndGet` CAS로, 동시 호출 수 > 한도 테스트 1개(optional build) | -| X1-#10b | FYI | SHA-256 헬퍼 65벌, notification `MessageDigestPort`는 과한 추상화 → 흡수 | 남음 | `application-notification/.../dispatch/MessageDigestPort.java` + `Sha256MessageDigestAdapter.java` 그대로. 헬퍼 수는 X2-P1-5 | W3 | X2-P1-5와 같이. `MessageDigestPort`는 application-notification이 shared-contract edge를 가져야 흡수 가능 → edge 추가 후 포트·adapter 2개 삭제 | +| X1-#10b | FYI | SHA-256 헬퍼 65벌, notification `MessageDigestPort`는 과한 추상화 → 흡수 | 완료 | Wave 3 W3-P19 (Wave 3 라운드 3 커밋): 커밋 `bca2c682`. application-notification → shared-contract edge 추가(modules.json) 후 `MessageDigestPort`·`Sha256MessageDigestAdapter`·`NotificationDigest` 삭제 | - | X2-P1-5와 같이. `MessageDigestPort`는 application-notification이 shared-contract edge를 가져야 흡수 가능 → edge 추가 후 포트·adapter 2개 삭제 | | X2-P1-1a | Required | S3 시크릿이 `System::getenv` 고정 → `SecretSourcePort` bridge | 완료 | Wave 1–2 P2 (fcddab7e·Wave 2 커밋): `S3ProviderCompositionTest.capabilityConfigResolvesS3CredentialsThroughTheSecretSourcePort` FAIL(`IllegalArgumentException: S3 provider binding is invalid: credential environment references did not resolve completely`)→PASS. `s3/S3ObjectStorageProviderContribution.java:33`(공개 생성자가 `SecretSourcePort`를 받고 `System::getenv` 제거), `config/ObjectStorageCapabilityConfig.java:47-51`(`ObjectProvider`를 자격 증명을 실제로 풀 때 조회 — secret backend 없는 local-only 조립도 기동됨). 새 설정·env 키 없음 | - | S3 contribution에 `SecretSourcePort`를 주입해 `secretSource::resolve`(Redis `RedisCapabilityConfig.java:66-67` 방식), `System::getenv` 기본값 제거 | | X2-P1-1b | Required | Mongo credential bridge 없음(기본 `unconfigured()`) | 완료 | Wave 1–2 P12 (fcddab7e·Wave 2 커밋): `MongoProfileClientSettingsAutoConfigurationTest.aTypedProfileResolvesItsUriThroughTheApplicationSecretSource` FAIL(`IllegalStateException: MongoDB typed profiles are configured but no MongoCredentialResolver bean is available`)→PASS, `aSecretSourceWithoutTheReferencedKeyFailsClosed`. `src/config/architecture/modules.json:81-86`(`adapter-outbound-persistence-mongo` → `application-core`), `src/adapter/outbound/persistence-mongo/build.gradle:32`(`implementation project(':application-core')`), bridge bean `client/MongoProfileClientSettingsAutoConfiguration.java:57`(`@ConditionalOnBean(SecretSourcePort)`·`@ConditionalOnMissingBean(MongoCredentialResolver)`, `MongoCredentialResolver.fromSecretSource(secretSource::resolve)`), `security/MongoCredentialResolver.java:42`(key = `secret:///`의 ``, Redis·httpclient와 같은 규칙). `MongoRegistryPermissionParityTest`(app-bootstrap) PASS. 이유는 W1 커밋 메시지에 적음. | - | modules.json에 persistence-mongo→application-core edge 추가 후 Mongo auto-config에 `MongoCredentialResolver` bridge bean 1개(`secretSource::resolve`) | | X2-P1-2a | Required | websocket prod 판정 직접 구현(`Prod`·공백 미인식) (= A-2) | 해당 없음(코드 삭제) | `WebSocketPlatformSafetyConfiguration`·`app.websocket.platform.*` 삭제(`docs/capability-status.md:186`), websocket main에 `"prod"` 문자열 0 | - | - | @@ -734,10 +737,10 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | X2-P1-3b | Required | gRPC adapter strict prefix `ca-skeleton.grpc`가 벤더 `ca-skeleton.grpc.platform`과 겹침 | 완료 | Wave 1–2 P5 (fcddab7e·Wave 2 커밋): `GrpcSafeActivationTest.theVendorPlatformNamespaceBesideTheAdapterDoesNotFailItsStrictBinding` FAIL(`UnboundConfigurationPropertiesException: The elements [ca-skeleton.grpc.platform.enabled] were left unbound`)→PASS. 어댑터 prefix `ca-skeleton.grpc` → `ca-skeleton.grpc.server` `src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerSettings.java:17`, `GrpcServerConfig.java`. 어댑터 키는 env-keys registry에 행이 없었다(추가·수정 없음). 갱신: `src/adapter/inbound/grpc/{CLAUDE,README}.md`, `src/README.md:269`(env `CA_SKELETON_GRPC_SERVER_ALLOW_INSECURE_LOCAL`). **오케스트레이터 할 일:** `docs/capability-status.md:42`의 `ca-skeleton.grpc.enabled`·`ca-skeleton.grpc.allow-insecure-local`을 `.server.` 경로로. Wave 3-B(`app.*`)에서도 `app.grpc.server`처럼 벤더 prefix와 형제로 둬야 같은 충돌이 다시 안 생긴다. 커밋 `a498ad84` | - | adapter prefix를 `ca-skeleton.grpc.server` 등으로 분리(설정 키·env key·README 갱신) | | X2-P1-3c | Required | 오타 키 거부가 일부 capability에만 적용 | 남음 | strict 바인딩 4곳(fileserver·httpclient `StrictSettingsBinder`, `GrpcServerSettings.java:17`, `GrpcPlatformProperties.java:19`) / main `@ConfigurationProperties` 54파일(`git grep -l "@ConfigurationProperties" -- 'src/**/src/main/java/**'`) | W3 | `AGENTS.md:216` 기준대로 capability 모듈(cache-redis, persistence-jpa, persistence-mongo, messaging, notification, objectstorage, graphql, websocket) settings를 `StrictSettingsBinder`로 바인딩 | | X2-P1-4a | Consider | web `cursor/CursorCodec`(dev key 하드코딩) 삭제 | 완료 | `docs/capability-status.md:94`, `HmacWebCursorCodec`도 삭제(`:97`), 커밋 `6d27356e` | - | - | -| X2-P1-4b | Consider | 서명 계층 하나(inbound에서 서명, persistence는 typed keyset), 남으면 공용 서명 헬퍼 | 남음 | HMAC codec 7 → 4: graphql `HmacGraphQlCursorCodec`, persistence-jpa `SignedJsonCursorCodec`, persistence-mongo `MongoKeysetCursorCodec`, 벤더 `GrpcResumeTokenCodec`. 앱 쪽 3개 모두 production 생성 0(라이브러리 API) | W3 | 결정(2026-09-25): Wave 3 라이브러리 유지 결정을 따름 — 서명 codec 유지, shared-contract에 sign/verify 헬퍼 하나로 중복 제거 | -| X2-P1-5 | Consider | SHA-256 보일러플레이트 → shared-contract `Sha256` | 남음 | `MessageDigest.getInstance` main 72곳/68파일(`208077fd`) → 40곳/36파일(현재, `git grep -c 'MessageDigest.getInstance' -- 'src/**/src/main/java/**'`). shared-contract에 `Sha256` 없음(app-core `application/messaging/contract/Sha256.java` 값 타입만) | W3 | shared-contract `Sha256.hex(String)`·`digest(byte[])` 추가, edge 있는 25파일 교체(objectstorage 12, sample 3, graphql 2, cache-redis 2, fileserver 2, notification 2, persistence-jpa 2); mongo 3·application-objectstorage 2(edge 없음)와 벤더 5는 유지 | +| X2-P1-4b | Consider | 서명 계층 하나(inbound에서 서명, persistence는 typed keyset), 남으면 공용 서명 헬퍼 | 완료 | Wave 3 W3-P19 (Wave 3 라운드 3 커밋): 커밋 `35e1df8a`. `shared-contract/.../digest/HmacSha256.java`(sign/verify, 길이 먼저 확인 후 constant-time), `HmacSha256Test` 5건. 사용: graphql `HmacGraphQlCursorCodec`·`GraphQlIdentityFingerprinter`, persistence-jpa `SignedJsonCursorCodec`, notification HMAC 3곳, sample digester. 서명 codec은 유지(2026-09-25 결정). mongo `MongoKeysetCursorCodec`은 shared-contract edge 없어 유지, redis·identifier·fileserver는 동시 묶음/edge 없음으로 유지 | - | 결정(2026-09-25): Wave 3 라이브러리 유지 결정을 따름 — 서명 codec 유지, shared-contract에 sign/verify 헬퍼 하나로 중복 제거 | +| X2-P1-5 | Consider | SHA-256 보일러플레이트 → shared-contract `Sha256` | 완료 | Wave 3 W3-P19 (Wave 3 라운드 3 커밋): 커밋 `bca2c682`. `shared-contract/.../digest/Sha256.java`(of/ofUtf8/newMessageDigest/hex), `Sha256Test` 5건. `MessageDigest.getInstance` main 36곳 → 10곳(mongo 3, application-objectstorage 2 — shared-contract edge 없음; vendored messaging 2·gRPC 2; cache-redis SHA-1 1) | - | shared-contract `Sha256.hex(String)`·`digest(byte[])` 추가, edge 있는 25파일 교체(objectstorage 12, sample 3, graphql 2, cache-redis 2, fileserver 2, notification 2, persistence-jpa 2); mongo 3·application-objectstorage 2(edge 없음)와 벤더 5는 유지 | | X2-P1-6 | Consider | JSON 문자열 escape 동작 3가지 | 완료 | Wave 3 W3-P15 (Wave 3 라운드 1 커밋): sample 3곳의 사본을 `sample-portfolio/.../application/event/EventJson.java:11`(RFC 8259 §7) 하나로. `PosterImagePublicationEventPublisher`의 제어문자 누락 제거. 재현 FAIL은 못 만듦: 그 publisher의 입력(`PosterId`·`ObjectOperationId`·`PosterImageReference`·`ObjectMediaType`)이 모두 형식 검증돼 현재 경로로 제어문자가 들어갈 수 없는 잠재 결함이다. escape 표는 기존 `WorkLogReservedIntegrationEventMapperJsonTest.escapeProducesRfc8259EscapedText`가 `EventJson.escape`를 검증(PASS). 앱 쪽 `OutboxEnvelopeJson`은 지시대로 그대로. 커밋 `8ad36211` | - | sample 3곳을 Jackson 직렬화(또는 sample 안 helper 1개)로 통일해 `PosterImagePublicationEventPublisher` 제어문자 누락 수정. 앱 쪽 사본은 `OutboxEnvelopeJson` 1개뿐이라 공용 `JsonStrings`는 만들지 않음 | -| X2-P1-7 | Consider | 주입된 Clock을 우회하는 시간 조회 | 남음 | `RoutingObjectMutationAdapter.java:60` `clock` 필드가 있는데 `Instant.now()` 12곳(:128-349), 기본 생성자 `Clock.systemUTC()`(:64); objectstorage 설정 5곳(`ObjectStorageBindingCompiler.java:40`, `ObjectStorageCapabilityConfig.java:110`, `ObjectStorageScanMaintenanceConfig.java:23`, `S3ObjectStorageProviderContribution.java:33,35`); `MvcStreamWriter` 5, `LiveEventStompBroadcaster`·`MongoTenantClientRegistry`·`KeyOperationRequests` 각 1. main 전체 `Instant.now()` 26곳/11파일, `Clock.systemUTC()` 11곳/10파일 | W3 | objectstorage 설정 5곳에 `Clock` bean 주입, `RoutingObjectMutationAdapter` 12곳을 `clock.instant()`로; 나머지 4파일은 생성자로 Clock 주입 | +| X2-P1-7 | Consider | 주입된 Clock을 우회하는 시간 조회 | 완료 | Wave 3 W3-P19 (Wave 3 라운드 3 커밋): 커밋 `c3b7bacb`·`ccb90e82`. objectstorage 설정 5곳(`ObjectStorageCapabilityConfig` capability·handoff·binding compiler·S3 contribution, `ObjectStorageScanMaintenanceConfig`)이 `ObjectProvider`(Clock bean, 없으면 system UTC)을 주입(`ObjectStorageCapabilityConfig.clock`); `S3ObjectStorageProviderContribution(SecretSourcePort, Clock)`. 생성자 Clock: `LiveEventStompBroadcaster`(websocket), `MongoTenantClientRegistry`(mongo, `MongoTenancyContractTest.anAcquireWithoutAnInstantReadsTheInjectedClock`), `MvcStreamWriter`(web-advanced 5곳). redis-sdk `KeyOperationRequests`는 동시 묶음 P22 영역이라 손대지 않음(남은 1곳) | - | objectstorage 설정 5곳에 `Clock` bean 주입, `RoutingObjectMutationAdapter` 12곳을 `clock.instant()`로; 나머지 4파일은 생성자로 Clock 주입 | | X2-P2-1a | Required | `VALIDATION_FAILED`가 Envelope 400 vs problem-catalog 422 (= I-9) | 해당 없음(코드 삭제) | `problem-catalog.yaml`·`ProblemCatalog` 삭제(`docs/capability-status.md:104`), 남은 정의 `OperationalError.java:15` 400 하나 | - | - | | X2-P2-1b | Required | budget 경로가 `URI_TOO_LONG`·JSON 깊이 초과를 다른 코드·problem+json으로 | 해당 없음(코드 삭제) | `WebMvcBudgetFilter`·`BudgetProblemMapper` 삭제(`docs/capability-status.md:105`) | - | - | | X2-P2-1c | Required | `ProblemCode`·`ProblemCatalog` 동의어 어휘 제거 | 완료 | `docs/capability-status.md:104`, `git grep -w ProblemCode -- 'src/**/src/main/**'` → 0, 커밋 `6d27356e` | - | - | @@ -748,9 +751,9 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | X2-P2-2b | Required | `IllegalArgumentException`: web 400, GraphQL·gRPC `INTERNAL_ERROR` | 완료 | Wave 3 W3-P15 (Wave 3 라운드 1 커밋): GraphQL `GraphQlWireErrorMapperTest.anIllegalArgumentIsABadParameterRequestError` FAIL(`["INTERNAL_ERROR", "INTERNAL"]`)→PASS(`error/GraphQlWireErrorMapper.java:174`); gRPC `GrpcExceptionHandlingInterceptorTest.mapsAnIllegalArgumentToInvalidArgumentBadParameter` FAIL(`[INTERNAL, "INTERNAL_ERROR"]`)→PASS(`GrpcExceptionHandlingInterceptor.java:114`); STOMP `SafeStompSubProtocolErrorHandlerTest.anIllegalArgumentReportsBadParameter` FAIL(`but was: "WEBSOCKET_REQUEST_REJECTED"`)→PASS; web은 기존 동작 유지(`GlobalExceptionHandler.java:76`) | - | 결정(2026-09-25): `IllegalArgumentException`은 모든 전송에서 400(GraphQL `BAD_USER_INPUT`, gRPC `INVALID_ARGUMENT`) — web 현재 동작 유지 | | X2-P2-3a | Required | 같은 servlet 앱에서 Envelope와 fileserver problem+json 혼재(소유자 결정: Envelope 하나) | 완료 | Wave 3 W3-P15 (Wave 3 라운드 1 커밋): `FileserverHardeningContractTest.aFailureIsTheSharedEnvelopeCarryingTheStableCode` FAIL(`Response header 'Content-Type' expected: but was:`)→PASS. `web-fileserver/.../problem/FileserverExceptionHandler.java:47`. problem 타입 4개 삭제(아래 표). 이름 중복 3개(`UNAUTHENTICATED`·`PRECONDITION_FAILED`·`UNSUPPORTED_MEDIA_TYPE`)는 **더 작은 수정**: `FileserverFailureContext.code()`가 `FileserverErrorCode` 하나라서 그 3개를 `OperationalError`로 바꾸면 context·header 표·application-fileserver 전반의 타입이 바뀐다(같은 시기 fileserver 상태 전이 묶음과 충돌). 두 enum의 category·status·retryable이 이미 같아 wire는 동일하므로 `FileserverExceptionTest.aCodeNamedLikeAnOperationalErrorMeansTheSameOnTheWire`(28 case PASS)로 동일성을 고정했다 | - | `FileserverExceptionHandler`가 web `ErrorResponseFactory.envelope`로 응답, `FileserverProblemHeaders`(Retry-After·Content-Range·tus 헤더)는 유지, problem 타입 4개 삭제, 이름 중복 3개는 `OperationalError` 사용 | | X2-P2-3b | Required | Draft-12 upload offset 불일치 응답이 규격 problem 문서 | 완료 | Wave 3 W3-P15 (Wave 3 라운드 1 커밋): 결정 12대로 유지 + 예외 명시: `Draft12UploadController.java:165` Javadoc("Protocol exception to the Envelope rule"), `Draft12OffsetProblem` Javadoc, `docs/fileserver/http-contract.md` 「Protocol exceptions to the Envelope rule」 절, `FileserverExceptionHandler` Javadoc. `Draft12ProtocolTest.offsetMismatchReturnsTheDraftProblemDetailWithBothOffsets` PASS(그대로 problem+json) | - | 결정(2026-09-25): Draft-12 offset 불일치 problem 문서는 프로토콜 예외로 유지(tus 헤더와 같은 취급), 예외 목록을 문서에 명시 | -| X2-P2-4 | Required | 한 요청에서 traceparent를 두 규칙으로 파싱 (= I-4 영역) | 남음 | `WebMvcRequestIdFilter.java:49-50,113-118` 정규식(version 무시, 전부 0인 trace-id 허용) vs `RequestLoggingFilter.java:105-106` `TraceParent.parse`. WebFlux 사본은 삭제. request id는 `RequestLoggingFilter.java:59-60`이 `WebRequestId`를 재사용하도록 바뀜 | W3 | `WebMvcRequestIdFilter`의 `TRACEPARENT` 정규식을 지우고 shared-contract `TraceParent.parse` 사용(1곳) | -| X2-P2-5 | Consider | correlation이 HTTP 밖으로 안 이어짐, `MdcKeys`가 web에 갇힘 | 남음 | `adapter/inbound/web/.../observability/MdcKeys.java`(사용 5파일, web-fileserver 포함), `MDC.put`은 `RequestLoggingFilter.java:65-71,147`뿐, `CorrelationIdPort` 구현은 `MdcCorrelationIdPortAdapter` 1개, GraphQL은 `GraphQlPlatformWebInterceptor.java:157` Spring request id | W3 | `MdcKeys`를 shared-contract로(원본 `docs/registries/mdc-keys.yaml`), 사용 5파일 import 변경; websocket STOMP·gRPC interceptor에 MDC 채우는 코드, GraphQL은 `WebRequestId` 사용 | -| X2-P2-6a | Required | 같은 이름 `TenantContext` 2개, 허용 문법이 다름 | 남음 | web `core/TenantContext.java:20` `[A-Za-z0-9][A-Za-z0-9_.-]{0,63}` vs graphql `context/TenantContext.java:17,30`(비어있지 않고 128자 이하). 그 밖에 persistence-jpa `experimental/tenant/TenantId`, application-notification `TenantId` | W3 | application-core에 tenant id 값 타입 1개(web 문법) 두고 web·graphql `TenantContext` 2곳이 감쌈, notification·jpa `TenantId`도 같은 타입으로 맞춤 | +| X2-P2-4 | Required | 한 요청에서 traceparent를 두 규칙으로 파싱 (= I-4 영역) | 완료 | Wave 3 W3-P19 (Wave 3 라운드 3 커밋): 수정 자체는 Wave 2 `016597ac`에서 이미 됨(`WebMvcRequestIdFilter`가 정규식 대신 `TraceParent.parse`). 이번에 회귀 테스트 추가(커밋 `ccb90e82`): `WebMvcRequestIdFilterTest.aTraceparentTheSharedParserRefusesIsReplaced`(버전 ff, 0 trace id, 0 span id). gRPC 쪽도 같은 parser(`GrpcCorrelationInterceptorTest.aTraceparentTheSharedParserRefusesIsNotAdopted`) | - | `WebMvcRequestIdFilter`의 `TRACEPARENT` 정규식을 지우고 shared-contract `TraceParent.parse` 사용(1곳) | +| X2-P2-5 | Consider | correlation이 HTTP 밖으로 안 이어짐, `MdcKeys`가 web에 갇힘 | 완료 | Wave 3 W3-P19 (Wave 3 라운드 3 커밋): 커밋 `c3b7bacb`·`ccb90e82`. `shared-contract/.../observability/MdcKeys.java`(web에서 이동, 사용처 web·web-fileserver·app-bootstrap import 변경). gRPC `GrpcCorrelationInterceptor`(outermost, 콜백마다 MDC put/복원) — `GrpcCorrelationInterceptorTest` 3건; STOMP `WebSocketCorrelationInterceptor`(ExecutorChannelInterceptor) — 테스트 2건; GraphQL은 web leaf에 의존할 수 없어 `WebRequestId` 대신 filter가 MDC에 둔 `request_id`를 executionId로 사용 — `GraphQlPlatformWebInterceptorRequestBoundsTest.aRejectionNamesTheHttpRequestIdTheFilterAssigned`. registry 원본 `docs/registries/mdc-keys.yaml`은 키가 같아 변경 없음 | - | `MdcKeys`를 shared-contract로(원본 `docs/registries/mdc-keys.yaml`), 사용 5파일 import 변경; websocket STOMP·gRPC interceptor에 MDC 채우는 코드, GraphQL은 `WebRequestId` 사용 | +| X2-P2-6a | Required | 같은 이름 `TenantContext` 2개, 허용 문법이 다름 | 완료 | Wave 3 W3-P19 (Wave 3 라운드 3 커밋): 커밋 `b64471cb`. `application-core/.../tenant/TenantId.java`(web 문법, `optional()`은 형식이 틀리면 거부), `TenantIdTest`. web `core/TenantContext(Optional)`, graphql `context/TenantContext`가 이것으로 검증(`tenantId()` 추가). 수정 방향 중 notification·jpa `TenantId`를 같은 타입으로 맞추는 부분은 하지 않음: notification은 100자·임의 문자로 이미 저장된 행을 새 문법으로 읽으면 기존 데이터 읽기가 실패(데이터 호환 결정 필요 → P19-new-1), persistence-jpa experimental `TenantId`는 schema 이름에 들어가 소문자만 허용하는 더 엄격한 문법이 의도(보안상 넓히면 안 됨) | - | application-core에 tenant id 값 타입 1개(web 문법) 두고 web·graphql `TenantContext` 2곳이 감쌈, notification·jpa `TenantId`도 같은 타입으로 맞춤 | | X2-P2-7a | Required | 연결 안 된 두 번째 rate-limit stack 삭제 (= I-8 일부) | 완료 | `WebRateLimiter`·`WebMvcThrottleFilter`·`ThrottleProblemWriter` 삭제(`docs/capability-status.md:99-100`), WebFlux throttle은 WebFlux와 함께 삭제(`:88`), 커밋 `6d27356e` | - | - | | X2-P2-7b | Required | client IP 신뢰 규칙이 두 갈래 (= I-5) | 완료 | Wave 1–2 P10 (fcddab7e·Wave 2 커밋): I-5a와 같은 결함. client IP 해석 경로가 `getRemoteAddr()` 하나만 남음(XFF를 직접 읽는 main 코드 grep 0건, `ForwardedHeaderClientIpResolver` 삭제). 남은 `web-notification/.../ExternalRequestUrlResolver`는 client IP가 아니라 URL(proto/host) 해석이고 이미 trusted proxy일 때만 읽는다. 그 forwarded 파싱 삭제·설정 통합은 현황표 I-5b(W3)가 소유해서 이번에 건드리지 않음 | - | `ForwardedHeaderClientIpResolver`도 `remoteAddr`가 trusted proxy일 때만 XFF 사용(아니면 `remoteAddr`), 규칙은 `ExternalRequestUrlResolver`와 같은 설정 하나로 | | X2-P2-8 | Consider | Origin 검증기 3개, env key 3개 기본값 다름 | 해당 없음(코드 삭제) | web `WebCorsPolicyValidator` 삭제(`docs/capability-status.md:206`), websocket platform origin 정책·`APP_WEBSOCKET_PLATFORM_*` 삭제(`:186`); 남은 검증은 `WebSocketSettings.java:25`(+`@AssertTrue`) 1개 | - | - | @@ -786,7 +789,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | S1-#9 | Consider | 같은 전략만 담은 레지스트리 2개 | 완료 | Wave 3 W3-P23 (Wave 3 라운드 3 커밋): `TemplateRendererRegistry`·`MapTemplateRendererRegistry`·`ThymeleafNotificationRenderer`, `ProviderEventProjectorRegistry`·`MapProviderEventProjectorRegistry`·`SesDeliveryProjector` 삭제(`bff135d6`). renderer 하나(`CanonicalNotificationRenderer`, channel은 `RenderCommand`에서; `NotificationPlatformProviderConfig.java:53`)와 projector 하나(`StandardDeliveryProjector`; `NotificationPlatformRegistriesConfig.java:38`)를 직접 주입. `ProviderEventProjector.providerId()`·`NotificationTemplateRenderer.channel()`, `AssembledProvider`/`AssembledPlatform`의 projector 슬롯, `ProviderCallbackAssembler.projector()`, `NO_PROJECTOR` 분기 삭제. 테스트 `NotificationProviderAssemblyTest.anSesHardBounceIsProjectedByTheSharedProjector` PASS. PG 테스트 `PostgreSqlNotificationBackgroundPassIntegrationTest.replayMarksAnEventWithNoProjectorFailed`는 그 분기가 없어져 삭제 | - | 레지스트리·`Map*Registry` 삭제, 구현체 직접 주입 | | S1-#10a | Consider | `NotificationOrchestrator`·Reactor facade (= B-8) | 해당 없음(코드 삭제) | 「제거된 코드」 `NotificationOrchestrator`, Notification Reactor facade 행 | - | - | | S1-#10b | Consider | 제출 흐름 `prepare→inWrite→recordAccepted`가 서비스 public 진입점과 use case 2개에 3벌 | 완료 | Wave 3 W3-P23 (Wave 3 라운드 3 커밋): `NotificationSubmissionService`의 `submit`/`schedule`/private `accept` 삭제(`ce863643`). 테스트는 `SubmitNotificationApplicationUseCase`/`ScheduleNotificationApplicationUseCase`로 호출(`NotificationSubmissionServiceTest`, `NotificationDispatchServiceTest`). 수정 방향의 "두 use case가 private 헬퍼 1개 공유"는 하지 않음: ArchUnit 규칙 `useCaseCapabilityMatchesTransactionPortBoundary`(`ArchitectureViolationFixtureTest.java:272`)가 WRITE_REPOSITORY use case마다 `TransactionPort.inWrite`를 직접 호출하길 요구하므로 공유 헬퍼로 빼면 규칙 위반. 3벌→2벌(각 3줄) | - | 서비스의 `submit`/`schedule`/`accept` 삭제(테스트는 use case로), 두 use case는 scheduleAt만 다른 private 헬퍼 1개 공유 | -| S1-#11 | Consider | SHA-256 헬퍼 분산, `MessageDigestPort`가 stdlib를 포트로 감쌈, `RequestFingerprint` 이름 충돌 (= X2 P1-5) | 남음 | `application-notification/.../dispatch/MessageDigestPort.java:4` + `adapter/outbound/notification/.../Sha256MessageDigestAdapter.java`, main 33파일이 `MessageDigest.getInstance("SHA-256")` 직접, `RequestFingerprint` 2개(`application-core/.../idempotency/RequestFingerprint.java:17`, `application-notification/.../dispatch/RequestFingerprint.java:15`) | W3 | 기존 `application-core/.../messaging/contract/Sha256`에 `hex(byte[])` 두고 포트·어댑터 삭제, notification 쪽은 `PlanFingerprint`로 개명 | +| S1-#11 | Consider | SHA-256 헬퍼 분산, `MessageDigestPort`가 stdlib를 포트로 감쌈, `RequestFingerprint` 이름 충돌 (= X2 P1-5) | 완료 | Wave 3 W3-P19 (Wave 3 라운드 3 커밋): 커밋 `bca2c682`. app-core `messaging.contract.Sha256` 값 타입을 shared-contract로 옮겨 헬퍼와 합침(같은 이름 두 타입 방지), notification `RequestFingerprint` → `PlanFingerprint` | - | 기존 `application-core/.../messaging/contract/Sha256`에 `hex(byte[])` 두고 포트·어댑터 삭제, notification 쪽은 `PlanFingerprint`로 개명 | | S1-#12 | Consider | fileserver content SPI 확장 4개 구현·호출 0 | 완료 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): `b4fe7c8b`. `AsyncContentStore`·`CopyCapableContentStore`·`CapacityAwareContentStore`·`DelegatedDownloadStore`와 전용 타입 3개 삭제, `BlockingContentStore`를 `adapter/outbound/fileserver/.../platform/local/BlockingContentStore.java`로 이동. 표면 검사는 `BlockingContentStoreSurfaceTest.noMethodNamesAFilesystemOrFrameworkType`·`theStoreDeclaresTheExactDesignSurface`로 옮기고, application에는 `ContentStoreCapabilitiesTest` | - | 확장 4개 삭제, `BlockingContentStore`는 `adapter:outbound:fileserver` 내부로 이동 | | S1-#13 | Consider | `FileStateMachine` 인터페이스+구현+bean이 전이표 Map 하나 | 완료 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): `1ec8f087`. `FileState.canTransitionTo`/`requireTransitionTo`(`api/FileState.java:40`), `FileStateMachine`·`DefaultFileStateMachine`·bean(`FileserverVerificationConfiguration`, PG 테스트 context) 삭제, `JpaFileMetadataStore` 생성자에서 인자 제거. `FileStateTransitionTest.everyStatePairMatchesTheDesignTransitionTable` PASS | - | `FileState.canTransitionTo(target)` enum 메서드로 대체 | | S1-#14 | Consider | notification platform 미사용 약 920줄(예외 12, security 3, sms/push/email/webpush) (= B-8) | 해당 없음(코드 삭제) | 「제거된 코드」 notification `sms`·`push`·`email`·`webpush` facade, throw 0 예외 12종, redaction 5종 행. 해당 디렉터리 없음 확인 | - | - | @@ -802,7 +805,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | S1-#19 | Nit | 이력 주석·inline FQN | 남음 | 재측정: 이력 문구("used to" 등) application-core 14·notification 23·fileserver 9·objectstorage 1줄, notification inline FQN 74줄 | W5 | 불변 조건 1~2줄만 남기고 이력은 git/ADR로, FQN은 import로 | | S1-#20 | Nit | notification `dispatch/` 패키지에 여러 기능 | 남음 | `application-notification/.../platform/dispatch/` 46파일 3,855줄(제출·템플릿 게시·`ContactPoint*`·reconciliation 포함) | W5 | `submission/`, `dispatch/`, `reconciliation/`로 이동, `ContactPoint*`는 `contact/`로 | | S1-lead-1 | 권고 | messaging 자체 outbox/inbox와 app-core outbox/inbox가 같은 패턴 3~4벌 | 완료 | app-core inbox 삭제(「제거된 코드」 same-store inbox 행), outbox V2 삭제. 남은 2벌(app outbox + vendored `messaging_outbox`)은 D2 결정(`docs/superpowers/specs/2026-09-25-capability-module-packaging-design.md:104` "messaging platform outbox는 vendored라 유지") | - | - | -| S1-lead-2 | 권고 | UUID 생성기 제각각 | 남음 | notification 자체 `adapter/outbound/notification/.../dispatch/UuidV7Generator.java`, fileserver `RandomUploadIdentifierFactory`(v4), sample `Uuid*IdFactory`(uuid-creator v7) | W3 | notification `UuidV7Generator`를 sample이 쓰는 uuid-creator로 대체(v7 생성 1벌), fileserver v4는 유지 | +| S1-lead-2 | 권고 | UUID 생성기 제각각 | 완료 | Wave 3 W3-P19 (Wave 3 라운드 3 커밋): 커밋 `19ffd755`. notification `UuidV7Generator`가 uuid-creator `TimeOrderedEpochFactory`(주입 Clock, `withIncrementPlus1`)로 생성; `UuidV7GeneratorTest` 2건(버전 7, 같은 ms 1000개 정렬·중복 없음). lockfile 3개 재생성. fileserver v4 유지 | - | notification `UuidV7Generator`를 sample이 쓰는 uuid-creator로 대체(v7 생성 1벌), fileserver v4는 유지 | | S1-lead-3 | 권고 | 멱등성 executor 조립 위치 (= G-11) | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): NEW-2b와 같다. | - | `IdempotencyProviderSelectionConfig`·`IdempotencySettings`를 새 `composition:idempotency`(가칭) 모듈로 이동, registry 등록 | | S1-lead-4 | 권고 | `Local*Gateway`가 `LocalBlockingContentStore`로 넘기기만 | 완료 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): `b4fe7c8b`. `LocalBlockingContentStore`가 `DownloadContentPort`·`ZeroCopyDownloadPort`를 직접 구현(`platform/local/LocalBlockingContentStore.java:47`), `LocalDownloadContentGateway`·`LocalZeroCopyDownloadGateway`와 bean 2개 삭제. `LocalCleanupContentGateway`는 `purgeQuarantined`를 orphan scan에 넘기는 두 협력자 조합이라 위임 전용이 아니어서 유지. `LocalStorageGatewayContractTest` PASS | - | 위임만 하는 3개는 `LocalBlockingContentStore`가 해당 gateway 인터페이스를 직접 구현, 로직 있는 Copy/Upload는 유지 | | S1-lead-5 | 권고 | persistence-jpa `SpringPolicyTransactionPort` 정리 | 해당 없음(코드 삭제) | 「제거된 코드」 `SpringPolicyTransactionPort`… 행 | - | - | @@ -832,7 +835,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | S2-#14d | Nit | `JpaAdapterComponentsConfig`가 classpath 밖 leaf로 `{@link}` | 완료 | `persistence-jpa/.../config/JpaAdapterComponentsConfig.java:36`이 `{@code FileserverJpaPersistenceConfig}`로 변경(`208077fd`에서는 `{@link`) | - | - | | S2-lead-1 | 권고 | app-core 포트 버전이 #4의 원인 | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): 포트 버전이 하나로 줄었다: `OutboxAppendPort`(append)와 `OutboxStorePort`(claim/완료). 근거는 S1-#2b와 같다. | - | 결정(2026-09-25): canonical 통일(S1-#2b와 같은 작업) | | S2-lead-2 | 권고 | 멱등성 claim 판정표가 Redis·PG에 따로 (= X1-#3) | 남음 | Redis 판정은 Lua 안(`cache-redis/.../idempotency/IdempotencyScripts.java`) + 응답 매핑 `RedisIdempotencyStoreAdapter.java:135-157`, PG는 `postgresql/idempotency/IdempotencyClaimGateway.java`. 공통 계약 테스트 없음(`application-core/src/testFixtures/.../idempotency/testkit/`에 `InMemoryIdempotencyStore`만) | W4 | application-core testFixtures에 `IdempotencyStoreContract` 추가, InMemory·Redis·PG adapter가 모두 상속 | -| S2-lead-3 | 권고 | 서명 cursor codec 여러 벌 (= X2 P1-4) | 남음 | web `CursorCodec`·`HmacWebCursorCodec` 삭제(「제거된 코드」 서명 커서 코덱·2세대 페이지네이션 행). 남은 3벌: `persistence-jpa/.../api/query/SignedJsonCursorCodec.java`, `persistence-mongo/.../query/pagination/MongoKeysetCursorCodec.java`, `graphql/.../pagination/HmacGraphQlCursorCodec.java` | W3 | X2 P1-4대로 서명은 inbound 한 계층, persistence는 typed keyset만(jpa·mongo codec 삭제 또는 서명 제거) | +| S2-lead-3 | 권고 | 서명 cursor codec 여러 벌 (= X2 P1-4) | 완료 | Wave 3 W3-P19 (Wave 3 라운드 3 커밋): X2-P1-4b와 같음(`35e1df8a`). 수정 방향의 "jpa·mongo codec 삭제"는 2026-09-25 라이브러리 유지 결정과 충돌해 서명 헬퍼 공유로 좁힘(프롬프트 기본값) | - | X2 P1-4대로 서명은 inbound 한 계층, persistence는 typed keyset만(jpa·mongo codec 삭제 또는 서명 제거) | | S2-lead-4 | 권고 | persistence 실패 예외 계층 3벌 | 완료 | Wave 3 W3-P15 (Wave 3 라운드 1 커밋): `JpaPersistenceExceptionCodeTest.aJpaFailureCarriesTheOperationalCodeOfItsCategory` 16건 FAIL(`Expecting actual throwable to be an instance of: PersistenceFailureException`)→PASS. `persistence-jpa/.../api/error/JpaPersistenceException.java:22`(상속), `:59`(`FailureCategory`→`DB_*`; 직렬화 후에도 `errorCode()`가 category에서 계산). 대응 코드가 없던 2개는 `DB_OPTIMISTIC_CONFLICT`(CONFLICT/409/false)·`DB_COMPLETION_UNKNOWN`(DATA_INTEGRITY/500/false) 신설, SCHEMA_MISMATCH·DATA_CORRUPTION·ENTITY_NOT_FOUND·UNKNOWN은 이전 catch-all과 같은 `INTERNAL_ERROR`. `LockFailureClassificationContractTest`의 REGISTRY-GAP-1("optimistic 코드 없음") 고정 테스트를 `anOptimisticLockConflictIsANonRetryableConflict`로 승격. testFixtures에 `:shared-contract` 추가(mongo는 edge 없어 유지) | - | `JpaPersistenceException`이 `PersistenceFailureException`을 상속해 inbound가 한 계층만 매핑(mongo는 edge 없어 유지) | | S2-lead-5 | 권고 | sample이 `PostgreSqlPersistenceConfig`의 claim repository bean을 재선언 | 완료 | `sample-portfolio/.../bootstrap/persistence/SamplePostgreSqlPersistenceConfig.java:28-48`은 sample Flyway 전략만 선언, claim repository bean 없음 | - | - | | S2-lead-6 | 권고 | JPA 조립이 leaf와 bootstrap에 나뉨 | 완료 | 「제거된 코드」 `JpaPlatformAutoConfiguration`·`JpaPlatformRuntimeAutoConfiguration` 행, 조립은 `persistence-jpa/src/main/resources/META-INF/spring/...AutoConfiguration.imports`(3개)에만, `app-bootstrap/.../autoconfigure/`에 jpa 없음 | - | - | @@ -942,7 +945,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | S5-#14e | Nit | `GraphQlPlatformWebInterceptor` 생성자 인자 9개 | 남음 | `GraphQlPlatformWebInterceptor.java:66-75`. anonymous 관련 3개(`anonymousProfile`, `anonymousTenant`, `anonymousProfileProtected`) | W5 | anonymous 3값을 record 하나로 묶는다 | | S5-lead-1 | 권고 | client 에러 문구 언어가 전송마다 다름(web 영어, graphql 한국어) (= X2-P2-1) | 완료 | Wave 3 W3-P15 (Wave 3 라운드 1 커밋): 결정 11: `ClientErrorMessages`(한국어, Category별) 하나를 web·fileserver·GraphQL·gRPC(status description) 모두 사용. gRPC `GrpcExceptionHandlingInterceptorTest.theStatusDescriptionIsTheSharedClientMessageOfTheCategory` FAIL(`expected: "요청한 리소스를 찾을 수 없습니다." but was: "ROUTE_NOT_FOUND"`)→PASS, `GrpcP1BoundaryWireTest` 기대값 갱신 PASS. STOMP `message` 헤더는 X2-P2-9b 지시대로 고정값 유지 | - | 결정(2026-09-25): client 에러 문구는 한국어 — `Category`별 문구 표 하나를 shared-contract에 두고 모든 전송이 사용 | | S5-lead-2 | 권고 | moduleboundary 세 번째 사본(websocket) | 해당 없음(코드 삭제) | `WebSocketStableModule`·`WebSocketBuildModel` 0건. 표 80행 | - | - | -| S5-lead-3 | 권고 | request/tenant context 타입이 전송마다 따로 있음 (= X2-P2-6) | 남음 | 이름이 같은 `TenantContext` 두 개의 모양·검증이 다름. web `core/TenantContext.java:17,20`은 `(String tenantId)`, `[A-Za-z0-9][A-Za-z0-9_.-]{0,63}`. graphql `context/TenantContext.java:15,17,30`은 `(value, source)`, 비어 있지 않고 128자 이하면 모두 허용. 같은 tenant가 한 전송은 통과하고 다른 전송은 거부됨
Wave 1–2 P8: 미완 — 이유: 공통 tenant 값 타입(shared-contract/application-core)을 만들고 web·graphql(그리고 messaging·persistence·notification의 tenant 타입)이 담게 하는 일은 계획서 Wave 3 3-D 「tenant 값 타입」 공통 작업이고 web은 P10 범위. 이번에는 증상만 막음: GraphQL `TenantContext` 검증을 web과 같은 문법 `[A-Za-z0-9][A-Za-z0-9_.-]{0,63}`으로 맞춰 "한 전송만 통과하는 tenant"를 없앰. `context/GraphQlRequestContextTest.aTenantTheWebTransportRefusesIsRefusedHereToo`(4건) FAIL(`Expecting actual not to be null`) → PASS. `.../context/TenantContext.java:38`. 커밋 `aa5f4d90` | W2 | tenant 값 타입 하나(검증 규칙 하나)를 application-core/shared-contract에 두고, 두 전송 context가 그것을 담게 한다 | +| S5-lead-3 | 권고 | request/tenant context 타입이 전송마다 따로 있음 (= X2-P2-6) | 완료 | Wave 3 W3-P19 (Wave 3 라운드 3 커밋): X2-P2-6a와 같음(`b64471cb`): 두 전송 context가 같은 값 타입을 담는다 | - | tenant 값 타입 하나(검증 규칙 하나)를 application-core/shared-contract에 두고, 두 전송 context가 그것을 담게 한다 | | S5-lead-4 | 권고 | release/promotion gate가 websocket/grpc에도 반복되는지 | 완료 | Wave 3 W3-P16 (Wave 3 라운드 1 커밋): `grpc/grpc-testkit/.../release/`(4 main + 1 test), `grpc-advanced/grpc-advanced-bootstrap/.../release/`(4 main + 1 test) 삭제, 문서 4곳 정정. `-p optional-platforms ci` PASS. build 파일은 건드리지 않음 | - | 두 gate와 테스트를 삭제하거나 test source set으로 옮긴다(S6/S7 grpc 항목과 같이) | | S5-lead-5 | 권고 | bulkhead: graphql·fileserver·httpclient가 겹치는지 | 해당 없음(코드 삭제) | 겹치던 web `BlockingBridgeBudget`·`SemaphoreAdmissionController`는 삭제. 남은 3개는 방식이 다름: `GraphQlBlockingBridge.java:45-57`(bounded `ThreadPoolExecutor`+AbortPolicy), `BlockingTransferExecutor.java:26`(Spring `ThreadPoolTaskExecutor`), `BlockingAttemptBulkhead.java:39`(`Semaphore`). 각 100줄 이하 | - | - | @@ -1158,8 +1161,8 @@ Wave 1–2 구현 묶음(`P1`–`P13`)이 작업 중 찾은 결함과 통합 검 | P9-new-1 | 발견 | `InboxItemEntity.archive()`가 EXPIRED·DELETED 항목도 ARCHIVED로 바꾼다(`src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxItemEntity.java` `archive`). terminal … | 완료 | Wave 2.5 W2-P14 (Wave 3 라운드 1 커밋): `InboxItemEntityTest.archiveLeavesAnExpiredOrDeletedItemInItsTerminalState[EXPIRED,DELETED]` FAIL(`[true, "ARCHIVED", ...]`)→PASS. `.../platform/inbox/InboxItemEntity.java:145-146` EXPIRED·DELETED면 no-op(false) | - | `archive()`가 EXPIRED·DELETED를 거부 | | P9-new-2 | 발견 | `PostgreSqlInboxCutoffIntegrationTest`가 repository의 SQL이 아니라 테스트 안의 사본을 실행하고 있어 E-4a가 PG lane에서 보이지 않았다. 고침(repository `@Query`를 읽어 실행). | 완료 | Wave 1–2 P9 (fcddab7e·Wave 2 커밋): 결과 파일 `docs/reviews/2026-09-25-review-followup-results/P9.md` | - | - | | P9-new-3 | 발견 | 같은 operationId를 다른 요청(다른 scope)으로 재사용하면 fake(`InMemoryDurableOperationStore`)는 조용히 덮어쓰고 PG adapter는 PK 위반으로 실패한다 — fake/adapter 불일치. HTTP 경로는 id를 서버가 발급해 영향 없음. 고치지 않음. | 남음 | 결과 파일 `docs/reviews/2026-09-25-review-followup-results/P9.md` | W4 | durable operation store 계약 테스트에 id 재사용 경우 추가, fake를 adapter와 맞춤 | -| P9-new-4 | 발견 | `WebMvcRequestContextHolder.store(...)`를 부르는 운영 코드가 없어 `WebRequestContext`를 파라미터로 받는 컨트롤러는 항상 `IllegalStateException`으로 실패한다(`src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/context/WebMvcRequestContex… | 남음 | 결과 파일 `docs/reviews/2026-09-25-review-followup-results/P9.md` | W2 | 운영 경로에서 `WebRequestContext`를 채우거나 파라미터 사용처 제거 | -| P9-new-5 | 발견 | 웹 운영 경로에 tenant 해석이 없다(`TenantContext.resolved` 호출자 없음). durable operation HTTP는 tenant를 null로 넘긴다. 결함이라기보다 미구현 — 기록만. | 남음 | 결과 파일 `docs/reviews/2026-09-25-review-followup-results/P9.md` | W3 | tenant 해석(3-D tenant 값 타입과 함께) | +| P9-new-4 | 발견 | `WebMvcRequestContextHolder.store(...)`를 부르는 운영 코드가 없어 `WebRequestContext`를 파라미터로 받는 컨트롤러는 항상 `IllegalStateException`으로 실패한다(`src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/context/WebMvcRequestContex… | 완료 | Wave 3 W3-P19 (Wave 3 라운드 3 커밋): I-1c와 같은 커밋 `d19cf5e5`(파라미터 사용처 제거 쪽) | - | 운영 경로에서 `WebRequestContext`를 채우거나 파라미터 사용처 제거 | +| P9-new-5 | 발견 | 웹 운영 경로에 tenant 해석이 없다(`TenantContext.resolved` 호출자 없음). durable operation HTTP는 tenant를 null로 넘긴다. 결함이라기보다 미구현 — 기록만. | 완료 | Wave 3 W3-P19 (Wave 3 라운드 3 커밋): 커밋 `b64471cb`. `AuthenticatedPrincipal`에 `Optional tenant`(검증된 JWT의 `tenant_id` claim — `JwtToAuthenticatedPrincipalConverter.TENANT_CLAIM`, 에이전트 기본값: MDC·baggage 키와 같은 이름), 형식이 틀린 claim은 "없음"이 아니라 `InvalidBearerTokenException`(401). `DurableOperationController`가 submit·get·cancel에 tenant를 넘김(전에는 null). 테스트: `DurableOperationControllerTest.theSameSubjectInAnotherTenantGetsTheSame404`·`theSubmitterReadsTheirOperationInTheTenantTheyAreSignedInTo`, `JwtToAuthenticatedPrincipalConverterTest` 3건. 한계: redis-session 인증(`PrimitiveSessionSecurityContextRepository`)은 세션 인코딩에 tenant가 없어 tenant 없는 principal을 만든다(세션 형식 변경은 하지 않음) | - | tenant 해석(3-D tenant 값 타입과 함께) | | P10-new-1 | 발견 | `src/.env.example:25`가 `APP_SERVER_FORWARD_HEADERS_STRATEGY=framework`를 권했다. `framework`는 Spring `ForwardedHeaderFilter`가 모든 peer의 `X-Forwarded-For`를 믿어 `getRemoteAddr()` 자체를 호출자가 고르게 하므로, rate-limit 모드와 상관없이 비인증 키를 우회할 수 있었다. `na… | 완료 | Wave 1–2 P10 (fcddab7e·Wave 2 커밋): 결과 파일 `docs/reviews/2026-09-25-review-followup-results/P10.md` | - | - | | P10-new-2 | 발견 | `WebMvcRequestIdFilter`의 traceparent 정규식은 all-zero trace id 등을 받아들였고 `RequestLoggingFilter`의 `TraceParent.parse`는 거부해서, 같은 요청에서 두 필터가 다른 trace id를 가질 수 있었다(I-4b의 한 원인). 이제 `TraceParent.parse` 하나만 쓴다. | 완료 | Wave 1–2 P10 (fcddab7e·Wave 2 커밋): 결과 파일 `docs/reviews/2026-09-25-review-followup-results/P10.md` | - | - | | P10-new-3 | 발견 | 옛 콜백 컨트롤러의 `@RequestBody byte[]`는 form POST(`application/x-www-form-urlencoded`, query string 없음)에서 Spring 7 `ServletServerHttpRequest.getBody()`가 요청 파라미터로 다시 만든 본문을 준다(`getBodyFromServletRequestParameters`, spring-web 7.0.9 bytec… | 완료 | Wave 1–2 P10 (fcddab7e·Wave 2 커밋): 결과 파일 `docs/reviews/2026-09-25-review-followup-results/P10.md` | - | - | @@ -1192,7 +1195,7 @@ Wave 1–2 구현 묶음(`P1`–`P13`)이 작업 중 찾은 결함과 통합 검 | P16-new-2 | 발견 | `FileserverDocumentationCoverageTest`가 읽는 문서·workflow·소스가 test inputs에 없음. | 완료 | Wave 3 P16: `src/composition/fileserver-platform/build.gradle` | - | - | | P16-new-3 | 발견 | sample `PublishPosterImageUseCase.handle`이 `UUID.randomUUID()`로 attempt id 생성(ArchUnit 밖이라 안 보였음). | 완료 | Wave 3 P16: `ids.allocate()`, sample을 ArchUnit 대상에 포함 | - | - | | P16-new-4 | 발견 | `S3AsyncResponseBodyBridgeTest.oversizedSdkChunkFailsClosed` 간헐 실패(소비 스레드와 chunk 크기 검사 경합). | 완료 | Wave 3 P24 (라운드 2 커밋): P24-new-1 — bridge 순서 경합(결과 게시 전 source 무효화, 취소 전 원인 기록) 수정, bridge 테스트 40회 반복 통과 | - | P14-new-2와 함께 결정적 테스트로 | -| P16-new-5 | 발견 | S1-#16 나머지: `NotificationIdGeneratorPort`·`UploadIdentifierFactory`를 domain `IdFactory` 기반으로. | 남음 | Wave 3 P16 결과 파일 | W3 | 3-D(P19) | +| P16-new-5 | 발견 | S1-#16 나머지: `NotificationIdGeneratorPort`·`UploadIdentifierFactory`를 domain `IdFactory` 기반으로. | 보류 | Wave 3 W3-P19 (Wave 3 라운드 3 커밋): `NotificationIdGeneratorPort`(UUID 반환)·`UploadIdentifierFactory`를 domain `IdFactory>` 기반으로 바꾸려면 application-notification·application-fileserver에 domain-core edge가 필요하고(현재 둘 다 없음), 모든 notification id를 `ResourceId` 타입으로 바꿔야 한다. fileserver 쪽은 동시 묶음 P28이 같은 파일군을 바꾸는 중. 사유: 결정 필요 — 두 application leaf에 domain-core edge를 줄지. 승인자: 저장소 소유자 결정 필요 / 승인자: 소유자 결정 34(2026-09-29) | W3 | 3-D(P19) | | P16-new-6 | 발견 | persistence-fileserver 공개 타입의 adopter import를 보는 검사가 없어짐(예전 정규식 테스트가 접두어 전체를 봤음). | 완료 | Wave 3 W3-P27 (Wave 3 라운드 3 커밋): `976c175f`: persistence-fileserver에 `ca.api-surface`, 공개 타입 24개 기준선과 adopter 목록(`FileserverSchemaActivation`) 승인 — 목록에서 빼면 composition import로 `verifyPersistenceFileserverApiSurface` 실패 | - | persistence-fileserver에 `ca.api-surface` 적용 — 빌드 잔여 묶음 | | P16-new-7 | 발견 | `docs/study/postgresql-jpa-walkthrough.ko.md` §15.6 등이 삭제된 JPA evidence manifest를 설명. | 남음 | Wave 3 P16 결과 파일 | W5 | 결정 6: 현재 코드 기준으로 갱신 | | P24-new-1 | 발견 | S3 응답 bridge가 source 무효화 전에 결과를 게시하고, 실패 원인 기록 전에 취소해 테스트가 간헐 실패(P14-new-2·P16-new-4의 원인). | 완료 | Wave 3 P24: 순서 수정, bridge 테스트 40회 반복 통과 | - | - | @@ -1208,7 +1211,7 @@ Wave 1–2 구현 묶음(`P1`–`P13`)이 작업 중 찾은 결함과 통합 검 | P23-new-2 | 발견 | profile마다 만드는 SES SDK client를 닫지 않는다(기동 때 한 번이라 유한). | 남음 | Wave 3 P23 결과 파일 | W3 | provider 종료 시 close. P28 | | P23-new-3 | 발견 | `app-bootstrap/build.gradle` 알림 선택 줄 주석이 persistence-jpa 줄을 함께 풀라고 함(composition이 직접 가져옴). | 완료 | Wave 3 라운드 3 통합: 주석 수정 | - | - | | ORCH-new-2 | 발견 | `NotificationPayloadAtRestContractTest`가 저장소 소스·migration을 읽지만 test inputs를 선언하지 않아(`notification/build.gradle:98`이 필요 없다고 주장) 파일이 옮겨져도 up-to-date로 건너뜀. P23 worktree에서 통과, main 통합에서 실패(옛 `persistence-jpa` 경로·`build/` 경합 walk). | 남음 | 경로와 walk 범위는 통합 때 수정(`src/main/java`만) | W4 | 읽는 파일을 test `inputs`로 선언(CLAUDE.md build-logic 규칙) | -| ORCH-new-3 | 발견 | `web-advanced` `WebStreamingSoakIT.concurrent arrivals never exceed the node's ceiling`가 부하 중 `expected: 1000 but was: 1001`로 실패, 단독 3회 통과 — 상한을 1 넘는 실제 경합일 수 있다. | 남음 | Wave 3 라운드 3 P27 통합 `ci`(2026-09-29) | W2 | 재현(반복·부하)으로 경합 여부 판정, 경합이면 admission 카운터 수정. P19 | +| ORCH-new-3 | 발견 | `web-advanced` `WebStreamingSoakIT.concurrent arrivals never exceed the node's ceiling`가 부하 중 `expected: 1000 but was: 1001`로 실패, 단독 3회 통과 — 상한을 1 넘는 실제 경합일 수 있다. | 완료 | Wave 3 W3-P19 (Wave 3 라운드 3 커밋): 커밋 `c3380270`. 원인: `WebStreamRegistry.register`가 `compute()` 안에서 `sessions.size()`를 읽음 — compute는 한 bin만 잠그고 크기 카운터는 잠금 해제 뒤 갱신되므로 다른 bin의 두 도착이 모두 999를 보고 삽입(실제 경합, 테스트 타이밍 문제 아님: 먼저 단언하는 `activeStreams()`가 1001). 수정: AtomicInteger CAS로 슬롯 선예약 + `putIfAbsent`, 중복·deregister는 슬롯 반환. 테스트 `stream/WebStreamRegistryAdmissionTest`(경쟁 도착 200라운드, 슬롯 반환 2건). FAIL 근거: P27 통합 ci의 `expected: 1000 but was: 1001` — 로컬에서는 수정 전 soak 형태 6회 + 200라운드로도 재현되지 않았다(창이 `addCount` 한 구간뿐). 수정 후 `WebStreamingSoakIT`+새 테스트 3회 반복 통과 | - | 재현(반복·부하)으로 경합 여부 판정, 경합이면 admission 카운터 수정. P19 | | P21-new-1 | 발견 | handler가 `Retry`를 답하면 Kafka consumer가 시도 횟수를 세지 않아 partition이 영구히 멈췄다. | 완료 | Wave 3 P21: 예외와 같은 시도 예산·격리 사용 | - | - | | P21-new-2 | 발견 | 다시 읽은 delivery가 항상 `deliveryAttempt=1`을 보고했다. | 완료 | Wave 3 P21 | - | - | | P21-new-3 | 발견 | `src/messaging/CLAUDE.md`가 `MessagingPublicSurfaceContractTest`를 인용 — 테스트는 app-bootstrap에 있다(P21은 없다고 보고). 통합 때 이 테스트가 P21 변경(reactive facade 삭제, leaf 병합, starter-kafka 공개 consumer seam)을 반영하지 못해 실패 → 기대값 수정, starter-kafka에 `api kafka-clients` 선언. | 남음 | Wave 3 라운드 3 통합 | W5 | messaging CLAUDE.md의 테스트 위치 문구를 app-bootstrap 경로로 | @@ -1216,3 +1219,6 @@ Wave 1–2 구현 묶음(`P1`–`P13`)이 작업 중 찾은 결함과 통합 검 | P22-new-2 | 발견 | `infra/redis-sdk/acl/application.acl`·`all-accounts.acl`이 pub/sub 삭제 뒤에도 `+@pubsub`·`&prod:*`를 준다(최소 권한 위반, fixture). | 남음 | Wave 3 P22 결과 파일 | W3 | ACL fixture에서 제거 후 topology lane 재실행. P20 | | P22-new-3 | 발견 | redis-sdk 공개 API가 runtime 타입을 노출하면서 runtime을 `implementation`으로만 의존. `ca.spring-library`에 `api` 구성이 없어 한 줄로 못 고침. | 남음 | Wave 3 P22 결과 파일, 통합 때 시도 | W3 | 컨벤션에 `java-library` 적용 또는 공개 표면에서 runtime 타입 제거. P29 | | ORCH-new-4 | 발견 | redis-sdk `RedisSdkModuleBoundaryTest`·`RedisSupportMatrixTest`가 옛 split package(`redis-runtime/.../redis/sdk`)를 훑음 — P22 worktree에서 통과, main 통합에서 `NoSuchFileException`(ORCH-new-2와 같은 유형: 저장소 파일을 읽지만 test inputs 미선언). | 남음 | 경로는 통합 때 수정(`redis-sdk` 하나) | W4 | 읽는 파일을 test `inputs`로 선언 | +| P19-new-1 | 발견 | notification `platform.api.TenantId`가 비어 있지 않음·100자 이하만 검사 — web·GraphQL이 거부하는 tenant(공백·줄바꿈·경로 문자)를 받는다. 강화하면 이미 저장된 행을 못 읽을 수 있다. | 남음 | Wave 3 P19 결과 파일 | W3 | 읽기는 관대하게, 새 쓰기만 공용 `TenantId` 문법으로. P30 | +| P19-new-2 | 발견 | redis-session 인증 경로(`PrimitiveSessionSecurityContextRepository.java:116`)가 세션에 tenant를 저장하지 않아 JWT 경로와 달리 principal에 tenant가 없다. | 남음 | Wave 3 P19 결과 파일 | W3 | 세션 저장·복원에 tenant 포함. P30 | +| P19-new-3 | 발견 | `docs/study/postgresql-jpa-walkthrough.ko.md:818`이 삭제된 `JpaStreamScope`를 설명. | 남음 | Wave 3 P19 결과 파일 | W5 | 결정 6: 현재 코드 기준으로 | diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/context/ActorRef.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/context/ActorRef.java index a207b0c6..75cc0b99 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/context/ActorRef.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/context/ActorRef.java @@ -1,8 +1,6 @@ package dev.caskeleton.adapter.inbound.graphql.context; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; +import dev.caskeleton.shared.digest.Sha256; import java.util.HexFormat; /** @@ -66,14 +64,6 @@ public record ActorRef(String value, boolean authenticated) { } static String sha256Prefix(String source) { - try { - byte[] digest = - MessageDigest.getInstance("SHA-256").digest(source.getBytes(StandardCharsets.UTF_8)); - byte[] prefix = new byte[FINGERPRINT_BYTES]; - System.arraycopy(digest, 0, prefix, 0, FINGERPRINT_BYTES); - return HexFormat.of().formatHex(prefix); - } catch (NoSuchAlgorithmException ex) { - throw new IllegalStateException("SHA-256 is required for actor fingerprints", ex); - } + return HexFormat.of().formatHex(Sha256.ofUtf8(source).bytes(), 0, FINGERPRINT_BYTES); } } diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/context/GraphQlIdentityFingerprinter.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/context/GraphQlIdentityFingerprinter.java index 83ed00c4..12539d2b 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/context/GraphQlIdentityFingerprinter.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/context/GraphQlIdentityFingerprinter.java @@ -1,14 +1,10 @@ package dev.caskeleton.adapter.inbound.graphql.context; -import java.nio.charset.StandardCharsets; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; +import dev.caskeleton.shared.digest.HmacSha256; import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; /** * Turns an actor or tenant identity into a value that may be stored outside this process. @@ -41,8 +37,6 @@ public final class GraphQlIdentityFingerprinter { /** Shortest key accepted, matching the block size a truncated key would be padded to anyway. */ public static final int MINIMUM_KEY_BYTES = 16; - private static final String ALGORITHM = "HmacSHA256"; - /** * Domain tags, so the same string used as an actor and as a tenant does not fingerprint the same. * @@ -131,20 +125,13 @@ public final class GraphQlIdentityFingerprinter { } private String fingerprint(String domain, String value) { - try { - Mac mac = Mac.getInstance(ALGORITHM); - mac.init(new SecretKeySpec(keys.get(activeKeyId), ALGORITHM)); - // Length-framed, for the reason the canonical mutation input is: concatenating a domain and a - // caller-influenced value lets one of them absorb the other's boundary, and two different - // identities then produce one fingerprint. - byte[] digest = - mac.doFinal( - (domain.length() + ":" + domain + "|" + value.length() + ":" + value + "|") - .getBytes(StandardCharsets.UTF_8)); - return activeKeyId + ":" + HexFormat.of().formatHex(digest); - } catch (NoSuchAlgorithmException | InvalidKeyException unavailable) { - throw new IllegalStateException( - "HMAC-SHA256 is required for identity fingerprints", unavailable); - } + // Length-framed, for the reason the canonical mutation input is: concatenating a domain and a + // caller-influenced value lets one of them absorb the other's boundary, and two different + // identities then produce one fingerprint. + byte[] digest = + HmacSha256.sign( + keys.get(activeKeyId), + domain.length() + ":" + domain + "|" + value.length() + ":" + value + "|"); + return activeKeyId + ":" + HexFormat.of().formatHex(digest); } } diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/context/TenantContext.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/context/TenantContext.java index 8a7a87a6..3c003e3b 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/context/TenantContext.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/context/TenantContext.java @@ -1,6 +1,6 @@ package dev.caskeleton.adapter.inbound.graphql.context; -import java.util.regex.Pattern; +import dev.caskeleton.application.tenant.TenantId; /** * The tenant a request executes in, together with where that decision came from. @@ -16,14 +16,6 @@ import java.util.regex.Pattern; */ public record TenantContext(String value, TenantSource source) { - /** - * The web transport's tenant grammar ({@code adapter.inbound.web.core.TenantContext}). - * - *

Duplicated on purpose until the shared tenant value type exists (review S5-lead-3, Wave 3): - * while the two transports disagreed, the same tenant passed one and was refused by the other. - */ - private static final Pattern GRAMMAR = Pattern.compile("[A-Za-z0-9][A-Za-z0-9_.-]{0,63}"); - /** Trusted inputs a tenant may be derived from. */ public enum TenantSource { /** A claim on the verified credential. */ @@ -35,14 +27,20 @@ public record TenantContext(String value, TenantSource source) { } public TenantContext { - if (value == null || !GRAMMAR.matcher(value).matches()) { - throw new IllegalArgumentException("tenant identity must match " + GRAMMAR.pattern()); - } + // The grammar is application-core's TenantId, the one the web transport uses too (review + // X2-P2-6a): while the two transports disagreed, the same tenant passed one and was refused by + // the other. + value = new TenantId(value).value(); if (source == null) { throw new IllegalArgumentException("tenant source is required"); } } + /** The tenant as the application-core value type. */ + public TenantId tenantId() { + return new TenantId(value); + } + /** Tenant taken from a claim on the verified credential. */ public static TenantContext fromAuthenticatedCredential(String value) { return new TenantContext(value, TenantSource.AUTHENTICATED_CREDENTIAL); diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/pagination/HmacGraphQlCursorCodec.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/pagination/HmacGraphQlCursorCodec.java index 23f6f323..d0166d0f 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/pagination/HmacGraphQlCursorCodec.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/pagination/HmacGraphQlCursorCodec.java @@ -1,14 +1,12 @@ package dev.caskeleton.adapter.inbound.graphql.pagination; +import dev.caskeleton.shared.digest.HmacSha256; import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; import java.util.Base64; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; /** * An HMAC-authenticated cursor codec (design §14). @@ -17,8 +15,8 @@ import javax.crypto.spec.SecretKeySpec; * decode, edit and send back, which turns pagination into an arbitrary "start reading from here" * parameter. Here the envelope is signed, so an edited cursor fails verification. * - *

Signatures are compared with {@link MessageDigest#isEqual}, whose timing does not depend on - * where the first differing byte is — a normal string comparison would leak that position. + *

Signatures are verified by {@link HmacSha256#verify}, whose timing does not depend on where + * the first differing byte is — a normal string comparison would leak that position. * *

The codec chooses the signing key. Letting the payload name it meant a caller could pin every * new cursor to a key that was being retired, which is rotation that never completes. @@ -28,7 +26,6 @@ public final class HmacGraphQlCursorCodec implements GraphQlCursorCodec { /** Largest cursor token accepted, before any decoding work is done. */ public static final int MAXIMUM_CURSOR_CHARS = 4096; - private static final String ALGORITHM = "HmacSHA256"; private static final Base64.Encoder ENCODER = Base64.getUrlEncoder().withoutPadding(); private static final Base64.Decoder DECODER = Base64.getUrlDecoder(); @@ -50,7 +47,7 @@ public final class HmacGraphQlCursorCodec implements GraphQlCursorCodec { } GraphQlCursorPayload signed = payload.signedWith(keyRing.activeKeyId()); String canonical = signed.canonicalForm(); - byte[] signature = sign(canonical, keyRing.secret(signed.keyId())); + byte[] signature = HmacSha256.sign(keyRing.secret(signed.keyId()), canonical); return ENCODER.encodeToString(canonical.getBytes(StandardCharsets.UTF_8)) + "." + ENCODER.encodeToString(signature); @@ -82,8 +79,7 @@ public final class HmacGraphQlCursorCodec implements GraphQlCursorCodec { } GraphQlCursorPayload payload = parse(canonical); - byte[] expectedSignature = sign(canonical, keyRing.secret(payload.keyId())); - if (!MessageDigest.isEqual(expectedSignature, presentedSignature)) { + if (!HmacSha256.verify(keyRing.secret(payload.keyId()), canonical, presentedSignature)) { throw new GraphQlCursorException("cursor signature mismatch"); } expected.verify(payload); @@ -168,14 +164,4 @@ public final class HmacGraphQlCursorCodec implements GraphQlCursorCodec { private static String unescape(String value) { return value.replace("\\;", ";").replace("\\=", "=").replace("\\|", "|").replace("\\\\", "\\"); } - - private static byte[] sign(String canonical, byte[] secret) { - try { - Mac mac = Mac.getInstance(ALGORITHM); - mac.init(new SecretKeySpec(secret, ALGORITHM)); - return mac.doFinal(canonical.getBytes(StandardCharsets.UTF_8)); - } catch (java.security.GeneralSecurityException ex) { - throw new IllegalStateException("HMAC-SHA256 is required for signed cursors", ex); - } - } } diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformWebInterceptor.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformWebInterceptor.java index 8d354b2e..88e229ff 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformWebInterceptor.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformWebInterceptor.java @@ -13,6 +13,7 @@ import dev.caskeleton.adapter.inbound.graphql.http.GraphQlRequestTooLargeExcepti import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy; import dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthenticatedPrincipal; import dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthenticationContextFactory; +import dev.caskeleton.shared.observability.MdcKeys; import graphql.ExecutionInput; import graphql.ExecutionResult; import java.nio.charset.StandardCharsets; @@ -20,6 +21,7 @@ import java.time.Clock; import java.util.Map; import java.util.Objects; import java.util.Optional; +import org.slf4j.MDC; import org.springframework.graphql.ExecutionGraphQlResponse; import org.springframework.graphql.server.WebGraphQlInterceptor; import org.springframework.graphql.server.WebGraphQlRequest; @@ -154,10 +156,16 @@ public final class GraphQlPlatformWebInterceptor implements WebGraphQlIntercepto /** * A bounded correlation identity for an anonymous request. * - *

Derived from the execution id Spring already assigned rather than from a client header: a + *

The HTTP request id when the servlet request-id filter assigned one (review X2-P2-5): it is + * already on MDC and in the response's {@code meta}, so a GraphQL error names the same request a + * log search finds. Otherwise the execution id Spring assigned — never a client header: a * caller-supplied trace id becomes a log and metric value, and this one has to stay bounded. */ private static String traceId(WebGraphQlRequest request) { + String requestId = MDC.get(MdcKeys.REQUEST_ID); + if (requestId != null && !requestId.isBlank()) { + return requestId; + } String id = request.getId(); return id == null || id.isBlank() ? "graphql" : id; } diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPreparsedDocumentAdapter.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPreparsedDocumentAdapter.java index ca09b45e..250bbe01 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPreparsedDocumentAdapter.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPreparsedDocumentAdapter.java @@ -3,13 +3,10 @@ package dev.caskeleton.adapter.inbound.graphql.runtime; import dev.caskeleton.adapter.inbound.graphql.context.GraphQlRequestContext; import dev.caskeleton.adapter.inbound.graphql.execution.BoundedPreparsedDocumentProvider; import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlPreparsedCacheKey; +import dev.caskeleton.shared.digest.Sha256; import graphql.ExecutionInput; import graphql.execution.preparsed.PreparsedDocumentEntry; import graphql.execution.preparsed.PreparsedDocumentProvider; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.function.Function; @@ -107,11 +104,6 @@ public final class GraphQlPreparsedDocumentAdapter implements PreparsedDocumentP * @param value the text to hash */ public static String sha256(String value) { - try { - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - return HexFormat.of().formatHex(digest.digest(value.getBytes(StandardCharsets.UTF_8))); - } catch (NoSuchAlgorithmException absent) { - throw new IllegalStateException("SHA-256 is required by every Java platform", absent); - } + return Sha256.ofUtf8(value).hex(); } } diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/context/GraphQlRequestContextTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/context/GraphQlRequestContextTest.java index 803648fb..14ee448a 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/context/GraphQlRequestContextTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/context/GraphQlRequestContextTest.java @@ -66,7 +66,7 @@ class GraphQlRequestContextTest { // then assertThat(thrown) .isInstanceOf(IllegalArgumentException.class) - .hasMessage("tenant identity must match [A-Za-z0-9][A-Za-z0-9_.-]{0,63}"); + .hasMessage("tenant identifier must match [A-Za-z0-9][A-Za-z0-9_.-]{0,63}"); } @Test diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformWebInterceptorRequestBoundsTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformWebInterceptorRequestBoundsTest.java index e84e22c7..44e0b689 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformWebInterceptorRequestBoundsTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformWebInterceptorRequestBoundsTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.inbound.graphql.autoconfigure.GraphQlRootAutoConfiguration; import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy; +import dev.caskeleton.shared.observability.MdcKeys; import java.net.URI; import java.time.Duration; import java.util.List; @@ -12,6 +13,7 @@ import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.slf4j.MDC; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.graphql.ResponseError; @@ -126,6 +128,35 @@ class GraphQlPlatformWebInterceptorRequestBoundsTest { .containsExactly(false, "REQUEST_ERROR"); } + @Test + @DisplayName("servlet filter가 MDC에 둔 request_id가 거부 오류의 executionId가 된다") + void aRejectionNamesTheHttpRequestIdTheFilterAssigned() { + // given + MDC.put(MdcKeys.REQUEST_ID, "http-request-7"); + String[] executionId = new String[1]; + + // when + try { + runner.run( + context -> { + WebGraphQlResponse response = + context + .getBean(GraphQlPlatformWebInterceptor.class) + .intercept( + request("{ _health }", Map.of(), Map.of("unregistered", "x")), + next -> Mono.empty()) + .block(); + executionId[0] = + String.valueOf(response.getErrors().get(0).getExtensions().get("executionId")); + }); + } finally { + MDC.remove(MdcKeys.REQUEST_ID); + } + + // then + assertThat(executionId[0]).isEqualTo("http-request-7"); + } + private Outcome intercept( String document, Map variables, Map extensions) { AtomicBoolean executed = new AtomicBoolean(); diff --git a/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcCorrelationInterceptor.java b/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcCorrelationInterceptor.java new file mode 100644 index 00000000..2100cdde --- /dev/null +++ b/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcCorrelationInterceptor.java @@ -0,0 +1,99 @@ +package dev.caskeleton.adapter.inbound.grpc; + +import dev.caskeleton.shared.observability.MdcKeys; +import dev.caskeleton.shared.tracing.TraceParent; +import io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.function.Supplier; +import org.slf4j.MDC; + +/** + * Puts a call's correlation on MDC under the same keys the HTTP path uses (review X2-P2-5). + * + *

Correlation used to stop at the servlet filter: a log line written while a gRPC call ran + * carried no {@code request_id}, so it could not be joined to anything. Each call gets its own + * request id — minted here, never taken from the caller, for the reason the web filter gives — and + * the trace of a {@code traceparent} header that the shared {@link TraceParent} parser accepts. + * + *

gRPC runs a call's callbacks on whichever executor thread is free, so the entries are put + * around every callback and the thread's previous MDC is restored afterwards, rather than set once. + */ +final class GrpcCorrelationInterceptor implements ServerInterceptor { + + static final Metadata.Key TRACEPARENT = + Metadata.Key.of("traceparent", Metadata.ASCII_STRING_MARSHALLER); + + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + Map correlation = correlation(headers); + ServerCall.Listener delegate = withMdc(correlation, () -> next.startCall(call, headers)); + return new SimpleForwardingServerCallListener<>(delegate) { + @Override + public void onMessage(Q message) { + withMdc(correlation, () -> super.onMessage(message)); + } + + @Override + public void onHalfClose() { + withMdc(correlation, super::onHalfClose); + } + + @Override + public void onCancel() { + withMdc(correlation, super::onCancel); + } + + @Override + public void onComplete() { + withMdc(correlation, super::onComplete); + } + + @Override + public void onReady() { + withMdc(correlation, super::onReady); + } + }; + } + + private static Map correlation(Metadata headers) { + Map entries = new HashMap<>(); + entries.put(MdcKeys.REQUEST_ID, UUID.randomUUID().toString()); + TraceParent.parse(headers.get(TRACEPARENT)) + .ifPresent( + trace -> { + entries.put(MdcKeys.TRACE_ID, trace.traceId()); + entries.put(MdcKeys.SPAN_ID, trace.spanId()); + }); + return Map.copyOf(entries); + } + + private static void withMdc(Map correlation, Runnable callback) { + withMdc( + correlation, + () -> { + callback.run(); + return null; + }); + } + + private static T withMdc(Map correlation, Supplier callback) { + Map previous = MDC.getCopyOfContextMap(); + correlation.forEach(MDC::put); + try { + return callback.get(); + } finally { + if (previous == null) { + MDC.clear(); + } else { + MDC.setContextMap(previous); + } + } + } +} diff --git a/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerRunner.java b/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerRunner.java index d9f5931a..58fb8409 100644 --- a/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerRunner.java +++ b/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerRunner.java @@ -78,10 +78,13 @@ public class GrpcServerRunner implements SmartLifecycle { ? null : new GrpcAuthenticationInterceptor(authenticationPolicy, statusMapper); + // Last, so outermost: the correlation is on MDC before authentication or error mapping logs. + var correlationInterceptor = new GrpcCorrelationInterceptor(); int registered = 0; for (BindableService service : featureServices) { builder.addService( - ServerInterceptors.intercept(service, exceptionInterceptor, authenticationInterceptor)); + ServerInterceptors.intercept( + service, exceptionInterceptor, authenticationInterceptor, correlationInterceptor)); registered++; } diff --git a/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcCorrelationInterceptorTest.java b/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcCorrelationInterceptorTest.java new file mode 100644 index 00000000..1f8f241e --- /dev/null +++ b/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcCorrelationInterceptorTest.java @@ -0,0 +1,136 @@ +package dev.caskeleton.adapter.inbound.grpc; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.shared.observability.MdcKeys; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.Status; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.slf4j.MDC; + +class GrpcCorrelationInterceptorTest { + + private static final String TRACEPARENT = + "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"; + + @AfterEach + void clearMdc() { + MDC.clear(); + } + + @Test + @DisplayName("callback이 도는 동안 MDC에 request_id와 traceparent의 trace가 있다") + void aCallbackRunsWithTheCallsCorrelationOnMdc() { + // given + Metadata headers = new Metadata(); + headers.put(GrpcCorrelationInterceptor.TRACEPARENT, TRACEPARENT); + Map seen = new HashMap<>(); + ServerCall.Listener listener = + new GrpcCorrelationInterceptor() + .interceptCall(new NoopCall(), headers, (call, h) -> recordingListener(seen)); + + // when + listener.onMessage("request"); + + // then + assertThat(seen) + .containsEntry(MdcKeys.TRACE_ID, "0af7651916cd43dd8448eb211c80319c") + .containsEntry(MdcKeys.SPAN_ID, "b7ad6b7169203331") + .containsKey(MdcKeys.REQUEST_ID); + } + + @Test + void theThreadsMdcIsRestoredAfterTheCallback() { + // given + MDC.put("unrelated", "kept"); + ServerCall.Listener listener = + new GrpcCorrelationInterceptor() + .interceptCall( + new NoopCall(), new Metadata(), (call, h) -> recordingListener(new HashMap<>())); + + // when + listener.onHalfClose(); + + // then + assertThat(MDC.getCopyOfContextMap()).containsExactlyEntriesOf(Map.of("unrelated", "kept")); + } + + @Test + @DisplayName("공유 parser가 거부하는 traceparent(버전 ff)는 trace로 쓰지 않는다") + void aTraceparentTheSharedParserRefusesIsNotAdopted() { + // given + Metadata headers = new Metadata(); + headers.put( + GrpcCorrelationInterceptor.TRACEPARENT, + "ff-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"); + Map seen = new HashMap<>(); + ServerCall.Listener listener = + new GrpcCorrelationInterceptor() + .interceptCall(new NoopCall(), headers, (call, h) -> recordingListener(seen)); + + // when + listener.onMessage("request"); + + // then + assertThat(seen).containsOnlyKeys(MdcKeys.REQUEST_ID); + } + + private static ServerCall.Listener recordingListener(Map seen) { + return new ServerCall.Listener<>() { + @Override + public void onMessage(String message) { + seen.putAll(MDC.getCopyOfContextMap()); + } + }; + } + + private static final class NoopCall extends ServerCall { + + private static final MethodDescriptor.Marshaller UNUSED = + new MethodDescriptor.Marshaller<>() { + @Override + public InputStream stream(String value) { + throw new UnsupportedOperationException(); + } + + @Override + public String parse(InputStream stream) { + throw new UnsupportedOperationException(); + } + }; + + @Override + public void request(int numMessages) {} + + @Override + public void sendHeaders(Metadata headers) {} + + @Override + public void sendMessage(String message) {} + + @Override + public void close(Status status, Metadata trailers) {} + + @Override + public boolean isCancelled() { + return false; + } + + @Override + public MethodDescriptor getMethodDescriptor() { + return MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("test.correlation.Feature/Check") + .setRequestMarshaller(UNUSED) + .setResponseMarshaller(UNUSED) + .build(); + } + } +} diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcJsonSequenceConfiguration.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcJsonSequenceConfiguration.java index c4c48e26..48abd79d 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcJsonSequenceConfiguration.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcJsonSequenceConfiguration.java @@ -2,6 +2,8 @@ package dev.caskeleton.adapter.inbound.web.advanced.mvc; import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.StreamFraming; import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.StreamRecordEncoder; +import java.time.Clock; +import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -21,7 +23,9 @@ public class MvcJsonSequenceConfiguration { @Bean @ConditionalOnMissingBean(name = "mvcJsonSequenceWriter") - public MvcStreamWriter mvcJsonSequenceWriter(StreamRecordEncoder encoder) { - return new MvcStreamWriter(encoder, StreamFraming.JSON_SEQUENCE); + public MvcStreamWriter mvcJsonSequenceWriter( + StreamRecordEncoder encoder, ObjectProvider clocks) { + return new MvcStreamWriter( + encoder, StreamFraming.JSON_SEQUENCE, clocks.getIfAvailable(Clock::systemUTC)); } } diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamWriter.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamWriter.java index 479a4cb2..c836c18f 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamWriter.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamWriter.java @@ -8,7 +8,7 @@ import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.StreamFraming import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.StreamRecordEncoder; import java.io.IOException; import java.io.OutputStream; -import java.time.Instant; +import java.time.Clock; import java.util.Iterator; import java.util.Objects; @@ -28,10 +28,12 @@ public final class MvcStreamWriter { private final StreamRecordEncoder encoder; private final StreamFraming framing; + private final Clock clock; - public MvcStreamWriter(StreamRecordEncoder encoder, StreamFraming framing) { + public MvcStreamWriter(StreamRecordEncoder encoder, StreamFraming framing, Clock clock) { this.encoder = Objects.requireNonNull(encoder, "encoder"); this.framing = Objects.requireNonNull(framing, "framing"); + this.clock = Objects.requireNonNull(clock, "clock"); } /** The media type to set on the response. */ @@ -63,11 +65,11 @@ public final class MvcStreamWriter { } } writeRecord(NdjsonRecord.complete(lastSequence), output); - evidence.recordTermination(WebStreamTermination.NORMAL_COMPLETE, Instant.now()); + evidence.recordTermination(WebStreamTermination.NORMAL_COMPLETE, clock.instant()); return WebStreamTermination.NORMAL_COMPLETE; } catch (IOException failure) { WebStreamTermination how = MvcDisconnectDetector.classify(failure); - evidence.recordTermination(how, Instant.now()); + evidence.recordTermination(how, clock.instant()); return how; } catch (RuntimeException failure) { return terminate(failure, output, evidence, lastSequence); @@ -84,7 +86,7 @@ public final class MvcStreamWriter { // gone would then be counted as a server fault, and the fault rate would track the // tab-closing rate. if (MvcDisconnectDetector.clientWentAway(failure)) { - evidence.recordTermination(WebStreamTermination.CLIENT_DISCONNECTED, Instant.now()); + evidence.recordTermination(WebStreamTermination.CLIENT_DISCONNECTED, clock.instant()); return WebStreamTermination.CLIENT_DISCONNECTED; } // Otherwise the source failed after commit. The status is already 200, so the failure goes @@ -97,11 +99,11 @@ public final class MvcStreamWriter { "DEPENDENCY_FAILURE", "the stream ended early because a dependency failed"), output); - evidence.recordTermination(WebStreamTermination.TERMINAL_ERROR_RECORD, Instant.now()); + evidence.recordTermination(WebStreamTermination.TERMINAL_ERROR_RECORD, clock.instant()); return WebStreamTermination.TERMINAL_ERROR_RECORD; } catch (IOException | RuntimeException unwritable) { Objects.requireNonNull(unwritable); - evidence.recordTermination(WebStreamTermination.ABRUPT_CLOSE, Instant.now()); + evidence.recordTermination(WebStreamTermination.ABRUPT_CLOSE, clock.instant()); return WebStreamTermination.ABRUPT_CLOSE; } } diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingExecutorConfiguration.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingExecutorConfiguration.java index 9994d46b..f173fc4b 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingExecutorConfiguration.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingExecutorConfiguration.java @@ -2,6 +2,8 @@ package dev.caskeleton.adapter.inbound.web.advanced.mvc; import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.StreamFraming; import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.StreamRecordEncoder; +import java.time.Clock; +import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -21,7 +23,9 @@ public class MvcStreamingExecutorConfiguration { @Bean @ConditionalOnMissingBean(name = "mvcNdjsonWriter") - public MvcStreamWriter mvcNdjsonWriter(StreamRecordEncoder encoder) { - return new MvcStreamWriter(encoder, StreamFraming.NDJSON); + public MvcStreamWriter mvcNdjsonWriter( + StreamRecordEncoder encoder, ObjectProvider clocks) { + return new MvcStreamWriter( + encoder, StreamFraming.NDJSON, clocks.getIfAvailable(Clock::systemUTC)); } } diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamRegistry.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamRegistry.java index a117c8af..ac8f559b 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamRegistry.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamRegistry.java @@ -7,6 +7,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; /** * Every stream currently open on this node. @@ -23,6 +24,10 @@ import java.util.concurrent.ConcurrentHashMap; public final class WebStreamRegistry { private final Map sessions = new ConcurrentHashMap<>(); + + /** Admitted streams, including one whose insert is in progress; never above the ceiling. */ + private final AtomicInteger slots = new AtomicInteger(); + private final int maxConcurrentStreams; public WebStreamRegistry(int maxConcurrentStreams) { @@ -39,31 +44,41 @@ public final class WebStreamRegistry { */ public boolean register(WebStreamSession session) { Objects.requireNonNull(session, "session"); - // Checked and inserted under computeIfAbsent so two concurrent admissions cannot both see room - // for the last slot. - boolean[] admitted = new boolean[1]; - sessions.compute( - session.streamId(), - (id, existing) -> { - if (existing != null) { - throw new IllegalStateException( - "two streams registered as " - + id.value() - + "; one would be unreachable to a drain"); - } - if (sessions.size() >= maxConcurrentStreams) { - admitted[0] = false; - return null; - } - admitted[0] = true; - return session; - }); - return admitted[0]; + // The slot is reserved before the insert, on a counter of its own. Checking the map's size + // inside compute() was not atomic: compute() locks one bin, and the map's size is updated after + // that lock is released, so two arrivals on different bins could both read 999 of 1000 and + // both insert (ORCH-new-3: a soak run admitted 1001). + if (!reserveSlot()) { + return false; + } + if (sessions.putIfAbsent(session.streamId(), session) != null) { + slots.decrementAndGet(); + throw new IllegalStateException( + "two streams registered as " + + session.streamId().value() + + "; one would be unreachable to a drain"); + } + return true; + } + + private boolean reserveSlot() { + int taken; + do { + taken = slots.get(); + if (taken >= maxConcurrentStreams) { + return false; + } + } while (!slots.compareAndSet(taken, taken + 1)); + return true; } /** Forget a stream that has ended. */ public boolean deregister(StreamId streamId) { - return sessions.remove(streamId) != null; + boolean removed = sessions.remove(streamId) != null; + if (removed) { + slots.decrementAndGet(); + } + return removed; } /** Every open stream. */ diff --git a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingWiringTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingWiringTest.java index c9e600d1..c738bbbe 100644 --- a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingWiringTest.java +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingWiringTest.java @@ -15,6 +15,7 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.StandardCharsets; +import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.List; @@ -48,7 +49,8 @@ class MvcStreamingWiringTest { // and fails the only property the client wanted. CountingStream output = new CountingStream(); MvcStreamWriter writer = - new MvcStreamWriter(encoder(WebStreamPolicy.conventional()), StreamFraming.NDJSON); + new MvcStreamWriter( + encoder(WebStreamPolicy.conventional()), StreamFraming.NDJSON, Clock.systemUTC()); writer.write( List.>of(NdjsonRecord.item(1, "a"), NdjsonRecord.item(2, "b")) @@ -67,7 +69,8 @@ class MvcStreamingWiringTest { CountingStream output = new CountingStream(); WebStreamEvidence evidence = new WebStreamEvidence(new StreamId("feed"), NOW); MvcStreamWriter writer = - new MvcStreamWriter(encoder(WebStreamPolicy.conventional()), StreamFraming.NDJSON); + new MvcStreamWriter( + encoder(WebStreamPolicy.conventional()), StreamFraming.NDJSON, Clock.systemUTC()); assertThat(writer.write(List.>of().iterator(), output, evidence)) .isEqualTo(WebStreamTermination.NORMAL_COMPLETE); @@ -80,7 +83,10 @@ class MvcStreamingWiringTest { CountingStream output = new CountingStream(); WebStreamEvidence evidence = new WebStreamEvidence(new StreamId("feed"), NOW); MvcStreamWriter writer = - new MvcStreamWriter(encoder(WebStreamPolicy.conventional()), StreamFraming.JSON_SEQUENCE); + new MvcStreamWriter( + encoder(WebStreamPolicy.conventional()), + StreamFraming.JSON_SEQUENCE, + Clock.systemUTC()); WebStreamTermination how = writer.write(failingAfter(NdjsonRecord.item(1, "a")), output, evidence); @@ -98,7 +104,8 @@ class MvcStreamingWiringTest { output.failAt = 1; WebStreamEvidence evidence = new WebStreamEvidence(new StreamId("feed"), NOW); MvcStreamWriter writer = - new MvcStreamWriter(encoder(WebStreamPolicy.conventional()), StreamFraming.NDJSON); + new MvcStreamWriter( + encoder(WebStreamPolicy.conventional()), StreamFraming.NDJSON, Clock.systemUTC()); assertThat( writer.write( diff --git a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamRegistryAdmissionTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamRegistryAdmissionTest.java new file mode 100644 index 00000000..5c70dc5d --- /dev/null +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamRegistryAdmissionTest.java @@ -0,0 +1,134 @@ +package dev.caskeleton.adapter.inbound.web.advanced.stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** The admission ceiling under racing arrivals (ORCH-new-3). */ +@Tag("web-advanced") +class WebStreamRegistryAdmissionTest { + + private static final Instant NOW = Instant.parse("2026-08-25T10:00:00Z"); + private static final int CEILING = 64; + private static final int RACERS = 96; + private static final int ROUNDS = 200; + + @Test + @DisplayName("다른 stream id로 동시에 도착한 요청들도 상한을 한 번도 넘지 못한다") + void racingArrivalsWithDistinctIdsNeverExceedTheCeiling() throws Exception { + // given + List overAdmittedRounds = new ArrayList<>(); + + // when + try (ExecutorService executor = Executors.newFixedThreadPool(RACERS)) { + for (int round = 0; round < ROUNDS; round++) { + WebStreamRegistry registry = new WebStreamRegistry(CEILING); + CyclicBarrier start = new CyclicBarrier(RACERS); + List> arrivals = new ArrayList<>(); + for (int racer = 0; racer < RACERS; racer++) { + String id = "r" + round + "-" + racer; + arrivals.add( + executor.submit( + () -> { + start.await(10, TimeUnit.SECONDS); + return registry.register(new Session(id)); + })); + } + for (Future arrival : arrivals) { + arrival.get(10, TimeUnit.SECONDS); + } + if (registry.activeStreams() > CEILING) { + overAdmittedRounds.add(round); + } + } + } + + // then + assertThat(overAdmittedRounds).isEmpty(); + } + + @Test + void aDeregisteredStreamFreesItsSlot() { + // given + WebStreamRegistry registry = new WebStreamRegistry(1); + registry.register(new Session("first")); + registry.deregister(new StreamId("first")); + + // when + boolean admitted = registry.register(new Session("second")); + + // then + assertThat(admitted).isTrue(); + } + + @Test + void aSecondRegistrationOfTheSameIdIsRefused() { + // given + WebStreamRegistry registry = new WebStreamRegistry(2); + registry.register(new Session("same")); + + // when + Throwable thrown = catchThrowable(() -> registry.register(new Session("same"))); + + // then + assertThat(thrown) + .isInstanceOf(IllegalStateException.class) + .hasMessage("two streams registered as same; one would be unreachable to a drain"); + } + + @Test + void aRefusedDuplicateRegistrationTakesNoSlot() { + // given + WebStreamRegistry registry = new WebStreamRegistry(2); + registry.register(new Session("same")); + Throwable duplicate = catchThrowable(() -> registry.register(new Session("same"))); + assertThat(duplicate).isInstanceOf(IllegalStateException.class); + + // when + boolean admitted = registry.register(new Session("other")); + + // then + assertThat(admitted).isTrue(); + } + + private static final class Session implements WebStreamSession { + + private final StreamId id; + + Session(String id) { + this.id = new StreamId(id); + } + + @Override + public StreamId streamId() { + return id; + } + + @Override + public Instant startedAt() { + return NOW; + } + + @Override + public void requestReconnect() {} + + @Override + public void forceClose(WebStreamTermination reason) {} + + @Override + public boolean open() { + return true; + } + } +} diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/security/FileserverRequestContextFactory.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/security/FileserverRequestContextFactory.java index cf046ff9..6521c764 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/security/FileserverRequestContextFactory.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/security/FileserverRequestContextFactory.java @@ -1,9 +1,9 @@ package dev.caskeleton.adapter.inbound.web.fileserver.security; import dev.caskeleton.adapter.inbound.web.auth.AuthenticatedPrincipal; -import dev.caskeleton.adapter.inbound.web.observability.MdcKeys; import dev.caskeleton.application.fileserver.api.security.FileAccessSubject; import dev.caskeleton.application.fileserver.api.security.RequestContext; +import dev.caskeleton.shared.observability.MdcKeys; import java.util.LinkedHashSet; import java.util.Set; import org.slf4j.MDC; diff --git a/src/adapter/inbound/web/README.md b/src/adapter/inbound/web/README.md index 153e4804..e4b82a6f 100644 --- a/src/adapter/inbound/web/README.md +++ b/src/adapter/inbound/web/README.md @@ -384,7 +384,8 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML ## observability ### MdcKeys -- snake_case MDC 키 이름은 로그/진단 레지스트리(`mdc-keys.yaml`)를 따른다. +- 키 상수는 shared-contract `observability/MdcKeys` 가 소유한다(GraphQL·WebSocket·gRPC 도 같은 이름을 + 쓰도록 web 에서 옮겼다). snake_case MDC 키 이름은 로그/진단 레지스트리(`mdc-keys.yaml`)를 따른다. 같은 논리 ID 의 envelope 형태(camelCase)와 HTTP 헤더 형태(kebab-case)는 D19 projection 이며, 변환 단일 지점은 `ResponseMetaFactory`. diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/AuthenticatedPrincipal.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/AuthenticatedPrincipal.java index d85d9cae..dfd17e84 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/AuthenticatedPrincipal.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/AuthenticatedPrincipal.java @@ -1,16 +1,33 @@ package dev.caskeleton.adapter.inbound.web.auth; +import dev.caskeleton.application.tenant.TenantId; +import java.util.Optional; import java.util.Set; /** * Principal exposed to controllers via {@code @AuthenticationPrincipal}. Carries the IdP-side * identifier ({@code idpUserId}, JWT {@code sub} claim) plus any claims a controller is likely to * want without reaching into the raw Jwt. + * + *

{@code tenant} is the verified token's tenant claim, when it has one — the only place a web + * request's tenant comes from. A request parameter or header never becomes one. + * + * @param idpUserId the verified subject + * @param email the email claim, when present + * @param roles the granted roles + * @param tenant the verified tenant, empty for a token without a tenant claim */ -public record AuthenticatedPrincipal(String idpUserId, String email, Set roles) { +public record AuthenticatedPrincipal( + String idpUserId, String email, Set roles, Optional tenant) { public AuthenticatedPrincipal { roles = roles == null ? Set.of() : Set.copyOf(roles); + tenant = tenant == null ? Optional.empty() : tenant; + } + + /** A principal whose token carries no tenant. */ + public AuthenticatedPrincipal(String idpUserId, String email, Set roles) { + this(idpUserId, email, roles, Optional.empty()); } public boolean hasRole(String role) { diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/JwtToAuthenticatedPrincipalConverter.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/JwtToAuthenticatedPrincipalConverter.java index 2f07433a..3cab5f29 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/JwtToAuthenticatedPrincipalConverter.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/JwtToAuthenticatedPrincipalConverter.java @@ -1,11 +1,13 @@ package dev.caskeleton.adapter.inbound.web.auth; +import dev.caskeleton.application.tenant.TenantId; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.springframework.core.convert.converter.Converter; @@ -13,6 +15,7 @@ import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import org.springframework.stereotype.Component; @@ -26,11 +29,20 @@ import org.springframework.stereotype.Component; public class JwtToAuthenticatedPrincipalConverter implements Converter { + /** + * The claim a token names its tenant in. + * + *

Snake case like the rest of this platform's field names ({@code tenant_id} is also the MDC + * and baggage key). An IdP that puts the tenant elsewhere maps it to this claim. + */ + public static final String TENANT_CLAIM = "tenant_id"; + @Override public AbstractAuthenticationToken convert(Jwt jwt) { Set roles = extractRoles(jwt); String email = jwt.getClaimAsString("email"); - AuthenticatedPrincipal principal = new AuthenticatedPrincipal(jwt.getSubject(), email, roles); + AuthenticatedPrincipal principal = + new AuthenticatedPrincipal(jwt.getSubject(), email, roles, tenant(jwt)); Collection authorities = roles.stream() .map(r -> new SimpleGrantedAuthority("ROLE_" + r.toUpperCase(Locale.ROOT))) @@ -38,6 +50,23 @@ public class JwtToAuthenticatedPrincipalConverter return new AuthenticatedJwtToken(jwt, authorities, principal); } + /** + * The token's tenant, refusing the token when the claim is present but malformed. + * + *

A malformed tenant is not read as "no tenant": an operation submitted without a tenant is + * visible to every call made without one, so that reading would widen what the caller sees. + */ + @SuppressWarnings("UnusedException") // see the catch block + private static Optional tenant(Jwt jwt) { + try { + return TenantId.optional(jwt.getClaimAsString(TENANT_CLAIM)); + } catch (IllegalArgumentException malformed) { + // No cause: Spring's (description, cause) constructor replaces the description with the + // cause's message, and a 401 description names the claim, not our grammar. + throw new InvalidBearerTokenException("the token's tenant claim is malformed"); + } + } + private Set extractRoles(Jwt jwt) { Set roles = new HashSet<>(); diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/core/ExternalRequestContext.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/core/ExternalRequestContext.java deleted file mode 100644 index 81061fc7..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/core/ExternalRequestContext.java +++ /dev/null @@ -1,65 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.core; - -import java.util.Locale; -import java.util.Objects; - -/** - * How the request looked from outside the trust boundary, normalised. - * - *

The platform builds absolute URLs — {@code Location} headers, pagination links, sunset links — - * and it must build them the way a client sees the deployment, not the way the application server - * sees itself. Behind a proxy those differ: the server believes it is {@code http://10.0.0.4:8080} - * while the client asked {@code https://api.example.com/gateway}. - * - *

Only scheme, host, port and prefix are kept, and each is normalised on the way in. Everything - * else a forwarded header could carry — the original path, the query, a client-chosen prefix — is - * discarded, because this record is consumed to build URLs and anything retained here would become - * a way for a caller to choose where a {@code Location} header points. - * - * @param scheme the external scheme, lower case - * @param host the external host, lower case - * @param port the external port - * @param prefix the external path prefix, empty or beginning with a slash and never ending in one - */ -public record ExternalRequestContext(String scheme, String host, int port, String prefix) { - - public ExternalRequestContext { - Objects.requireNonNull(scheme, "scheme"); - Objects.requireNonNull(host, "host"); - Objects.requireNonNull(prefix, "prefix"); - scheme = scheme.toLowerCase(Locale.ROOT); - host = host.toLowerCase(Locale.ROOT); - if (!scheme.equals("http") && !scheme.equals("https")) { - throw new IllegalArgumentException("external scheme must be http or https, was: " + scheme); - } - if (host.isBlank()) { - throw new IllegalArgumentException("external host is required"); - } - if (port < 1 || port > 65535) { - throw new IllegalArgumentException("external port out of range: " + port); - } - if (!prefix.isEmpty()) { - if (!prefix.startsWith("/")) { - throw new IllegalArgumentException("external prefix must begin with a slash: " + prefix); - } - if (prefix.endsWith("/")) { - throw new IllegalArgumentException("external prefix must not end with a slash: " + prefix); - } - if (prefix.contains("..")) { - throw new IllegalArgumentException("external prefix must not traverse: " + prefix); - } - } - } - - /** The origin a client would type, with the default port for the scheme left implicit. */ - public String origin() { - boolean defaultPort = - (scheme.equals("https") && port == 443) || (scheme.equals("http") && port == 80); - return defaultPort ? scheme + "://" + host : scheme + "://" + host + ":" + port; - } - - /** The absolute base every generated URL is built from. */ - public String baseUrl() { - return origin() + prefix; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/core/TenantContext.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/core/TenantContext.java index 742ea591..dda574c7 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/core/TenantContext.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/core/TenantContext.java @@ -1,8 +1,8 @@ package dev.caskeleton.adapter.inbound.web.core; +import dev.caskeleton.application.tenant.TenantId; import java.util.Objects; import java.util.Optional; -import java.util.regex.Pattern; /** * Which tenant the request is scoped to, as established by the security layer. @@ -12,39 +12,37 @@ import java.util.regex.Pattern; * caller. {@link #resolved} is the only way to name one, and the platform calls it from the * security bridge alone. * - * @param tenantId the resolved tenant identifier, empty when the operation is not tenant scoped + *

The identifier is application-core's {@link TenantId}, the grammar GraphQL shares: a tenant + * one transport accepts, the other accepts too. + * + * @param tenant the resolved tenant, empty when the operation is not tenant scoped */ -public record TenantContext(String tenantId) { - - /** Tenant identifiers are opaque, short and safe to place in a log field. */ - private static final Pattern GRAMMAR = Pattern.compile("[A-Za-z0-9][A-Za-z0-9_.-]{0,63}"); +public record TenantContext(Optional tenant) { public TenantContext { - Objects.requireNonNull(tenantId, "tenantId"); - if (!tenantId.isEmpty() && !GRAMMAR.matcher(tenantId).matches()) { - throw new IllegalArgumentException("invalid tenant identifier: " + tenantId); - } + Objects.requireNonNull(tenant, "tenant"); } /** The context for an operation that is not scoped to a tenant. */ public static TenantContext none() { - return new TenantContext(""); + return new TenantContext(Optional.empty()); } /** * A tenant the security layer resolved. * * @param tenantId the resolved tenant identifier + * @throws IllegalArgumentException when it is blank or breaks the {@link TenantId} grammar */ public static TenantContext resolved(String tenantId) { if (tenantId == null || tenantId.isBlank()) { throw new IllegalArgumentException("a resolved tenant must carry an identifier"); } - return new TenantContext(tenantId); + return new TenantContext(Optional.of(new TenantId(tenantId))); } /** The tenant, when the operation is scoped to one. */ public Optional value() { - return tenantId.isEmpty() ? Optional.empty() : Optional.of(tenantId); + return tenant.map(TenantId::value); } } diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/core/WebRequestContext.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/core/WebRequestContext.java deleted file mode 100644 index e80feb5e..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/core/WebRequestContext.java +++ /dev/null @@ -1,78 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.core; - -import java.time.Duration; -import java.time.Instant; -import java.util.Locale; -import java.util.Objects; - -/** - * Everything the platform knows about one request, fixed at admission. - * - *

Immutable on purpose. This value is read by the filter chain, the controller, the idempotency - * gate, the evidence recorder and the access log, and a mutable context read by that many stages is - * a context whose value at the point of a failure nobody can reconstruct. Anything that needs to - * change produces a new context rather than editing this one. - * - *

The deadline is absolute rather than a duration. A budget expressed as "three seconds" - * restarts at every hop that reads it, so a request with a three second budget can spend nine; an - * instant cannot be accidentally renewed. - * - * @param requestId this exchange's identity - * @param traceId the distributed trace this exchange belongs to - * @param operationName the low-cardinality operation identity - * @param apiVersion the major API version addressed - * @param actor who is calling, as the security layer established it - * @param tenant which tenant the call is scoped to - * @param locale the negotiated locale - * @param receivedAt when the platform admitted the request - * @param deadline when the request's budget expires - * @param externalRequest how the request looked from outside the trust boundary - */ -public record WebRequestContext( - WebRequestId requestId, - WebTraceId traceId, - WebOperationName operationName, - ApiMajorVersion apiVersion, - ActorContext actor, - TenantContext tenant, - Locale locale, - Instant receivedAt, - Instant deadline, - ExternalRequestContext externalRequest) { - - public WebRequestContext { - Objects.requireNonNull(requestId, "requestId"); - Objects.requireNonNull(traceId, "traceId"); - Objects.requireNonNull(operationName, "operationName"); - Objects.requireNonNull(apiVersion, "apiVersion"); - Objects.requireNonNull(actor, "actor"); - Objects.requireNonNull(tenant, "tenant"); - Objects.requireNonNull(locale, "locale"); - Objects.requireNonNull(receivedAt, "receivedAt"); - Objects.requireNonNull(deadline, "deadline"); - Objects.requireNonNull(externalRequest, "externalRequest"); - if (deadline.isBefore(receivedAt)) { - throw new IllegalArgumentException( - "deadline precedes receive time; a request admitted already out of budget would be " - + "cancelled before any stage could report why"); - } - } - - /** How much of the budget is left at an instant, never negative. */ - public Duration remainingBudget(Instant now) { - Objects.requireNonNull(now, "now"); - Duration remaining = Duration.between(now, deadline); - return remaining.isNegative() ? Duration.ZERO : remaining; - } - - /** Whether the budget has run out at an instant. */ - public boolean expired(Instant now) { - Objects.requireNonNull(now, "now"); - return !now.isBefore(deadline); - } - - /** The whole budget this request was admitted with. */ - public Duration budget() { - return Duration.between(receivedAt, deadline); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/filter/RequestLoggingFilter.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/filter/RequestLoggingFilter.java index e904d7ca..23902fdd 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/filter/RequestLoggingFilter.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/filter/RequestLoggingFilter.java @@ -1,8 +1,8 @@ package dev.caskeleton.adapter.inbound.web.filter; import dev.caskeleton.adapter.inbound.web.auth.AuthenticatedPrincipal; -import dev.caskeleton.adapter.inbound.web.observability.MdcKeys; import dev.caskeleton.application.observability.UserPrincipalPseudonymizerPort; +import dev.caskeleton.shared.observability.MdcKeys; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfiguration.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfiguration.java index 66ef0bbc..8863613c 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfiguration.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfiguration.java @@ -1,11 +1,9 @@ package dev.caskeleton.adapter.inbound.web.mvc.autoconfigure; import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler; -import dev.caskeleton.adapter.inbound.web.mvc.context.WebMvcRequestContextArgumentResolver; import dev.caskeleton.adapter.inbound.web.mvc.filter.JsonBodyLimitFilter; import dev.caskeleton.adapter.inbound.web.mvc.filter.WebMvcRequestIdFilter; import dev.caskeleton.shared.tracing.SpanErrorRecorder; -import java.util.List; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; @@ -14,8 +12,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplicat import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.jackson.autoconfigure.JsonMapperBuilderCustomizer; import org.springframework.context.annotation.Bean; -import org.springframework.web.method.support.HandlerMethodArgumentResolver; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import tools.jackson.core.StreamReadFeature; /** @@ -25,10 +21,9 @@ import tools.jackson.core.StreamReadFeature; * corrected onto: the condition lives here and everything else is imported, so "off" means no beans * rather than beans that happen not to be called. * - *

The {@code Envelope} error handler, the request-id filter, the request-body boundary (JSON - * size ceiling and duplicate-key refusal), and the argument resolver that lets a controller declare - * {@code WebRequestContext}. HTTP errors are the {@code Envelope} this handler writes; {@code - * spring.mvc.problemdetails.enabled} stays false. + *

The {@code Envelope} error handler, the request-id filter and the request-body boundary (JSON + * size ceiling and duplicate-key refusal). HTTP errors are the {@code Envelope} this handler + * writes; {@code spring.mvc.problemdetails.enabled} stays false. * *

Every bean is {@link ConditionalOnMissingBean}: the platform supplies the one that would * otherwise be missing rather than the one that must be used. @@ -83,16 +78,4 @@ public class WebMvcPlatformAutoConfiguration { public JsonMapperBuilderCustomizer strictDuplicateJsonKeys() { return builder -> builder.enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION); } - - /** Lets a controller declare the request context instead of the servlet request. */ - @Bean - @ConditionalOnMissingBean(name = "webMvcRequestContextConfigurer") - public WebMvcConfigurer webMvcRequestContextConfigurer() { - return new WebMvcConfigurer() { - @Override - public void addArgumentResolvers(List resolvers) { - resolvers.add(new WebMvcRequestContextArgumentResolver()); - } - }; - } } diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/context/WebMvcRequestContextArgumentResolver.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/context/WebMvcRequestContextArgumentResolver.java deleted file mode 100644 index 4a2ddb15..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/context/WebMvcRequestContextArgumentResolver.java +++ /dev/null @@ -1,42 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.mvc.context; - -import dev.caskeleton.adapter.inbound.web.core.WebRequestContext; -import jakarta.servlet.http.HttpServletRequest; -import org.springframework.core.MethodParameter; -import org.springframework.web.bind.support.WebDataBinderFactory; -import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.method.support.HandlerMethodArgumentResolver; -import org.springframework.web.method.support.ModelAndViewContainer; - -/** - * Lets a controller declare {@link WebRequestContext} as a parameter. - * - *

This is what keeps {@code HttpServletRequest} out of controller signatures. A controller that - * takes the servlet request has to be given one by every test, cannot be called by another - * transport, and — the part that matters most here — can read any header it likes, which routes - * around the normalisation the platform did on the way in. - * - *

Resolution fails rather than returning null when no context is bound. A null actor reaching a - * use case is an authorization decision made by accident. - */ -public final class WebMvcRequestContextArgumentResolver implements HandlerMethodArgumentResolver { - - @Override - public boolean supportsParameter(MethodParameter parameter) { - return WebRequestContext.class.equals(parameter.getParameterType()); - } - - @Override - public Object resolveArgument( - MethodParameter parameter, - ModelAndViewContainer mavContainer, - NativeWebRequest webRequest, - WebDataBinderFactory binderFactory) { - HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class); - if (request == null) { - throw new IllegalStateException( - "no servlet request available to resolve the web request context from"); - } - return WebMvcRequestContextHolder.require(request); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/context/WebMvcRequestContextHolder.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/context/WebMvcRequestContextHolder.java deleted file mode 100644 index 2a32453e..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/context/WebMvcRequestContextHolder.java +++ /dev/null @@ -1,66 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.mvc.context; - -import dev.caskeleton.adapter.inbound.web.core.WebRequestContext; -import jakarta.servlet.http.HttpServletRequest; -import java.util.Objects; -import java.util.Optional; - -/** - * Where the request context lives for the duration of one servlet request. - * - *

A request attribute rather than a {@code ThreadLocal}. The platform serves async dispatches - * and virtual threads, and both break the assumption a thread-local encodes: the thread that - * completes a response is not always the thread that started it, so a thread-local either loses the - * context or — worse, and this is the failure that is hard to see — hands the next request the - * previous one's actor. - * - *

The attribute travels with the request object, which is the thing that actually spans the - * dispatches. - */ -public final class WebMvcRequestContextHolder { - - /** Where the context lives. */ - public static final String CONTEXT_ATTRIBUTE = - WebMvcRequestContextHolder.class.getName() + ".context"; - - private WebMvcRequestContextHolder() {} - - /** - * Stores the context for this request. - * - * @throws IllegalStateException when a context is already present, because a second one would - * mean two stages disagree about who the caller is - */ - public static void store(HttpServletRequest request, WebRequestContext context) { - Objects.requireNonNull(request, "request"); - Objects.requireNonNull(context, "context"); - if (request.getAttribute(CONTEXT_ATTRIBUTE) != null) { - throw new IllegalStateException( - "a request context is already bound to this request; replacing it would let two stages" - + " disagree about the actor, the tenant and the deadline"); - } - request.setAttribute(CONTEXT_ATTRIBUTE, context); - } - - /** The context for this request, when one has been established. */ - public static Optional find(HttpServletRequest request) { - Objects.requireNonNull(request, "request"); - Object value = request.getAttribute(CONTEXT_ATTRIBUTE); - return value instanceof WebRequestContext context ? Optional.of(context) : Optional.empty(); - } - - /** - * The context for this request. - * - * @throws IllegalStateException when none was established, rather than fabricating an anonymous - * one that would make an unauthenticated request look like a deliberate decision - */ - public static WebRequestContext require(HttpServletRequest request) { - return find(request) - .orElseThrow( - () -> - new IllegalStateException( - "no web request context on this request; a fabricated one here would make an" - + " unauthenticated call look like an anonymous actor somebody chose")); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcRequestIdFilter.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcRequestIdFilter.java index b74dd321..27c9c3f7 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcRequestIdFilter.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcRequestIdFilter.java @@ -3,7 +3,7 @@ package dev.caskeleton.adapter.inbound.web.mvc.filter; import dev.caskeleton.adapter.inbound.web.core.WebRequestId; import dev.caskeleton.adapter.inbound.web.core.WebTraceId; import dev.caskeleton.adapter.inbound.web.observability.HeaderSanitizer; -import dev.caskeleton.adapter.inbound.web.observability.MdcKeys; +import dev.caskeleton.shared.observability.MdcKeys; import dev.caskeleton.shared.tracing.TraceParent; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/MdcCorrelationIdPortAdapter.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/MdcCorrelationIdPortAdapter.java index ef9f1d3a..4e4bdba9 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/MdcCorrelationIdPortAdapter.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/MdcCorrelationIdPortAdapter.java @@ -1,6 +1,7 @@ package dev.caskeleton.adapter.inbound.web.observability; import dev.caskeleton.application.observability.CorrelationIdPort; +import dev.caskeleton.shared.observability.MdcKeys; import java.util.Optional; import org.slf4j.MDC; import org.springframework.stereotype.Component; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/MdcKeys.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/MdcKeys.java deleted file mode 100644 index 5e4cfcea..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/MdcKeys.java +++ /dev/null @@ -1,13 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.observability; - -/** snake_case MDC key names. See README for the design rationale. */ -public final class MdcKeys { - - public static final String REQUEST_ID = "request_id"; - public static final String TRACE_ID = "trace_id"; - public static final String SPAN_ID = "span_id"; - public static final String CORRELATION_ID = "correlation_id"; - public static final String USER_PRINCIPAL = "user_principal"; - - private MdcKeys() {} -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/ResponseMetaFactory.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/ResponseMetaFactory.java index a790a5ee..953d27ec 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/ResponseMetaFactory.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/ResponseMetaFactory.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.inbound.web.observability; +import dev.caskeleton.shared.observability.MdcKeys; import dev.caskeleton.shared.response.ResponseMeta; import org.slf4j.MDC; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationController.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationController.java index 2ea90e57..8b829dee 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationController.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationController.java @@ -12,6 +12,7 @@ import dev.caskeleton.application.operation.GetDurableOperationUseCase; import dev.caskeleton.application.operation.OperationAcceptance; import dev.caskeleton.application.operation.OperationCommand; import dev.caskeleton.application.operation.SubmitDurableOperationUseCase; +import dev.caskeleton.application.tenant.TenantId; import dev.caskeleton.shared.response.Envelope; import jakarta.validation.Valid; import java.net.URI; @@ -39,8 +40,9 @@ import org.springframework.web.servlet.support.ServletUriComponentsBuilder; * operation exactly as for one that does not exist — so both are the same 404 here. Registered by * the composition that assembles those use cases, which exists only when a store is selected. * - *

No tenant is passed: nothing on this transport resolves one yet, and an operation submitted - * without a tenant is visible only to calls made without one. + *

The tenant is the verified token's ({@link AuthenticatedPrincipal#tenant()}, claim {@code + * tenant_id}); a token without one submits and reads operations without a tenant, which are visible + * only to calls made without one. */ @RestController @RequestMapping("/operations") @@ -84,7 +86,7 @@ public class DurableOperationController { new DurableOperationId(UUID.randomUUID().toString()), request.operationName(), principalId(principal), - null, + tenantOf(principal), RequestFingerprint.ofSha256(payload.getBytes(StandardCharsets.UTF_8)), payload, OperationCommand.DEFAULT_TIME_TO_LIVE)); @@ -106,7 +108,7 @@ public class DurableOperationController { @PathVariable String operationId, @AuthenticationPrincipal AuthenticatedPrincipal principal) { return get.handle( new GetDurableOperationQuery( - new DurableOperationId(operationId), principalId(principal), null)) + new DurableOperationId(operationId), principalId(principal), tenantOf(principal))) .>>map( operation -> ResponseEntity.ok( @@ -127,7 +129,7 @@ public class DurableOperationController { @PathVariable String operationId, @AuthenticationPrincipal AuthenticatedPrincipal principal) { DurableOperationId id = new DurableOperationId(operationId); return cancel - .handle(new CancelDurableOperationCommand(id, principalId(principal), null)) + .handle(new CancelDurableOperationCommand(id, principalId(principal), tenantOf(principal))) .>>map( canceled -> ResponseEntity.accepted() @@ -148,6 +150,11 @@ public class DurableOperationController { return principal.idpUserId(); } + // The operation use cases take the tenant as a plain string; null means "not tenant scoped". + private static String tenantOf(AuthenticatedPrincipal principal) { + return principal == null ? null : principal.tenant().map(TenantId::value).orElse(null); + } + private static ResponseEntity> notFound() { return ResponseEntity.status(HttpStatus.NOT_FOUND) .body(ErrorResponseFactory.body(OperationErrorCode.OPERATION_NOT_FOUND, null)); diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/JwtToAuthenticatedPrincipalConverterTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/JwtToAuthenticatedPrincipalConverterTest.java index 75de183b..abbbd658 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/JwtToAuthenticatedPrincipalConverterTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/JwtToAuthenticatedPrincipalConverterTest.java @@ -1,12 +1,16 @@ package dev.caskeleton.adapter.inbound.web.auth; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import dev.caskeleton.application.tenant.TenantId; import java.util.List; import java.util.Locale; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException; class JwtToAuthenticatedPrincipalConverterTest { @@ -31,4 +35,46 @@ class JwtToAuthenticatedPrincipalConverterTest { Locale.setDefault(originalDefault); } } + + @Test + void theTokensTenantClaimBecomesThePrincipalsTenant() { + // given + Jwt jwt = token().claim(JwtToAuthenticatedPrincipalConverter.TENANT_CLAIM, "acme").build(); + + // when + var authentication = new JwtToAuthenticatedPrincipalConverter().convert(jwt); + + // then + assertThat(((AuthenticatedPrincipal) authentication.getPrincipal()).tenant()) + .contains(new TenantId("acme")); + } + + @Test + void aTokenWithoutATenantClaimHasNoTenant() { + // when + var authentication = new JwtToAuthenticatedPrincipalConverter().convert(token().build()); + + // then + assertThat(((AuthenticatedPrincipal) authentication.getPrincipal()).tenant()).isEmpty(); + } + + @Test + @DisplayName("형식이 틀린 tenant claim은 '없음'이 아니라 잘못된 token으로 거부한다(401)") + void aTokenWithAMalformedTenantClaimIsRefused() { + // given + Jwt jwt = token().claim(JwtToAuthenticatedPrincipalConverter.TENANT_CLAIM, "ac me").build(); + + // when + Throwable thrown = + catchThrowable(() -> new JwtToAuthenticatedPrincipalConverter().convert(jwt)); + + // then + assertThat(thrown) + .isInstanceOf(InvalidBearerTokenException.class) + .hasMessage("the token's tenant claim is malformed"); + } + + private static Jwt.Builder token() { + return Jwt.withTokenValue("token").header("alg", "none").subject("user-1"); + } } diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/core/WebRequestContextTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/core/WebRequestContextTest.java deleted file mode 100644 index beacf79d..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/core/WebRequestContextTest.java +++ /dev/null @@ -1,112 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.core; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Duration; -import java.time.Instant; -import java.util.Locale; -import java.util.Set; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** The request context fixes the facts a whole request path reads, and refuses impossible ones. */ -class WebRequestContextTest { - - private static final Instant NOW = Instant.parse("2026-08-13T00:00:00Z"); - - @Test - @DisplayName("a deadline before the receive time is rejected") - void aDeadlineBeforeTheReceiveTimeIsRejected() { - assertThatThrownBy(() -> context(NOW, NOW.minusSeconds(1))) - .as("a request admitted already out of budget is cancelled before any stage reports why") - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("deadline precedes receive time"); - } - - @Test - @DisplayName("the remaining budget is measured against the absolute deadline") - void theRemainingBudgetIsMeasuredAgainstTheAbsoluteDeadline() { - WebRequestContext context = context(NOW, NOW.plusSeconds(3)); - - assertThat(context.budget()).isEqualTo(Duration.ofSeconds(3)); - assertThat(context.remainingBudget(NOW.plusSeconds(1))).isEqualTo(Duration.ofSeconds(2)); - assertThat(context.remainingBudget(NOW.plusSeconds(9))) - .as("a spent budget is zero, never negative, so a caller cannot read it as more time") - .isEqualTo(Duration.ZERO); - assertThat(context.expired(NOW.plusSeconds(3))).isTrue(); - assertThat(context.expired(NOW.plusSeconds(2))).isFalse(); - } - - @Test - @DisplayName("an anonymous actor cannot carry a subject") - void anAnonymousActorCannotCarryASubject() { - assertThat(ActorContext.anonymous().authenticated()).isFalse(); - assertThat(ActorContext.authenticated("user-1", Set.of("ROLE_USER")).subject()) - .isEqualTo("user-1"); - assertThatThrownBy(() -> new ActorContext("user-1", false, Set.of())) - .as("an unverified identifier that reaches an audit record looking verified is the risk") - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> ActorContext.authenticated(" ", Set.of())) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("a tenant is resolved or absent, never a caller-supplied blank") - void aTenantIsResolvedOrAbsent() { - assertThat(TenantContext.none().value()).isEmpty(); - assertThat(TenantContext.resolved("acme").value()).contains("acme"); - assertThatThrownBy(() -> TenantContext.resolved(" ")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new TenantContext("../other")) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("the external request keeps only a normalised origin and prefix") - void theExternalRequestKeepsOnlyANormalisedOriginAndPrefix() { - ExternalRequestContext external = - new ExternalRequestContext("HTTPS", "API.Example.COM", 443, "/gateway"); - - assertThat(external.scheme()).isEqualTo("https"); - assertThat(external.host()).isEqualTo("api.example.com"); - assertThat(external.origin()) - .as("the default port is left implicit so generated URLs match what a client typed") - .isEqualTo("https://api.example.com"); - assertThat(external.baseUrl()).isEqualTo("https://api.example.com/gateway"); - assertThat(new ExternalRequestContext("http", "localhost", 8080, "").baseUrl()) - .isEqualTo("http://localhost:8080"); - } - - @Test - @DisplayName("an external prefix that could redirect a generated URL is rejected") - void anExternalPrefixThatCouldRedirectAGeneratedUrlIsRejected() { - assertThatThrownBy(() -> new ExternalRequestContext("https", "api.example.com", 443, "gateway")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> new ExternalRequestContext("https", "api.example.com", 443, "/gateway/")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> new ExternalRequestContext("https", "api.example.com", 443, "/../evil")) - .as("a prefix is used to build Location headers, so traversal in it chooses a target") - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new ExternalRequestContext("ftp", "api.example.com", 21, "")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new ExternalRequestContext("https", "api.example.com", 0, "")) - .isInstanceOf(IllegalArgumentException.class); - } - - private static WebRequestContext context(Instant receivedAt, Instant deadline) { - return new WebRequestContext( - new WebRequestId("req-1"), - new WebTraceId("0af7651916cd43dd8448eb211c80319c"), - new WebOperationName("orders.list"), - new ApiMajorVersion(1), - ActorContext.anonymous(), - TenantContext.none(), - Locale.ENGLISH, - receivedAt, - deadline, - new ExternalRequestContext("https", "api.example.com", 443, "")); - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/filter/RequestLoggingFilterTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/filter/RequestLoggingFilterTest.java index 076d1207..1ddfd48d 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/filter/RequestLoggingFilterTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/filter/RequestLoggingFilterTest.java @@ -6,7 +6,7 @@ import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.read.ListAppender; import dev.caskeleton.adapter.inbound.web.auth.AuthenticatedPrincipal; import dev.caskeleton.adapter.inbound.web.mvc.filter.WebMvcRequestIdFilter; -import dev.caskeleton.adapter.inbound.web.observability.MdcKeys; +import dev.caskeleton.shared.observability.MdcKeys; import jakarta.servlet.http.HttpServletRequest; import java.util.List; import java.util.Set; diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfigurationTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfigurationTest.java index 0882f6c6..8b08659d 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfigurationTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfigurationTest.java @@ -30,7 +30,7 @@ class WebMvcPlatformAutoConfigurationTest { .hasNotFailed() .hasSingleBean(GlobalExceptionHandler.class) .hasSingleBean(WebMvcRequestIdFilter.class) - .hasBean("webMvcRequestContextConfigurer")); + .doesNotHaveBean("webMvcRequestContextConfigurer")); } @Test diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcRequestIdFilterTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcRequestIdFilterTest.java index b9b21c87..3d3fa5dd 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcRequestIdFilterTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcRequestIdFilterTest.java @@ -2,7 +2,7 @@ package dev.caskeleton.adapter.inbound.web.mvc.filter; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.inbound.web.observability.MdcKeys; +import dev.caskeleton.shared.observability.MdcKeys; import dev.caskeleton.shared.tracing.TraceParent; import jakarta.servlet.DispatcherType; import java.util.HashMap; @@ -10,6 +10,8 @@ import java.util.List; import java.util.Map; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.slf4j.MDC; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; @@ -74,6 +76,28 @@ class WebMvcRequestIdFilterTest { .isPresent(); } + @ParameterizedTest + @ValueSource( + strings = { + "ff-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01", + "00-00000000000000000000000000000000-b7ad6b7169203331-01", + "00-0af7651916cd43dd8448eb211c80319c-0000000000000000-01" + }) + @DisplayName("공유 TraceParent가 거부하는 traceparent(버전 ff, 0 trace/span id)는 채택하지 않는다") + void aTraceparentTheSharedParserRefusesIsReplaced(String traceparent) throws Exception { + // given + MockHttpServletRequest request = new MockHttpServletRequest(); + request.addHeader(WebMvcRequestIdFilter.TRACEPARENT_HEADER, traceparent); + + // when + new WebMvcRequestIdFilter() + .doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); + + // then + assertThat(WebMvcRequestIdFilter.traceId(request).orElseThrow().value()) + .isNotEqualTo(traceparent.substring(3, 35)); + } + @Test void assignedIdentifiersAreOnMdcDuringTheChainAndMatchWhatTheResponseCarries() throws Exception { // given diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/observability/MdcCorrelationIdPortAdapterTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/observability/MdcCorrelationIdPortAdapterTest.java index bdfb21f0..bbdaf01f 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/observability/MdcCorrelationIdPortAdapterTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/observability/MdcCorrelationIdPortAdapterTest.java @@ -2,6 +2,7 @@ package dev.caskeleton.adapter.inbound.web.observability; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.shared.observability.MdcKeys; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.slf4j.MDC; diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/observability/ResponseMetaFactoryTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/observability/ResponseMetaFactoryTest.java index 4e01d57f..b84f1428 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/observability/ResponseMetaFactoryTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/observability/ResponseMetaFactoryTest.java @@ -2,6 +2,7 @@ package dev.caskeleton.adapter.inbound.web.observability; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.shared.observability.MdcKeys; import dev.caskeleton.shared.response.ResponseMeta; import org.junit.jupiter.api.Test; import org.slf4j.MDC; diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationControllerTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationControllerTest.java index f9088af9..28683a00 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationControllerTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationControllerTest.java @@ -19,15 +19,18 @@ import dev.caskeleton.application.operation.GetDurableOperationUseCase; import dev.caskeleton.application.operation.SubmitDurableOperationUseCase; import dev.caskeleton.application.operation.testkit.InMemoryDurableOperationStore; import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore; +import dev.caskeleton.application.tenant.TenantId; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import dev.caskeleton.shared.tracing.SpanErrorRecorder; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; import java.util.List; +import java.util.Optional; import java.util.Set; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.http.MediaType; import org.springframework.security.authentication.TestingAuthenticationToken; @@ -160,6 +163,38 @@ class DurableOperationControllerTest { .andExpect(jsonPath("$.error.code").value("OPERATION_NOT_FOUND")); } + @Test + @DisplayName("같은 subject라도 token의 tenant가 다르면 남의 operation처럼 404다") + void theSameSubjectInAnotherTenantGetsTheSame404() throws Exception { + // given + signIn("alice", "tenant-a"); + String operationId = operationIdOf(submit(REPORT).andReturn()); + signIn("alice", "tenant-b"); + + // when + ResultActions response = mvc.perform(get("/operations/" + operationId)); + + // then + response + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.error.code").value("OPERATION_NOT_FOUND")); + } + + @Test + void theSubmitterReadsTheirOperationInTheTenantTheyAreSignedInTo() throws Exception { + // given + signIn("alice", "tenant-a"); + String operationId = operationIdOf(submit(REPORT).andReturn()); + + // when + ResultActions response = mvc.perform(get("/operations/" + operationId)); + + // then + response + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.operationId").value(operationId)); + } + @Test void anUnknownOperationIs404() throws Exception { // given @@ -245,4 +280,16 @@ class DurableOperationControllerTest { new TestingAuthenticationToken( new AuthenticatedPrincipal(subject, subject + "@example.test", Set.of()), "n/a")); } + + private static void signIn(String subject, String tenant) { + SecurityContextHolder.getContext() + .setAuthentication( + new TestingAuthenticationToken( + new AuthenticatedPrincipal( + subject, + subject + "@example.test", + Set.of(), + Optional.of(new TenantId(tenant))), + "n/a")); + } } diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/LiveEventStompBroadcaster.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/LiveEventStompBroadcaster.java index b120c0dc..67155a50 100644 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/LiveEventStompBroadcaster.java +++ b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/LiveEventStompBroadcaster.java @@ -1,11 +1,13 @@ package dev.caskeleton.adapter.inbound.websocket.stomp; import dev.caskeleton.domain.stereotype.DomainEvent; +import java.time.Clock; import java.time.Instant; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.event.EventListener; @@ -39,14 +41,17 @@ public class LiveEventStompBroadcaster { private final SimpMessagingTemplate messaging; private final WebSocketSettings properties; private final List> projectors; + private final Clock clock; public LiveEventStompBroadcaster( SimpMessagingTemplate messaging, WebSocketSettings properties, - List> projectors) { + List> projectors, + Clock clock) { this.messaging = messaging; this.properties = properties; this.projectors = List.copyOf(projectors); + this.clock = Objects.requireNonNull(clock, "clock"); } /** @@ -90,13 +95,13 @@ public class LiveEventStompBroadcaster { } } - private static LiveEvent project(LiveEventProjector projector, Object event) { + private LiveEvent project(LiveEventProjector projector, Object event) { String eventType = projector.eventType(); Map fields = projector.project(projector.sourceType().cast(event)); if (!validEventType(eventType) || !validFields(fields)) { return null; } - return new LiveEvent(eventType, fields, Instant.now()); + return new LiveEvent(eventType, fields, clock.instant()); } private static boolean validEventType(String eventType) { diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketConfig.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketConfig.java index a1561a11..f08eec43 100644 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketConfig.java +++ b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketConfig.java @@ -1,6 +1,8 @@ package dev.caskeleton.adapter.inbound.websocket.stomp; +import java.time.Clock; import java.util.List; +import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; @@ -49,6 +51,7 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { private final SafeStompSubProtocolErrorHandler errorHandler = new SafeStompSubProtocolErrorHandler(); private final WebSocketInboundAuthorizationInterceptor inboundAuthorization; + private final WebSocketCorrelationInterceptor correlation = new WebSocketCorrelationInterceptor(); public WebSocketConfig(WebSocketSettings properties) { this.properties = properties; @@ -67,7 +70,8 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void configureClientInboundChannel(ChannelRegistration registration) { - bounded(registration).interceptors(inboundAuthorization); + // Correlation first, so an authorization refusal is logged with the frame's request id. + bounded(registration).interceptors(correlation, inboundAuthorization); } @Override @@ -106,7 +110,10 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Bean LiveEventStompBroadcaster liveEventStompBroadcaster( - SimpMessagingTemplate messaging, List> projectors) { - return new LiveEventStompBroadcaster(messaging, properties, projectors); + SimpMessagingTemplate messaging, + List> projectors, + ObjectProvider clocks) { + return new LiveEventStompBroadcaster( + messaging, properties, projectors, clocks.getIfAvailable(Clock::systemUTC)); } } diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketCorrelationInterceptor.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketCorrelationInterceptor.java new file mode 100644 index 00000000..96065fe0 --- /dev/null +++ b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketCorrelationInterceptor.java @@ -0,0 +1,53 @@ +package dev.caskeleton.adapter.inbound.websocket.stomp; + +import dev.caskeleton.shared.observability.MdcKeys; +import java.util.Map; +import java.util.UUID; +import org.slf4j.MDC; +import org.springframework.messaging.Message; +import org.springframework.messaging.MessageChannel; +import org.springframework.messaging.MessageHandler; +import org.springframework.messaging.simp.SimpMessageHeaderAccessor; +import org.springframework.messaging.support.ExecutorChannelInterceptor; + +/** + * Puts an inbound STOMP message's correlation on MDC under the keys the HTTP path uses (review + * X2-P2-5). + * + *

Correlation used to stop at the servlet filter, so a log line written while a STOMP frame was + * handled could not be joined to anything. Each inbound message gets its own {@code request_id}, + * minted here; {@code correlation_id} is the server-assigned session id, which joins every frame of + * one connection. Neither is taken from a client header. + * + *

An {@link ExecutorChannelInterceptor} because the frames are handled on the inbound channel's + * executor threads: the entries go on for the handling and the thread's previous MDC comes back + * after it. + */ +final class WebSocketCorrelationInterceptor implements ExecutorChannelInterceptor { + + private static final ThreadLocal> PREVIOUS = new ThreadLocal<>(); + + @Override + public Message beforeHandle( + Message message, MessageChannel channel, MessageHandler handler) { + PREVIOUS.set(MDC.getCopyOfContextMap()); + MDC.put(MdcKeys.REQUEST_ID, UUID.randomUUID().toString()); + String session = SimpMessageHeaderAccessor.getSessionId(message.getHeaders()); + if (session != null) { + MDC.put(MdcKeys.CORRELATION_ID, session); + } + return message; + } + + @Override + public void afterMessageHandled( + Message message, MessageChannel channel, MessageHandler handler, Exception failure) { + Map restored = PREVIOUS.get(); + PREVIOUS.remove(); + if (restored == null) { + MDC.clear(); + } else { + MDC.setContextMap(restored); + } + } +} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/LiveEventStompBroadcasterTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/LiveEventStompBroadcasterTest.java index e76f8e6f..144d14d8 100644 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/LiveEventStompBroadcasterTest.java +++ b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/LiveEventStompBroadcasterTest.java @@ -11,6 +11,9 @@ import static org.mockito.Mockito.verifyNoInteractions; import dev.caskeleton.adapter.inbound.websocket.stomp.LiveEventStompBroadcaster.LiveEvent; import dev.caskeleton.domain.stereotype.DomainEvent; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -144,7 +147,8 @@ class LiveEventStompBroadcasterTest { } private LiveEventStompBroadcaster broadcaster(List> projectors) { - return new LiveEventStompBroadcaster(messaging, properties, projectors); + return new LiveEventStompBroadcaster( + messaging, properties, projectors, Clock.fixed(Instant.EPOCH, ZoneOffset.UTC)); } private static LiveEventProjector sampleProjector() { diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketCorrelationInterceptorTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketCorrelationInterceptorTest.java new file mode 100644 index 00000000..92c5dec6 --- /dev/null +++ b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketCorrelationInterceptorTest.java @@ -0,0 +1,57 @@ +package dev.caskeleton.adapter.inbound.websocket.stomp; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.shared.observability.MdcKeys; +import java.util.Map; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.slf4j.MDC; +import org.springframework.messaging.Message; +import org.springframework.messaging.simp.stomp.StompCommand; +import org.springframework.messaging.simp.stomp.StompHeaderAccessor; +import org.springframework.messaging.support.MessageBuilder; + +class WebSocketCorrelationInterceptorTest { + + private final WebSocketCorrelationInterceptor interceptor = new WebSocketCorrelationInterceptor(); + + @AfterEach + void clearMdc() { + MDC.clear(); + } + + @Test + @DisplayName("frame을 처리하는 동안 MDC에 request_id와 session id(correlation_id)가 있다") + void aFrameIsHandledWithItsCorrelationOnMdc() { + // when + interceptor.beforeHandle(frame("session-1"), null, null); + + // then + assertThat(MDC.getCopyOfContextMap()) + .containsEntry(MdcKeys.CORRELATION_ID, "session-1") + .containsKey(MdcKeys.REQUEST_ID); + } + + @Test + void theThreadsMdcIsRestoredAfterTheFrame() { + // given + MDC.put("unrelated", "kept"); + Message frame = frame("session-1"); + interceptor.beforeHandle(frame, null, null); + + // when + interceptor.afterMessageHandled(frame, null, null, null); + + // then + assertThat(MDC.getCopyOfContextMap()).containsExactlyEntriesOf(Map.of("unrelated", "kept")); + } + + private static Message frame(String session) { + StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SEND); + accessor.setSessionId(session); + accessor.setDestination("/app/echo"); + return MessageBuilder.createMessage(new byte[0], accessor.getMessageHeaders()); + } +} diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/cache/CacheEnvelope.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/cache/CacheEnvelope.java index 292c44d3..f2ac5181 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/cache/CacheEnvelope.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/cache/CacheEnvelope.java @@ -1,8 +1,8 @@ package dev.caskeleton.adapter.outbound.cache.redis.cache; +import dev.caskeleton.shared.digest.Sha256; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.time.Instant; import java.util.HexFormat; import java.util.Objects; @@ -211,11 +211,7 @@ final class CacheEnvelope { } private static byte[] sha256(byte[] value) { - try { - return MessageDigest.getInstance("SHA-256").digest(value); - } catch (NoSuchAlgorithmException impossible) { - throw new IllegalStateException("SHA-256 is unavailable", impossible); - } + return Sha256.of(value).bytes(); } /** A stored entry this deployment must not treat as an ordinary miss. */ diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalOrphanScanAdapter.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalOrphanScanAdapter.java index 9e098cfc..12d3c7f7 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalOrphanScanAdapter.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalOrphanScanAdapter.java @@ -4,21 +4,18 @@ import dev.caskeleton.application.fileserver.admin.ContentReferenceLedgerPort; import dev.caskeleton.application.fileserver.admin.OrphanObject; import dev.caskeleton.application.fileserver.admin.OrphanScanPort; import dev.caskeleton.application.fileserver.api.ContentKey; +import dev.caskeleton.shared.digest.Sha256; import java.io.File; import java.io.IOException; import java.io.UncheckedIOException; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.StandardCopyOption; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; -import java.util.HexFormat; import java.util.Iterator; import java.util.List; import java.util.Optional; @@ -227,13 +224,6 @@ public final class LocalOrphanScanAdapter implements OrphanScanPort { private static String fingerprint(ContentKey key, long size, Instant modifiedAt) { String material = key.value() + '|' + size + '|' + modifiedAt.toEpochMilli(); - try { - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - return HexFormat.of() - .formatHex(digest.digest(material.getBytes(StandardCharsets.UTF_8))) - .substring(0, 32); - } catch (NoSuchAlgorithmException unavailable) { - throw new IllegalStateException("SHA-256 is required by the platform", unavailable); - } + return Sha256.ofUtf8(material).hex().substring(0, 32); } } diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/StreamingDigest.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/StreamingDigest.java index c66e4523..ae906606 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/StreamingDigest.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/StreamingDigest.java @@ -1,8 +1,8 @@ package dev.caskeleton.adapter.outbound.fileserver.platform.local; +import dev.caskeleton.shared.digest.Sha256; import java.nio.ByteBuffer; import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.util.HexFormat; /** @@ -14,8 +14,6 @@ import java.util.HexFormat; */ final class StreamingDigest { - private static final String ALGORITHM = "SHA-256"; - private final MessageDigest digest; private long offset; @@ -25,7 +23,7 @@ final class StreamingDigest { } static StreamingDigest empty() { - return new StreamingDigest(newDigest(), 0); + return new StreamingDigest(Sha256.newMessageDigest(), 0); } void update(ByteBuffer buffer) { @@ -56,12 +54,4 @@ final class StreamingDigest { throw new IllegalStateException("SHA-256 digest is not cloneable", exception); } } - - private static MessageDigest newDigest() { - try { - return MessageDigest.getInstance(ALGORITHM); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 is required by the Java platform", exception); - } - } } diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/ExponentialFullJitterBackoff.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/ExponentialFullJitterBackoff.java index bd908670..811347c6 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/ExponentialFullJitterBackoff.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/ExponentialFullJitterBackoff.java @@ -2,6 +2,7 @@ package dev.caskeleton.adapter.outbound.httpclient.resilience; import dev.caskeleton.adapter.outbound.httpclient.profile.JitterStrategy; import dev.caskeleton.adapter.outbound.httpclient.profile.RetryAfterPolicy; +import dev.caskeleton.shared.retry.Backoff; import java.time.Duration; import java.util.Objects; import java.util.Optional; @@ -9,7 +10,9 @@ import java.util.random.RandomGenerator; /** * Exponential backoff with jitter, bounded by max backoff, {@code Retry-After}, and the remaining - * deadline (design §17.5). + * deadline (design §17.5). The ceiling and the jitter words ({@code NONE}, {@code FULL}, {@code + * DECORRELATED}) are shared-contract {@link Backoff}'s, so "full jitter" means {@code U[0, + * ceiling]} here as everywhere else. * *

Jitter is not decoration: without it, a fleet that failed together retries together, and the * upstream recovery window never opens. The random source is injectable so the schedule is @@ -22,6 +25,7 @@ public final class ExponentialFullJitterBackoff implements BackoffStrategy { private final JitterStrategy jitter; private final RetryAfterPolicy retryAfterPolicy; private final RandomGenerator random; + private final Backoff schedule; private Duration previousDelay; public ExponentialFullJitterBackoff( @@ -35,6 +39,7 @@ public final class ExponentialFullJitterBackoff implements BackoffStrategy { this.jitter = Objects.requireNonNull(jitter, "jitter strategy"); this.retryAfterPolicy = Objects.requireNonNull(retryAfterPolicy, "retry-after policy"); this.random = Objects.requireNonNull(random, "random generator"); + this.schedule = new Backoff(baseBackoff, maxBackoff); this.previousDelay = baseBackoff; } @@ -70,17 +75,11 @@ public final class ExponentialFullJitterBackoff implements BackoffStrategy { } private Duration computed(int completedAttempts) { - long exponent = Math.max(0, completedAttempts - 1); - long scaled = baseBackoff.toMillis() << Math.min(exponent, 20); - long capped = Math.min(scaled, maxBackoff.toMillis()); + int attempt = Math.max(1, completedAttempts); return switch (jitter) { - case NONE -> Duration.ofMillis(capped); - case FULL -> Duration.ofMillis(capped <= 0 ? 0 : random.nextLong(capped + 1)); - case DECORRELATED -> { - long lower = baseBackoff.toMillis(); - long upper = Math.min(maxBackoff.toMillis(), Math.max(lower, previousDelay.toMillis() * 3)); - yield Duration.ofMillis(upper <= lower ? lower : random.nextLong(lower, upper + 1)); - } + case NONE -> schedule.ceiling(attempt); + case FULL -> schedule.fullJitter(attempt, random); + case DECORRELATED -> schedule.decorrelatedJitter(previousDelay, random); }; } diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxMessagePublishAdapterTest.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxMessagePublishAdapterTest.java index f415114d..ef3443d9 100644 --- a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxMessagePublishAdapterTest.java +++ b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxMessagePublishAdapterTest.java @@ -5,7 +5,6 @@ import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.application.messaging.contract.ContractId; import dev.caskeleton.application.messaging.contract.LogicalDestinationId; -import dev.caskeleton.application.messaging.contract.Sha256; import dev.caskeleton.application.messaging.event.AggregateIdentity; import dev.caskeleton.application.messaging.event.AggregateOrder; import dev.caskeleton.application.messaging.event.EventId; @@ -16,6 +15,7 @@ import dev.caskeleton.application.outbox.OutboxEventStatus; import dev.caskeleton.application.outbox.OutboxPublishAmbiguousException; import dev.caskeleton.application.outbox.OutboxPublishOutcome; import dev.caskeleton.application.outbox.OutboxPublishRefusedException; +import dev.caskeleton.shared.digest.Sha256; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.ArrayList; diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapterTest.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapterTest.java index 046d7fb2..12d6393c 100644 --- a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapterTest.java +++ b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapterTest.java @@ -5,7 +5,6 @@ import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.application.messaging.contract.ContractId; import dev.caskeleton.application.messaging.contract.LogicalDestinationId; -import dev.caskeleton.application.messaging.contract.Sha256; import dev.caskeleton.application.messaging.event.AggregateIdentity; import dev.caskeleton.application.messaging.event.AggregateOrder; import dev.caskeleton.application.messaging.event.EventId; @@ -26,6 +25,7 @@ import dev.caskeleton.messaging.api.publish.RoutingOutcome; import dev.caskeleton.messaging.api.publish.TransmissionEvidence; import dev.caskeleton.messaging.schema.EncodedMessage; import dev.caskeleton.messaging.schema.EncodedMessagePublisher; +import dev.caskeleton.shared.digest.Sha256; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.time.Instant; diff --git a/src/adapter/outbound/notification/build.gradle b/src/adapter/outbound/notification/build.gradle index 48fc13e9..b7fa5aef 100644 --- a/src/adapter/outbound/notification/build.gradle +++ b/src/adapter/outbound/notification/build.gradle @@ -9,6 +9,8 @@ dependencies { implementation project(':application-notification') implementation project(':shared-contract') implementation project(':adapter:outbound:support') + // UUIDv7 for notification ids: the generator the sample's identifier adapters already use. + implementation libs.uuid.creator implementation 'org.springframework.boot:spring-boot-autoconfigure' implementation 'org.springframework.boot:spring-boot-actuator' diff --git a/src/adapter/outbound/notification/gradle.lockfile b/src/adapter/outbound/notification/gradle.lockfile index 40a2db21..ebeaae35 100644 --- a/src/adapter/outbound/notification/gradle.lockfile +++ b/src/adapter/outbound/notification/gradle.lockfile @@ -7,6 +7,7 @@ ch.qos.logback:logback-core:1.5.38=compileClasspath,runtimeClasspath,testCompile com.ethlo.time:itu:1.14.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath com.fasterxml.jackson.core:jackson-annotations:2.21=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor +com.github.f4b6a3:uuid-creator:6.1.1=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs com.github.spotbugs:spotbugs:4.10.2=spotbugs diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformCoreConfig.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformCoreConfig.java index 10045300..cbc0aef1 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformCoreConfig.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformCoreConfig.java @@ -5,8 +5,6 @@ import dev.caskeleton.adapter.outbound.notification.platform.template.JacksonNot import dev.caskeleton.adapter.outbound.notification.platform.template.JsonSchemaVariableValidator; import dev.caskeleton.adapter.outbound.notification.platform.template.NotificationTemplateEngine; import dev.caskeleton.adapter.outbound.notification.platform.template.PlaceholderTemplateEngine; -import dev.caskeleton.adapter.outbound.notification.platform.template.Sha256MessageDigestAdapter; -import dev.caskeleton.application.notification.platform.dispatch.MessageDigestPort; import dev.caskeleton.application.notification.platform.dispatch.NotificationVariablesCodecPort; import dev.caskeleton.application.notification.platform.security.ContactPointProtector; import dev.caskeleton.application.notification.platform.security.SecretMaterialProvider; @@ -40,13 +38,6 @@ class NotificationPlatformCoreConfig { return new JacksonNotificationVariablesCodec(); } - /** Request fingerprint hashing. */ - @Bean - @ConditionalOnMissingBean - public MessageDigestPort notificationMessageDigest() { - return new Sha256MessageDigestAdapter(); - } - /** JSON Schema 2020-12 variable validation. */ @Bean @ConditionalOnMissingBean diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformPolicyConfig.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformPolicyConfig.java index 8fbe271d..6c1d162c 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformPolicyConfig.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformPolicyConfig.java @@ -1,10 +1,9 @@ package dev.caskeleton.adapter.outbound.notification.platform.autoconfigure; import dev.caskeleton.application.notification.platform.dispatch.CanonicalNotificationPlanWriter; -import dev.caskeleton.application.notification.platform.dispatch.MessageDigestPort; import dev.caskeleton.application.notification.platform.dispatch.NotificationIdGeneratorPort; import dev.caskeleton.application.notification.platform.dispatch.NotificationRoutePlannerPort; -import dev.caskeleton.application.notification.platform.dispatch.RequestFingerprint; +import dev.caskeleton.application.notification.platform.dispatch.PlanFingerprint; import dev.caskeleton.application.notification.platform.dispatch.SyntheticEventFingerprint; import dev.caskeleton.application.notification.platform.policy.CompositeNotificationEligibilityPolicy; import dev.caskeleton.application.notification.platform.policy.DeduplicationService; @@ -100,21 +99,20 @@ class NotificationPlatformPolicyConfig { return new RoutingDecisionEngine(); } - /** Canonical request fingerprint. */ + /** Canonical plan fingerprint. */ @Bean - public RequestFingerprint requestFingerprint(MessageDigestPort digest) { - return new RequestFingerprint(digest); + public PlanFingerprint planFingerprint() { + return new PlanFingerprint(); } /** * Identity of an event the platform synthesised from a provider's answer. * - * @param digest the hashing boundary * @return the fingerprint */ @Bean - public SyntheticEventFingerprint syntheticEventFingerprint(MessageDigestPort digest) { - return new SyntheticEventFingerprint(digest); + public SyntheticEventFingerprint syntheticEventFingerprint() { + return new SyntheticEventFingerprint(); } /** Durable row factory for a submission. */ diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/UuidV7Generator.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/UuidV7Generator.java index 938430f0..5ae5747c 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/UuidV7Generator.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/UuidV7Generator.java @@ -1,54 +1,36 @@ package dev.caskeleton.adapter.outbound.notification.platform.dispatch; +import com.github.f4b6a3.uuid.factory.standard.TimeOrderedEpochFactory; import dev.caskeleton.application.notification.platform.dispatch.NotificationIdGeneratorPort; -import java.security.SecureRandom; import java.time.Clock; import java.util.Objects; import java.util.UUID; -import java.util.concurrent.atomic.AtomicLong; /** - * RFC 9562 UUIDv7. + * RFC 9562 UUIDv7, minted by uuid-creator — the same generator the sample's identifier adapters use + * (review S1-lead-2), rather than a second hand-written bit layout. * *

Time-ordered rather than random because these identifiers are primary keys: a random UUID * scatters inserts across the whole index, and a notification table takes the highest insert rate * in the platform. * - *

The monotonic counter guards the case two identifiers are requested inside the same - * millisecond, so ordering holds even under a burst. + *

{@code withIncrementPlus1}: two identifiers requested inside the same millisecond still come + * out in order, so ordering holds even under a burst. */ public final class UuidV7Generator implements NotificationIdGeneratorPort { - private static final long VERSION_7 = 0x7000L; - private static final long VARIANT_RFC = 0x8000000000000000L; - - private final Clock clock; - private final SecureRandom random; - private final AtomicLong lastMillis = new AtomicLong(); - private final AtomicLong sequence = new AtomicLong(); + private final TimeOrderedEpochFactory factory; public UuidV7Generator(Clock clock) { - this(clock, new SecureRandom()); - } - - UuidV7Generator(Clock clock, SecureRandom random) { - this.clock = Objects.requireNonNull(clock, "clock"); - this.random = Objects.requireNonNull(random, "random"); + this.factory = + TimeOrderedEpochFactory.builder() + .withClock(Objects.requireNonNull(clock, "clock")) + .withIncrementPlus1() + .build(); } @Override public UUID nextId() { - long millis = clock.millis(); - long previous = lastMillis.getAndSet(millis); - long counter = millis == previous ? sequence.incrementAndGet() : sequence.updateAndGet(x -> 0L); - - long high = (millis & 0xFFFFFFFFFFFFL) << 16; - high |= VERSION_7; - high |= counter & 0x0FFFL; - - long low = random.nextLong(); - low &= 0x3FFFFFFFFFFFFFFFL; - low |= VARIANT_RFC; - return new UUID(high, low); + return factory.create(); } } diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/security/AesGcmCallbackPayloadProtection.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/security/AesGcmCallbackPayloadProtection.java index 48d455b4..6b75e6b4 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/security/AesGcmCallbackPayloadProtection.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/security/AesGcmCallbackPayloadProtection.java @@ -1,20 +1,17 @@ package dev.caskeleton.adapter.outbound.notification.platform.security; -import dev.caskeleton.adapter.outbound.notification.platform.template.NotificationDigest; import dev.caskeleton.application.notification.platform.api.NormalizedProviderEvent; import dev.caskeleton.application.notification.platform.api.ProviderProfileId; import dev.caskeleton.application.notification.platform.callback.CallbackPayloadProtectionPort; import dev.caskeleton.application.notification.platform.security.NotificationPayloadProtection; import dev.caskeleton.application.notification.platform.security.SecretMaterialProvider; import dev.caskeleton.application.notification.platform.security.SecretPurpose; -import java.nio.charset.StandardCharsets; -import java.security.GeneralSecurityException; +import dev.caskeleton.shared.digest.HmacSha256; +import dev.caskeleton.shared.digest.Sha256; import java.util.Arrays; import java.util.HexFormat; import java.util.Objects; import java.util.TreeMap; -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; /** * Bounded, encrypted retention of raw callback payloads. @@ -101,7 +98,7 @@ public final class AesGcmCallbackPayloadProtection implements CallbackPayloadPro @Override public String digest(byte[] rawBody) { Objects.requireNonNull(rawBody, "rawBody"); - return NotificationDigest.hex(rawBody); + return Sha256.of(rawBody).hex(); } @Override @@ -128,17 +125,9 @@ public final class AesGcmCallbackPayloadProtection implements CallbackPayloadPro + '\u001f' + rawPayloadDigest; - try { - Mac mac = Mac.getInstance("HmacSHA256"); - mac.init( - new SecretKeySpec( - // A fingerprint key and a contact-lookup key protect different things and must not - // fall - // together. - secrets.activeKey(SecretPurpose.CALLBACK_FINGERPRINT_HMAC).material(), "HmacSHA256")); - return HexFormat.of().formatHex(mac.doFinal(seed.getBytes(StandardCharsets.UTF_8))); - } catch (GeneralSecurityException failure) { - throw new IllegalStateException("callback fingerprinting failed", failure); - } + // A fingerprint key and a contact-lookup key protect different things and must not fall + // together. + byte[] key = secrets.activeKey(SecretPurpose.CALLBACK_FINGERPRINT_HMAC).material(); + return HexFormat.of().formatHex(HmacSha256.sign(key, seed)); } } diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/security/AesGcmContactPointProtector.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/security/AesGcmContactPointProtector.java index 573e39e5..679080bd 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/security/AesGcmContactPointProtector.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/security/AesGcmContactPointProtector.java @@ -16,6 +16,7 @@ import dev.caskeleton.application.notification.platform.security.ProtectedContac import dev.caskeleton.application.notification.platform.security.SecretKeyMaterial; import dev.caskeleton.application.notification.platform.security.SecretMaterialProvider; import dev.caskeleton.application.notification.platform.security.SecretPurpose; +import dev.caskeleton.shared.digest.HmacSha256; import java.net.URI; import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; @@ -24,7 +25,6 @@ import java.util.Base64; import java.util.HexFormat; import java.util.Objects; import javax.crypto.Cipher; -import javax.crypto.Mac; import javax.crypto.spec.GCMParameterSpec; import javax.crypto.spec.SecretKeySpec; @@ -42,7 +42,6 @@ import javax.crypto.spec.SecretKeySpec; public final class AesGcmContactPointProtector implements ContactPointProtector { private static final String CIPHER = "AES/GCM/NoPadding"; - private static final String HMAC = "HmacSHA256"; private static final String KEY_ALGORITHM = "AES"; private static final int NONCE_BYTES = 12; private static final int TAG_BITS = 128; @@ -163,14 +162,8 @@ public final class AesGcmContactPointProtector implements ContactPointProtector private static String fingerprint( SecretKeyMaterial key, ContactPointType type, String normalized) { - try { - Mac mac = Mac.getInstance(HMAC); - mac.init(new SecretKeySpec(key.material(), HMAC)); - mac.update((type.name() + ":").getBytes(StandardCharsets.UTF_8)); - return HexFormat.of().formatHex(mac.doFinal(normalized.getBytes(StandardCharsets.UTF_8))); - } catch (GeneralSecurityException failure) { - throw new IllegalStateException("contact point fingerprinting failed", failure); - } + return HexFormat.of() + .formatHex(HmacSha256.sign(key.material(), type.name() + ":" + normalized)); } /** diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/security/HmacProviderRequestIdHasher.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/security/HmacProviderRequestIdHasher.java index e7354819..06bc9c78 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/security/HmacProviderRequestIdHasher.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/security/HmacProviderRequestIdHasher.java @@ -4,12 +4,9 @@ import dev.caskeleton.application.notification.platform.api.ProviderProfileId; import dev.caskeleton.application.notification.platform.dispatch.ProviderRequestIdHasherPort; import dev.caskeleton.application.notification.platform.security.SecretMaterialProvider; import dev.caskeleton.application.notification.platform.security.SecretPurpose; -import java.nio.charset.StandardCharsets; -import java.security.GeneralSecurityException; +import dev.caskeleton.shared.digest.HmacSha256; import java.util.HexFormat; import java.util.Objects; -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; /** * Keyed hash of a provider request id. @@ -32,22 +29,11 @@ public final class HmacProviderRequestIdHasher implements ProviderRequestIdHashe public String hash(ProviderProfileId profileId, String providerRequestId) { Objects.requireNonNull(profileId, "profileId"); Objects.requireNonNull(providerRequestId, "providerRequestId"); - try { - Mac mac = Mac.getInstance("HmacSHA256"); - mac.init( - new SecretKeySpec( - // Its own purpose. This shared the contact-lookup key, so one compromised key forged - // both - // the contact index and the provider-request index — purpose separation exists to - // stop - // exactly that. - secrets.activeKey(SecretPurpose.PROVIDER_REQUEST_LOOKUP_HMAC).material(), - "HmacSHA256")); - mac.update((profileId.value() + ":").getBytes(StandardCharsets.UTF_8)); - return HexFormat.of() - .formatHex(mac.doFinal(providerRequestId.getBytes(StandardCharsets.UTF_8))); - } catch (GeneralSecurityException failure) { - throw new IllegalStateException("provider request id hashing failed", failure); - } + // Its own purpose. This shared the contact-lookup key, so one compromised key forged both the + // contact index and the provider-request index — purpose separation exists to stop exactly + // that. + byte[] key = secrets.activeKey(SecretPurpose.PROVIDER_REQUEST_LOOKUP_HMAC).material(); + return HexFormat.of() + .formatHex(HmacSha256.sign(key, profileId.value() + ":" + providerRequestId)); } } diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/template/CanonicalNotificationRenderer.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/template/CanonicalNotificationRenderer.java index e2f96b86..33bc5c70 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/template/CanonicalNotificationRenderer.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/template/CanonicalNotificationRenderer.java @@ -18,6 +18,7 @@ import dev.caskeleton.application.notification.platform.template.RenderedNotific import dev.caskeleton.application.notification.platform.template.TemplateRegistry; import dev.caskeleton.application.notification.platform.template.TemplateSlot; import dev.caskeleton.application.notification.platform.template.TemplateVariableValidator; +import dev.caskeleton.shared.digest.Sha256; import java.net.URI; import java.util.List; import java.util.Map; @@ -67,16 +68,17 @@ public final class CanonicalNotificationRenderer implements NotificationTemplate NotificationContent content = buildContent(command.channel(), template, command.variables()); String digest = - NotificationDigest.hex( - command.channel().name() - + '\u001f' - + template.templateId() - + '\u001f' - + template.version() - + '\u001f' - + template.locale().toLanguageTag() - + '\u001f' - + canonicalForm(content)); + Sha256.ofUtf8( + command.channel().name() + + '\u001f' + + template.templateId() + + '\u001f' + + template.version() + + '\u001f' + + template.locale().toLanguageTag() + + '\u001f' + + canonicalForm(content)) + .hex(); return new RenderedNotificationContent(content, digest, command.selection(), template.locale()); } diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/template/NotificationDigest.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/template/NotificationDigest.java deleted file mode 100644 index df06a261..00000000 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/template/NotificationDigest.java +++ /dev/null @@ -1,31 +0,0 @@ -package dev.caskeleton.adapter.outbound.notification.platform.template; - -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; - -/** SHA-256 helper shared by rendering, fingerprinting and payload protection. */ -public final class NotificationDigest { - - private NotificationDigest() {} - - /** Hex SHA-256 of a UTF-8 string. */ - public static String hex(String value) { - return hex(value.getBytes(StandardCharsets.UTF_8)); - } - - /** Hex SHA-256 of raw bytes. */ - public static String hex(byte[] value) { - return HexFormat.of().formatHex(sha256(value)); - } - - /** Raw SHA-256 of bytes. */ - public static byte[] sha256(byte[] value) { - try { - return MessageDigest.getInstance("SHA-256").digest(value); - } catch (NoSuchAlgorithmException impossible) { - throw new IllegalStateException("SHA-256 is required by the Java platform", impossible); - } - } -} diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/template/Sha256MessageDigestAdapter.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/template/Sha256MessageDigestAdapter.java deleted file mode 100644 index 15a9409b..00000000 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/template/Sha256MessageDigestAdapter.java +++ /dev/null @@ -1,12 +0,0 @@ -package dev.caskeleton.adapter.outbound.notification.platform.template; - -import dev.caskeleton.application.notification.platform.dispatch.MessageDigestPort; - -/** Hashing adapter for the canonical request fingerprint. */ -public final class Sha256MessageDigestAdapter implements MessageDigestPort { - - @Override - public byte[] sha256(byte[] input) { - return NotificationDigest.sha256(input); - } -} diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformCoreConfigurationTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformCoreConfigurationTest.java index 72bc4107..967da7fe 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformCoreConfigurationTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformCoreConfigurationTest.java @@ -6,7 +6,6 @@ import dev.caskeleton.adapter.outbound.notification.platform.security.AesGcmCont import dev.caskeleton.adapter.outbound.notification.platform.template.NotificationTemplateEngine; import dev.caskeleton.adapter.outbound.notification.platform.template.PlaceholderTemplateEngine; import dev.caskeleton.application.notification.platform.admin.NotificationAdminService; -import dev.caskeleton.application.notification.platform.dispatch.MessageDigestPort; import dev.caskeleton.application.notification.platform.security.ContactPointProtector; import dev.caskeleton.application.notification.platform.security.SecretKeyMaterial; import dev.caskeleton.application.notification.platform.security.SecretMaterialProvider; @@ -37,19 +36,13 @@ class NotificationPlatformCoreConfigurationTest { .run( context -> { assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(MessageDigestPort.class); assertThat(context).doesNotHaveBean(TemplateVariableValidator.class); }); } @Test void enablingThePlatformContributesItsDefaultRuntimeBeans() { - enabled() - .run( - context -> { - assertThat(context).hasSingleBean(MessageDigestPort.class); - assertThat(context).hasSingleBean(TemplateVariableValidator.class); - }); + enabled().run(context -> assertThat(context).hasSingleBean(TemplateVariableValidator.class)); } @Test diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/UuidV7GeneratorTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/UuidV7GeneratorTest.java new file mode 100644 index 00000000..0b4a2442 --- /dev/null +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/UuidV7GeneratorTest.java @@ -0,0 +1,46 @@ +package dev.caskeleton.adapter.outbound.notification.platform.dispatch; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class UuidV7GeneratorTest { + + private static final Clock FIXED = + Clock.fixed(Instant.parse("2026-09-29T00:00:00Z"), ZoneOffset.UTC); + + @Test + void anIdIsAVersionSevenUuid() { + assertThat(new UuidV7Generator(FIXED).nextId().version()).isEqualTo(7); + } + + @Test + @DisplayName("같은 밀리초 안의 연속 id도 생성 순서대로 정렬된다") + void idsMintedInOneMillisecondStayInOrder() { + // given + UuidV7Generator generator = new UuidV7Generator(FIXED); + List ids = new ArrayList<>(); + + // when + for (int i = 0; i < 1_000; i++) { + ids.add(generator.nextId()); + } + + // then + assertThat(ids).isSortedAccordingTo(UuidV7GeneratorTest::unsigned).doesNotHaveDuplicates(); + } + + private static int unsigned(UUID left, UUID right) { + int high = Long.compareUnsigned(left.getMostSignificantBits(), right.getMostSignificantBits()); + return high != 0 + ? high + : Long.compareUnsigned(left.getLeastSignificantBits(), right.getLeastSignificantBits()); + } +} diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/NotificationPerformanceCertificationTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/NotificationPerformanceCertificationTest.java index cbcc07ee..acaded40 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/NotificationPerformanceCertificationTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/NotificationPerformanceCertificationTest.java @@ -127,7 +127,7 @@ class NotificationPerformanceCertificationTest { void backoffStaysWithinItsCeilingAcrossManyAttempts() { var backoff = new dev.caskeleton.application.notification.platform.policy.RetryBackoff( - Duration.ofSeconds(1), Duration.ofMinutes(5), 2.0d); + Duration.ofSeconds(1), Duration.ofMinutes(5)); var jitter = dev.caskeleton.application.notification.platform.policy.JitterSource.none(); for (int attempt = 1; attempt <= 40; attempt++) { diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/codec/CrockfordBase32.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/codec/CrockfordBase32.java index f4e47e0f..17bda8dc 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/codec/CrockfordBase32.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/codec/CrockfordBase32.java @@ -1,10 +1,7 @@ package dev.caskeleton.adapter.outbound.objectstorage.codec; +import dev.caskeleton.shared.digest.Sha256; import java.math.BigInteger; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; /** Canonical lowercase Crockford Base32 and bounded namespace support. */ public final class CrockfordBase32 { @@ -46,12 +43,6 @@ public final class CrockfordBase32 { } static String sha256Hex(String value) { - try { - return HexFormat.of() - .formatHex( - MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 must be available", exception); - } + return Sha256.ofUtf8(value).hex(); } } diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/codec/ObjectIdentityCodec.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/codec/ObjectIdentityCodec.java index d319e229..8db7c0cc 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/codec/ObjectIdentityCodec.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/codec/ObjectIdentityCodec.java @@ -2,9 +2,7 @@ package dev.caskeleton.adapter.outbound.objectstorage.codec; import dev.caskeleton.application.objectstorage.identity.ObjectId; import dev.caskeleton.application.objectstorage.identity.ObjectOperationKey; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; +import dev.caskeleton.shared.digest.Sha256; import java.util.Arrays; import java.util.Objects; @@ -31,13 +29,8 @@ public final class ObjectIdentityCodec { + operationKey.operationId().value() + "\n" + requestFingerprint; - try { - byte[] digest = - MessageDigest.getInstance("SHA-256").digest(seed.getBytes(StandardCharsets.UTF_8)); - return ObjectId.parse(CrockfordBase32.encode(Arrays.copyOf(digest, 16), 26)); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 must be available", exception); - } + byte[] digest = Sha256.ofUtf8(seed).bytes(); + return ObjectId.parse(CrockfordBase32.encode(Arrays.copyOf(digest, 16), 26)); } /** Lower-case hex SHA-256 of the UTF-8 bytes of {@code value}. */ diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageCapabilityConfig.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageCapabilityConfig.java index c5255d35..a6da14a3 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageCapabilityConfig.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageCapabilityConfig.java @@ -6,6 +6,7 @@ import dev.caskeleton.adapter.outbound.objectstorage.routing.RoutingObjectMutati import dev.caskeleton.adapter.outbound.objectstorage.routing.RoutingObjectReadAdapter; import dev.caskeleton.adapter.outbound.objectstorage.s3.S3ObjectStorageProviderContribution; import dev.caskeleton.application.outbound.SecretSourcePort; +import java.time.Clock; import java.util.Arrays; import java.util.List; import java.util.Set; @@ -41,10 +42,11 @@ public class ObjectStorageCapabilityConfig { matchIfMissing = true) @ConditionalOnMissingBean(name = "s3ObjectStorageProviderContribution") public ObjectStorageProviderContribution s3ObjectStorageProviderContribution( - ObjectProvider secretSources) { + ObjectProvider secretSources, ObjectProvider clocks) { // Looked up when an S3 binding actually resolves a credential, so a local-only composition // without a secret backend still starts; an S3 credential without one fails at that point. - return new S3ObjectStorageProviderContribution(key -> secretSources.getObject().resolve(key)); + return new S3ObjectStorageProviderContribution( + key -> secretSources.getObject().resolve(key), clock(clocks)); } @Bean @@ -54,7 +56,9 @@ public class ObjectStorageCapabilityConfig { havingValue = "true", matchIfMissing = true) public ObjectStorageBindingCompiler objectStorageBindingCompiler( - List contributions, Environment environment) { + List contributions, + Environment environment, + ObjectProvider clocks) { Set profiles = Set.copyOf( Arrays.asList( @@ -64,7 +68,8 @@ public class ObjectStorageCapabilityConfig { boolean scannerWorkflowEnabled = environment.getProperty( "app.object-storage.scan-maintenance.enabled", Boolean.class, false); - return new ObjectStorageBindingCompiler(contributions, profiles, scannerWorkflowEnabled); + return new ObjectStorageBindingCompiler( + contributions, profiles, scannerWorkflowEnabled, clock(clocks)); } @Bean @@ -97,8 +102,9 @@ public class ObjectStorageCapabilityConfig { havingValue = "true", matchIfMissing = true) public RoutingObjectMutationAdapter routingObjectMutationAdapter( - ObjectStorageCapabilityAssembler.AssembledCapability capability) { - return new RoutingObjectMutationAdapter(capability); + ObjectStorageCapabilityAssembler.AssembledCapability capability, + ObjectProvider clocks) { + return new RoutingObjectMutationAdapter(capability, clock(clocks)); } @Bean @@ -108,8 +114,9 @@ public class ObjectStorageCapabilityConfig { havingValue = "true", matchIfMissing = true) public ObjectPublicationHandoffService objectPublicationHandoffService( - ObjectStorageCapabilityAssembler.AssembledCapability capability) { - return new ObjectPublicationHandoffService(capability, java.time.Clock.systemUTC()); + ObjectStorageCapabilityAssembler.AssembledCapability capability, + ObjectProvider clocks) { + return new ObjectPublicationHandoffService(capability, clock(clocks)); } @Bean @@ -122,4 +129,14 @@ public class ObjectStorageCapabilityConfig { ObjectStorageCapabilityAssembler.AssembledCapability capability) { return new RoutingObjectReadAdapter(capability); } + + /** + * The application's {@link Clock} bean, or the system UTC clock when the composition has none. + * + *

One clock for the whole capability: a component that read {@code Instant.now()} beside an + * injected clock recorded times a test (or a deployment with a controlled clock) could not see. + */ + static Clock clock(ObjectProvider clocks) { + return clocks.getIfAvailable(Clock::systemUTC); + } } diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageScanMaintenanceConfig.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageScanMaintenanceConfig.java index bdc3f580..16daee02 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageScanMaintenanceConfig.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageScanMaintenanceConfig.java @@ -1,6 +1,8 @@ package dev.caskeleton.adapter.outbound.objectstorage.config; import dev.caskeleton.adapter.outbound.objectstorage.routing.RoutingObjectScanMaintenanceAdapter; +import java.time.Clock; +import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -20,7 +22,9 @@ public class ObjectStorageScanMaintenanceConfig { name = "enabled", havingValue = "true") public RoutingObjectScanMaintenanceAdapter routingObjectScanMaintenanceAdapter( - ObjectStorageCapabilityAssembler.AssembledCapability capability) { - return new RoutingObjectScanMaintenanceAdapter(capability, java.time.Clock.systemUTC()); + ObjectStorageCapabilityAssembler.AssembledCapability capability, + ObjectProvider clocks) { + return new RoutingObjectScanMaintenanceAdapter( + capability, ObjectStorageCapabilityConfig.clock(clocks)); } } diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/control/CanonicalJsonObjectControlRecordCodec.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/control/CanonicalJsonObjectControlRecordCodec.java index 399cec43..e1310e1c 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/control/CanonicalJsonObjectControlRecordCodec.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/control/CanonicalJsonObjectControlRecordCodec.java @@ -24,14 +24,13 @@ import dev.caskeleton.application.objectstorage.model.ObjectMediaType; import dev.caskeleton.application.objectstorage.model.ObjectPublicationRequirement; import dev.caskeleton.application.objectstorage.model.ObjectRetentionRequirement; import dev.caskeleton.application.objectstorage.model.ObjectScanState; +import dev.caskeleton.shared.digest.Sha256; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.time.Instant; import java.util.Base64; import java.util.Comparator; import java.util.EnumSet; -import java.util.HexFormat; import java.util.Objects; import java.util.stream.Collectors; @@ -104,11 +103,7 @@ public final class CanonicalJsonObjectControlRecordCodec implements ObjectContro } public String sha256Hex(byte[] value) { - try { - return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 must be available", exception); - } + return Sha256.of(value).hex(); } private static byte[] payload(ObjectControlRecord record) { diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/control/ObjectPublicationHandoffRecord.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/control/ObjectPublicationHandoffRecord.java index 4ea6bd6a..67cdfcc8 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/control/ObjectPublicationHandoffRecord.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/control/ObjectPublicationHandoffRecord.java @@ -3,12 +3,9 @@ package dev.caskeleton.adapter.outbound.objectstorage.control; import dev.caskeleton.application.objectstorage.identity.ObjectOperationKey; import dev.caskeleton.application.objectstorage.identity.ObjectStageHandle; import dev.caskeleton.application.objectstorage.identity.ObjectVersionToken; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; +import dev.caskeleton.shared.digest.Sha256; import java.time.Duration; import java.time.Instant; -import java.util.HexFormat; import java.util.Objects; /** Durable monotonically fenced application-to-publication handoff lease. */ @@ -191,13 +188,6 @@ public record ObjectPublicationHandoffRecord( if (claimant == null || claimant.isBlank() || claimant.length() > 128) { throw new IllegalArgumentException("handoff claimant is invalid"); } - try { - return HexFormat.of() - .formatHex( - MessageDigest.getInstance("SHA-256") - .digest(claimant.getBytes(StandardCharsets.UTF_8))); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 must be available", exception); - } + return Sha256.ofUtf8(claimant).hex(); } } diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/filesystem/LocalDevObjectDataStore.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/filesystem/LocalDevObjectDataStore.java index 8c0e5d93..1f6be928 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/filesystem/LocalDevObjectDataStore.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/filesystem/LocalDevObjectDataStore.java @@ -11,6 +11,7 @@ import dev.caskeleton.application.objectstorage.identity.ObjectId; import dev.caskeleton.application.objectstorage.identity.ObjectVersionToken; import dev.caskeleton.application.objectstorage.model.ObjectContentIdentity; import dev.caskeleton.application.objectstorage.model.ObjectDigest; +import dev.caskeleton.shared.digest.Sha256; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; @@ -20,7 +21,6 @@ import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.util.Base64; import java.util.Optional; @@ -90,7 +90,7 @@ public final class LocalDevObjectDataStore { return Optional.empty(); } try { - MessageDigest digest = sha256(); + MessageDigest digest = Sha256.newMessageDigest(); long size = 0; ByteBuffer buffer = ByteBuffer.allocate(64 * 1024); try (FileChannel channel = FileChannel.open(source, StandardOpenOption.READ)) { @@ -173,14 +173,6 @@ public final class LocalDevObjectDataStore { ObjectRouteToken.parse(segments[2]), ObjectId.parse(segments[4])); } - private static MessageDigest sha256() { - try { - return MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 must be available", exception); - } - } - private static ObjectStorageProviderException conflict() { return new ObjectStorageProviderException( ObjectStorageProviderException.Failure.CONFLICT, "local immutable object already exists"); diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/filesystem/LocalObjectStreamTransfer.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/filesystem/LocalObjectStreamTransfer.java index ab238c3d..25b68b05 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/filesystem/LocalObjectStreamTransfer.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/filesystem/LocalObjectStreamTransfer.java @@ -15,13 +15,13 @@ import dev.caskeleton.application.objectstorage.content.ObjectContentProductionE import dev.caskeleton.application.objectstorage.content.ObjectContentReadContext; import dev.caskeleton.application.objectstorage.model.ObjectContentIdentity; import dev.caskeleton.application.objectstorage.model.ObjectDigest; +import dev.caskeleton.shared.digest.Sha256; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.util.Base64; import java.util.Objects; @@ -39,7 +39,7 @@ public final class LocalObjectStreamTransfer { throws IOException { Objects.requireNonNull(producer, "producer must be non-null"); requireActive(operation.budget(), operation.cancellation().isCancelled()); - MessageDigest digest = sha256(); + MessageDigest digest = Sha256.newMessageDigest(); long[] written = {0}; ObjectContentProductionContext context = ObjectContentProductionContext.open( @@ -160,14 +160,6 @@ public final class LocalObjectStreamTransfer { } } - private static MessageDigest sha256() { - try { - return MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 must be available", exception); - } - } - private static void requireActive( dev.caskeleton.application.outbound.CallBudget budget, boolean cancelled) { if (cancelled) { diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/kernel/ManagedObjectPublicationKernel.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/kernel/ManagedObjectPublicationKernel.java index 81503733..cd1ced75 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/kernel/ManagedObjectPublicationKernel.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/kernel/ManagedObjectPublicationKernel.java @@ -19,7 +19,7 @@ import dev.caskeleton.application.objectstorage.model.ObjectMutationOutcome; import dev.caskeleton.application.objectstorage.model.ObjectPublicationRequirement; import dev.caskeleton.application.objectstorage.model.ObjectPublishReceipt; import dev.caskeleton.application.objectstorage.request.ObjectPublishRequest; -import java.time.Instant; +import java.time.Clock; import java.util.Objects; import java.util.Optional; @@ -33,12 +33,14 @@ import java.util.Optional; public final class ManagedObjectPublicationKernel { private final ObjectStorageCapabilityAssembler.DestinationRuntime runtime; + private final Clock clock; private final ObjectReferencePublicationService references = new ObjectReferencePublicationService(); public ManagedObjectPublicationKernel( - ObjectStorageCapabilityAssembler.DestinationRuntime runtime) { + ObjectStorageCapabilityAssembler.DestinationRuntime runtime, Clock clock) { this.runtime = Objects.requireNonNull(runtime, "runtime must be non-null"); + this.clock = Objects.requireNonNull(clock, "clock must be non-null"); } public ObjectPublishReceipt publish( @@ -69,7 +71,7 @@ public final class ManagedObjectPublicationKernel { runtime.destination().route(), runtime.destination().policySnapshot(), request.contentIdentity(), - Instant.now()); + clock.instant()); if (reserved.decision() == ObjectOperationKernelResult.Decision.CONFLICT) { throw new IllegalArgumentException("operation identity conflicts with a different intent"); } @@ -100,7 +102,7 @@ public final class ManagedObjectPublicationKernel { operation, PublicationOperationState.PUBLISHED, stored.contentIdentity(), - Instant.now()); + clock.instant()); } } ObjectOperationRecord terminal = requireOperation(request); @@ -118,7 +120,7 @@ public final class ManagedObjectPublicationKernel { runtime.destination().policySnapshot().policyRevision().value()); } - private static ObjectStorageProvider.StoredData continueDataPublication( + private ObjectStorageProvider.StoredData continueDataPublication( ObjectOperationKernel kernel, ObjectOperationRecord initial, ObjectStorageProviderOperation providerOperation, @@ -128,7 +130,7 @@ public final class ManagedObjectPublicationKernel { if (operation.stablePhase() == PublicationOperationState.RESERVED) { operation = kernel.advancePublication( - operation, PublicationOperationState.DATA_UPLOAD_IN_PROGRESS, null, Instant.now()); + operation, PublicationOperationState.DATA_UPLOAD_IN_PROGRESS, null, clock.instant()); } if (operation.stablePhase() != PublicationOperationState.DATA_UPLOAD_IN_PROGRESS) { return provider @@ -160,17 +162,17 @@ public final class ManagedObjectPublicationKernel { throw new IllegalStateException("provider create cannot be resolved safely"); } if (operation.effectCertainty() != ObjectEffectCertainty.CONFIRMED) { - operation = kernel.confirmEffect(operation, Instant.now()); + operation = kernel.confirmEffect(operation, clock.instant()); } kernel.advancePublication( operation, PublicationOperationState.DATA_UPLOADED, stored.contentIdentity(), - Instant.now()); + clock.instant()); return stored; } - private static ObjectOperationRecord advanceToReferencePublication( + private ObjectOperationRecord advanceToReferencePublication( ObjectOperationKernel kernel, ObjectOperationRecord initial) { ObjectOperationRecord operation = initial; if (operation.stablePhase() == PublicationOperationState.DATA_UPLOADED) { @@ -179,7 +181,7 @@ public final class ManagedObjectPublicationKernel { operation, PublicationOperationState.INTEGRITY_VERIFIED, operation.observedContentIdentity(), - Instant.now()); + clock.instant()); } if (operation.stablePhase() == PublicationOperationState.INTEGRITY_VERIFIED) { operation = @@ -187,7 +189,7 @@ public final class ManagedObjectPublicationKernel { operation, PublicationOperationState.REFERENCE_PUBLISH_IN_PROGRESS, operation.observedContentIdentity(), - Instant.now()); + clock.instant()); } return operation; } diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/routing/RoutingObjectMutationAdapter.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/routing/RoutingObjectMutationAdapter.java index dc5d60a6..9db65609 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/routing/RoutingObjectMutationAdapter.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/routing/RoutingObjectMutationAdapter.java @@ -30,7 +30,6 @@ import dev.caskeleton.application.objectstorage.request.ObjectRetireRequest; import dev.caskeleton.application.objectstorage.request.ObjectStageRequest; import dev.caskeleton.application.objectstorage.request.ObjectVerifyRequest; import java.time.Clock; -import java.time.Instant; import java.util.Optional; /** Normal mutation router. It never implements privileged purge or scanner-maintenance ports. */ @@ -43,11 +42,6 @@ public final class RoutingObjectMutationAdapter private final ObjectStorageCapabilityAssembler.AssembledCapability capability; private final Clock clock; - public RoutingObjectMutationAdapter( - ObjectStorageCapabilityAssembler.AssembledCapability capability) { - this(capability, Clock.systemUTC()); - } - public RoutingObjectMutationAdapter( ObjectStorageCapabilityAssembler.AssembledCapability capability, Clock clock) { this.capability = java.util.Objects.requireNonNull(capability); @@ -80,7 +74,7 @@ public final class RoutingObjectMutationAdapter public ObjectPublishReceipt publish( ObjectPublishRequest request, ObjectContentProducer producer) { return new ManagedObjectPublicationKernel( - capability.destination(request.operationKey().destination())) + capability.destination(request.operationKey().destination()), clock) .publish(request, producer); } @@ -106,7 +100,7 @@ public final class RoutingObjectMutationAdapter request.operationKey(), ObjectMutationOutcome.REJECTED, ObjectOperationError.CONFLICT, - Instant.now()); + clock.instant()); } if (record.state() == PublishedReferenceState.RETIRED || record.state() == PublishedReferenceState.PURGE_ELIGIBLE @@ -115,7 +109,7 @@ public final class RoutingObjectMutationAdapter request.operationKey(), ObjectMutationOutcome.REPLAYED, ObjectOperationError.NONE, - Instant.now()); + clock.instant()); } ObjectReferenceRecord pending = new ObjectReferenceRecord( @@ -126,7 +120,7 @@ public final class RoutingObjectMutationAdapter record.objectId(), record.immutableDataVersion(), PublishedReferenceState.RETIREMENT_PENDING, - Instant.now()); + clock.instant()); current = store.compareAndSet(key, new ObjectControlMutation(current.version(), pending)); ObjectReferenceRecord retired = new ObjectReferenceRecord( @@ -137,13 +131,13 @@ public final class RoutingObjectMutationAdapter record.objectId(), record.immutableDataVersion(), PublishedReferenceState.RETIRED, - Instant.now()); + clock.instant()); store.compareAndSet(key, new ObjectControlMutation(current.version(), retired)); return new ObjectMutationReceipt( request.operationKey(), ObjectMutationOutcome.APPLIED, ObjectOperationError.NONE, - Instant.now()); + clock.instant()); } @Override diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncRequestBodyBridge.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncRequestBodyBridge.java index 019d1113..08c6e87d 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncRequestBodyBridge.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncRequestBodyBridge.java @@ -9,9 +9,9 @@ import dev.caskeleton.application.objectstorage.content.ObjectContentProducer; import dev.caskeleton.application.objectstorage.content.ObjectContentProductionContext; import dev.caskeleton.application.objectstorage.model.ObjectContentIdentity; import dev.caskeleton.application.objectstorage.model.ObjectDigest; +import dev.caskeleton.shared.digest.Sha256; import java.nio.ByteBuffer; import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Objects; import java.util.Optional; @@ -113,7 +113,7 @@ public final class S3AsyncRequestBodyBridge implements AsyncRequestBody { } private void produce() { - MessageDigest digest = sha256(); + MessageDigest digest = Sha256.newMessageDigest(); long[] written = {0}; CancellationView cancellation = () -> operation.cancellation().isCancelled() || isCancelled(); ObjectContentProductionContext context = @@ -243,14 +243,6 @@ public final class S3AsyncRequestBodyBridge implements AsyncRequestBody { } } - private static MessageDigest sha256() { - try { - return MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 must be available", exception); - } - } - private static ObjectStorageProviderException providerFailure( ObjectStorageProviderException.Failure failure, String message, Throwable cause) { return cause == null diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncResponseBodyBridge.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncResponseBodyBridge.java index 82bd4910..046a7eca 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncResponseBodyBridge.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncResponseBodyBridge.java @@ -6,9 +6,9 @@ import dev.caskeleton.application.objectstorage.content.ObjectChunkReadException import dev.caskeleton.application.objectstorage.content.ObjectChunkSource; import dev.caskeleton.application.objectstorage.content.ObjectContentConsumer; import dev.caskeleton.application.objectstorage.content.ObjectContentReadContext; +import dev.caskeleton.shared.digest.Sha256; import java.nio.ByteBuffer; import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Objects; import java.util.concurrent.ArrayBlockingQueue; @@ -109,7 +109,7 @@ public final class S3AsyncResponseBodyBridge implements AsyncResponseTransfor operation.contentIdentity(), operation.exactVersion(), operation.range()); - MessageDigest digest = sha256(); + MessageDigest digest = Sha256.newMessageDigest(); ChunkCursor cursor = new ChunkCursor(subscriber, digest); ObjectChunkSource source = ObjectChunkSource.scoped(context, cursor::read); Throwable failure = null; @@ -323,14 +323,6 @@ public final class S3AsyncResponseBodyBridge implements AsyncResponseTransfor } } - private static MessageDigest sha256() { - try { - return MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 must be available", exception); - } - } - private static final class Chunk { private final byte[] bytes; diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ObjectStorageProviderContribution.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ObjectStorageProviderContribution.java index 16163260..3dfc7bad 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ObjectStorageProviderContribution.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ObjectStorageProviderContribution.java @@ -35,11 +35,11 @@ public final class S3ObjectStorageProviderContribution * Production contribution. Credential references resolve through the deployment's configured * secret backend, never straight from the process environment. */ - public S3ObjectStorageProviderContribution(SecretSourcePort secretSource) { + public S3ObjectStorageProviderContribution(SecretSourcePort secretSource, Clock clock) { this( - Clock.systemUTC(), + clock, new S3ProviderQualifier( - Clock.systemUTC(), + clock, (binding, plan) -> { throw new IllegalStateException("startup S3 probing is not configured"); }), diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/query/SignedJsonCursorCodec.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/query/SignedJsonCursorCodec.java index e00104ac..2247ca14 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/query/SignedJsonCursorCodec.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/query/SignedJsonCursorCodec.java @@ -1,12 +1,9 @@ package dev.caskeleton.adapter.outbound.persistence.api.query; +import dev.caskeleton.shared.digest.HmacSha256; import java.nio.charset.StandardCharsets; -import java.security.GeneralSecurityException; -import java.security.MessageDigest; import java.util.Base64; import java.util.Objects; -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; /** * A versioned, tamper-evident cursor codec built only on the Java standard library (design §27.3). @@ -20,15 +17,14 @@ import javax.crypto.spec.SecretKeySpec; * seek to arbitrary keys, which turns a paging token into an access-control bypass wherever the * predicate depends on where the scan started. * - *

Verification is constant-time via {@link MessageDigest#isEqual}. A short-circuiting comparison - * here leaks the correct MAC one byte at a time. + *

Signing and constant-time verification are shared-contract {@link HmacSha256}; a + * short-circuiting comparison here would leak the correct MAC one byte at a time. */ public final class SignedJsonCursorCodec { /** The only cursor version this codec issues and accepts. */ public static final String VERSION = "v1"; - private static final String ALGORITHM = "HmacSHA256"; private static final int MINIMUM_KEY_LENGTH = 32; private static final char SEPARATOR = '.'; @@ -56,9 +52,6 @@ public final class SignedJsonCursorCodec { /** Largest payload this codec will decode, in bytes. */ public static final int MAX_PAYLOAD_BYTES = 2048; - /** HMAC-SHA256 produces exactly this many bytes. */ - private static final int MAC_LENGTH_BYTES = 32; - /** Encodes a cursor into a client-safe, tamper-evident token. */ public String encode(C cursor) { Objects.requireNonNull(cursor, "cursor"); @@ -71,7 +64,7 @@ public final class SignedJsonCursorCodec { } String payload = encoder.encodeToString(json); String signed = VERSION + SEPARATOR + payload; - String token = signed + SEPARATOR + encoder.encodeToString(mac(signed)); + String token = signed + SEPARATOR + encoder.encodeToString(HmacSha256.sign(key, signed)); if (token.length() > MAX_ENCODED_LENGTH) { throw new IllegalStateException( "cursor token is " + token.length() + " characters; the bound is " + MAX_ENCODED_LENGTH); @@ -114,12 +107,10 @@ public final class SignedJsonCursorCodec { } String signed = encoded.substring(0, macSeparator); byte[] presented = decodeBase64(encoded.substring(macSeparator + 1)); - if (presented.length != MAC_LENGTH_BYTES) { - // Checked before the comparison. `MessageDigest.isEqual` is constant time for equal-length - // inputs; feeding it a differently-sized array asks it a question it was not built to answer. + if (presented.length != HmacSha256.MAC_BYTES) { throw new IllegalArgumentException("malformed cursor"); } - if (!MessageDigest.isEqual(mac(signed), presented)) { + if (!HmacSha256.verify(key, signed, presented)) { throw new IllegalArgumentException("cursor signature does not verify"); } // The payload decoder runs only after the signature verified, so an unsigned token never @@ -140,14 +131,4 @@ public final class SignedJsonCursorCodec { throw new IllegalArgumentException("malformed cursor", malformed); } } - - private byte[] mac(String signed) { - try { - Mac mac = Mac.getInstance(ALGORITHM); - mac.init(new SecretKeySpec(key, ALGORITHM)); - return mac.doFinal(signed.getBytes(StandardCharsets.UTF_8)); - } catch (GeneralSecurityException unavailable) { - throw new IllegalStateException("cursor signing algorithm is unavailable", unavailable); - } - } } diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/jpa/IdempotencyRecordJpaRepository.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/jpa/IdempotencyRecordJpaRepository.java index 0c0288da..22a07ca7 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/jpa/IdempotencyRecordJpaRepository.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/jpa/IdempotencyRecordJpaRepository.java @@ -3,14 +3,20 @@ package dev.caskeleton.adapter.outbound.persistence.idempotency.jpa; import dev.caskeleton.adapter.outbound.persistence.idempotency.jpa.entity.IdempotencyRecordEntity; import java.time.Instant; import java.util.UUID; -import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.Repository; import org.springframework.data.repository.query.Param; -/** Spring Data repository for {@link IdempotencyRecordEntity}: the reaper's expiry purge. */ -public interface IdempotencyRecordJpaRepository - extends JpaRepository { +/** + * Spring Data repository for {@link IdempotencyRecordEntity}: the reaper's expiry purge, and + * nothing else. + * + *

A {@code Repository} marker rather than {@code JpaRepository}: the records belong to scopes, + * and the inherited {@code findAll}/{@code deleteAll} were statements across every scope that no + * caller used and any next caller could. + */ +public interface IdempotencyRecordJpaRepository extends Repository { /** Reaper / TTL boundary (§E): purge every record whose expiry is at/before {@code now}. */ @Modifying diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyCapabilityGuard.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyCapabilityGuard.java index 9bc0427e..f85dff19 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyCapabilityGuard.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyCapabilityGuard.java @@ -1,10 +1,10 @@ package dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql; +import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction; import java.util.Objects; import javax.sql.DataSource; import org.springframework.jdbc.core.ConnectionCallback; import org.springframework.jdbc.core.JdbcOperations; -import org.springframework.transaction.support.TransactionSynchronizationManager; /** * The preconditions a mutation must meet before any SQL runs. @@ -90,20 +90,6 @@ final class IdempotencyCapabilityGuard { * @throws IllegalStateException naming which of the three conditions failed */ void requirePrimaryWriteTransaction() { - if (!TransactionSynchronizationManager.isActualTransactionActive()) { - throw new IllegalStateException( - "owner-safe idempotency mutation requires an active primary transaction"); - } - if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { - throw new IllegalStateException( - "owner-safe idempotency mutation requires a read-write transaction"); - } - if (dataSource != null && !TransactionSynchronizationManager.hasResource(dataSource)) { - // The exact check the outbox and inbox adapters already make. Without it, a transaction on - // another data source satisfied the guard while this store's work committed on its own. - throw new IllegalStateException( - "owner-safe idempotency mutation requires a transaction bound to this store's data" - + " source; the active transaction belongs to another one"); - } + CallerTransaction.requireReadWrite("owner-safe idempotency mutation", dataSource); } } diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyDigestPolicy.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyDigestPolicy.java index 5754cad9..3bb75bd4 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyDigestPolicy.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyDigestPolicy.java @@ -1,9 +1,6 @@ package dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; +import dev.caskeleton.shared.digest.Sha256; import java.util.Objects; /** @@ -73,12 +70,6 @@ final class IdempotencyDigestPolicy { } private static String sha256(String value) { - try { - return HexFormat.of() - .formatHex( - MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); - } catch (NoSuchAlgorithmException unavailable) { - throw new IllegalStateException("SHA-256 unavailable", unavailable); - } + return Sha256.ofUtf8(value).hex(); } } diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlOwnerSafeIdempotencyStore.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlOwnerSafeIdempotencyStore.java index a16c145f..21302ccd 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlOwnerSafeIdempotencyStore.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlOwnerSafeIdempotencyStore.java @@ -19,9 +19,8 @@ import dev.caskeleton.application.idempotency.IdempotencyState; import dev.caskeleton.application.idempotency.IdempotencyStorePort; import dev.caskeleton.application.idempotency.StoredResponse; import dev.caskeleton.application.transaction.OperationId; +import dev.caskeleton.shared.digest.Sha256; import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.time.Duration; import java.time.Instant; @@ -645,13 +644,7 @@ public class PostgreSqlOwnerSafeIdempotencyStore implements IdempotencyStorePort } private static String sha256(String value) { - try { - byte[] digest = - MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)); - return HexFormat.of().formatHex(digest); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 unavailable", exception); - } + return Sha256.ofUtf8(value).hex(); } private IllegalStateException indeterminateClaim() { diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/liveevent/JpaLiveEventReplayAdapter.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/liveevent/JpaLiveEventReplayAdapter.java index 6d7c4ee0..5f5daea7 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/liveevent/JpaLiveEventReplayAdapter.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/liveevent/JpaLiveEventReplayAdapter.java @@ -1,6 +1,7 @@ package dev.caskeleton.adapter.outbound.persistence.liveevent; import dev.caskeleton.adapter.outbound.persistence.liveevent.entity.LiveEventEntity; +import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction; import dev.caskeleton.application.realtime.LiveEventReplayPort; import dev.caskeleton.application.realtime.ReplayCursorUnavailableException; import dev.caskeleton.application.realtime.ReplayWindow; @@ -16,7 +17,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.data.domain.Limit; import org.springframework.jdbc.core.JdbcOperations; import org.springframework.stereotype.Repository; -import org.springframework.transaction.support.TransactionSynchronizationManager; /** * Retained live-event history, on PostgreSQL. @@ -161,9 +161,6 @@ public class JpaLiveEventReplayAdapter implements LiveEventReplayPort { } private static void requireCallerTransaction(String operation) { - if (!TransactionSynchronizationManager.isActualTransactionActive()) { - throw new IllegalStateException( - "live-event " + operation + " requires an active caller transaction"); - } + CallerTransaction.require("live-event " + operation); } } diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationStoreAdapter.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationStoreAdapter.java index 31669c76..e4827b96 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationStoreAdapter.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationStoreAdapter.java @@ -1,6 +1,7 @@ package dev.caskeleton.adapter.outbound.persistence.operation; import dev.caskeleton.adapter.outbound.persistence.operation.entity.DurableOperationEntity; +import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction; import dev.caskeleton.application.idempotency.RequestFingerprint; import dev.caskeleton.application.operation.DurableOperation; import dev.caskeleton.application.operation.DurableOperationId; @@ -16,7 +17,6 @@ import java.time.Instant; import java.util.List; import java.util.Optional; import org.springframework.stereotype.Repository; -import org.springframework.transaction.support.TransactionSynchronizationManager; /** * The PostgreSQL-backed {@link DurableOperationStorePort}. @@ -171,10 +171,7 @@ public class DurableOperationStoreAdapter implements DurableOperationStorePort { } private static void requireCallerTransaction(String operation) { - if (!TransactionSynchronizationManager.isActualTransactionActive()) { - throw new IllegalStateException( - "durable operation " + operation + " requires an active caller transaction"); - } + CallerTransaction.require("durable operation " + operation); } private static DurableOperation expireIfStale(DurableOperation operation, Instant now) { diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxEventJpaRepository.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxEventJpaRepository.java index c323e644..c7572f94 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxEventJpaRepository.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxEventJpaRepository.java @@ -3,9 +3,10 @@ package dev.caskeleton.adapter.outbound.persistence.outbox.jpa; import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity; import java.time.Instant; import java.util.List; -import org.springframework.data.jpa.repository.JpaRepository; +import java.util.Optional; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.Repository; import org.springframework.data.repository.query.Param; import org.springframework.transaction.annotation.Transactional; @@ -13,8 +14,19 @@ import org.springframework.transaction.annotation.Transactional; * Spring Data repository for {@link OutboxEventEntity} — only vendor-neutral operations. * Vendor-specific row claiming lives in the {@link OutboxClaimRepository} SPI (see README * "outbox"). + * + *

A {@code Repository} marker declaring only what the store uses. It extended {@code + * JpaRepository}, which put {@code findAll}/{@code deleteAll} over the whole outbox on the + * interface every caller holds; nothing used them, and a {@code deleteAll} there is every + * unpublished event. */ -public interface OutboxEventJpaRepository extends JpaRepository { +public interface OutboxEventJpaRepository extends Repository { + + /** Appends a row (the store's {@code append}). */ + S save(S entity); + + /** Reads one row by its event id. */ + Optional findById(String eventId); /** * Deletes at most {@code limit} PUBLISHED rows whose {@code occurred_at} is before {@code diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxStoreAdapter.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxStoreAdapter.java index 708bed94..12b7ec4c 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxStoreAdapter.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxStoreAdapter.java @@ -1,9 +1,9 @@ package dev.caskeleton.adapter.outbound.persistence.outbox.jpa; import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity; +import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction; import dev.caskeleton.application.messaging.contract.ContractId; import dev.caskeleton.application.messaging.contract.LogicalDestinationId; -import dev.caskeleton.application.messaging.contract.Sha256; import dev.caskeleton.application.messaging.event.AggregateIdentity; import dev.caskeleton.application.messaging.event.AggregateOrder; import dev.caskeleton.application.messaging.event.EventId; @@ -14,6 +14,7 @@ import dev.caskeleton.application.outbox.OutboxCompletion; import dev.caskeleton.application.outbox.OutboxEventStatus; import dev.caskeleton.application.outbox.OutboxLease; import dev.caskeleton.application.outbox.OutboxStorePort; +import dev.caskeleton.shared.digest.Sha256; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.time.Instant; @@ -29,7 +30,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Repository; -import org.springframework.transaction.support.TransactionSynchronizationManager; /** * JPA-backed {@link OutboxAppendPort} + {@link OutboxStorePort}. {@link #append} and the claim/mark @@ -166,10 +166,7 @@ public class OutboxStoreAdapter implements OutboxAppendPort, OutboxStorePort { } private static void requireTransaction(String operation) { - if (!TransactionSynchronizationManager.isActualTransactionActive()) { - throw new IllegalStateException( - "outbox " + operation + " requires an active caller transaction"); - } + CallerTransaction.require("outbox " + operation); } @Override diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/springdata/JpaStreamExecutor.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/springdata/JpaStreamExecutor.java index f61e9808..0f8d1fbb 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/springdata/JpaStreamExecutor.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/springdata/JpaStreamExecutor.java @@ -4,6 +4,7 @@ import dev.caskeleton.adapter.outbound.persistence.api.query.QueryName; import dev.caskeleton.adapter.outbound.persistence.api.query.QueryObservation; import dev.caskeleton.adapter.outbound.persistence.api.query.QueryScope; import dev.caskeleton.adapter.outbound.persistence.hibernate.QueryNameContext; +import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction; import java.util.Objects; import java.util.Optional; import java.util.Set; @@ -58,7 +59,7 @@ public final class JpaStreamExecutor { Objects.requireNonNull(policy, "policy"); Objects.requireNonNull(supplier, "supplier"); Objects.requireNonNull(consumer, "consumer"); - JpaStreamScope.requireActiveReadOnly(); + CallerTransaction.requireReadOnly("streaming"); return QueryNameContext.with( query, diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/springdata/JpaStreamScope.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/springdata/JpaStreamScope.java deleted file mode 100644 index 430ef502..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/springdata/JpaStreamScope.java +++ /dev/null @@ -1,45 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.springdata; - -import org.springframework.transaction.support.TransactionSynchronizationManager; - -/** - * The guard every streaming read passes through (design §27.4). - * - *

A JPA {@code Stream} is a live cursor: it holds a JDBC {@code ResultSet}, which holds a - * statement, which holds the connection. All three are released only when the stream closes and the - * transaction ends. Returning one past the transaction boundary — from a repository to a - * controller, or out of a service method — leaves that chain open until the pool notices, which is - * a connection leak that presents as unrelated timeouts elsewhere. - * - *

Requiring a read-only transaction is not cosmetic either. Streaming inside a write transaction - * keeps a write connection pinned for the whole traversal, which is the slowest possible way to - * hold the most contended resource. - */ -public final class JpaStreamScope { - - private JpaStreamScope() {} - - /** - * Fails unless an actual read-only transaction is active. - * - * @throws IllegalStateException when no transaction is active, or the active one is a write - */ - public static void requireActiveReadOnly() { - if (!TransactionSynchronizationManager.isActualTransactionActive()) { - throw new IllegalStateException( - "streaming requires an active transaction; without one the cursor closes after the first" - + " statement and the connection is returned mid-traversal"); - } - if (!TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { - throw new IllegalStateException( - "streaming requires a read-only transaction; a write transaction pins a write connection" - + " for the whole traversal"); - } - } - - /** Whether a read-only transaction is currently active. */ - public static boolean readOnlyTransactionActive() { - return TransactionSynchronizationManager.isActualTransactionActive() - && TransactionSynchronizationManager.isCurrentTransactionReadOnly(); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/CallerTransaction.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/CallerTransaction.java new file mode 100644 index 00000000..a9de24e6 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/CallerTransaction.java @@ -0,0 +1,76 @@ +package dev.caskeleton.adapter.outbound.persistence.transaction; + +import java.util.Objects; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * The guard a store runs before a write that must join the caller's transaction. + * + *

A driven adapter does not open its own transaction around application work (the use case owns + * it through {@code TransactionPort}). Without this check a store called outside one still works — + * each statement commits on its own — and the write it was meant to be atomic with commits + * separately: an outbox row without its business row, a lease without its claim. The outbox, the + * durable operation store, the live-event replay store and owner-safe idempotency each carried a + * copy of the check; this is the one they call. + */ +public final class CallerTransaction { + + private CallerTransaction() {} + + /** + * Fails unless an actual transaction is active on this thread. + * + * @param operation what is being attempted, for the message ({@code "outbox append"}) + * @throws IllegalStateException when no transaction is active + */ + public static void require(String operation) { + Objects.requireNonNull(operation, "operation"); + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException(operation + " requires an active caller transaction"); + } + } + + /** + * Fails unless an actual read-only transaction is active: the guard every streaming read passes + * through (design §27.4, formerly {@code springdata.JpaStreamScope}). + * + *

A JPA {@code Stream} is a live cursor: it holds a JDBC {@code ResultSet}, which holds a + * statement, which holds the connection. Without a transaction the cursor closes after the first + * statement and the connection is returned mid-traversal; returned past the transaction boundary + * it leaks the connection. Read-only is not cosmetic either: streaming inside a write transaction + * pins a write connection for the whole traversal. + * + * @param operation what is being attempted, for the message ({@code "streaming"}) + * @throws IllegalStateException when no transaction is active, or the active one is a write + */ + public static void requireReadOnly(String operation) { + require(operation); + if (!TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException(operation + " requires a read-only caller transaction"); + } + } + + /** + * Fails unless an actual read-write transaction is active and bound to {@code resource}. + * + *

The binding check matters when a deployment has more than one data source: a transaction on + * another one satisfies {@link #require} while this store's statements commit on their own. + * + * @param operation what is being attempted, for the message + * @param resource the store's transactional resource (its {@code DataSource}); {@code null} skips + * the binding check + * @throws IllegalStateException naming which condition failed + */ + public static void requireReadWrite(String operation, Object resource) { + require(operation); + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException(operation + " requires a read-write caller transaction"); + } + if (resource != null && !TransactionSynchronizationManager.hasResource(resource)) { + throw new IllegalStateException( + operation + + " requires a transaction bound to this store's data source; the active" + + " transaction belongs to another one"); + } + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java index 982d5787..c4d95c48 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java @@ -37,8 +37,6 @@ import dev.caskeleton.application.notification.platform.provider.ReconciliationR import dev.caskeleton.application.notification.platform.security.NotificationPayloadProtection; import dev.caskeleton.application.transaction.TransactionPort; import jakarta.persistence.EntityManagerFactory; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.sql.Timestamp; import java.time.Clock; import java.time.Duration; @@ -152,8 +150,7 @@ class PostgreSqlNotificationBackgroundPassIntegrationTest { projection, event -> {}, new NoMetrics(), - new SyntheticEventFingerprint( - PostgreSqlNotificationBackgroundPassIntegrationTest::sha256), + new SyntheticEventFingerprint(), transactions, clock); } @@ -400,17 +397,9 @@ class PostgreSqlNotificationBackgroundPassIntegrationTest { event); } - private static byte[] sha256(byte[] input) { - try { - return MessageDigest.getInstance("SHA-256").digest(input); - } catch (NoSuchAlgorithmException impossible) { - throw new IllegalStateException(impossible); - } - } - private static String sha256Hex(String value) { return java.util.HexFormat.of() - .formatHex(sha256(value.getBytes(java.nio.charset.StandardCharsets.UTF_8))); + .formatHex(dev.caskeleton.shared.digest.Sha256.ofUtf8(value).bytes()); } /** The notification entities and repositories, wired the way the production scan wires them. */ diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/JpaModuleBoundaryTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/JpaModuleBoundaryTest.java index bd07f7b0..153638ee 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/JpaModuleBoundaryTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/JpaModuleBoundaryTest.java @@ -95,7 +95,9 @@ class JpaModuleBoundaryTest { Map.entry( "h2", Set.of("api", "config", "failure", "idempotency", "outbox", "transaction")), Map.entry("hibernate", Set.of("api")), - Map.entry("idempotency", Set.of("api", "audit", "failure")), + // `transaction` for the one caller-transaction guard (CallerTransaction) the stores + // share. + Map.entry("idempotency", Set.of("api", "audit", "failure", "transaction")), Map.entry("lock", Set.of("api")), Map.entry("migration", Set.of("api")), Map.entry("observation", Set.of("api")), @@ -103,12 +105,12 @@ class JpaModuleBoundaryTest { // logs: the outbox is a delivery queue whose rows are consumed and retired, and this is a // replay window whose rows are read many times and expire on a clock. Sharing a package // would put one retention policy on two different lifecycles. - Map.entry("liveevent", Set.of()), + Map.entry("liveevent", Set.of("transaction")), // Durable long-running operations. No edge to `idempotency` even though the two share a // fingerprint type: that type comes from application-core, and an edge here would let a // change to the idempotency store's row shape reach the operation queue. - Map.entry("operation", Set.of()), - Map.entry("outbox", Set.of("api", "audit", "failure")), + Map.entry("operation", Set.of("transaction")), + Map.entry("outbox", Set.of("api", "audit", "failure", "transaction")), Map.entry( "postgresql", Set.of( @@ -126,7 +128,7 @@ class JpaModuleBoundaryTest { "transaction")), Map.entry("querydsl", Set.of("api", "springdata")), Map.entry("security", Set.of("api")), - Map.entry("springdata", Set.of("api", "hibernate")), + Map.entry("springdata", Set.of("api", "hibernate", "transaction")), // The startup policy relational persistence runs under — migration sequencing and the // OSIV/DDL/pool/TLS/vendor guards — which the composition root used to own. Map.entry("startup", Set.of("api", "config", "hibernate", "migration", "security")), diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/ScopedRowRepositoryShapeTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/ScopedRowRepositoryShapeTest.java new file mode 100644 index 00000000..cd314247 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/ScopedRowRepositoryShapeTest.java @@ -0,0 +1,56 @@ +package dev.caskeleton.adapter.outbound.persistence; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.persistence.idempotency.jpa.IdempotencyRecordJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.operation.DurableOperationJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxEventJpaRepository; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.List; +import java.util.Set; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * Repositories over rows that belong to a tenant, a scope or a relay offer no statement that reads + * or deletes across all of them (review E-6b). + * + *

Extending {@code JpaRepository} used to put {@code findAll} and {@code deleteAll} on the one + * interface every caller holds: nothing in the adapters used them, and nothing stopped the next + * caller from doing so. + */ +class ScopedRowRepositoryShapeTest { + + private static final Set UNSCOPED_BULK_METHODS = + Set.of( + "findAll", + "findAllById", + "deleteAll", + "deleteAllById", + "deleteAllInBatch", + "deleteAllByIdInBatch", + "count"); + + @ParameterizedTest + @ValueSource( + classes = { + DurableOperationJpaRepository.class, + IdempotencyRecordJpaRepository.class, + OutboxEventJpaRepository.class + }) + @DisplayName("범위 없는 findAll·deleteAll·count 같은 일괄 메서드를 노출하지 않는다") + void repositoryExposesNoUnscopedBulkReadOrDelete(Class repository) { + // when + List exposed = + Arrays.stream(repository.getMethods()) + .map(Method::getName) + .filter(UNSCOPED_BULK_METHODS::contains) + .distinct() + .toList(); + + // then + assertThat(exposed).isEmpty(); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/OwnerSafeIdempotencyPreconditionTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/OwnerSafeIdempotencyPreconditionTest.java index ce2c52c0..3e318d89 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/OwnerSafeIdempotencyPreconditionTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/OwnerSafeIdempotencyPreconditionTest.java @@ -57,7 +57,7 @@ class OwnerSafeIdempotencyPreconditionTest { void aClaimWithNoTransactionIsRefused() { assertThatThrownBy(() -> store.claim(claimRequest())) .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("active primary transaction"); + .hasMessage("owner-safe idempotency mutation requires an active caller transaction"); verifyNothingWasWritten(); } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationJpaRepositoryShapeTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationJpaRepositoryShapeTest.java deleted file mode 100644 index 21cb6d9e..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationJpaRepositoryShapeTest.java +++ /dev/null @@ -1,44 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.operation; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.List; -import java.util.Set; -import org.junit.jupiter.api.Test; - -/** - * {@code durable_operation} rows belong to a tenant, so its repository offers no statement that - * reads or deletes across tenants. - * - *

Extending {@code JpaRepository} used to put {@code findAll} and {@code deleteAll} on the one - * interface every caller holds: nothing in the adapter used them, and nothing stopped the next - * caller from doing so. - */ -class DurableOperationJpaRepositoryShapeTest { - - private static final Set UNSCOPED_BULK_METHODS = - Set.of( - "findAll", - "findAllById", - "deleteAll", - "deleteAllById", - "deleteAllInBatch", - "deleteAllByIdInBatch", - "count"); - - @Test - void repositoryExposesNoUnscopedBulkReadOrDelete() { - // when - List exposed = - Arrays.stream(DurableOperationJpaRepository.class.getMethods()) - .map(Method::getName) - .filter(UNSCOPED_BULK_METHODS::contains) - .distinct() - .toList(); - - // then - assertThat(exposed).isEmpty(); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxStoreAdapterTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxStoreAdapterTest.java index 4061cb0d..5defb0d8 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxStoreAdapterTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxStoreAdapterTest.java @@ -16,7 +16,6 @@ import static org.mockito.Mockito.when; import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity; import dev.caskeleton.application.messaging.contract.ContractId; import dev.caskeleton.application.messaging.contract.LogicalDestinationId; -import dev.caskeleton.application.messaging.contract.Sha256; import dev.caskeleton.application.messaging.event.AggregateIdentity; import dev.caskeleton.application.messaging.event.AggregateOrder; import dev.caskeleton.application.messaging.event.EventId; @@ -25,6 +24,7 @@ import dev.caskeleton.application.outbox.ClaimedOutboxEvent; import dev.caskeleton.application.outbox.OutboxCompletion; import dev.caskeleton.application.outbox.OutboxEventStatus; import dev.caskeleton.application.outbox.OutboxLease; +import dev.caskeleton.shared.digest.Sha256; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.time.Instant; diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/springdata/JpaStreamExecutorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/springdata/JpaStreamExecutorTest.java index 6bf8a66e..0285649b 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/springdata/JpaStreamExecutorTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/springdata/JpaStreamExecutorTest.java @@ -82,7 +82,7 @@ class JpaStreamExecutorTest { executor.consume( QUERY, ScrollPolicy.bounded(100, 100), this::trackedStream, Stream::count)) .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("active transaction"); + .hasMessage("streaming requires an active caller transaction"); } @Test @@ -95,7 +95,7 @@ class JpaStreamExecutorTest { executor.consume( QUERY, ScrollPolicy.bounded(100, 100), this::trackedStream, Stream::count)) .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("read-only"); + .hasMessage("streaming requires a read-only caller transaction"); } @Test diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/CallerTransactionTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/CallerTransactionTest.java new file mode 100644 index 00000000..6a207346 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/CallerTransactionTest.java @@ -0,0 +1,79 @@ +package dev.caskeleton.adapter.outbound.persistence.transaction; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class CallerTransactionTest { + + private static final Object DATA_SOURCE = new Object(); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + if (TransactionSynchronizationManager.hasResource(DATA_SOURCE)) { + TransactionSynchronizationManager.unbindResource(DATA_SOURCE); + } + } + + @Test + void aWriteOutsideACallerTransactionIsRefusedNamingTheOperation() { + // when + Throwable thrown = catchThrowable(() -> CallerTransaction.require("outbox append")); + + // then + assertThat(thrown) + .isInstanceOf(IllegalStateException.class) + .hasMessage("outbox append requires an active caller transaction"); + } + + @Test + void aWriteInsideAReadOnlyTransactionIsRefused() { + // given + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + + // when + Throwable thrown = catchThrowable(() -> CallerTransaction.requireReadWrite("claim", null)); + + // then + assertThat(thrown) + .isInstanceOf(IllegalStateException.class) + .hasMessage("claim requires a read-write caller transaction"); + } + + @Test + void aWriteInsideATransactionOnAnotherDataSourceIsRefused() { + // given + TransactionSynchronizationManager.setActualTransactionActive(true); + + // when + Throwable thrown = + catchThrowable(() -> CallerTransaction.requireReadWrite("claim", DATA_SOURCE)); + + // then + assertThat(thrown) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "claim requires a transaction bound to this store's data source; the active" + + " transaction belongs to another one"); + } + + @Test + void aWriteInsideAReadWriteTransactionBoundToTheStoreIsAllowed() { + // given + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.bindResource(DATA_SOURCE, new Object()); + + // when + Throwable thrown = + catchThrowable(() -> CallerTransaction.requireReadWrite("claim", DATA_SOURCE)); + + // then + assertThat(thrown).isNull(); + } +} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/tenancy/database/MongoTenantClientRegistry.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/tenancy/database/MongoTenantClientRegistry.java index d322b447..ef80fdb1 100644 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/tenancy/database/MongoTenantClientRegistry.java +++ b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/tenancy/database/MongoTenantClientRegistry.java @@ -4,6 +4,7 @@ import dev.caskeleton.adapter.outbound.mongo.advanced.MongoAdvancedCapabilityGua import dev.caskeleton.adapter.outbound.mongo.advanced.MongoAdvancedEntryPoint; import dev.caskeleton.adapter.outbound.mongo.api.capability.MongoCapability; import dev.caskeleton.adapter.outbound.mongo.api.error.MongoOperationRejectedException; +import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.Map; @@ -31,6 +32,8 @@ public final class MongoTenantClientRegistry { private final java.util.function.Function clientFactory; + private final Clock clock; + public MongoTenantClientRegistry(MongoAdvancedCapabilityGuard guard, int maximumActiveClients) { this(guard, maximumActiveClients, Duration.ofMinutes(10)); } @@ -40,9 +43,20 @@ public final class MongoTenantClientRegistry { this(guard, maximumActiveClients, idleEviction, tenant -> () -> {}); } + public MongoTenantClientRegistry( + MongoAdvancedCapabilityGuard guard, + int maximumActiveClients, + Duration idleEviction, + java.util.function.Function clientFactory) { + this(guard, maximumActiveClients, idleEviction, clientFactory, Clock.systemUTC()); + } + /** * A registry that owns real clients. * + *

Idle eviction reads {@code clock}; {@link #acquire(String)} used to read {@code + * Instant.now()} beside it. + * *

The factory is called at most once per tenant, inside the map's own computation, so two * threads asking for the same tenant get one client rather than two — a per-tenant client carries * a connection pool and monitoring threads, and creating a second one silently doubles both. @@ -51,9 +65,11 @@ public final class MongoTenantClientRegistry { MongoAdvancedCapabilityGuard guard, int maximumActiveClients, Duration idleEviction, - java.util.function.Function clientFactory) { + java.util.function.Function clientFactory, + Clock clock) { Objects.requireNonNull(guard, "guard").require(MongoTenantClientRegistry.class); this.clientFactory = Objects.requireNonNull(clientFactory, "clientFactory"); + this.clock = Objects.requireNonNull(clock, "clock"); this.idleEviction = Objects.requireNonNull(idleEviction, "idleEviction"); if (maximumActiveClients <= 0) { throw new IllegalArgumentException("the client cap must be positive"); @@ -67,7 +83,7 @@ public final class MongoTenantClientRegistry { * @throws MongoOperationRejectedException when the cap is reached and nothing can be evicted */ public void acquire(String tenantKey) { - acquire(tenantKey, Instant.now()); + acquire(tenantKey, clock.instant()); } /** Acquires a client for a tenant at an explicit instant, so eviction is testable. */ diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/advanced/tenancy/MongoTenancyContractTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/advanced/tenancy/MongoTenancyContractTest.java index b3869ce2..97309f29 100644 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/advanced/tenancy/MongoTenancyContractTest.java +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/advanced/tenancy/MongoTenancyContractTest.java @@ -210,6 +210,43 @@ class MongoTenancyContractTest { assertThat(registry.activeCount()).isEqualTo(1); } + @Test + @org.junit.jupiter.api.DisplayName("acquire(tenant)는 주입된 clock으로 idle 여부를 판단한다") + void anAcquireWithoutAnInstantReadsTheInjectedClock() { + // given + java.util.List closed = new java.util.ArrayList<>(); + java.util.concurrent.atomic.AtomicReference now = + new java.util.concurrent.atomic.AtomicReference<>(Instant.parse("2026-08-13T00:00:00Z")); + java.time.Clock clock = + new java.time.Clock() { + @Override + public java.time.ZoneId getZone() { + return java.time.ZoneOffset.UTC; + } + + @Override + public java.time.Clock withZone(java.time.ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return now.get(); + } + }; + MongoTenantClientRegistry registry = + new MongoTenantClientRegistry( + TENANCY, 1, Duration.ofMinutes(5), tenant -> () -> closed.add(tenant), clock); + registry.acquire("t1"); + now.set(now.get().plus(Duration.ofMinutes(10))); + + // when + registry.acquire("t2"); + + // then + assertThat(closed).containsExactly("t1"); + } + @Test @org.junit.jupiter.api.DisplayName("eviction closes the client it evicts") void evictionClosesTheClient() { diff --git a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoder.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoder.java index cebd75d6..0ab521c2 100644 --- a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoder.java +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoder.java @@ -3,17 +3,16 @@ package dev.caskeleton.adapter.outbound.support.messaging; import dev.caskeleton.application.messaging.contract.ContractDescriptor; import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution; import dev.caskeleton.application.messaging.contract.IntegrationPayload; -import dev.caskeleton.application.messaging.contract.Sha256; import dev.caskeleton.application.messaging.event.IntegrationEventDraft; import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort; import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; +import dev.caskeleton.shared.digest.Sha256; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.RecordComponent; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -235,7 +234,7 @@ public final class JsonIntegrationEventEncoder implements IntegrationEventEncode } private static String partitionKey(IntegrationEventDraft draft) { - MessageDigest digest = sha256(); + MessageDigest digest = Sha256.newMessageDigest(); digest.update(PARTITION_KEY_DOMAIN); digest.update((byte) 0); lengthPrefixed(digest, CanonicalJson.strictUtf8(draft.aggregate().tenantScope())); @@ -246,7 +245,7 @@ public final class JsonIntegrationEventEncoder implements IntegrationEventEncode } private static Sha256 schemaSetHash(Sha256 envelope, Sha256 payload) { - MessageDigest digest = sha256(); + MessageDigest digest = Sha256.newMessageDigest(); digest.update(SCHEMA_SET_DOMAIN); digest.update((byte) 0); lengthPrefixed(digest, envelope.bytes()); @@ -260,7 +259,7 @@ public final class JsonIntegrationEventEncoder implements IntegrationEventEncode * delivery descriptors apart without the template owning a separate binding registry. */ private static String descriptorRevision(ContractDescriptor descriptor) { - MessageDigest digest = sha256(); + MessageDigest digest = Sha256.newMessageDigest(); digest.update(DESCRIPTOR_DOMAIN); digest.update((byte) 0); lengthPrefixed(digest, utf8(descriptor.ownerModule())); @@ -278,7 +277,7 @@ public final class JsonIntegrationEventEncoder implements IntegrationEventEncode private static String catalogRevision(Collection entries) { List ordered = new ArrayList<>(entries); ordered.sort(Comparator.comparing(Entry::key)); - MessageDigest digest = sha256(); + MessageDigest digest = Sha256.newMessageDigest(); digest.update(CATALOG_DOMAIN); digest.update((byte) 0); for (Entry entry : ordered) { @@ -308,14 +307,6 @@ public final class JsonIntegrationEventEncoder implements IntegrationEventEncode digest.update(value); } - private static MessageDigest sha256() { - try { - return MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("Java runtime does not provide SHA-256", exception); - } - } - private static String key(String contractId, int payloadVersion) { return contractId + ":v" + payloadVersion; } diff --git a/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoderTest.java b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoderTest.java index 29c49d37..6ccbe394 100644 --- a/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoderTest.java +++ b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoderTest.java @@ -9,13 +9,13 @@ import dev.caskeleton.application.messaging.contract.IntegrationEventContractCon import dev.caskeleton.application.messaging.contract.IntegrationPayload; import dev.caskeleton.application.messaging.contract.LogicalDestinationId; import dev.caskeleton.application.messaging.contract.SchemaResourceId; -import dev.caskeleton.application.messaging.contract.Sha256; import dev.caskeleton.application.messaging.event.AggregateIdentity; import dev.caskeleton.application.messaging.event.AggregateOrder; import dev.caskeleton.application.messaging.event.EventId; import dev.caskeleton.application.messaging.event.IntegrationEventDraft; import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; import dev.caskeleton.application.operation.DurableOperationSubmittedContract; +import dev.caskeleton.shared.digest.Sha256; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; diff --git a/src/app-bootstrap/gradle.lockfile b/src/app-bootstrap/gradle.lockfile index 268753dc..f4d9d3fb 100644 --- a/src/app-bootstrap/gradle.lockfile +++ b/src/app-bootstrap/gradle.lockfile @@ -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 +com.github.f4b6a3:uuid-creator:6.1.1=architectureTestRuntimeClasspath,qualificationRuntimeClasspath 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 diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DistributedTracingContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DistributedTracingContractTest.java index 38f409d5..912ef5fa 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DistributedTracingContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DistributedTracingContractTest.java @@ -2,12 +2,12 @@ package dev.caskeleton.bootstrap.contract; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.inbound.web.observability.MdcKeys; import dev.caskeleton.adapter.inbound.web.observability.ResponseMetaFactory; import dev.caskeleton.bootstrap.async.AsyncContextTaskDecorator; import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources; import dev.caskeleton.composition.runtime.tracing.TracingSamplingRateGauge; import dev.caskeleton.shared.concurrency.ThreadLocalDomainContextPropagator; +import dev.caskeleton.shared.observability.MdcKeys; import dev.caskeleton.shared.response.ResponseMeta; import dev.caskeleton.shared.tracing.BaggageAllowlist; import io.micrometer.core.instrument.Meter; diff --git a/src/application-core/CLAUDE.md b/src/application-core/CLAUDE.md index bd4f9a71..74abf48b 100644 --- a/src/application-core/CLAUDE.md +++ b/src/application-core/CLAUDE.md @@ -73,6 +73,7 @@ Package root: `dev.caskeleton.application`. | `messaging.event.ValidatedIntegrationEvent` | Stable semantic identities plus immutable exact encoded bytes and hashes, ready for a later durable append boundary. | | `messaging.event.IntegrationEventEncoderPort` | Framework-free local draft-to-validated-event boundary implemented by an outbound adapter (the template's: `adapter:outbound:support` `JsonIntegrationEventEncoder`). | | `outbox.OutboxAppendPort` | The one outbox append: a `ValidatedIntegrationEvent`, in the caller's write transaction. | +| `tenant.TenantId` | The tenant identifier and its one grammar (`[A-Za-z0-9][A-Za-z0-9_.-]{0,63}`); the web and GraphQL transport contexts both carry it. Built by a transport from verified authentication data only. | ## Notification (NOTIF-ADR-005) diff --git a/src/application-core/README.md b/src/application-core/README.md index fbd8e001..97864c52 100644 --- a/src/application-core/README.md +++ b/src/application-core/README.md @@ -397,16 +397,19 @@ claim → 트랜잭션 밖에서 발행 → at-least-once 보장. ### OutboxBackoffPolicy -- relay 재시도 스케줄링용 exponential-backoff-with-full-jitter 정책(I10). -- 공식: `base = 30s`, `maxAttempts = 3`, `delay = base × 2^(attemptCount-1) + jitter(0..base)`, - `nextAttemptAt = now + delay`. 여기서 `attemptCount` 는 방금 실패한 시도의 1-based 번호다. -- full jitter 는 주입된 `RandomGenerator` 로 `[0, base]` 균등 분포에서 뽑는다. 고정 시드/0 을 - 반환하는 generator 를 주면 테스트가 결정적이 된다(I10). +- relay 재시도 스케줄링 정책(I10). 이름과 달리 "full jitter" 가 아니다 — full jitter 는 0 을 고를 + 수 있고, relay 재시도가 실패한 그 순간에 다시 due 가 되면 안 된다. +- 공식: `base = 30s`, `maxAttempts = 3`, `delay = ceiling(attemptCount) + U[0, base]`, + `nextAttemptAt = now + delay`. `ceiling` 은 shared-contract `Backoff` 의 + `base × 2^(attemptCount-1)` 이고 마지막 시도 값(120s)에서 멈춘다. `attemptCount` 는 방금 실패한 + 시도의 1-based 번호다. +- 더하는 spread 는 한 base 짜리 full jitter(`Backoff#fullJitter`, `[0, base]` 균등)이며 주입된 + `RandomGenerator` 로 뽑는다. 0 을 반환하는 generator 를 주면 테스트가 결정적이 된다(I10). - **상수는 고정이다(I10)**: `BASE_DELAY`·`MAX_ATTEMPTS`·jitter 범위는 설정 프로퍼티가 아니다. 외부화하면 registry alert 임계치(`error-codes.yaml` 의 `retry_after_seconds=30`)와 `outbox-publish-failed` runbook 이 실제 런타임 값과 어긋난다. 이 상수는 registry·runbook 업데이트와 **함께만** 바꾼다. -- 지수 계산은 overflow 방지를 위해 `2^30` 에서 cap 한다(`2^30 × 30s > 30년` 이라 안전). +- 지수 계산의 overflow 는 `Backoff` 가 포화 연산으로 막는다. ### outbox 값/상태 타입 (Status · ClaimedOutboxEvent · RelayResult · Command) diff --git a/src/application-core/build.gradle b/src/application-core/build.gradle index 1a3a8b54..a8ce03b7 100644 --- a/src/application-core/build.gradle +++ b/src/application-core/build.gradle @@ -13,6 +13,7 @@ dependencies { implementation project(':shared-contract') // Port contracts (`*Contract`) are abstract JUnit classes that fakes and adapters both extend. + testFixturesImplementation project(':shared-contract') testFixturesImplementation 'org.junit.jupiter:junit-jupiter-api' testFixturesImplementation 'org.assertj:assertj-core' } diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/RequestFingerprint.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/RequestFingerprint.java index d640de46..ec8cdb7d 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/RequestFingerprint.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/RequestFingerprint.java @@ -1,8 +1,6 @@ package dev.caskeleton.application.idempotency; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; +import dev.caskeleton.shared.digest.Sha256; import java.util.Objects; /** @@ -27,12 +25,6 @@ public record RequestFingerprint(String hex) { /** Compute the SHA-256 fingerprint of the raw request body bytes. */ public static RequestFingerprint ofSha256(byte[] body) { byte[] payload = body == null ? new byte[0] : body; - try { - byte[] digest = MessageDigest.getInstance("SHA-256").digest(payload); - return new RequestFingerprint(HexFormat.of().formatHex(digest)); - } catch (NoSuchAlgorithmException e) { - // SHA-256 is mandated by every JDK — unreachable. - throw new IllegalStateException("SHA-256 algorithm unavailable", e); - } + return new RequestFingerprint(Sha256.of(payload).hex()); } } diff --git a/src/application-core/src/main/java/dev/caskeleton/application/messaging/contract/IntegrationEventContractContribution.java b/src/application-core/src/main/java/dev/caskeleton/application/messaging/contract/IntegrationEventContractContribution.java index 8ab18703..92a39ea3 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/messaging/contract/IntegrationEventContractContribution.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/messaging/contract/IntegrationEventContractContribution.java @@ -1,5 +1,6 @@ package dev.caskeleton.application.messaging.contract; +import dev.caskeleton.shared.digest.Sha256; import java.util.List; /** diff --git a/src/application-core/src/main/java/dev/caskeleton/application/messaging/contract/Sha256.java b/src/application-core/src/main/java/dev/caskeleton/application/messaging/contract/Sha256.java deleted file mode 100644 index dc1507d0..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/messaging/contract/Sha256.java +++ /dev/null @@ -1,50 +0,0 @@ -package dev.caskeleton.application.messaging.contract; - -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Arrays; -import java.util.HexFormat; - -/** Immutable SHA-256 digest value. */ -@SuppressWarnings("ArrayRecordComponent") -public record Sha256(byte[] bytes) { - - public static final int BYTE_LENGTH = 32; - - public Sha256 { - if (bytes == null || bytes.length != BYTE_LENGTH) { - throw new IllegalArgumentException("SHA-256 digest must contain exactly 32 bytes"); - } - bytes = bytes.clone(); - } - - /** The SHA-256 digest of {@code content}. */ - public static Sha256 of(byte[] content) { - try { - return new Sha256(MessageDigest.getInstance("SHA-256").digest(content)); - } catch (NoSuchAlgorithmException e) { - // SHA-256 is mandated by every JDK — unreachable. - throw new IllegalStateException("SHA-256 algorithm unavailable", e); - } - } - - @Override - public byte[] bytes() { - return bytes.clone(); - } - - @Override - public boolean equals(Object other) { - return this == other || (other instanceof Sha256 sha256 && Arrays.equals(bytes, sha256.bytes)); - } - - @Override - public int hashCode() { - return Arrays.hashCode(bytes); - } - - @Override - public String toString() { - return HexFormat.of().formatHex(bytes); - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/ValidatedIntegrationEvent.java b/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/ValidatedIntegrationEvent.java index 27cd2dbc..b438adc2 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/ValidatedIntegrationEvent.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/ValidatedIntegrationEvent.java @@ -2,7 +2,7 @@ package dev.caskeleton.application.messaging.event; import dev.caskeleton.application.messaging.contract.ContractId; import dev.caskeleton.application.messaging.contract.LogicalDestinationId; -import dev.caskeleton.application.messaging.contract.Sha256; +import dev.caskeleton.shared.digest.Sha256; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.Arrays; diff --git a/src/application-core/src/main/java/dev/caskeleton/application/operation/DurableOperationSubmittedContract.java b/src/application-core/src/main/java/dev/caskeleton/application/operation/DurableOperationSubmittedContract.java index 091f925b..492af944 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/operation/DurableOperationSubmittedContract.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/operation/DurableOperationSubmittedContract.java @@ -5,7 +5,7 @@ import dev.caskeleton.application.messaging.contract.ContractId; import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution; import dev.caskeleton.application.messaging.contract.LogicalDestinationId; import dev.caskeleton.application.messaging.contract.SchemaResourceId; -import dev.caskeleton.application.messaging.contract.Sha256; +import dev.caskeleton.shared.digest.Sha256; import java.util.HexFormat; import java.util.List; diff --git a/src/application-core/src/main/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCase.java b/src/application-core/src/main/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCase.java index ac4cb158..8ecb3d5a 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCase.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCase.java @@ -13,11 +13,8 @@ import dev.caskeleton.application.security.RequiresPermission; import dev.caskeleton.application.transaction.TransactionMode; import dev.caskeleton.application.transaction.TransactionPort; import dev.caskeleton.application.usecase.CommandUseCase; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; +import dev.caskeleton.shared.digest.Sha256; import java.time.Clock; -import java.util.HexFormat; import java.util.Objects; import java.util.Optional; import java.util.regex.Pattern; @@ -172,12 +169,6 @@ public class SubmitDurableOperationUseCase if (value.length() <= MAXIMUM_EVENT_ID_LENGTH && EVENT_ID_GRAMMAR.matcher(value).matches()) { return value; } - try { - byte[] digest = - MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)); - return "operation-" + HexFormat.of().formatHex(digest); - } catch (NoSuchAlgorithmException unreachable) { - throw new IllegalStateException("Java runtime does not provide SHA-256", unreachable); - } + return "operation-" + Sha256.ofUtf8(value).hex(); } } diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxBackoffPolicy.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxBackoffPolicy.java index 34058fe8..616f7190 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxBackoffPolicy.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxBackoffPolicy.java @@ -1,16 +1,22 @@ package dev.caskeleton.application.outbox; +import dev.caskeleton.shared.retry.Backoff; import java.time.Duration; import java.time.Instant; import java.util.Objects; import java.util.random.RandomGenerator; /** - * Exponential-backoff-with-full-jitter policy for outbox relay retry scheduling: {@code delay = - * base × 2^(attemptCount-1) + jitter(0..base)} with {@code base = 30s}, {@code maxAttempts = 3}; - * {@code attemptCount} is the 1-based just-failed attempt. Full jitter uses the injected {@link - * RandomGenerator} (deterministic in tests with a fixed-seed generator). The constants are fixed, - * not configurable — see README for why. + * Retry scheduling for the outbox relay: {@code delay = ceiling(attemptCount) + U[0, base]}, where + * the ceiling is the shared {@link Backoff} exponential {@code base × 2^(attemptCount-1)} capped at + * the last attempt's value, {@code base = 30s} and {@code maxAttempts = 3}; {@code attemptCount} is + * the 1-based just-failed attempt. + * + *

This is not "full jitter", although it used to be called that: full jitter ({@link + * Backoff#fullJitter}) may choose zero, and a relay retry must never be due at the instant it + * failed. The spread added on top of the exponential ceiling is a full jitter of one base, drawn + * from the injected {@link RandomGenerator} (deterministic in tests). The constants are fixed, not + * configurable — see README for why. */ public final class OutboxBackoffPolicy { @@ -20,6 +26,13 @@ public final class OutboxBackoffPolicy { /** Maximum delivery attempts before a row is DEAD-lettered. */ public static final int MAX_ATTEMPTS = 3; + /** The exponential part, capped where the last attempt already is. */ + private static final Backoff SCHEDULE = + new Backoff(BASE_DELAY, BASE_DELAY.multipliedBy(1L << (MAX_ATTEMPTS - 1))); + + /** The spread: a full jitter of one base. */ + private static final Backoff SPREAD = new Backoff(BASE_DELAY, BASE_DELAY); + private final RandomGenerator random; /** @@ -56,16 +69,6 @@ public final class OutboxBackoffPolicy { "attemptCount must be >= 1 (1-based), was " + attemptCount); } Objects.requireNonNull(now, "now must not be null"); - - // Exponential base: base * 2^(attemptCount-1) - // Capped to avoid overflow for very large attemptCount values. - long exponent = Math.min(attemptCount - 1, 30); // 2^30 * 30s > 30 years — safe cap - long baseSeconds = BASE_DELAY.toSeconds() * (1L << exponent); - - // Full jitter: uniform in [0, base] - double jitterSeconds = random.nextDouble() * BASE_DELAY.toSeconds(); - - long totalSeconds = baseSeconds + (long) jitterSeconds; - return now.plusSeconds(totalSeconds); + return now.plus(SCHEDULE.ceiling(attemptCount)).plus(SPREAD.fullJitter(1, random)); } } diff --git a/src/application-core/src/main/java/dev/caskeleton/application/tenant/TenantId.java b/src/application-core/src/main/java/dev/caskeleton/application/tenant/TenantId.java new file mode 100644 index 00000000..eefb0722 --- /dev/null +++ b/src/application-core/src/main/java/dev/caskeleton/application/tenant/TenantId.java @@ -0,0 +1,46 @@ +package dev.caskeleton.application.tenant; + +import java.util.Optional; +import java.util.regex.Pattern; + +/** + * A tenant identifier, with the one grammar every transport accepts. + * + *

Opaque, short and safe to place in a log field: {@code [A-Za-z0-9][A-Za-z0-9_.-]{0,63}}. The + * web and GraphQL transports each held a {@code TenantContext} with its own rule — web this + * grammar, GraphQL "non-blank, at most 128 characters" — so the same tenant passed one transport + * and was refused by the other (review X2-P2-6a, S5-lead-3). Both now carry this type. + * + *

A tenant is a security boundary, so where one comes from matters more than its shape: a + * transport builds it from verified authentication data, never from a request parameter. + * + * @param value the identifier + */ +public record TenantId(String value) { + + /** The grammar, for a transport that has to explain a refusal. */ + public static final String GRAMMAR = "[A-Za-z0-9][A-Za-z0-9_.-]{0,63}"; + + private static final Pattern PATTERN = Pattern.compile(GRAMMAR); + + public TenantId { + if (value == null || !PATTERN.matcher(value).matches()) { + throw new IllegalArgumentException("tenant identifier must match " + GRAMMAR); + } + } + + /** + * The tenant named by an optional value: empty for {@code null} or blank. + * + * @throws IllegalArgumentException when a non-blank value breaks the grammar — a malformed tenant + * is never read as "no tenant", which would widen what the caller sees + */ + public static Optional optional(String value) { + return value == null || value.isBlank() ? Optional.empty() : Optional.of(new TenantId(value)); + } + + @Override + public String toString() { + return value; + } +} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/messaging/contract/IntegrationEventContractContributionTest.java b/src/application-core/src/test/java/dev/caskeleton/application/messaging/contract/IntegrationEventContractContributionTest.java index 56775d76..469e8494 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/messaging/contract/IntegrationEventContractContributionTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/messaging/contract/IntegrationEventContractContributionTest.java @@ -3,6 +3,7 @@ package dev.caskeleton.application.messaging.contract; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import dev.caskeleton.shared.digest.Sha256; import java.lang.reflect.Modifier; import java.time.Duration; import java.util.Arrays; diff --git a/src/application-core/src/test/java/dev/caskeleton/application/messaging/event/ValidatedIntegrationEventTest.java b/src/application-core/src/test/java/dev/caskeleton/application/messaging/event/ValidatedIntegrationEventTest.java index bc2b3713..6e70fac4 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/messaging/event/ValidatedIntegrationEventTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/messaging/event/ValidatedIntegrationEventTest.java @@ -6,7 +6,7 @@ import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.application.messaging.contract.ContractId; import dev.caskeleton.application.messaging.contract.LogicalDestinationId; -import dev.caskeleton.application.messaging.contract.Sha256; +import dev.caskeleton.shared.digest.Sha256; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.Arrays; diff --git a/src/application-core/src/test/java/dev/caskeleton/application/tenant/TenantIdTest.java b/src/application-core/src/test/java/dev/caskeleton/application/tenant/TenantIdTest.java new file mode 100644 index 00000000..b21fbc7b --- /dev/null +++ b/src/application-core/src/test/java/dev/caskeleton/application/tenant/TenantIdTest.java @@ -0,0 +1,64 @@ +package dev.caskeleton.application.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import java.util.Optional; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class TenantIdTest { + + @ParameterizedTest + @ValueSource(strings = {"acme", "Acme-01", "a", "tenant_a.eu-1"}) + void aTenantInTheGrammarIsAccepted(String value) { + assertThat(new TenantId(value).value()).isEqualTo(value); + } + + @ParameterizedTest + @ValueSource(strings = {"", " ", "-acme", ".acme", "ac me", "acme\n", "../public", "테넌트"}) + @DisplayName("문법 밖의 tenant(선행 구분자, 공백, 줄바꿈, 경로, 비ASCII)는 거부한다") + void aTenantOutsideTheGrammarIsRefused(String value) { + // when + Throwable thrown = catchThrowable(() -> new TenantId(value)); + + // then + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("tenant identifier must match " + TenantId.GRAMMAR); + } + + @Test + @DisplayName("65자 tenant는 거부한다") + void aTenantLongerThanSixtyFourCharactersIsRefused() { + // when + Throwable thrown = catchThrowable(() -> new TenantId("a".repeat(65))); + + // then + assertThat(thrown).isInstanceOf(IllegalArgumentException.class); + } + + @Test + void anAbsentOptionalTenantIsEmpty() { + assertThat(TenantId.optional(null)).isEmpty(); + } + + @Test + void aPresentOptionalTenantIsParsed() { + assertThat(TenantId.optional("acme")).isEqualTo(Optional.of(new TenantId("acme"))); + } + + @Test + @DisplayName("형식이 틀린 tenant는 '없음'으로 읽지 않고 거부한다") + void aMalformedOptionalTenantIsRefusedRatherThanReadAsAbsent() { + // when + Throwable thrown = catchThrowable(() -> TenantId.optional("ac me")); + + // then + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("tenant identifier must match " + TenantId.GRAMMAR); + } +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/FakeIntegrationEventEncoder.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/FakeIntegrationEventEncoder.java index dda89154..18771a2c 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/FakeIntegrationEventEncoder.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/FakeIntegrationEventEncoder.java @@ -1,9 +1,9 @@ package dev.caskeleton.application.messaging.event.testkit; -import dev.caskeleton.application.messaging.contract.Sha256; import dev.caskeleton.application.messaging.event.IntegrationEventDraft; import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort; import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; +import dev.caskeleton.shared.digest.Sha256; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HexFormat; diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxEvents.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxEvents.java index 824bcd90..fedca02f 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxEvents.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxEvents.java @@ -2,13 +2,13 @@ package dev.caskeleton.application.outbox.testkit; import dev.caskeleton.application.messaging.contract.ContractId; import dev.caskeleton.application.messaging.contract.LogicalDestinationId; -import dev.caskeleton.application.messaging.contract.Sha256; import dev.caskeleton.application.messaging.event.AggregateIdentity; import dev.caskeleton.application.messaging.event.AggregateOrder; import dev.caskeleton.application.messaging.event.EventId; import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; import dev.caskeleton.application.outbox.ClaimedOutboxEvent; import dev.caskeleton.application.outbox.OutboxEventStatus; +import dev.caskeleton.shared.digest.Sha256; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.HexFormat; diff --git a/src/application-notification/build.gradle b/src/application-notification/build.gradle index 6ed7f34f..8c141de9 100644 --- a/src/application-notification/build.gradle +++ b/src/application-notification/build.gradle @@ -6,4 +6,5 @@ plugins { // application-core; this leaf contains the notification platform policy/use cases only. dependencies { implementation project(':application-core') + implementation project(':shared-contract') } diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminOperationCommandFingerprint.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminOperationCommandFingerprint.java index 6da6ba16..a2f1510d 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminOperationCommandFingerprint.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminOperationCommandFingerprint.java @@ -1,8 +1,6 @@ package dev.caskeleton.application.notification.platform.admin; -import dev.caskeleton.application.notification.platform.dispatch.MessageDigestPort; -import java.nio.charset.StandardCharsets; -import java.util.HexFormat; +import dev.caskeleton.shared.digest.Sha256; import java.util.Objects; /** @@ -14,12 +12,6 @@ import java.util.Objects; */ final class AdminOperationCommandFingerprint { - private final MessageDigestPort digests; - - AdminOperationCommandFingerprint(MessageDigestPort digests) { - this.digests = Objects.requireNonNull(digests, "digests"); - } - String of(RedriveCommand command) { Objects.requireNonNull(command, "command"); StringBuilder canonical = action("REDRIVE"); @@ -65,8 +57,7 @@ final class AdminOperationCommandFingerprint { } private String digest(StringBuilder canonical) { - byte[] bytes = canonical.toString().getBytes(StandardCharsets.UTF_8); - return HexFormat.of().formatHex(digests.sha256(bytes)); + return Sha256.ofUtf8(canonical.toString()).hex(); } private static StringBuilder action(String action) { diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminApplicationService.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminApplicationService.java index 4f06e9b1..684bad6e 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminApplicationService.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminApplicationService.java @@ -8,7 +8,6 @@ import dev.caskeleton.application.notification.platform.api.error.NotificationFa import dev.caskeleton.application.notification.platform.api.error.ProviderConfigurationException; import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptSnapshot; import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptStorePort; -import dev.caskeleton.application.notification.platform.dispatch.MessageDigestPort; import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryStorePort; import dev.caskeleton.application.notification.platform.dispatch.ReconciliationService; import dev.caskeleton.application.notification.platform.observation.NotificationAuditEvent; @@ -74,7 +73,6 @@ public final class NotificationAdminApplicationService implements NotificationAd NotificationAuditPort audit, TransactionPort transactions, dev.caskeleton.application.notification.platform.dispatch.NotificationIdGeneratorPort ids, - MessageDigestPort digests, Clock clock) { this.authorization = Objects.requireNonNull(authorization, "authorization"); this.duplicateRiskGuard = Objects.requireNonNull(duplicateRiskGuard, "duplicateRiskGuard"); @@ -86,8 +84,7 @@ public final class NotificationAdminApplicationService implements NotificationAd this.operations = Objects.requireNonNull(operations, "operations"); this.transactions = Objects.requireNonNull(transactions, "transactions"); this.operationExecutor = new AdminOperationExecutor(this.operations, this.transactions); - this.commandFingerprints = - new AdminOperationCommandFingerprint(Objects.requireNonNull(digests, "digests")); + this.commandFingerprints = new AdminOperationCommandFingerprint(); this.audit = Objects.requireNonNull(audit, "audit"); this.ids = Objects.requireNonNull(ids, "ids"); this.clock = Objects.requireNonNull(clock, "clock"); diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCase.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCase.java index b610ef54..1154cf17 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCase.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCase.java @@ -71,7 +71,7 @@ public class AcceptNotificationApplicationUseCase implements AcceptNotificationU new IdempotencyKey("derived-key-placeholder"); private final NotificationIdGeneratorPort ids; - private final RequestFingerprint fingerprints; + private final PlanFingerprint fingerprints; private final CanonicalNotificationPlanEncoder planEncoder = new CanonicalNotificationPlanEncoder(); private final TransactionPort transactions; @@ -98,7 +98,7 @@ public class AcceptNotificationApplicationUseCase implements AcceptNotificationU ContactPointProtector protector, TenantContextPort tenants, NotificationIdGeneratorPort ids, - RequestFingerprint fingerprints, + PlanFingerprint fingerprints, TransactionPort transactions, Clock clock, Locale defaultLocale) { diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/MessageDigestPort.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/MessageDigestPort.java deleted file mode 100644 index e04dabaf..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/MessageDigestPort.java +++ /dev/null @@ -1,8 +0,0 @@ -package dev.caskeleton.application.notification.platform.dispatch; - -/** Hashing boundary so application-core stays free of a concrete crypto provider. */ -public interface MessageDigestPort { - - /** SHA-256 of the given bytes. */ - byte[] sha256(byte[] input); -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/NotificationSubmissionService.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/NotificationSubmissionService.java index 31d3bef4..98f272c3 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/NotificationSubmissionService.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/NotificationSubmissionService.java @@ -40,7 +40,7 @@ public final class NotificationSubmissionService { private final RecipientDeliveryStorePort recipients; private final DeliveryAttemptStorePort attempts; private final TemplateRegistry templates; - private final RequestFingerprint fingerprints; + private final PlanFingerprint fingerprints; private final CanonicalNotificationPlanEncoder planEncoder = new CanonicalNotificationPlanEncoder(); private final CanonicalNotificationPlanWriter writer; @@ -56,7 +56,7 @@ public final class NotificationSubmissionService { RecipientDeliveryStorePort recipients, DeliveryAttemptStorePort attempts, TemplateRegistry templates, - RequestFingerprint fingerprints, + PlanFingerprint fingerprints, CanonicalNotificationPlanWriter writer, TransactionPort transactions, TenantContextPort tenants, diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/RequestFingerprint.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/PlanFingerprint.java similarity index 80% rename from src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/RequestFingerprint.java rename to src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/PlanFingerprint.java index f2c044fc..9b23372c 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/RequestFingerprint.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/PlanFingerprint.java @@ -1,7 +1,7 @@ package dev.caskeleton.application.notification.platform.dispatch; import dev.caskeleton.application.notification.platform.api.EncodedNotificationPlan; -import java.util.HexFormat; +import dev.caskeleton.shared.digest.Sha256; import java.util.Objects; /** @@ -11,14 +11,11 @@ import java.util.Objects; * fingerprint covers — the whole fallback order, the channel override, the deduplication action, * the collapse spec, the schedule, the metadata, the typed variables — is a question about {@link * CanonicalNotificationPlanEncoder}, which is the single place a plan becomes bytes. + * + *

Named for what it fingerprints: application-core's {@code RequestFingerprint} is the HTTP + * request-body fingerprint of the idempotency executor, a different value. */ -public final class RequestFingerprint { - - private final MessageDigestPort digest; - - public RequestFingerprint(MessageDigestPort digest) { - this.digest = Objects.requireNonNull(digest, "digest"); - } +public final class PlanFingerprint { /** * Fingerprint of one encoded plan. @@ -33,6 +30,6 @@ public final class RequestFingerprint { */ public String of(EncodedNotificationPlan encoded) { Objects.requireNonNull(encoded, "encoded"); - return HexFormat.of().formatHex(digest.sha256(encoded.bytes())); + return Sha256.of(encoded.bytes()).hex(); } } diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/PublishNotificationTemplateApplicationUseCase.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/PublishNotificationTemplateApplicationUseCase.java index f472aa3a..5b4e333e 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/PublishNotificationTemplateApplicationUseCase.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/PublishNotificationTemplateApplicationUseCase.java @@ -14,8 +14,7 @@ import dev.caskeleton.application.notification.platform.template.VariableSchema; import dev.caskeleton.application.security.RequiresPermission; import dev.caskeleton.application.transaction.TransactionMode; import dev.caskeleton.application.transaction.TransactionPort; -import java.nio.charset.StandardCharsets; -import java.util.HexFormat; +import dev.caskeleton.shared.digest.Sha256; import java.util.List; import java.util.Map; import java.util.Objects; @@ -36,7 +35,9 @@ import java.util.Objects; * prefixed. Concatenating slot sources in map order would hash {@code SUBJECT="ab", BODY="c"} and * {@code SUBJECT="a", BODY="bc"} alike, which is a content change the digest would call identical. */ -// externalOutboundAllowed because MessageDigestPort is adapter-bound and called from here; see +// externalOutboundAllowed although the hashing port is gone: the D7 architecture rule treats any +// interface an outbound adapter implements as an outbound port, and this use case calls +// java.util.Map (the command's slot map), which an adapter class implements. See // AcceptNotificationApplicationUseCase for why the flag states the reach rather than the distance. @UseCaseCapability( transactionMode = TransactionMode.WRITE, @@ -48,20 +49,17 @@ public class PublishNotificationTemplateApplicationUseCase implements PublishNotificationTemplateUseCase { private final TemplateRegistry templates; - private final MessageDigestPort digests; private final TransactionPort transactions; /** * Creates the use case. * * @param templates the registry this publishes into - * @param digests the hashing boundary, so application-core names no crypto provider * @param transactions the write boundary this use case owns */ public PublishNotificationTemplateApplicationUseCase( - TemplateRegistry templates, MessageDigestPort digests, TransactionPort transactions) { + TemplateRegistry templates, TransactionPort transactions) { this.templates = Objects.requireNonNull(templates, "templates"); - this.digests = Objects.requireNonNull(digests, "digests"); this.transactions = Objects.requireNonNull(transactions, "transactions"); } @@ -117,7 +115,6 @@ public class PublishNotificationTemplateApplicationUseCase .append(source) .append('\n'); } - return HexFormat.of() - .formatHex(digests.sha256(canonical.toString().getBytes(StandardCharsets.UTF_8))); + return Sha256.ofUtf8(canonical.toString()).hex(); } } diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/SyntheticEventFingerprint.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/SyntheticEventFingerprint.java index 966a6a21..45185ba0 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/SyntheticEventFingerprint.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/SyntheticEventFingerprint.java @@ -3,8 +3,7 @@ package dev.caskeleton.application.notification.platform.dispatch; import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; import dev.caskeleton.application.notification.platform.api.NormalizedProviderEvent; import dev.caskeleton.application.notification.platform.api.ProviderProfileId; -import java.nio.charset.StandardCharsets; -import java.util.HexFormat; +import dev.caskeleton.shared.digest.Sha256; import java.util.Objects; /** @@ -36,12 +35,6 @@ public final class SyntheticEventFingerprint { */ private static final String VERSION = "1"; - private final MessageDigestPort digest; - - public SyntheticEventFingerprint(MessageDigestPort digest) { - this.digest = Objects.requireNonNull(digest, "digest"); - } - /** * Fingerprint of one synthesised reconciliation event. * @@ -57,11 +50,7 @@ public final class SyntheticEventFingerprint { Objects.requireNonNull(providerProfileId, "providerProfileId"); Objects.requireNonNull(attemptId, "attemptId"); Objects.requireNonNull(event, "event"); - return HexFormat.of() - .formatHex( - digest.sha256( - canonicalForm(providerProfileId, attemptId, event) - .getBytes(StandardCharsets.UTF_8))); + return Sha256.ofUtf8(canonicalForm(providerProfileId, attemptId, event)).hex(); } /** diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/policy/RetryBackoff.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/policy/RetryBackoff.java index 7ce53291..f6ba8ab3 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/policy/RetryBackoff.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/policy/RetryBackoff.java @@ -1,20 +1,30 @@ package dev.caskeleton.application.notification.platform.policy; +import dev.caskeleton.shared.retry.Backoff; import java.time.Duration; import java.util.Objects; import java.util.Optional; +import java.util.random.RandomGenerator; /** - * Exponential backoff with full jitter and a hard ceiling. + * Full jitter over the shared exponential {@link Backoff}, never shorter than the base, with a hard + * ceiling. + * + *

"Full jitter" is the shared-contract word: uniform in {@code [0, ceiling]}. Delivery retries + * then raise it to at least {@code base}, so a provider that just failed is not called again in the + * same instant. * *

A provider-supplied {@code Retry-After} always wins over the computed value, but never over * the configured maximum: a provider asking for an hour must not silently extend a delivery * deadline. + * + * @param base the first attempt's ceiling and the shortest delay + * @param max the longest delay, {@code Retry-After} included */ -public record RetryBackoff(Duration base, Duration max, double multiplier) { +public record RetryBackoff(Duration base, Duration max) { public static final RetryBackoff DEFAULT = - new RetryBackoff(Duration.ofSeconds(1), Duration.ofMinutes(5), 2.0d); + new RetryBackoff(Duration.ofSeconds(1), Duration.ofMinutes(5)); public RetryBackoff { Objects.requireNonNull(base, "base"); @@ -25,9 +35,6 @@ public record RetryBackoff(Duration base, Duration max, double multiplier) { if (max.compareTo(base) < 0) { throw new IllegalArgumentException("max must not be smaller than base"); } - if (multiplier < 1.0d) { - throw new IllegalArgumentException("multiplier"); - } } /** Delay before attempt number {@code attemptNumber + 1}. */ @@ -37,11 +44,23 @@ public record RetryBackoff(Duration base, Duration max, double multiplier) { if (attemptNumber < 1) { throw new IllegalArgumentException("attemptNumber"); } - double exponential = base.toMillis() * Math.pow(multiplier, attemptNumber - 1d); - long ceilingMillis = (long) Math.min(exponential, (double) max.toMillis()); - long jittered = ceilingMillis <= 0 ? 0 : jitter.nextLong(ceilingMillis + 1); - Duration computed = Duration.ofMillis(Math.max(jittered, base.toMillis())); + Duration jittered = new Backoff(base, max).fullJitter(attemptNumber, asRandom(jitter)); + Duration computed = jittered.compareTo(base) < 0 ? base : jittered; Duration chosen = retryAfter.filter(hint -> hint.compareTo(computed) > 0).orElse(computed); return chosen.compareTo(max) > 0 ? max : chosen; } + + private static RandomGenerator asRandom(JitterSource jitter) { + return new RandomGenerator() { + @Override + public long nextLong() { + throw new UnsupportedOperationException("only bounded draws are used"); + } + + @Override + public long nextLong(long bound) { + return jitter.nextLong(bound); + } + }; + } } diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/admin/AdminOperationCommandFingerprintTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/admin/AdminOperationCommandFingerprintTest.java index 0fe7fd5a..d5f48645 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/admin/AdminOperationCommandFingerprintTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/admin/AdminOperationCommandFingerprintTest.java @@ -3,8 +3,6 @@ package dev.caskeleton.application.notification.platform.admin; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.util.List; import java.util.UUID; import org.junit.jupiter.api.Test; @@ -12,7 +10,7 @@ import org.junit.jupiter.api.Test; class AdminOperationCommandFingerprintTest { private final AdminOperationCommandFingerprint fingerprints = - new AdminOperationCommandFingerprint(AdminOperationCommandFingerprintTest::sha256); + new AdminOperationCommandFingerprint(); @Test void fingerprintIsStableSha256AndChangesWithCommandMeaning() { @@ -40,12 +38,4 @@ class AdminOperationCommandFingerprintTest { assertThat(fingerprints.of(ordered)).isEqualTo(fingerprints.of(reversed)); } - - private static byte[] sha256(byte[] bytes) { - try { - return MessageDigest.getInstance("SHA-256").digest(bytes); - } catch (NoSuchAlgorithmException impossible) { - throw new IllegalStateException(impossible); - } - } } diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminApplicationServiceTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminApplicationServiceTest.java index ad385a5d..2aba79d5 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminApplicationServiceTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminApplicationServiceTest.java @@ -244,7 +244,6 @@ class NotificationAdminApplicationServiceTest { audit, transactions, new PlatformFakes.SequentialIds(), - NotificationAdminApplicationServiceTest::sha256, CLOCK); } } @@ -322,12 +321,4 @@ class NotificationAdminApplicationServiceTest { return Optional.empty(); } } - - private static byte[] sha256(byte[] bytes) { - try { - return java.security.MessageDigest.getInstance("SHA-256").digest(bytes); - } catch (java.security.NoSuchAlgorithmException impossible) { - throw new IllegalStateException(impossible); - } - } } diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationPlatformNoops.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationPlatformNoops.java index 16fec4f0..567c5275 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationPlatformNoops.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationPlatformNoops.java @@ -63,7 +63,7 @@ public final class NotificationPlatformNoops { projection(ledger), audit(), metrics(), - new SyntheticEventFingerprint(NotificationPlatformNoops::sha256), + new SyntheticEventFingerprint(), new PlatformFakes.RecordingTransactions(), clock); } @@ -166,14 +166,6 @@ public final class NotificationPlatformNoops { metrics()); } - private static byte[] sha256(byte[] bytes) { - try { - return java.security.MessageDigest.getInstance("SHA-256").digest(bytes); - } catch (java.security.NoSuchAlgorithmException impossible) { - throw new IllegalStateException(impossible); - } - } - private static final class NoopLedger implements ProviderEventLedger { @Override public AppendEventResult append(VerifiedProviderEvent event) { diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/RequestFingerprintTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/PlanFingerprintTest.java similarity index 98% rename from src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/RequestFingerprintTest.java rename to src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/PlanFingerprintTest.java index ecca4644..a2bdcca5 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/RequestFingerprintTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/PlanFingerprintTest.java @@ -29,7 +29,7 @@ import org.junit.jupiter.api.Test; */ class RequestFingerprintTest { - private final RequestFingerprint fingerprint = PlatformFakes.fingerprints(); + private final PlanFingerprint fingerprint = PlatformFakes.fingerprints(); @Test @DisplayName("a different fallback tail is a different request") diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/PlatformFakes.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/PlatformFakes.java index 9ccb1f6a..34193f6d 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/PlatformFakes.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/PlatformFakes.java @@ -403,16 +403,8 @@ public final class PlatformFakes { *

The canonical form is production code and is exactly what decides whether a repeated * idempotency key converges or conflicts, so it is not stubbed out here. */ - public static RequestFingerprint fingerprints() { - return new RequestFingerprint(PlatformFakes::sha256); - } - - private static byte[] sha256(byte[] input) { - try { - return java.security.MessageDigest.getInstance("SHA-256").digest(input); - } catch (java.security.NoSuchAlgorithmException absent) { - throw new IllegalStateException(absent); - } + public static PlanFingerprint fingerprints() { + return new PlanFingerprint(); } /** Tenant context pinned to one tenant. */ diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/PublishNotificationTemplateApplicationUseCaseTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/PublishNotificationTemplateApplicationUseCaseTest.java index 3266d42a..c5ce0a55 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/PublishNotificationTemplateApplicationUseCaseTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/PublishNotificationTemplateApplicationUseCaseTest.java @@ -21,8 +21,7 @@ class PublishNotificationTemplateApplicationUseCaseTest { RecordingTemplates templates = new RecordingTemplates(); PlatformFakes.RecordingTransactions transactions = new PlatformFakes.RecordingTransactions(); PublishNotificationTemplateApplicationUseCase useCase = - new PublishNotificationTemplateApplicationUseCase( - templates, PublishNotificationTemplateApplicationUseCaseTest::sha256, transactions); + new PublishNotificationTemplateApplicationUseCase(templates, transactions); PublishNotificationTemplateCommand command = new PublishNotificationTemplateCommand( "payment-receipt", @@ -46,9 +45,7 @@ class PublishNotificationTemplateApplicationUseCaseTest { // given PublishNotificationTemplateApplicationUseCase useCase = new PublishNotificationTemplateApplicationUseCase( - new RecordingTemplates(), - PublishNotificationTemplateApplicationUseCaseTest::sha256, - new PlatformFakes.RecordingTransactions()); + new RecordingTemplates(), new PlatformFakes.RecordingTransactions()); PublishNotificationTemplateCommand command = new PublishNotificationTemplateCommand( "payment-receipt", @@ -67,14 +64,6 @@ class PublishNotificationTemplateApplicationUseCaseTest { assertThat(published.version()).isEqualTo(NotificationTemplateVersion.FIRST_VERSION); } - private static byte[] sha256(byte[] bytes) { - try { - return java.security.MessageDigest.getInstance("SHA-256").digest(bytes); - } catch (java.security.NoSuchAlgorithmException impossible) { - throw new IllegalStateException(impossible); - } - } - private static final class RecordingTemplates implements TemplateRegistry { private NotificationTemplateVersion published; diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/SyntheticEventFingerprintTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/SyntheticEventFingerprintTest.java index 0208cc39..e05f6237 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/SyntheticEventFingerprintTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/SyntheticEventFingerprintTest.java @@ -6,8 +6,6 @@ import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; import dev.caskeleton.application.notification.platform.api.NormalizedEventType; import dev.caskeleton.application.notification.platform.api.NormalizedProviderEvent; import dev.caskeleton.application.notification.platform.api.ProviderProfileId; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.time.Instant; import java.time.OffsetDateTime; import java.util.Map; @@ -31,8 +29,7 @@ class SyntheticEventFingerprintTest { private static final DeliveryAttemptId ATTEMPT = new DeliveryAttemptId(UUID.fromString("0198f1a2-3b4c-7d8e-9f01-234567890abc")); - private final SyntheticEventFingerprint fingerprints = - new SyntheticEventFingerprint(SyntheticEventFingerprintTest::sha256); + private final SyntheticEventFingerprint fingerprints = new SyntheticEventFingerprint(); @Test @DisplayName("accepted and delivered for the same attempt are different events") @@ -173,12 +170,4 @@ class SyntheticEventFingerprintTest { Optional.of(occurredAt), Map.of()); } - - private static byte[] sha256(byte[] input) { - try { - return MessageDigest.getInstance("SHA-256").digest(input); - } catch (NoSuchAlgorithmException unavailable) { - throw new IllegalStateException("SHA-256 is required by every Java platform", unavailable); - } - } } diff --git a/src/composition/notification-platform/gradle.lockfile b/src/composition/notification-platform/gradle.lockfile index 0d9c7810..a8a1638d 100644 --- a/src/composition/notification-platform/gradle.lockfile +++ b/src/composition/notification-platform/gradle.lockfile @@ -13,6 +13,7 @@ com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.21.5=runtimeClasspath,t com.fasterxml.jackson:jackson-bom:2.21.5=runtimeClasspath,testRuntimeClasspath com.fasterxml:classmate:1.7.3=runtimeClasspath,testRuntimeClasspath com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor +com.github.f4b6a3:uuid-creator:6.1.1=runtimeClasspath,testRuntimeClasspath com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs com.github.spotbugs:spotbugs:4.10.2=spotbugs diff --git a/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationDeliveryConfiguration.java b/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationDeliveryConfiguration.java index 2201f337..be41bed4 100644 --- a/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationDeliveryConfiguration.java +++ b/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationDeliveryConfiguration.java @@ -18,7 +18,6 @@ import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttempt import dev.caskeleton.application.notification.platform.dispatch.DispatchOutcomeRecorder; import dev.caskeleton.application.notification.platform.dispatch.DispatchPipeline; import dev.caskeleton.application.notification.platform.dispatch.LeaseRecoveryService; -import dev.caskeleton.application.notification.platform.dispatch.MessageDigestPort; import dev.caskeleton.application.notification.platform.dispatch.NotificationDispatchService; import dev.caskeleton.application.notification.platform.dispatch.NotificationIdGeneratorPort; import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestStorePort; @@ -161,7 +160,6 @@ class NotificationDeliveryConfiguration { NotificationAuditPort audit, TransactionPort transactions, NotificationIdGeneratorPort ids, - MessageDigestPort digests, Clock clock) { return new NotificationAdminApplicationService( authorization, @@ -175,7 +173,6 @@ class NotificationDeliveryConfiguration { audit, transactions, ids, - digests, clock); } } diff --git a/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationSubmissionConfiguration.java b/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationSubmissionConfiguration.java index f1b35282..f7debb0a 100644 --- a/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationSubmissionConfiguration.java +++ b/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationSubmissionConfiguration.java @@ -6,13 +6,12 @@ import dev.caskeleton.application.notification.platform.dispatch.CanonicalNotifi import dev.caskeleton.application.notification.platform.dispatch.ContactPointStorePort; import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptStorePort; import dev.caskeleton.application.notification.platform.dispatch.GetNotificationApplicationUseCase; -import dev.caskeleton.application.notification.platform.dispatch.MessageDigestPort; import dev.caskeleton.application.notification.platform.dispatch.NotificationIdGeneratorPort; import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestStorePort; import dev.caskeleton.application.notification.platform.dispatch.NotificationSubmissionService; +import dev.caskeleton.application.notification.platform.dispatch.PlanFingerprint; import dev.caskeleton.application.notification.platform.dispatch.PublishNotificationTemplateApplicationUseCase; import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryStorePort; -import dev.caskeleton.application.notification.platform.dispatch.RequestFingerprint; import dev.caskeleton.application.notification.platform.dispatch.ScheduleNotificationApplicationUseCase; import dev.caskeleton.application.notification.platform.dispatch.SubmitNotificationApplicationUseCase; import dev.caskeleton.application.notification.platform.dispatch.TenantContextPort; @@ -49,7 +48,7 @@ class NotificationSubmissionConfiguration { RecipientDeliveryStorePort recipients, DeliveryAttemptStorePort attempts, TemplateRegistry templates, - RequestFingerprint fingerprints, + PlanFingerprint fingerprints, CanonicalNotificationPlanWriter writer, TransactionPort transactions, TenantContextPort tenants, @@ -86,7 +85,7 @@ class NotificationSubmissionConfiguration { ContactPointProtector protector, TenantContextPort tenants, NotificationIdGeneratorPort ids, - RequestFingerprint fingerprints, + PlanFingerprint fingerprints, TransactionPort transactions, Clock clock, @Value("${ca-skeleton.notification.platform.default-locale:ko-KR}") String defaultLocale) { @@ -111,8 +110,8 @@ class NotificationSubmissionConfiguration { */ @Bean PublishNotificationTemplateUseCase publishNotificationTemplateUseCase( - TemplateRegistry templates, MessageDigestPort digests, TransactionPort transactions) { - return new PublishNotificationTemplateApplicationUseCase(templates, digests, transactions); + TemplateRegistry templates, TransactionPort transactions) { + return new PublishNotificationTemplateApplicationUseCase(templates, transactions); } @Bean diff --git a/src/config/architecture/modules.json b/src/config/architecture/modules.json index 8c3b06a6..61dd810b 100644 --- a/src/config/architecture/modules.json +++ b/src/config/architecture/modules.json @@ -26,7 +26,8 @@ "gradle_path": ":application-notification", "source_path": "src/application-notification", "allowed_dependencies": [ - "application-core" + "application-core", + "shared-contract" ] }, { diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/objectstorage/MultipartObjectContentProducer.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/objectstorage/MultipartObjectContentProducer.java index 85936e15..d213d346 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/objectstorage/MultipartObjectContentProducer.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/objectstorage/MultipartObjectContentProducer.java @@ -5,10 +5,10 @@ import dev.caskeleton.application.objectstorage.content.ObjectContentProducer; import dev.caskeleton.application.objectstorage.content.ObjectContentProductionContext; import dev.caskeleton.application.objectstorage.content.ObjectContentProductionException; import dev.caskeleton.application.objectstorage.model.ObjectContentIdentity; +import dev.caskeleton.shared.digest.Sha256; import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.util.concurrent.atomic.AtomicBoolean; import org.springframework.web.multipart.MultipartFile; @@ -34,7 +34,7 @@ public final class MultipartObjectContentProducer implements ObjectContentProduc throw new ObjectContentProductionException("multipart request content is already consumed"); } try (InputStream input = file.getInputStream()) { - MessageDigest digest = MessageDigest.getInstance("SHA-256"); + MessageDigest digest = Sha256.newMessageDigest(); byte[] buffer = new byte[Math.min(context.maximumChunkBytes(), 64 * 1024)]; long delivered = 0; int read; @@ -58,8 +58,6 @@ public final class MultipartObjectContentProducer implements ObjectContentProduc } catch (IOException exception) { throw new ObjectContentProductionException( "multipart request stream could not be read", exception); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 must be available", exception); } } } diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/identifier/HmacPosterImageIdempotencyScopeDigester.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/identifier/HmacPosterImageIdempotencyScopeDigester.java index 8d4c35c9..77cfe88c 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/identifier/HmacPosterImageIdempotencyScopeDigester.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/identifier/HmacPosterImageIdempotencyScopeDigester.java @@ -2,18 +2,16 @@ package dev.caskeleton.sample.portfolio.adapter.outbound.identifier; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageIdempotencyScopeDigest; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageIdempotencyScopeDigesterPort; +import dev.caskeleton.shared.digest.HmacSha256; import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; -import java.security.GeneralSecurityException; import java.util.Base64; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Supplier; -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; /** HMAC-SHA-256 length-prefixed scope digester with a versioned retained key ring. */ public final class HmacPosterImageIdempotencyScopeDigester @@ -115,14 +113,8 @@ public final class HmacPosterImageIdempotencyScopeDigester throw new IllegalStateException( "DB-active idempotency HMAC key is not retained by this process"); } - try { - Mac mac = Mac.getInstance("HmacSHA256"); - mac.init(new SecretKeySpec(key, "HmacSHA256")); - String encoded = - Base64.getUrlEncoder().withoutPadding().encodeToString(mac.doFinal(canonical)); - return new PosterImageIdempotencyScopeDigest(version, encoded); - } catch (GeneralSecurityException exception) { - throw new IllegalStateException("HmacSHA256 must be available", exception); - } + String encoded = + Base64.getUrlEncoder().withoutPadding().encodeToString(HmacSha256.sign(key, canonical)); + return new PosterImageIdempotencyScopeDigest(version, encoded); } } diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventContract.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventContract.java index 3540181c..bbc98193 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventContract.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventContract.java @@ -6,7 +6,7 @@ import dev.caskeleton.application.messaging.contract.IntegrationEventContractCon import dev.caskeleton.application.messaging.contract.IntegrationPayload; import dev.caskeleton.application.messaging.contract.LogicalDestinationId; import dev.caskeleton.application.messaging.contract.SchemaResourceId; -import dev.caskeleton.application.messaging.contract.Sha256; +import dev.caskeleton.shared.digest.Sha256; import java.lang.reflect.RecordComponent; import java.time.Duration; import java.util.Arrays; diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedContractContribution.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedContractContribution.java index 26704cb4..9c3c01fe 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedContractContribution.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedContractContribution.java @@ -5,7 +5,7 @@ import dev.caskeleton.application.messaging.contract.ContractId; import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution; import dev.caskeleton.application.messaging.contract.LogicalDestinationId; import dev.caskeleton.application.messaging.contract.SchemaResourceId; -import dev.caskeleton.application.messaging.contract.Sha256; +import dev.caskeleton.shared.digest.Sha256; import java.time.Duration; import java.util.HexFormat; import java.util.List; diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/PublishPosterImageUseCase.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/PublishPosterImageUseCase.java index e2210e94..5582c1f5 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/PublishPosterImageUseCase.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/PublishPosterImageUseCase.java @@ -37,13 +37,10 @@ import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageSaniti import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageUploadIntent; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageUploadIntentState; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageUploadIntentStorePort; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; +import dev.caskeleton.shared.digest.Sha256; import java.time.Clock; import java.time.Duration; import java.util.EnumSet; -import java.util.HexFormat; /** TX1 reservation followed by request-bound staging and a fenced TX2 PENDING handoff. */ @RequiresPermission("poster:write") @@ -265,12 +262,6 @@ public class PublishPosterImageUseCase } private static String sha256Hex(String value) { - try { - return HexFormat.of() - .formatHex( - MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 must be available", exception); - } + return Sha256.ofUtf8(value).hex(); } } diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/PosterImageReference.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/PosterImageReference.java index 9c668cb7..c0b9a0ea 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/PosterImageReference.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/PosterImageReference.java @@ -1,9 +1,6 @@ package dev.caskeleton.sample.portfolio.domain.poster; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; +import dev.caskeleton.shared.digest.Sha256; /** Bounded opaque object-storage published reference with its canonical checksum. */ public record PosterImageReference(String value) { @@ -31,13 +28,7 @@ public record PosterImageReference(String value) { } private static String sha256Hex(String value) { - try { - return HexFormat.of() - .formatHex( - MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 must be available", exception); - } + return Sha256.ofUtf8(value).hex(); } private static IllegalArgumentException invalid() { diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventContractsTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventContractsTest.java index 23612bdc..67b5a28f 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventContractsTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventContractsTest.java @@ -3,7 +3,7 @@ package dev.caskeleton.sample.portfolio.application.event; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution; -import dev.caskeleton.application.messaging.contract.Sha256; +import dev.caskeleton.shared.digest.Sha256; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedContractContributionTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedContractContributionTest.java index c5a28450..fd9ce67d 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedContractContributionTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedContractContributionTest.java @@ -13,7 +13,7 @@ import dev.caskeleton.application.messaging.contract.ContractId; import dev.caskeleton.application.messaging.contract.IntegrationPayload; import dev.caskeleton.application.messaging.contract.LogicalDestinationId; import dev.caskeleton.application.messaging.contract.SchemaResourceId; -import dev.caskeleton.application.messaging.contract.Sha256; +import dev.caskeleton.shared.digest.Sha256; import java.io.IOException; import java.io.InputStream; import java.net.URI; diff --git a/src/shared-contract/CLAUDE.md b/src/shared-contract/CLAUDE.md index 1521fa95..da28e91b 100644 --- a/src/shared-contract/CLAUDE.md +++ b/src/shared-contract/CLAUDE.md @@ -24,6 +24,13 @@ envelope shape, metric cardinality bounds, tracing seam, domain-context propagat - Tracing contract types (`tracing/TraceParent`, `tracing/SpanErrorRecorder`) — W3C `traceparent` value type and the span-error-recording seam (feature-distributed-tracing-contract; the OTel tracer runtime is a fork-activated seam, so these stay Java-stdlib-only). +- Stdlib helpers every leaf used to copy (review X2-P1-5, X2-P1-4b, X1-#9): `digest/Sha256` (the + SHA-256 digest value and the one `MessageDigest.getInstance("SHA-256")`), `digest/HmacSha256` + (sign and constant-time verify), `retry/Backoff` (capped exponential ceiling; "full jitter" means + `U[0, ceiling]` and nothing else). Vendored `messaging:*` and the optional gRPC build do not depend + on this module and keep their own copies. +- `observability/MdcKeys`: the snake_case MDC key names (registry `docs/registries/mdc-keys.yaml`) + every transport puts a request's correlation under — web, GraphQL, STOMP and gRPC alike. - Registry-rule mirrors read only by contract tests live in `testFixtures`, not `main`: `metrics/MetricNaming`, `metrics/CardinalityBounds`, `metrics/AlertSeverity`, `tracing/BaggageAllowlist`. Move one to `main` only when production code consumes it. diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/digest/HmacSha256.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/digest/HmacSha256.java new file mode 100644 index 00000000..a9f75cf4 --- /dev/null +++ b/src/shared-contract/src/main/java/dev/caskeleton/shared/digest/HmacSha256.java @@ -0,0 +1,74 @@ +package dev.caskeleton.shared.digest; + +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.MessageDigest; +import java.util.Objects; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; + +/** + * HMAC-SHA256 signing and constant-time verification. + * + *

The one sign/verify pair the signed codecs share (cursor codecs, keyed fingerprints). Each + * used to hold its own {@code Mac.getInstance} block, its own "unreachable" catch and — the part + * that matters — its own verification, where a short-circuiting comparison would leak the correct + * MAC one byte at a time. {@link #verify} compares with {@link MessageDigest#isEqual} and refuses a + * presented MAC of the wrong length before comparing. + * + *

{@link Mac} is not thread-safe, so every call takes a fresh instance. + */ +public final class HmacSha256 { + + /** HMAC-SHA256 produces exactly this many bytes. */ + public static final int MAC_BYTES = 32; + + private static final String ALGORITHM = "HmacSHA256"; + + private HmacSha256() {} + + /** + * The MAC of {@code message} under {@code key}. + * + * @throws IllegalArgumentException if the key is empty + */ + public static byte[] sign(byte[] key, byte[] message) { + Objects.requireNonNull(key, "key"); + Objects.requireNonNull(message, "message"); + if (key.length == 0) { + throw new IllegalArgumentException("HMAC key must not be empty"); + } + try { + Mac mac = Mac.getInstance(ALGORITHM); + mac.init(new SecretKeySpec(key, ALGORITHM)); + return mac.doFinal(message); + } catch (GeneralSecurityException unreachable) { + // HmacSHA256 is mandated by every JDK, and a non-empty raw key always initialises it. + throw new IllegalStateException("HMAC-SHA256 is unavailable", unreachable); + } + } + + /** The MAC of the UTF-8 encoding of {@code message} under {@code key}. */ + public static byte[] sign(byte[] key, String message) { + Objects.requireNonNull(message, "message"); + return sign(key, message.getBytes(StandardCharsets.UTF_8)); + } + + /** + * Whether {@code presented} is the MAC of {@code message} under {@code key}, in constant time. + * + * @return {@code false} for a MAC of the wrong length, without comparing + */ + public static boolean verify(byte[] key, byte[] message, byte[] presented) { + if (presented == null || presented.length != MAC_BYTES) { + return false; + } + return MessageDigest.isEqual(sign(key, message), presented); + } + + /** {@link #verify(byte[], byte[], byte[])} over the UTF-8 encoding of {@code message}. */ + public static boolean verify(byte[] key, String message, byte[] presented) { + Objects.requireNonNull(message, "message"); + return verify(key, message.getBytes(StandardCharsets.UTF_8), presented); + } +} diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/digest/Sha256.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/digest/Sha256.java new file mode 100644 index 00000000..c3d9b7bd --- /dev/null +++ b/src/shared-contract/src/main/java/dev/caskeleton/shared/digest/Sha256.java @@ -0,0 +1,84 @@ +package dev.caskeleton.shared.digest; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; + +/** + * An immutable SHA-256 digest, and the one place this repository asks the JDK for SHA-256. + * + *

Every JDK must ship SHA-256, so {@link NoSuchAlgorithmException} is unreachable; before this + * type each caller wrapped {@code MessageDigest.getInstance("SHA-256")} in its own try/catch, hex + * encoder and "unreachable" comment. One-shot hashing is {@link #of(byte[])} or {@link + * #ofUtf8(String)}; a caller that hashes a stream incrementally takes a fresh {@link + * #newMessageDigest()}. + * + *

Vendored {@code messaging:*} and the optional gRPC build keep their own copies: they do not + * depend on this module. + * + * @param bytes the 32 digest bytes + */ +@SuppressWarnings("ArrayRecordComponent") +public record Sha256(byte[] bytes) { + + public static final int BYTE_LENGTH = 32; + + private static final String ALGORITHM = "SHA-256"; + + public Sha256 { + if (bytes == null || bytes.length != BYTE_LENGTH) { + throw new IllegalArgumentException("SHA-256 digest must contain exactly 32 bytes"); + } + bytes = bytes.clone(); + } + + /** The SHA-256 digest of {@code content}. */ + public static Sha256 of(byte[] content) { + Objects.requireNonNull(content, "content"); + return new Sha256(newMessageDigest().digest(content)); + } + + /** The SHA-256 digest of the UTF-8 encoding of {@code content}. */ + public static Sha256 ofUtf8(String content) { + Objects.requireNonNull(content, "content"); + return of(content.getBytes(StandardCharsets.UTF_8)); + } + + /** A fresh SHA-256 {@link MessageDigest} for incremental hashing. */ + public static MessageDigest newMessageDigest() { + try { + return MessageDigest.getInstance(ALGORITHM); + } catch (NoSuchAlgorithmException unreachable) { + // SHA-256 is mandated by every JDK. + throw new IllegalStateException("SHA-256 algorithm unavailable", unreachable); + } + } + + @Override + public byte[] bytes() { + return bytes.clone(); + } + + /** The digest as 64 lowercase hex characters. */ + public String hex() { + return HexFormat.of().formatHex(bytes); + } + + @Override + public boolean equals(Object other) { + return this == other || (other instanceof Sha256 sha256 && Arrays.equals(bytes, sha256.bytes)); + } + + @Override + public int hashCode() { + return Arrays.hashCode(bytes); + } + + @Override + public String toString() { + return hex(); + } +} diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/observability/MdcKeys.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/observability/MdcKeys.java new file mode 100644 index 00000000..cfc4f438 --- /dev/null +++ b/src/shared-contract/src/main/java/dev/caskeleton/shared/observability/MdcKeys.java @@ -0,0 +1,19 @@ +package dev.caskeleton.shared.observability; + +/** + * The snake_case MDC key names every transport puts a request's correlation under. + * + *

The registry is {@code docs/registries/mdc-keys.yaml}. These lived in the web adapter, so a + * GraphQL, WebSocket or gRPC request could not name them without depending on the servlet adapter + * (review X2-P2-5); here any leaf that has the shared-contract edge can. + */ +public final class MdcKeys { + + public static final String REQUEST_ID = "request_id"; + public static final String TRACE_ID = "trace_id"; + public static final String SPAN_ID = "span_id"; + public static final String CORRELATION_ID = "correlation_id"; + public static final String USER_PRINCIPAL = "user_principal"; + + private MdcKeys() {} +} diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/retry/Backoff.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/retry/Backoff.java new file mode 100644 index 00000000..b6b6ffbb --- /dev/null +++ b/src/shared-contract/src/main/java/dev/caskeleton/shared/retry/Backoff.java @@ -0,0 +1,81 @@ +package dev.caskeleton.shared.retry; + +import java.time.Duration; +import java.util.Objects; +import java.util.random.RandomGenerator; + +/** + * Capped exponential backoff and the jitter words that go with it, defined once. + * + *

The retry loops of this repository each wrote the formula themselves, and "full jitter" meant + * three different things: {@code U(0, ceiling]}, {@code base·2ⁿ + U(0, base)} with no ceiling, and + * a full jitter floored at the base. Here the words have one meaning each: + * + *

    + *
  • {@link #ceiling(int) ceiling}: {@code min(max, base · 2^(attempt-1))}, attempt 1-based. + *
  • {@link #fullJitter(int, RandomGenerator) full jitter}: uniform in {@code [0, ceiling]}. + *
  • {@link #decorrelatedJitter(Duration, RandomGenerator) decorrelated jitter}: uniform in + * {@code [base, min(max, max(base, 3 · previous))]}. + *
+ * + *

Arithmetic is in milliseconds and saturates rather than overflowing, so a large attempt number + * yields the ceiling instead of a negative delay. The random source is injected so a schedule is + * deterministic in a test. + * + * @param base the first attempt's ceiling; not negative (zero means every delay is zero) + * @param max the largest delay this backoff produces; not smaller than {@code base} + */ +public record Backoff(Duration base, Duration max) { + + public Backoff { + Objects.requireNonNull(base, "base"); + Objects.requireNonNull(max, "max"); + if (base.isNegative()) { + throw new IllegalArgumentException("backoff base must not be negative"); + } + if (max.compareTo(base) < 0) { + throw new IllegalArgumentException("backoff max must not be smaller than base"); + } + } + + /** + * The exponential ceiling for a 1-based attempt: {@code min(max, base · 2^(attempt-1))}. + * + * @throws IllegalArgumentException if {@code attempt < 1} + */ + public Duration ceiling(int attempt) { + if (attempt < 1) { + throw new IllegalArgumentException("attempt must be >= 1 (1-based), was " + attempt); + } + long baseMillis = base.toMillis(); + long maxMillis = max.toMillis(); + int shift = attempt - 1; + // base << shift overflows once shift reaches the leading zeros of base; the ceiling is max + // then. + long scaled = + shift >= Long.numberOfLeadingZeros(baseMillis) - 1 ? Long.MAX_VALUE : baseMillis << shift; + return Duration.ofMillis(Math.min(scaled, maxMillis)); + } + + /** Full jitter: a delay uniform in {@code [0, ceiling(attempt)]}. */ + public Duration fullJitter(int attempt, RandomGenerator random) { + Objects.requireNonNull(random, "random"); + long ceilingMillis = ceiling(attempt).toMillis(); + return Duration.ofMillis(random.nextLong(ceilingMillis + 1)); + } + + /** + * Decorrelated jitter: a delay uniform in {@code [base, min(max, max(base, 3 · previous))]}. + * + * @param previous the delay this schedule chose last time; the base for the first retry + */ + public Duration decorrelatedJitter(Duration previous, RandomGenerator random) { + Objects.requireNonNull(previous, "previous"); + Objects.requireNonNull(random, "random"); + long lower = base.toMillis(); + long previousMillis = Math.max(0, previous.toMillis()); + long tripled = previousMillis > Long.MAX_VALUE / 3 ? Long.MAX_VALUE : previousMillis * 3; + long upper = Math.min(max.toMillis(), Math.max(lower, tripled)); + return Duration.ofMillis(upper <= lower ? lower : random.nextLong(lower, upper + 1)); + } +} diff --git a/src/shared-contract/src/test/java/dev/caskeleton/shared/digest/HmacSha256Test.java b/src/shared-contract/src/test/java/dev/caskeleton/shared/digest/HmacSha256Test.java new file mode 100644 index 00000000..280caaaa --- /dev/null +++ b/src/shared-contract/src/test/java/dev/caskeleton/shared/digest/HmacSha256Test.java @@ -0,0 +1,70 @@ +package dev.caskeleton.shared.digest; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import java.nio.charset.StandardCharsets; +import java.util.HexFormat; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class HmacSha256Test { + + private static final byte[] KEY = "key".getBytes(StandardCharsets.UTF_8); + private static final String MESSAGE = "The quick brown fox jumps over the lazy dog"; + + @Test + @DisplayName("널리 쓰이는 공개 예제(키 \"key\", quick brown fox)의 MAC 값과 같다") + void theMacMatchesThePublishedExample() { + assertThat(HexFormat.of().formatHex(HmacSha256.sign(KEY, MESSAGE))) + .isEqualTo("f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8"); + } + + @Test + void theMacOfTheMessageVerifies() { + // given + byte[] mac = HmacSha256.sign(KEY, MESSAGE); + + // when + boolean verified = HmacSha256.verify(KEY, MESSAGE, mac); + + // then + assertThat(verified).isTrue(); + } + + @Test + void aMacOfAnotherMessageDoesNotVerify() { + // given + byte[] mac = HmacSha256.sign(KEY, MESSAGE + "."); + + // when + boolean verified = HmacSha256.verify(KEY, MESSAGE, mac); + + // then + assertThat(verified).isFalse(); + } + + @Test + @DisplayName("길이가 32바이트가 아닌 MAC은 비교하지 않고 거부한다") + void aMacOfTheWrongLengthDoesNotVerify() { + // given + byte[] truncated = new byte[HmacSha256.MAC_BYTES - 1]; + + // when + boolean verified = HmacSha256.verify(KEY, MESSAGE, truncated); + + // then + assertThat(verified).isFalse(); + } + + @Test + void anEmptyKeyIsRefused() { + // when + Throwable thrown = catchThrowable(() -> HmacSha256.sign(new byte[0], MESSAGE)); + + // then + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("HMAC key must not be empty"); + } +} diff --git a/src/shared-contract/src/test/java/dev/caskeleton/shared/digest/Sha256Test.java b/src/shared-contract/src/test/java/dev/caskeleton/shared/digest/Sha256Test.java new file mode 100644 index 00000000..18812d1c --- /dev/null +++ b/src/shared-contract/src/test/java/dev/caskeleton/shared/digest/Sha256Test.java @@ -0,0 +1,64 @@ +package dev.caskeleton.shared.digest; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class Sha256Test { + + private static final String ABC_HEX = + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"; + + @Test + @DisplayName("\"abc\"의 digest는 FIPS 180-2 예제 값이다") + void theUtf8DigestMatchesTheStandardTestVector() { + assertThat(Sha256.ofUtf8("abc").hex()).isEqualTo(ABC_HEX); + } + + @Test + void byteAndUtf8DigestsOfTheSameContentAreEqual() { + assertThat(Sha256.of("abc".getBytes(StandardCharsets.UTF_8))).isEqualTo(Sha256.ofUtf8("abc")); + } + + @Test + void anIncrementalDigestMatchesTheOneShotDigest() { + // given + MessageDigest digest = Sha256.newMessageDigest(); + digest.update("a".getBytes(StandardCharsets.UTF_8)); + digest.update("bc".getBytes(StandardCharsets.UTF_8)); + + // when + Sha256 incremental = new Sha256(digest.digest()); + + // then + assertThat(incremental).isEqualTo(Sha256.ofUtf8("abc")); + } + + @Test + void theDigestBytesCannotBeChangedFromOutside() { + // given + Sha256 digest = Sha256.ofUtf8("abc"); + + // when + digest.bytes()[0] = 0; + + // then + assertThat(digest.hex()).isEqualTo(ABC_HEX); + } + + @Test + @DisplayName("32바이트가 아닌 digest는 거부한다") + void aDigestOfTheWrongLengthIsRefused() { + // when + Throwable thrown = catchThrowable(() -> new Sha256(new byte[31])); + + // then + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("SHA-256 digest must contain exactly 32 bytes"); + } +} diff --git a/src/shared-contract/src/test/java/dev/caskeleton/shared/retry/BackoffTest.java b/src/shared-contract/src/test/java/dev/caskeleton/shared/retry/BackoffTest.java new file mode 100644 index 00000000..c3a8cca9 --- /dev/null +++ b/src/shared-contract/src/test/java/dev/caskeleton/shared/retry/BackoffTest.java @@ -0,0 +1,109 @@ +package dev.caskeleton.shared.retry; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import java.time.Duration; +import java.util.random.RandomGenerator; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +class BackoffTest { + + private static final Backoff BACKOFF = new Backoff(Duration.ofMillis(100), Duration.ofSeconds(1)); + + /** Always draws the upper end of the requested range. */ + private static final RandomGenerator HIGHEST = + new RandomGenerator() { + @Override + public long nextLong() { + throw new UnsupportedOperationException(); + } + + @Override + public long nextLong(long bound) { + return bound - 1; + } + + @Override + public long nextLong(long origin, long bound) { + return bound - 1; + } + }; + + /** Always draws the lower end of the requested range. */ + private static final RandomGenerator LOWEST = + new RandomGenerator() { + @Override + public long nextLong() { + throw new UnsupportedOperationException(); + } + + @Override + public long nextLong(long bound) { + return 0; + } + + @Override + public long nextLong(long origin, long bound) { + return origin; + } + }; + + @ParameterizedTest + @CsvSource({"1, 100", "2, 200", "4, 800", "5, 1000", "64, 1000", "2147483647, 1000"}) + @DisplayName("ceiling은 base·2^(n-1)이고 max에서 멈추며 큰 n에서도 넘치지 않는다") + void theCeilingDoublesPerAttemptUpToTheMax(int attempt, long expectedMillis) { + assertThat(BACKOFF.ceiling(attempt)).isEqualTo(Duration.ofMillis(expectedMillis)); + } + + @Test + @DisplayName("full jitter의 위쪽 끝은 ceiling 자체다") + void fullJitterReachesTheCeiling() { + assertThat(BACKOFF.fullJitter(3, HIGHEST)).isEqualTo(Duration.ofMillis(400)); + } + + @Test + @DisplayName("full jitter의 아래쪽 끝은 0이다") + void fullJitterReachesZero() { + assertThat(BACKOFF.fullJitter(3, LOWEST)).isEqualTo(Duration.ZERO); + } + + @Test + @DisplayName("decorrelated jitter는 이전 지연의 3배와 max 중 작은 값까지다") + void decorrelatedJitterIsBoundedByThreeTimesThePreviousDelay() { + assertThat(BACKOFF.decorrelatedJitter(Duration.ofMillis(200), HIGHEST)) + .isEqualTo(Duration.ofMillis(600)); + } + + @Test + void decorrelatedJitterNeverGoesBelowTheBase() { + assertThat(BACKOFF.decorrelatedJitter(Duration.ofMillis(200), LOWEST)) + .isEqualTo(Duration.ofMillis(100)); + } + + @Test + void anAttemptBelowOneIsRefused() { + // when + Throwable thrown = catchThrowable(() -> BACKOFF.ceiling(0)); + + // then + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("attempt must be >= 1 (1-based), was 0"); + } + + @Test + void aMaxBelowTheBaseIsRefused() { + // when + Throwable thrown = + catchThrowable(() -> new Backoff(Duration.ofSeconds(2), Duration.ofSeconds(1))); + + // then + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("backoff max must not be smaller than base"); + } +}