diff --git a/docs/notification/api-surface-snapshot.txt b/docs/notification/api-surface-snapshot.txt index fb1fdbf5..9b274554 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: 375 +# types: 377 dev.caskeleton.adapter.outbound.notification.NotificationConfig dev.caskeleton.adapter.outbound.notification.NotificationRoutesSettings dev.caskeleton.adapter.outbound.notification.core.FailOpenNotificationProvider @@ -104,9 +104,11 @@ dev.caskeleton.application.notification.platform.admin.ChangeProviderStateComman dev.caskeleton.application.notification.platform.admin.ChangeProviderStateUseCase dev.caskeleton.application.notification.platform.admin.ChangeSuppressionCommand dev.caskeleton.application.notification.platform.admin.ChangeSuppressionUseCase +dev.caskeleton.application.notification.platform.admin.DeliveryAttemptNotFoundException dev.caskeleton.application.notification.platform.admin.DuplicateRiskApprovalRequiredException dev.caskeleton.application.notification.platform.admin.DuplicateRiskGuard dev.caskeleton.application.notification.platform.admin.NotificationAdminAuthority +dev.caskeleton.application.notification.platform.admin.NotificationAdminErrorCode dev.caskeleton.application.notification.platform.admin.NotificationAdminPermissions dev.caskeleton.application.notification.platform.admin.ProviderRuntimeControlPort dev.caskeleton.application.notification.platform.admin.ProviderStateRequest diff --git a/docs/notification/operations.md b/docs/notification/operations.md index 792f2cac..e9fb4a2c 100644 --- a/docs/notification/operations.md +++ b/docs/notification/operations.md @@ -51,8 +51,11 @@ redrive는 `NotificationId`와 `RecipientDeliveryId`를 유지하고, 새 `Deliv - 확인은 두 겹이다. permission은 전송의 호출자가 이 연산을 부를 수 있는지다(`@RequiresPermission`). authority와 tenant 범위는 command의 `AdminActor`가 쥐고, 연산이 건드리는 delivery의 tenant와 대조한다. -- redrive가 받은 attempt id가 없으면 남의 tenant attempt와 같은 거절(`AdminAccessDeniedException`)이다. 운영자 입력이라 - 서버 오류가 아니고, 다른 tenant에 그 id가 있는지도 응답으로 알 수 없다. reconcile은 묶음 안의 없는 id를 건너뛴다. +- redrive가 받은 attempt id가 없거나 그 attempt가 운영자 tenant 밖이면 둘 다 `DeliveryAttemptNotFoundException`이다. + 이 예외는 `ApiErrorCarrier`라서 모든 전송이 code `DELIVERY_ATTEMPT_NOT_FOUND`(category `NOT_FOUND`, retryable false)로 + 답하고 서버 오류로 남기지 않는다. web은 404다. 운영자 입력이라 서버 오류가 아니고, 두 경우가 같은 답이라 다른 tenant에 그 id가 있는지도 + 알 수 없다. 예외의 descriptor는 알림 code 목록의 `VALIDATION_FAILED`라 응답 code와 다르다. reconcile은 묶음 안의 없는 + id를 건너뛴다. - 모든 연산은 운영자가 준 operation id로 멱등이다. 같은 id·같은 요청은 저장된 결과를 돌려주고, 같은 id·다른 요청은 충돌이다. 대상 확인(tenant·중복 위험)과 claim과 쓰기는 한 쓰기 트랜잭션에서 커밋한다. reconcile만 대상 확인을 읽기 트랜잭션에서 하고, provider 호출은 트랜잭션 밖에서 하며, claim과 결과를 따로 커밋한다. diff --git a/docs/testing/TESTING_STRATEGY.md b/docs/testing/TESTING_STRATEGY.md index 49abd751..b28e2a03 100644 --- a/docs/testing/TESTING_STRATEGY.md +++ b/docs/testing/TESTING_STRATEGY.md @@ -416,6 +416,7 @@ Javadoc이 선언한 결과와 예외 타입, 그리고 `ObjectStorageFailureExc | --- | --- | --- | --- | --- | | `UserPrincipalPseudonymizerPort` | identifier `HmacUserPrincipalPseudonymizer` | 없음 — 의도 | 결정적 순수 함수라 테스트가 실제 구현을 그대로 쓴다. fake는 두 번째 복사본이 된다. 출력은 `HmacUserPrincipalPseudonymizerVectorTest`가 고정한다 | 해당 없음 | | `OutboxRelayFailureReportPort` | messaging `Slf4jOutboxRelayFailureReportAdapter` | 테스트마다 기록용 | 진단 출력 포트라 호출자가 기대는 동작이 "던지지 않는다" 하나뿐이다 | 해당 없음 | +| `NotificationAuditPort` (notification) | `LoggingNotificationAudit` | testFixtures `RecordingNotificationAudit`(기록용) | 실제 구현이 로그 한 줄을 쓴다. 호출자가 기대는 동작이 "기록하고 던지지 않는다" 하나뿐이라 계약이 없다. fake는 시험이 무엇을 audit했는지(또는 아무것도 안 했는지) 보게 기록만 한다 | 해당 없음 | | `NotificationServingStatePort` (notification) | `JdbcNotificationServingState` | 없음 — 의도 | 여러 표에 걸친 집계 읽기다. `FILTER`·`EXTRACT(EPOCH …)`·lease 조건이 답이라 fake는 쿼리를 다시 쓰는 복사본이 된다. `ServingStateContractTest`가 실 PostgreSQL에서 고정한다 | 해당 없음 | | `ConsentStorePort`·`NotificationInbox` (notification) | `JpaPolicyStores.Consents`·`JpaNotificationInbox` | 없음 — 의도 | 이 포트를 fake로 쓰는 유스케이스 테스트가 없다. 소비자 없는 fake는 두 번째 복사본이 된다(결정 2026-11-03, README 15절). inbox의 `@Version` 동작은 `InboxBulkReadVersionContractTest`가 실 PG에서 본다 | 해당 없음 — fake가 필요한 소비자 테스트가 생기면 계약과 함께 만든다 | diff --git a/docs/upgrade/2026-11-notification-admin-redrive.md b/docs/upgrade/2026-11-notification-admin-redrive.md index 8c13b026..26251e16 100644 --- a/docs/upgrade/2026-11-notification-admin-redrive.md +++ b/docs/upgrade/2026-11-notification-admin-redrive.md @@ -1,22 +1,39 @@ # 업그레이드 안내 — 2026-11 알림 운영자 redrive의 없는 attempt -- 범위: 알림 운영자 연산 `RedriveDeliveryUseCase`가 없는 attempt id를 받았을 때의 예외를 바꾼 변경. 설정 키와 공개 - 타입은 그대로다. 템플릿은 이 연산을 부르는 전송을 싣지 않으므로 따라 고칠 코드는 대개 없다. -- 근거: 2026-11-21 리뷰 발견 REV-BE-0039. 찾는 것이 없음은 클라이언트 탓이고 `IllegalStateException`은 있을 수 없는 - 서버 상태에만 쓴다는 것은 `docs/manual/06-errors.md` 「어떤 예외 타입으로 던지나」가 이미 약속한 응답이다. +- 범위: 알림 운영자 연산 `RedriveDeliveryUseCase`가 없는 attempt id나 운영자 tenant 밖의 attempt를 받았을 때의 + 예외를 두 번 바꾼 변경. 설정 키는 그대로다. 2026-11-23에 공개 타입이 둘 늘었다 + (`DeliveryAttemptNotFoundException`, `NotificationAdminErrorCode`). 템플릿은 이 연산을 부르는 전송을 싣지 않는다. +- 근거: 2026-11-21 리뷰 발견 REV-BE-0039와 2026-11-22 그 정정. 찾는 것이 없음·남의 것은 클라이언트 탓이라 404 + carrier로 답하고 존재를 숨긴다는 것은 `docs/manual/06-errors.md` 「어떤 예외 타입으로 던지나」와 + `docs/manual/07-authorization.md`가 이미 약속한 응답이다. `IllegalStateException`은 있을 수 없는 서버 상태에만 쓴다. ## 1. 누가 읽나 이 템플릿을 `upstream` remote로 두고 merge해 받는 파생 서비스가 읽는다. 특히 알림 운영자 연산을 부르는 전송(운영자 화면, admin endpoint)을 연 서비스다. -## 2. 바뀐 동작 (따라 할 일 없음) +## 2. 바뀐 동작 + +### 2.1 2026-11-23 — 없는 attempt와 남의 tenant attempt를 404 하나로 (따라 할 일 있음) + +| # | 바뀐 것 | 세 시점 | 할 일 | 안 하면 | 해당 서비스 | +| --- | --- | --- | --- | --- | --- | +| 2 | redrive가 없는 attempt id와 운영자 tenant 밖의 attempt를 dry run이든 아니든 같은 `DeliveryAttemptNotFoundException`으로 답한다. 이 예외는 `ApiErrorCarrier`이고 code는 `DELIVERY_ATTEMPT_NOT_FOUND`(404, category `NOT_FOUND`, retryable false)다. 공용 처리기(web `GlobalExceptionHandler`, GraphQL, gRPC, STOMP)는 둘 다 같은 code `DELIVERY_ATTEMPT_NOT_FOUND`로 답한다. web은 404와 같은 error 본문이고 서버 오류 로그·span 오류를 남기지 않는다. GraphQL·gRPC는 그 전송의 not-found 모양(GraphQL errors의 `NOT_FOUND`, gRPC status)으로 답한다. operation id를 claim하지 않고 audit도 남기지 않는다 | ① 2026-11-21 전: 없는 id는 `IllegalStateException("delivery attempt is not available")`, 남의 tenant는 `AdminAccessDeniedException(REDRIVE)`. 공용 처리기에서 둘 다 500 `INTERNAL_ERROR`. ② 2026-11-22(커밋 1a1340c43, 병합 457c91ec): 둘 다 `AdminAccessDeniedException(REDRIVE)`. 그 예외는 carrier가 아니어서 공용 처리기에서 여전히 500 `INTERNAL_ERROR`·ERROR 로그였다. ③ 이번: 둘 다 `DeliveryAttemptNotFoundException`, 404 | redrive의 `AdminAccessDeniedException`을 잡아 「없는 attempt」나 「남의 tenant attempt」로 다루던 코드를 `DeliveryAttemptNotFoundException`으로 바꾼다. 권한이 없는 운영자는 지금도 조회 전에 `AdminAccessDeniedException(REDRIVE)`다. 공용 처리기에 맡겼다면 고칠 코드는 없다(web 응답이 404로 바뀐다) | 그 catch가 이 예외를 놓쳐 공용 처리기로 간다. 서비스가 만든 거절 응답 대신 `DELIVERY_ATTEMPT_NOT_FOUND`(web은 404)가 나간다 | 알림 운영자 연산 전송을 연 서비스 | + +### 2.2 2026-11-22 — 옛 행 (그대로 둔다) | # | 바뀐 것 | 전에는 | 해당 서비스 | | --- | --- | --- | --- | | 1 | `RedriveDeliveryUseCase`가 없는 attempt id를 받으면 dry run이든 아니든 `AdminAccessDeniedException`(code `VALIDATION_FAILED`, category `AUTHORIZATION`, `required()`는 `REDRIVE`)을 던진다. 남의 tenant attempt를 받았을 때와 같은 거절이라 응답으로 다른 tenant에 그 id가 있는지 알 수 없다. operation id를 claim하지 않고 audit도 남기지 않는다 | `IllegalStateException("delivery attempt is not available")`이었다. 전송이 그것을 서버 오류(500)로 내보냈다면 거절 응답으로 바뀐다. 그 예외를 잡던 코드는 이 예외를 놓친다 | 알림 운영자 연산 전송을 연 서비스 | +- 이 행의 「거절 응답으로 바뀐다」는 틀렸다. `AdminAccessDeniedException`은 carrier가 아니어서 공용 처리기는 그대로 + 500으로 답했다. 2.1의 2행이 이 행을 대신한다. + ## 3. 바뀌지 않은 것 - `ReconcileDeliveriesUseCase`는 묶음 안의 없는 attempt id를 그대로 건너뛴다. -- 오류 code 목록(`NotificationFailureCode`)은 그대로다. 운영자 연산에 not-found 코드를 따로 두지 않았다. +- suppression·reconcile·provider 상태 연산은 남의 tenant 대상을 전처럼 `AdminAccessDeniedException`으로 거절한다. + authority가 없을 때의 답도 네 연산 모두 그대로다. +- 오류 code 목록(`NotificationFailureCode`)과 템플릿 오류 code registry(`docs/registries/error-codes.yaml`)는 그대로다. + not-found 코드는 그 목록이 아니라 전송이 읽는 `NotificationAdminErrorCode`에 두었다. 새 예외의 descriptor는 있는 + 값(`VALIDATION_FAILED`, `INVALID_PAYLOAD`)이라 descriptor code와 응답 code가 다르다. diff --git a/docs/web/http-contract.md b/docs/web/http-contract.md index c5df1788..e74fb134 100644 --- a/docs/web/http-contract.md +++ b/docs/web/http-contract.md @@ -189,7 +189,8 @@ CORS가 켜져 있으면(`app.cors.enabled=true`) cross-origin 실제 응답의 ## 4. web 전용 오류 코드 -`OperationalError`(`docs/registries/error-codes.yaml`) 밖에서 HTTP 어댑터가 내는 코드다. +`OperationalError`(`docs/registries/error-codes.yaml`) 밖의 코드다. HTTP 어댑터가 내는 코드와, 기능 leaf의 enum이 내고 +HTTP가 그대로 답하는 코드(`DELIVERY_ATTEMPT_NOT_FOUND`)가 있다. | 코드 | status | category | `retryable` | `Retry-After` | 언제 | | --- | --- | --- | --- | --- | --- | @@ -198,6 +199,7 @@ CORS가 켜져 있으면(`app.cors.enabled=true`) cross-origin 실제 응답의 | `RATE_LIMIT_UNAVAILABLE` | 503 | `TRANSIENT_DEPENDENCY` | `true` | 있음 | rate-limit 저장소 응답 없음(`docs/web/runbook.md`) | | `RATE_LIMIT_INCOMPATIBLE` | 503 | `INTERNAL` | `false` | 없음 | rate-limit 제공자가 계약과 맞지 않음 | | `OPERATION_NOT_FOUND` | 404 | `NOT_FOUND` | `false` | 없음 | durable operation 조회(`DurableOperationController`)에서 그 operation이 없거나 다른 호출자의 것이다. 둘을 가르지 않는다 | +| `DELIVERY_ATTEMPT_NOT_FOUND` | 404 | `NOT_FOUND` | `false` | 없음 | 알림 운영자 redrive(`RedriveDeliveryUseCase`)가 받은 attempt가 없거나 운영자 tenant 밖이다. 둘을 가르지 않는다. 코드는 `application-notification`의 `NotificationAdminErrorCode`라 모든 전송이 같은 코드로 답한다. 템플릿은 이 연산의 전송을 싣지 않는다(`docs/notification/operations.md`) | - 컨트롤러 파라미터 제약 위반(`@RequestParam @Max(10)`)은 요청 본문 위반과 같은 `400 VALIDATION_FAILED`이고 `details`는 `[{field, code, message}]`다. 거절된 값은 싣지 않는다. diff --git a/docs/work/reference/decisions.md b/docs/work/reference/decisions.md index d2fc6ab3..f7032c98 100644 --- a/docs/work/reference/decisions.md +++ b/docs/work/reference/decisions.md @@ -111,6 +111,7 @@ | GraphQL DataLoader 키 실패 | 등록된 `ApiErrorCode`만 노출 | 소유자 | 결정 25 | | Draft-12 offset 불일치 | problem 문서는 프로토콜 예외로 유지 | 소유자 | 결정 12 | | 알림 category 생략 | 거부(400), 판정은 유스케이스 | 소유자 | 결정 13 | +| 알림 redrive의 없는·남의 attempt | 없는 attempt id와 운영자 tenant 밖의 attempt를 같은 404 carrier(`DeliveryAttemptNotFoundException`, code `DELIVERY_ATTEMPT_NOT_FOUND`) 하나로 답한다. 권한 거절(403)로 바꾸는 안과 문서만 500으로 고치는 안은 버렸다. 알림 code 목록(`NotificationFailureCode`)과 템플릿 registry는 넓히지 않는다. 다른 운영자 연산의 tenant 거절은 그대로다 | 기본값(2026-11-22, review 허브가 고른 권하는 안, 자율 운영. 소유자가 정한 것이 아니고 뒤집을 수 있다) | review 허브 REV-BE-0039 정정(2026-11-22 12:51), `docs/upgrade/2026-11-notification-admin-redrive.md` 2.1절 | | 오류 코드 로그 레벨 | `error-codes.yaml`에 `log_level` 칸을 두지 않는다. 레벨은 실패 종류·경로가 정한다(`ServerFailureLog`, 보안 필터 `AuthErrorResponseWriter`). 칸이 다시 생기면 `OperationalErrorRegistryContractTest`가 실패한다. 보안 필터는 5xx(`AUTH_JWKS_UNAVAILABLE`·`INTERNAL_AUTH_MISCONFIGURATION`)를 ERROR, 4xx를 WARN으로 남긴다. 401 서명·issuer·audience 불일치는 WARN | 소유자 | 2026-11-06, `docs/design/2026-11-06-error-code-log-level-design.md` 10절 | | 감싼 carrier를 전송이 읽는 법 | web·GraphQL·STOMP·gRPC 네 전송 모두 원인 사슬의 첫 carrier를 본다. 감싼 carrier의 응답이 500 `INTERNAL_ERROR` 대신 그 carrier의 코드가 된다. 그보다 먼저 답하는 것은 아래 「GraphQL 판정 순서」(등록 매핑)와 「인자 변환 단계의 감싼 carrier」 두 행이다 | 소유자 | `1103` 18.4절(RR7-01-05), 2026-11-06 | | GraphQL 판정 순서 | 플랫폼 거부 → 실패 자신이 carrier → 등록된 application 매핑 → 원인 사슬의 첫 carrier → 거부된 인자(`IllegalArgumentException`, 인자 binder의 `BindException`) → 가림(`INTERNAL_ERROR`). 앱이 등록한 실패는 carrier를 원인으로 들어도 등록한 코드로 답한다(web에서 앱의 도메인 advice가 먼저 받는 것과 같다). 실패 자신이 carrier인 타입(예: `LockAcquisitionTimeoutException`)을 등록한 매핑은 쓰이지 않는다. 로그 줄은 어느 단계가 답하든 원인 사슬의 첫 carrier로 정한다 — 등록 매핑이 답해도 그 안의 서버 쪽 carrier 줄은 남는다 | 소유자(2026-11-07). 로그 줄도 소유자(2026-11-07, 기본값 확인) | `1103` 19.4절 ①(RR8-01-01), 2026-11-07 총괄 세션 전달 | diff --git a/src/adapter/inbound/web-notification/build.gradle b/src/adapter/inbound/web-notification/build.gradle index 27313db3..7453b0ab 100644 --- a/src/adapter/inbound/web-notification/build.gradle +++ b/src/adapter/inbound/web-notification/build.gradle @@ -27,4 +27,8 @@ dependencies { implementation 'org.springframework.boot:spring-boot-starter-validation' testImplementation 'org.springframework.boot:spring-boot-starter-test' + // The operator refusal test runs the real redrive use case over the notification port fakes and + // application-core's transaction fake, then sends its failure through the real error handler. + testImplementation testFixtures(project(':application-notification')) + testImplementation testFixtures(project(':application-core')) } diff --git a/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationAdminRefusalHttpAnswerTest.java b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationAdminRefusalHttpAnswerTest.java new file mode 100644 index 00000000..b5bec64b --- /dev/null +++ b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationAdminRefusalHttpAnswerTest.java @@ -0,0 +1,200 @@ +package dev.caskeleton.adapter.inbound.web.notification; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import com.jayway.jsonpath.JsonPath; +import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler; +import dev.caskeleton.application.notification.platform.admin.AdminActor; +import dev.caskeleton.application.notification.platform.admin.AdminAuthorizationGuard; +import dev.caskeleton.application.notification.platform.admin.DuplicateRiskGuard; +import dev.caskeleton.application.notification.platform.admin.NotificationAdminAuthority; +import dev.caskeleton.application.notification.platform.admin.NotificationAdminErrorCode; +import dev.caskeleton.application.notification.platform.admin.RedriveDeliveryCommand; +import dev.caskeleton.application.notification.platform.admin.RedriveDeliveryUseCase; +import dev.caskeleton.application.notification.platform.admin.RedriveRequest; +import dev.caskeleton.application.notification.platform.admin.testkit.InMemoryAdminOperationStore; +import dev.caskeleton.application.notification.platform.api.ContactPointId; +import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; +import dev.caskeleton.application.notification.platform.api.ProviderProfileId; +import dev.caskeleton.application.notification.platform.api.TenantId; +import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState; +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestRecord; +import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryRecord; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryDeliveryAttemptStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryNotificationRequestStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryRecipientQueue; +import dev.caskeleton.application.notification.platform.dispatch.testkit.NotificationRows; +import dev.caskeleton.application.notification.platform.observation.testkit.RecordingNotificationAudit; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import dev.caskeleton.shared.error.ClientErrorMessages; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.slf4j.LoggerFactory; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +/** + * What an HTTP caller sees when a notification operator's redrive names an attempt the operator + * cannot reach. + * + *

