diff --git a/docs/notification/operations.md b/docs/notification/operations.md index 5199a655..792f2cac 100644 --- a/docs/notification/operations.md +++ b/docs/notification/operations.md @@ -51,6 +51,8 @@ redrive는 `NotificationId`와 `RecipientDeliveryId`를 유지하고, 새 `Deliv - 확인은 두 겹이다. permission은 전송의 호출자가 이 연산을 부를 수 있는지다(`@RequiresPermission`). authority와 tenant 범위는 command의 `AdminActor`가 쥐고, 연산이 건드리는 delivery의 tenant와 대조한다. +- redrive가 받은 attempt id가 없으면 남의 tenant attempt와 같은 거절(`AdminAccessDeniedException`)이다. 운영자 입력이라 + 서버 오류가 아니고, 다른 tenant에 그 id가 있는지도 응답으로 알 수 없다. reconcile은 묶음 안의 없는 id를 건너뛴다. - 모든 연산은 운영자가 준 operation id로 멱등이다. 같은 id·같은 요청은 저장된 결과를 돌려주고, 같은 id·다른 요청은 충돌이다. 대상 확인(tenant·중복 위험)과 claim과 쓰기는 한 쓰기 트랜잭션에서 커밋한다. reconcile만 대상 확인을 읽기 트랜잭션에서 하고, provider 호출은 트랜잭션 밖에서 하며, claim과 결과를 따로 커밋한다. diff --git a/docs/upgrade/2026-11-notification-admin-redrive.md b/docs/upgrade/2026-11-notification-admin-redrive.md new file mode 100644 index 00000000..8c13b026 --- /dev/null +++ b/docs/upgrade/2026-11-notification-admin-redrive.md @@ -0,0 +1,22 @@ +# 업그레이드 안내 — 2026-11 알림 운영자 redrive의 없는 attempt + +- 범위: 알림 운영자 연산 `RedriveDeliveryUseCase`가 없는 attempt id를 받았을 때의 예외를 바꾼 변경. 설정 키와 공개 + 타입은 그대로다. 템플릿은 이 연산을 부르는 전송을 싣지 않으므로 따라 고칠 코드는 대개 없다. +- 근거: 2026-11-21 리뷰 발견 REV-BE-0039. 찾는 것이 없음은 클라이언트 탓이고 `IllegalStateException`은 있을 수 없는 + 서버 상태에만 쓴다는 것은 `docs/manual/06-errors.md` 「어떤 예외 타입으로 던지나」가 이미 약속한 응답이다. + +## 1. 누가 읽나 + +이 템플릿을 `upstream` remote로 두고 merge해 받는 파생 서비스가 읽는다. 특히 알림 운영자 연산을 부르는 전송(운영자 +화면, admin endpoint)을 연 서비스다. + +## 2. 바뀐 동작 (따라 할 일 없음) + +| # | 바뀐 것 | 전에는 | 해당 서비스 | +| --- | --- | --- | --- | +| 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)로 내보냈다면 거절 응답으로 바뀐다. 그 예외를 잡던 코드는 이 예외를 놓친다 | 알림 운영자 연산 전송을 연 서비스 | + +## 3. 바뀌지 않은 것 + +- `ReconcileDeliveriesUseCase`는 묶음 안의 없는 attempt id를 그대로 건너뛴다. +- 오류 code 목록(`NotificationFailureCode`)은 그대로다. 운영자 연산에 not-found 코드를 따로 두지 않았다. 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 9616916d..128f2215 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 @@ -5,7 +5,11 @@ import dev.caskeleton.application.notification.platform.api.error.NotificationEx import dev.caskeleton.application.notification.platform.api.error.NotificationFailureCode; import dev.caskeleton.application.notification.platform.api.error.NotificationFailureDescriptor; -/** Raised when an actor lacks the operator authority an action requires. */ +/** + * 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. + */ public class AdminAccessDeniedException extends NotificationException { private static final long serialVersionUID = 1L; @@ -19,7 +23,7 @@ public class AdminAccessDeniedException extends NotificationException { private final transient NotificationAdminAuthority required; - /** Authority that was missing. */ + /** Authority the refused action exercises. */ public NotificationAdminAuthority required() { return required; } 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 3b96e42c..3f37e908 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,10 +109,13 @@ 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. DeliveryAttemptSnapshot original = attempts .snapshot(request.attemptId()) - .orElseThrow(() -> new IllegalStateException("delivery attempt is not available")); + .orElseThrow(() -> new AdminAccessDeniedException(NotificationAdminAuthority.REDRIVE)); authorization.requireTenant(actor, original.tenantId(), NotificationAdminAuthority.REDRIVE); 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 14fddc5f..096634dc 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 @@ -48,6 +48,7 @@ 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; /** @@ -457,6 +458,52 @@ class NotificationAdminUseCasesTest { 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). + */ + @ParameterizedTest(name = "tenant scope={0}, dryRun={1}") + @MethodSource("unknownAttemptRedrives") + void aRedriveOfAnUnknownAttemptIsRefusedLikeAnotherTenantsAttemptAndClaimsNothing( + Optional scope, boolean dryRun) { + // given + Fixture fixture = new Fixture(); + AdminActor operator = + new AdminActor("operator-b", Set.of(NotificationAdminAuthority.REDRIVE), scope); + DeliveryAttemptId unknown = + new DeliveryAttemptId(UUID.fromString("00000000-0000-7000-8000-000000000099")); + RedriveRequest request = + new RedriveRequest("op-rd-unknown", unknown, "provider outage", true, dryRun); + + // when + Throwable failure = + catchThrowable(() -> fixture.redrive.handle(new RedriveDeliveryCommand(request, operator))); + + // then + assertThat(failure) + .as("refused with AdminAccessDeniedException(REDRIVE), as a foreign attempt is") + .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)); + } + @Test void anAmbiguousAttemptIsNotRedrivenWithoutTheDuplicateRiskApproval() { // given diff --git a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/policy/NotificationEligibilityTest.java b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/policy/NotificationEligibilityTest.java index d0545e9a..e04e4191 100644 --- a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/policy/NotificationEligibilityTest.java +++ b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/policy/NotificationEligibilityTest.java @@ -7,7 +7,11 @@ import java.time.Instant; import java.util.List; import java.util.Optional; import java.util.Set; +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; class NotificationEligibilityTest { @@ -46,6 +50,37 @@ class NotificationEligibilityTest { assertThat(engine.evaluate(PolicyFixtures.context(NOW)).allowed()).isTrue(); } + /** + * A category suppression must neither spread to other categories (a marketing opt-out would then + * block a security notice) nor be ignored (a marketing opt-out would then never apply). + */ + @ParameterizedTest + @MethodSource("categorySuppressions") + void aCategorySuppressionBlocksItsOwnCategoryOnly( + String suppressedCategory, EligibilityResult expected) { + // given + var engine = + new CompositeNotificationEligibilityPolicy( + new PolicyFixtures.FixedSuppressionStore( + List.of( + PolicyFixtures.categorySuppression( + SuppressionReason.USER_OPT_OUT, suppressedCategory, NOW.minusSeconds(60)))), + new PolicyFixtures.FixedPreferenceStore(Optional.empty()), + NotificationEligibilityPolicy.permitAll()); + + // when + var result = engine.evaluate(PolicyFixtures.context(NOW)); + + // then + assertThat(result).isEqualTo(expected); + } + + private static Stream categorySuppressions() { + return Stream.of( + Arguments.of(PolicyFixtures.CATEGORY, EligibilityResult.blocked("SUPPRESSED_USER_OPT_OUT")), + Arguments.of("marketing", EligibilityResult.permitted())); + } + @Test void injectedBusinessPolicyCanBlockWithoutTheCoreKnowingWhy() { var engine = diff --git a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/policy/NotificationRetryPolicyTest.java b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/policy/NotificationRetryPolicyTest.java index d774edc0..d5450922 100644 --- a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/policy/NotificationRetryPolicyTest.java +++ b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/policy/NotificationRetryPolicyTest.java @@ -10,7 +10,12 @@ import dev.caskeleton.application.notification.platform.provider.ProviderRuntime import java.time.Duration; import java.time.Instant; import java.util.Optional; +import java.util.stream.Stream; +import org.junit.jupiter.api.Named; 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; class NotificationRetryPolicyTest { @@ -138,6 +143,116 @@ class NotificationRetryPolicyTest { .isEqualTo("BUDGET_EXHAUSTED"); } + /** + * Each row changes the evidence one rule reads in a context that would otherwise retry (the + * transient failure of {@link #transientFailureWithBudgetAndDeadlineRetries}), so a deleted rule + * shows up as a retry instead of the row's decision. That is one field per row, except the + * accepted row, which changes the confirmation with the submission outcome. + */ + @ParameterizedTest(name = "{0}") + @MethodSource("evidenceThatRulesOutAnotherAttempt") + void evidenceThatRulesOutAnotherAttemptStopsOrFallsBackWithItsReason( + RetryContext context, RetryDecision expected) { + assertThat(policy.decide(context)).isEqualTo(expected); + } + + private static Stream evidenceThatRulesOutAnotherAttempt() { + return Stream.of( + row( + "INVALID_PAYLOAD", + otherwiseRetrying( + FailureCategory.INVALID_PAYLOAD, + AttemptConfirmation.REJECTED, + SubmissionOutcome.NOT_SUBMITTED, + true, + ProviderRuntimeState.HEALTHY), + new RetryDecision.Stop("NON_RETRYABLE_REQUEST")), + row( + "TEMPLATE_FAILURE", + otherwiseRetrying( + FailureCategory.TEMPLATE_FAILURE, + AttemptConfirmation.REJECTED, + SubmissionOutcome.NOT_SUBMITTED, + true, + ProviderRuntimeState.HEALTHY), + new RetryDecision.Stop("NON_RETRYABLE_REQUEST")), + row( + "provider already accepted", + otherwiseRetrying( + FailureCategory.TRANSIENT_PROVIDER, + AttemptConfirmation.CONFIRMED, + SubmissionOutcome.CONFIRMED_ACCEPTED, + true, + ProviderRuntimeState.HEALTHY), + new RetryDecision.Stop("PROVIDER_ALREADY_ACCEPTED")), + row( + "contact point inactive", + otherwiseRetrying( + FailureCategory.TRANSIENT_PROVIDER, + AttemptConfirmation.REJECTED, + SubmissionOutcome.NOT_SUBMITTED, + false, + ProviderRuntimeState.HEALTHY), + new RetryDecision.Fallback("CONTACT_POINT_INACTIVE")), + row( + "provider AUTHENTICATION_FAILED", + otherwiseRetrying( + FailureCategory.TRANSIENT_PROVIDER, + AttemptConfirmation.REJECTED, + SubmissionOutcome.NOT_SUBMITTED, + true, + ProviderRuntimeState.AUTHENTICATION_FAILED), + new RetryDecision.Stop("PROVIDER_UNAVAILABLE")), + row( + "provider DISABLED", + otherwiseRetrying( + FailureCategory.TRANSIENT_PROVIDER, + AttemptConfirmation.REJECTED, + SubmissionOutcome.NOT_SUBMITTED, + true, + ProviderRuntimeState.DISABLED), + new RetryDecision.Stop("PROVIDER_UNAVAILABLE")), + row( + "provider DRAINING", + otherwiseRetrying( + FailureCategory.TRANSIENT_PROVIDER, + AttemptConfirmation.REJECTED, + SubmissionOutcome.NOT_SUBMITTED, + true, + ProviderRuntimeState.DRAINING), + new RetryDecision.Stop("PROVIDER_UNAVAILABLE"))); + } + + private static Arguments row(String name, RetryContext context, RetryDecision expected) { + return Arguments.of(Named.of(name, context), expected); + } + + /** The retrying transient failure with the fields the rows change. */ + private static RetryContext otherwiseRetrying( + FailureCategory category, + AttemptConfirmation confirmation, + SubmissionOutcome submissionOutcome, + boolean contactPointActive, + ProviderRuntimeState providerState) { + return new RetryContext( + category, + confirmation, + submissionOutcome, + ProviderExecutionEvidence.notStarted(), + false, + false, + contactPointActive, + false, + false, + Optional.of(NOW.plus(Duration.ofHours(1))), + Optional.empty(), + 1, + RetryBudget.of(3), + providerState, + Duration.ofSeconds(1), + NOW); + } + private static RetryContext context( FailureCategory category, AttemptConfirmation confirmation, diff --git a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/policy/PolicyFixtures.java b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/policy/PolicyFixtures.java index d978e386..c610091f 100644 --- a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/policy/PolicyFixtures.java +++ b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/policy/PolicyFixtures.java @@ -17,6 +17,7 @@ final class PolicyFixtures { static final TenantId TENANT = new TenantId("tenant-a"); static final String FINGERPRINT = "f".repeat(64); + static final String CATEGORY = "payment.receipt"; private PolicyFixtures() {} @@ -25,7 +26,7 @@ final class PolicyFixtures { TENANT, new NotificationId(UUID.randomUUID()), "user-1", - "payment.receipt", + CATEGORY, Channel.EMAIL, new ContactPointId(UUID.randomUUID()), FINGERPRINT, @@ -47,6 +48,20 @@ final class PolicyFixtures { SuppressionSource.PROVIDER); } + static SuppressionEntry categorySuppression( + SuppressionReason reason, String category, Instant effectiveAt) { + return new SuppressionEntry( + new SuppressionId(UUID.randomUUID()), + TENANT, + SuppressionScope.CONTACT_POINT, + reason, + FINGERPRINT, + Optional.of(category), + effectiveAt, + Optional.empty(), + SuppressionSource.INTERNAL); + } + static SuppressionEntry temporarySuppression(Instant effectiveAt, Instant expiresAt) { return new SuppressionEntry( new SuppressionId(UUID.randomUUID()),