The template ships no operator endpoint. The probe controller below is the transport a service + * would write: it hands the command to the real use case over the notification fakes and lets the + * failure reach the real {@link GlobalExceptionHandler}. The use case's own table (both refusals, + * claims, audit) is {@code NotificationAdminUseCasesTest}; this one is the answer on the wire. + */ +class NotificationAdminRefusalHttpAnswerTest { + + private static final Clock CLOCK = + Clock.fixed(Instant.parse("2026-11-23T00:00:00Z"), ZoneOffset.UTC); + private static final AdminActor TENANT_B_OPERATOR = + new AdminActor( + "operator-b", + Set.of(NotificationAdminAuthority.REDRIVE), + Optional.of(new TenantId("tenant-b"))); + private static final String UNKNOWN_ATTEMPT = "00000000-0000-7000-8000-000000000099"; + + private final InMemoryNotificationRequestStore requests = new InMemoryNotificationRequestStore(); + private final InMemoryDeliveryAttemptStore attempts = new InMemoryDeliveryAttemptStore(requests); + private final RecordingNotificationAudit audit = new RecordingNotificationAudit(); + private final List spanErrorCodes = new ArrayList<>(); + private final MockMvc mvc = + MockMvcBuilders.standaloneSetup( + new RedriveProbe( + new RedriveDeliveryUseCase( + new AdminAuthorizationGuard(), + new DuplicateRiskGuard(), + attempts, + new InMemoryRecipientQueue(requests, CLOCK), + new InMemoryAdminOperationStore(), + audit, + new DirectTransactionPort(), + CLOCK))) + .setControllerAdvice( + new GlobalExceptionHandler((error, code) -> spanErrorCodes.add(code))) + .build(); + + /** + * An unknown id and another tenant's attempt answer the same 404 with the same error object, and + * the handler records neither as a server failure: no log line, no span error. Nothing is + * audited. + */ + @ParameterizedTest(name = "{0} attempt, dryRun={1}") + @CsvSource({"unknown, false", "unknown, true", "foreign, false", "foreign, true"}) + void anUnreachableRedriveAnswersOneNotFoundAndRecordsNoServerFailure( + String target, boolean dryRun) throws Exception { + // given + String attemptId = "foreign".equals(target) ? storedAttemptOfTenantA() : UNKNOWN_ATTEMPT; + Logger handlerLogger = (Logger) LoggerFactory.getLogger(GlobalExceptionHandler.class); + ListAppender handlerLog = new ListAppender<>(); + handlerLog.start(); + handlerLogger.addAppender(handlerLog); + + // when + MockHttpServletResponse response; + try { + response = + mvc.perform( + post("/operator/redrives/{attemptId}", attemptId) + .param("dryRun", String.valueOf(dryRun))) + .andReturn() + .getResponse(); + } finally { + handlerLogger.detachAppender(handlerLog); + handlerLog.stop(); + } + + // then + String body = response.getContentAsString(); + assertThat( + List.of( + response.getStatus(), + JsonPath.read(body, "$.success"), + JsonPath.read(body, "$.error.code"), + JsonPath.read(body, "$.error.category"), + JsonPath.read(body, "$.error.message"), + JsonPath.read(body, "$.error.retryable"), + audit.events().size(), + handlerLog.list.size(), + spanErrorCodes)) + .as( + "[status, success, error code, category, message, retryable, audit events, handler" + + " log lines, span error codes]") + .containsExactly( + 404, + false, + "DELIVERY_ATTEMPT_NOT_FOUND", + "NOT_FOUND", + ClientErrorMessages.of(NotificationAdminErrorCode.DELIVERY_ATTEMPT_NOT_FOUND), + false, + 0, + 0, + List.of()); + } + + /** Stores a FAILED delivery of tenant-a and its attempt, and returns the attempt id. */ + private String storedAttemptOfTenantA() { + NotificationRequestRecord request = + NotificationRows.request(new TenantId("tenant-a"), "idem-a", CLOCK.instant()); + RecipientDeliveryRecord job = + NotificationRows.job( + request, + RecipientDeliveryState.FAILED, + Optional.empty(), + Optional.empty(), + CLOCK.instant()); + requests.insert(request, List.of(job)); + return attempts + .insertDispatching( + NotificationRows.dispatchingAttempt( + job.id(), + new ContactPointId(UUID.fromString("00000000-0000-7000-8000-000000000014")), + 1, + new ProviderProfileId("ses-primary"), + CLOCK.instant())) + .id() + .value() + .toString(); + } + + /** The operator transport a service would write, as a tenant-b operator. */ + @RestController + static final class RedriveProbe { + + private final RedriveDeliveryUseCase redrive; + + RedriveProbe(RedriveDeliveryUseCase redrive) { + this.redrive = redrive; + } + + @PostMapping("/operator/redrives/{attemptId}") + String redrive( + @PathVariable("attemptId") String attemptId, @RequestParam("dryRun") boolean dryRun) { + RedriveRequest request = + new RedriveRequest( + "op-rd-http", + new DeliveryAttemptId(UUID.fromString(attemptId)), + "provider outage", + true, + dryRun); + redrive.handle(new RedriveDeliveryCommand(request, TENANT_B_OPERATOR)); + return "redriven"; + } + } +} diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminAccessDeniedException.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminAccessDeniedException.java index 128f2215..b2e34683 100644 --- a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminAccessDeniedException.java +++ b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminAccessDeniedException.java @@ -7,8 +7,11 @@ import dev.caskeleton.application.notification.platform.api.error.NotificationFa /** * Raised when an operator action is refused: the actor lacks the authority, or the target is - * outside the actor's tenant scope or unknown. The last two give the same refusal, so it does not - * tell which ids exist in other tenants. + * outside the actor's tenant scope. + * + *

It does not hide whether a target exists. A reconcile skips an attempt id that does not exist + * and refuses another tenant's attempt with this exception, so the refusal tells that the id exists + * in another tenant. A redrive answers both with {@link DeliveryAttemptNotFoundException} instead. */ public class AdminAccessDeniedException extends NotificationException { diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminAuthorizationGuard.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminAuthorizationGuard.java index e7f5be9b..48060518 100644 --- a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminAuthorizationGuard.java +++ b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/AdminAuthorizationGuard.java @@ -40,15 +40,26 @@ public final class AdminAuthorizationGuard { */ public void requireTenant( AdminActor actor, TenantId tenantId, NotificationAdminAuthority authority) { - Objects.requireNonNull(actor, "actor"); - Objects.requireNonNull(tenantId, "tenantId"); Objects.requireNonNull(authority, "authority"); - Optional scope = actor.tenantId(); - if (scope.isPresent() && !scope.get().equals(tenantId)) { + if (!mayActOn(actor, tenantId)) { throw new AdminAccessDeniedException(authority); } } + /** + * Whether the actor's tenant scope covers a tenant: a global operator's covers every tenant, a + * tenant-bound one's only its own. + * + *

For an operation that answers a target outside the scope as it answers a target that does + * not exist, rather than with {@link #requireTenant}'s refusal. + */ + public boolean mayActOn(AdminActor actor, TenantId tenantId) { + Objects.requireNonNull(actor, "actor"); + Objects.requireNonNull(tenantId, "tenantId"); + Optional scope = actor.tenantId(); + return scope.isEmpty() || scope.get().equals(tenantId); + } + /** * Require a global operator. * diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/DeliveryAttemptNotFoundException.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/DeliveryAttemptNotFoundException.java new file mode 100644 index 00000000..11678e0a --- /dev/null +++ b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/DeliveryAttemptNotFoundException.java @@ -0,0 +1,40 @@ +package dev.caskeleton.application.notification.platform.admin; + +import dev.caskeleton.application.notification.platform.api.error.FailureCategory; +import dev.caskeleton.application.notification.platform.api.error.NotificationException; +import dev.caskeleton.application.notification.platform.api.error.NotificationFailureCode; +import dev.caskeleton.application.notification.platform.api.error.NotificationFailureDescriptor; +import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.ApiErrorCode; + +/** + * Raised when a redrive names an attempt the operator cannot act on: no attempt has the id, or the + * attempt belongs to a tenant outside the operator's scope. Both raise this one exception with no + * state of its own, so neither the answer nor the exception tells a tenant-scoped operator which + * ids exist in other tenants. + * + *

The id is the operator's input, so this is the caller's failure, not a server fault: a + * transport answers {@link NotificationAdminErrorCode#DELIVERY_ATTEMPT_NOT_FOUND} (404) and logs no + * server failure. + * + *

The two codes differ on purpose. The {@linkplain #descriptor() descriptor} keeps the closed + * notification registry, which has no not-found code ({@code VALIDATION_FAILED}, {@code + * INVALID_PAYLOAD}: the request names a target it may not use). The code on the wire is {@link + * #errorCode()}. + */ +public final class DeliveryAttemptNotFoundException extends NotificationException + implements ApiErrorCarrier { + + private static final long serialVersionUID = 1L; + + public DeliveryAttemptNotFoundException() { + super( + NotificationFailureDescriptor.preDispatch( + NotificationFailureCode.VALIDATION_FAILED, FailureCategory.INVALID_PAYLOAD)); + } + + @Override + public ApiErrorCode errorCode() { + return NotificationAdminErrorCode.DELIVERY_ATTEMPT_NOT_FOUND; + } +} diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminErrorCode.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminErrorCode.java new file mode 100644 index 00000000..66088c12 --- /dev/null +++ b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminErrorCode.java @@ -0,0 +1,50 @@ +package dev.caskeleton.application.notification.platform.admin; + +import dev.caskeleton.shared.error.ApiErrorCode; +import dev.caskeleton.shared.error.Category; + +/** + * Codes the notification operator operations answer a transport with. + * + *

The closed {@code NotificationFailureCode} registry is the platform's own vocabulary — metric + * tags, ledger rows, audit — and has no not-found code. A transport answers with this code instead, + * read through {@link dev.caskeleton.shared.error.ApiErrorCarrier}, so every transport gives the + * same status without naming the feature. + */ +public enum NotificationAdminErrorCode implements ApiErrorCode { + /** + * A redrive named an attempt the operator cannot act on: no attempt has that id, or it belongs to + * a tenant outside the operator's scope. The two are one code so the answer does not tell which. + */ + DELIVERY_ATTEMPT_NOT_FOUND(404, Category.NOT_FOUND, false); + + private final int httpStatus; + private final Category category; + private final boolean retryable; + + NotificationAdminErrorCode(int httpStatus, Category category, boolean retryable) { + this.httpStatus = httpStatus; + this.category = category; + this.retryable = retryable; + } + + @Override + public String code() { + return name(); + } + + @Override + public Category category() { + return category; + } + + @Override + public int httpStatus() { + return httpStatus; + } + + @Override + public boolean retryable() { + return retryable; + } +} diff --git a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/RedriveDeliveryUseCase.java b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/RedriveDeliveryUseCase.java index 3f37e908..587c2e95 100644 --- a/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/RedriveDeliveryUseCase.java +++ b/src/application/notification/src/main/java/dev/caskeleton/application/notification/platform/admin/RedriveDeliveryUseCase.java @@ -109,14 +109,14 @@ public class RedriveDeliveryUseCase } private DeliveryAttemptSnapshot checkedOriginal(RedriveRequest request, AdminActor actor) { - // The id is the operator's input, so an unknown one is a refused request, not an impossible - // state. It is refused exactly like another tenant's attempt, so the answer does not tell a - // tenant-scoped operator which ids exist elsewhere. + // The id is the operator's input, so an unknown one is the caller's failure (not found), not + // an impossible state. Another tenant's attempt takes the same path to the same exception, so + // the answer does not tell a tenant-scoped operator which ids exist elsewhere. DeliveryAttemptSnapshot original = attempts .snapshot(request.attemptId()) - .orElseThrow(() -> new AdminAccessDeniedException(NotificationAdminAuthority.REDRIVE)); - authorization.requireTenant(actor, original.tenantId(), NotificationAdminAuthority.REDRIVE); + .filter(attempt -> authorization.mayActOn(actor, attempt.tenantId())) + .orElseThrow(DeliveryAttemptNotFoundException::new); duplicateRiskGuard.verify(original, request.approveDuplicateRisk()); return original; } diff --git a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminUseCasesTest.java b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminUseCasesTest.java index 096634dc..a822d012 100644 --- a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminUseCasesTest.java +++ b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminUseCasesTest.java @@ -27,13 +27,16 @@ import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemor import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryNotificationRequestStore; import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryRecipientQueue; import dev.caskeleton.application.notification.platform.observation.NotificationAuditEvent; -import dev.caskeleton.application.notification.platform.observation.NotificationAuditPort; +import dev.caskeleton.application.notification.platform.observation.testkit.RecordingNotificationAudit; import dev.caskeleton.application.notification.platform.policy.SuppressionReason; import dev.caskeleton.application.notification.platform.policy.SuppressionScope; import dev.caskeleton.application.notification.platform.policy.testkit.InMemorySuppressionStore; import dev.caskeleton.application.notification.platform.provider.ProviderRuntimeState; import dev.caskeleton.application.notification.platform.provider.ReconciliationResult; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.ApiErrorCode; +import dev.caskeleton.shared.error.Category; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; @@ -48,7 +51,6 @@ import java.util.function.BiFunction; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; /** @@ -63,6 +65,8 @@ class NotificationAdminUseCasesTest { private static final AdminActor ACTOR = new AdminActor( "operator-1", Set.of(NotificationAdminAuthority.PROVIDER_CONTROL), Optional.empty()); + private static final DeliveryAttemptId UNKNOWN_ATTEMPT = + new DeliveryAttemptId(UUID.fromString("00000000-0000-7000-8000-000000000099")); @Test void providerStateMutationClaimsBeforeCallingTheRuntime() { @@ -84,7 +88,7 @@ class NotificationAdminUseCasesTest { assertThat(fixture.runtime.calls).isEqualTo(1); assertThat(fixture.runtime.profile).isEqualTo(new ProviderProfileId("ses-primary")); assertThat(fixture.runtime.state).isEqualTo(ProviderRuntimeState.DISABLED); - assertThat(fixture.audit.events) + assertThat(fixture.audit.events()) .extracting(NotificationAuditEvent::action) .containsExactly("ADMIN_PROVIDER_STATE"); } @@ -248,7 +252,7 @@ class NotificationAdminUseCasesTest { List.of( fixture.recipients.find(attempt.recipientDeliveryId()).orElseThrow().state(), fixture.operations.claimsInTransaction, - fixture.audit.events.stream().map(NotificationAuditEvent::action).toList())) + fixture.audit.events().stream().map(NotificationAuditEvent::action).toList())) .containsExactly( RecipientDeliveryState.READY_TO_DISPATCH, List.of(true), List.of("ADMIN_REDRIVE")); } @@ -420,61 +424,25 @@ class NotificationAdminUseCasesTest { .containsExactly(NotificationAdminAuthority.SUPPRESS, 0, 0)); } - @Test - void aTenantScopedOperatorCannotRedriveAnotherTenantsAttempt() { - // given - Fixture fixture = new Fixture(); - DeliveryAttemptSnapshot foreign = attemptOf(new TenantId("tenant-a")); - AttemptSnapshots.store( - fixture.requests, fixture.attempts, foreign, RecipientDeliveryState.FAILED); - AdminActor tenantB = - new AdminActor( - "operator-b", - Set.of(NotificationAdminAuthority.REDRIVE), - Optional.of(new TenantId("tenant-b"))); - RedriveRequest approved = - new RedriveRequest("op-rd-b", foreign.attemptId(), "provider outage", true, false); - - // when - Throwable failure = - catchThrowable(() -> fixture.redrive.handle(new RedriveDeliveryCommand(approved, tenantB))); - - // then - assertThat(failure) - .as("refused with AdminAccessDeniedException(REDRIVE)") - .isInstanceOfSatisfying( - AdminAccessDeniedException.class, - denied -> - assertThat( - List.of( - denied.required(), - fixture - .recipients - .find(foreign.recipientDeliveryId()) - .orElseThrow() - .state(), - fixture.operations.claims)) - .containsExactly( - NotificationAdminAuthority.REDRIVE, RecipientDeliveryState.FAILED, 0)); - } - /** - * The attempt id is the operator's input, so an unknown one must not surface as an {@code - * IllegalStateException} (a server fault that pages) nor as a refusal other than a foreign - * attempt's (which would tell the operator the id exists in another tenant). + * The attempt id is the operator's input. An id no attempt has and an attempt of another tenant + * get one answer, not found: an {@code IllegalStateException} would page as a server fault, a + * refusal would answer a typo as missing authority, and two different answers would tell a + * tenant-scoped operator which ids exist in other tenants. */ - @ParameterizedTest(name = "tenant scope={0}, dryRun={1}") - @MethodSource("unknownAttemptRedrives") - void aRedriveOfAnUnknownAttemptIsRefusedLikeAnotherTenantsAttemptAndClaimsNothing( - Optional scope, boolean dryRun) { + @ParameterizedTest(name = "{0}") + @MethodSource("unreachableRedrives") + void aRedriveOfAnUnknownOrForeignAttemptIsNotFoundAndChangesNothing(UnreachableRedrive redrive) { // given Fixture fixture = new Fixture(); + DeliveryAttemptSnapshot stored = attemptOf(new TenantId("tenant-a")); + AttemptSnapshots.store( + fixture.requests, fixture.attempts, stored, RecipientDeliveryState.FAILED); AdminActor operator = - new AdminActor("operator-b", Set.of(NotificationAdminAuthority.REDRIVE), scope); - DeliveryAttemptId unknown = - new DeliveryAttemptId(UUID.fromString("00000000-0000-7000-8000-000000000099")); + new AdminActor("operator-b", Set.of(NotificationAdminAuthority.REDRIVE), redrive.scope()); RedriveRequest request = - new RedriveRequest("op-rd-unknown", unknown, "provider outage", true, dryRun); + new RedriveRequest( + "op-rd-unreachable", redrive.target(stored), "provider outage", true, redrive.dryRun()); // when Throwable failure = @@ -482,26 +450,81 @@ class NotificationAdminUseCasesTest { // then assertThat(failure) - .as("refused with AdminAccessDeniedException(REDRIVE), as a foreign attempt is") + .as("answered DeliveryAttemptNotFoundException") + .isInstanceOf(DeliveryAttemptNotFoundException.class) + .satisfies( + notFound -> { + ApiErrorCode code = + ApiErrorCarrier.firstIn(notFound) + .map(ApiErrorCarrier.class::cast) + .orElseThrow() + .errorCode(); + assertThat( + List.of( + code.code(), + code.category(), + code.httpStatus(), + code.retryable(), + fixture.operations.claims, + fixture.audit.events().size(), + fixture + .recipients + .find(stored.recipientDeliveryId()) + .orElseThrow() + .state())) + .as("[code, category, status, retryable, claims, audit events, job state]") + .containsExactly( + "DELIVERY_ATTEMPT_NOT_FOUND", + Category.NOT_FOUND, + 404, + false, + 0, + 0, + RecipientDeliveryState.FAILED); + }); + } + + private static Stream unreachableRedrives() { + Optional tenantB = Optional.of(new TenantId("tenant-b")); + Optional global = Optional.empty(); + return Stream.of( + new UnreachableRedrive("tenant operator, unknown id, redrive", tenantB, false, false), + new UnreachableRedrive("tenant operator, unknown id, dry run", tenantB, false, true), + new UnreachableRedrive("tenant operator, foreign id, redrive", tenantB, true, false), + new UnreachableRedrive("tenant operator, foreign id, dry run", tenantB, true, true), + new UnreachableRedrive("global operator, unknown id, redrive", global, false, false), + new UnreachableRedrive("global operator, unknown id, dry run", global, false, true)); + } + + /** + * The authority is checked before the attempt is read: an operator without it is refused for + * that, and does not learn whether the id exists. + */ + @Test + void aRedriveWithoutTheAuthorityIsRefusedBeforeItsAttemptIsLookedUp() { + // given + Fixture fixture = new Fixture(); + AdminActor withoutRedrive = + new AdminActor( + "operator-b", + EnumSet.complementOf(EnumSet.of(NotificationAdminAuthority.REDRIVE)), + Optional.of(new TenantId("tenant-b"))); + RedriveRequest request = + new RedriveRequest("op-rd-no-authority", UNKNOWN_ATTEMPT, "provider outage", true, false); + + // when + Throwable failure = + catchThrowable( + () -> fixture.redrive.handle(new RedriveDeliveryCommand(request, withoutRedrive))); + + // then + assertThat(failure) + .as("refused with AdminAccessDeniedException(REDRIVE), not answered as an unknown attempt") .isInstanceOfSatisfying( AdminAccessDeniedException.class, denied -> - assertThat( - List.of( - denied.required(), - fixture.operations.claims, - fixture.audit.events.size())) - .as("[required authority, claims, audit events]") - .containsExactly(NotificationAdminAuthority.REDRIVE, 0, 0)); - } - - private static Stream unknownAttemptRedrives() { - Optional tenantB = Optional.of(new TenantId("tenant-b")); - return Stream.of( - Arguments.of(tenantB, false), - Arguments.of(tenantB, true), - Arguments.of(Optional.empty(), false), - Arguments.of(Optional.empty(), true)); + assertThat(List.of(denied.required(), fixture.operations.claims)) + .containsExactly(NotificationAdminAuthority.REDRIVE, 0)); } @Test @@ -593,6 +616,23 @@ class NotificationAdminUseCasesTest { false); } + /** + * A redrive the operator cannot reach: the operator's tenant scope, whether the id is the stored + * attempt of tenant-a or one no attempt has, and whether it is a dry run. + */ + private record UnreachableRedrive( + String name, Optional scope, boolean foreign, boolean dryRun) { + + DeliveryAttemptId target(DeliveryAttemptSnapshot stored) { + return foreign ? stored.attemptId() : UNKNOWN_ATTEMPT; + } + + @Override + public String toString() { + return name; + } + } + /** One operator use case, the authority it exercises, and how to call it as an actor. */ private record OperatorCall( String useCase, @@ -640,7 +680,7 @@ class NotificationAdminUseCasesTest { private final InMemoryRecipientQueue recipients = new InMemoryRecipientQueue(requests, CLOCK); private final RecordingRuntime runtime = new RecordingRuntime(); private final RecordingOperations operations = new RecordingOperations(); - private final RecordingAudit audit = new RecordingAudit(); + private final RecordingNotificationAudit audit = new RecordingNotificationAudit(); private final DirectTransactionPort transactions = new DirectTransactionPort(); private final InMemorySuppressionStore suppressions = new InMemorySuppressionStore(); private final ChangeProviderStateUseCase providerState; @@ -741,13 +781,4 @@ class NotificationAdminUseCasesTest { return AdminOperationClaim.claimed(); } } - - private static final class RecordingAudit implements NotificationAuditPort { - private final List events = new ArrayList<>(); - - @Override - public void record(NotificationAuditEvent event) { - events.add(event); - } - } } diff --git a/src/application/notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/observation/testkit/RecordingNotificationAudit.java b/src/application/notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/observation/testkit/RecordingNotificationAudit.java new file mode 100644 index 00000000..2ed06c48 --- /dev/null +++ b/src/application/notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/observation/testkit/RecordingNotificationAudit.java @@ -0,0 +1,30 @@ +package dev.caskeleton.application.notification.platform.observation.testkit; + +import dev.caskeleton.application.notification.platform.observation.NotificationAuditEvent; +import dev.caskeleton.application.notification.platform.observation.NotificationAuditPort; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + * The fake of {@link NotificationAuditPort}: keeps every recorded event so a test can assert what + * an operation audited, or that it audited nothing. + * + *

No shared contract: the adapter ({@code LoggingNotificationAudit}) writes a log line, so the + * one behaviour a caller relies on is that recording does not throw ({@code + * docs/testing/TESTING_STRATEGY.md} 9.2). + */ +public final class RecordingNotificationAudit implements NotificationAuditPort { + + private final List events = new ArrayList<>(); + + @Override + public synchronized void record(NotificationAuditEvent event) { + events.add(Objects.requireNonNull(event, "event")); + } + + /** The recorded events, oldest first. */ + public synchronized List events() { + return List.copyOf(events); + } +} diff --git a/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectHandoffClaimRequest.java b/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectHandoffClaimRequest.java index 740e2552..8045cc42 100644 --- a/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectHandoffClaimRequest.java +++ b/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectHandoffClaimRequest.java @@ -23,7 +23,7 @@ public record ObjectHandoffClaimRequest( ObjectRequestSupport.required(stageHandle, "stageHandle"); ObjectRequestSupport.required(exactVersion, "exactVersion"); claimant = ObjectModelSupport.requireBoundedToken("claimant", claimant, 128); - leaseDuration = ObjectRequestSupport.grantTtl(leaseDuration); + leaseDuration = ObjectRequestSupport.grantTtl(leaseDuration, "leaseDuration"); ObjectRequestSupport.required(budget, "budget"); ObjectRequestSupport.required(cancellation, "cancellation"); } diff --git a/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectHandoffRenewRequest.java b/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectHandoffRenewRequest.java index f99ab41d..6b98695c 100644 --- a/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectHandoffRenewRequest.java +++ b/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectHandoffRenewRequest.java @@ -22,7 +22,7 @@ public record ObjectHandoffRenewRequest( ObjectRequestSupport.required(stageHandle, "stageHandle"); ObjectRequestSupport.positive(fence, "fence"); claimant = ObjectModelSupport.requireBoundedToken("claimant", claimant, 128); - leaseDuration = ObjectRequestSupport.grantTtl(leaseDuration); + leaseDuration = ObjectRequestSupport.grantTtl(leaseDuration, "leaseDuration"); ObjectRequestSupport.required(budget, "budget"); ObjectRequestSupport.required(cancellation, "cancellation"); } diff --git a/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectRequestSupport.java b/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectRequestSupport.java index 02b02c77..ab6023b8 100644 --- a/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectRequestSupport.java +++ b/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectRequestSupport.java @@ -28,14 +28,16 @@ final class ObjectRequestSupport { return Set.copyOf(capabilities); } - static Duration grantTtl(Duration requestedTtl) { - required(requestedTtl, "requestedTtl"); - if (requestedTtl.isZero() - || requestedTtl.isNegative() - || requestedTtl.compareTo(MAXIMUM_GRANT_TTL) > 0) { - throw new IllegalArgumentException("requestedTtl is outside the supported range"); + /** + * A grant duration in (0, 24h], refused under the caller's field name: a refusal naming a field + * the request does not have sends whoever built it looking in the wrong place. + */ + static Duration grantTtl(Duration value, String label) { + required(value, label); + if (value.isZero() || value.isNegative() || value.compareTo(MAXIMUM_GRANT_TTL) > 0) { + throw new IllegalArgumentException(label + " is outside the supported range"); } - return requestedTtl; + return value; } static long positive(long value, String label) { diff --git a/src/application/objectstorage/src/test/java/dev/caskeleton/application/objectstorage/ObjectStorageValueContractTest.java b/src/application/objectstorage/src/test/java/dev/caskeleton/application/objectstorage/ObjectStorageValueContractTest.java index a2e03f95..ea6827e9 100644 --- a/src/application/objectstorage/src/test/java/dev/caskeleton/application/objectstorage/ObjectStorageValueContractTest.java +++ b/src/application/objectstorage/src/test/java/dev/caskeleton/application/objectstorage/ObjectStorageValueContractTest.java @@ -29,6 +29,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; class ObjectStorageValueContractTest { @@ -107,7 +108,21 @@ class ObjectStorageValueContractTest { assertThat(thrown) .as("%s leaseDuration=%s", request, leaseDuration) .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("requestedTtl is outside the supported range"); + .hasMessage("leaseDuration is outside the supported range"); + } + + @ParameterizedTest(name = "{0}") + @ValueSource(strings = {"claim", "renew"}) + @DisplayName("handoff claim·renew의 leaseDuration이 없으면 그 필드 이름으로 거절한다") + void aMissingHandoffLeaseIsRejectedNamingTheField(String request) { + // when + Throwable thrown = catchThrowable(() -> handoffLease(request, null)); + + // then + assertThat(thrown) + .as("%s leaseDuration=null", request) + .isInstanceOf(NullPointerException.class) + .hasMessage("leaseDuration must be non-null"); } @ParameterizedTest(name = "{0} leaseDuration={1}")