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 23681873..14fddc5f 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 @@ -15,6 +15,7 @@ import dev.caskeleton.application.notification.platform.api.delivery.DeliveryOut import dev.caskeleton.application.notification.platform.api.delivery.EvidenceLevel; import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState; import dev.caskeleton.application.notification.platform.api.delivery.SubmissionOutcome; +import dev.caskeleton.application.notification.platform.api.error.FailureCategory; import dev.caskeleton.application.notification.platform.api.routing.Channel; import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptSnapshot; import dev.caskeleton.application.notification.platform.dispatch.AttemptSnapshots; @@ -37,12 +38,17 @@ import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; import java.util.ArrayList; +import java.util.EnumSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; +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.MethodSource; /** * The four operator-plane use cases, each its own entrypoint with its own permission (round9 review @@ -347,6 +353,215 @@ class NotificationAdminUseCasesTest { .containsExactly(1, 1, List.of(true)); } + /** + * The actor holds every operator authority but the one the use case exercises, and is global, so + * the tenant checks pass and the use case's own {@code require} is the only thing that refuses. + */ + @ParameterizedTest(name = "{0}") + @MethodSource("operatorUseCases") + void eachOperatorUseCaseRefusesAnActorMissingItsOwnAuthority(OperatorCall call) { + // given + Fixture fixture = new Fixture(); + AttemptSnapshots.store( + fixture.requests, + fixture.attempts, + attemptOf(new TenantId("tenant-a")), + RecipientDeliveryState.FAILED); + AdminActor everyOtherAuthority = + new AdminActor( + "operator-1", EnumSet.complementOf(EnumSet.of(call.authority())), Optional.empty()); + + // when + Throwable failure = catchThrowable(() -> call.invoke(fixture, everyOtherAuthority)); + + // then + assertThat(failure) + .as("refused with AdminAccessDeniedException(%s)", call.authority()) + .isInstanceOfSatisfying( + AdminAccessDeniedException.class, + denied -> + assertThat(List.of(denied.required(), fixture.operations.claims)) + .containsExactly(call.authority(), 0)); + } + + @Test + void aTenantScopedOperatorCannotSuppressAnotherTenantsContactPoint() { + // given + Fixture fixture = new Fixture(); + TenantId tenantA = new TenantId("tenant-a"); + AdminActor tenantB = + new AdminActor( + "operator-b", + Set.of(NotificationAdminAuthority.SUPPRESS), + Optional.of(new TenantId("tenant-b"))); + + // when + Throwable failure = + catchThrowable( + () -> + fixture.suppression.handle( + new ChangeSuppressionCommand(suppressionOf(tenantA), tenantB))); + + // then + assertThat(failure) + .as("refused with AdminAccessDeniedException(SUPPRESS)") + .isInstanceOfSatisfying( + AdminAccessDeniedException.class, + denied -> + assertThat( + List.of( + denied.required(), + fixture + .suppressions + .activeFor(tenantA, "c".repeat(64), CLOCK.instant()) + .size(), + fixture.operations.claims)) + .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)); + } + + @Test + void anAmbiguousAttemptIsNotRedrivenWithoutTheDuplicateRiskApproval() { + // given + Fixture fixture = new Fixture(); + DeliveryAttemptSnapshot ambiguous = attemptOf(new TenantId("tenant-a")); + AttemptSnapshots.store( + fixture.requests, fixture.attempts, ambiguous, RecipientDeliveryState.FAILED); + AdminActor operator = + new AdminActor("operator-1", Set.of(NotificationAdminAuthority.REDRIVE), Optional.empty()); + RedriveRequest unapproved = + new RedriveRequest("op-rd-risk", ambiguous.attemptId(), "provider outage", false, false); + + // when + Throwable failure = + catchThrowable( + () -> fixture.redrive.handle(new RedriveDeliveryCommand(unapproved, operator))); + + // then + assertThat(failure) + .as("refused with DuplicateRiskApprovalRequiredException(AMBIGUOUS_SUBMISSION)") + .isInstanceOfSatisfying( + DuplicateRiskApprovalRequiredException.class, + refused -> + assertThat( + List.of( + refused.descriptor().category(), + fixture + .recipients + .find(ambiguous.recipientDeliveryId()) + .orElseThrow() + .state(), + fixture.operations.claims)) + .containsExactly( + FailureCategory.AMBIGUOUS_SUBMISSION, RecipientDeliveryState.FAILED, 0)); + } + + private static Stream operatorUseCases() { + DeliveryAttemptId attempt = attemptOf(new TenantId("tenant-a")).attemptId(); + return Stream.of( + new OperatorCall( + "ChangeSuppressionUseCase", + NotificationAdminAuthority.SUPPRESS, + (fixture, actor) -> + fixture.suppression.handle( + new ChangeSuppressionCommand(suppressionOf(new TenantId("tenant-a")), actor))), + new OperatorCall( + "RedriveDeliveryUseCase", + NotificationAdminAuthority.REDRIVE, + (fixture, actor) -> + fixture.redrive.handle( + new RedriveDeliveryCommand( + new RedriveRequest("op-rd", attempt, "provider outage", true, false), + actor))), + new OperatorCall( + "ReconcileDeliveriesUseCase", + NotificationAdminAuthority.RECONCILE, + (fixture, actor) -> + fixture.reconcile.handle( + new ReconcileDeliveriesCommand( + new ReconcileRequest("op-r", List.of(attempt), "stuck attempt", false), + actor))), + new OperatorCall( + "ChangeProviderStateUseCase", + NotificationAdminAuthority.PROVIDER_CONTROL, + (fixture, actor) -> + fixture.providerState.handle( + new ChangeProviderStateCommand( + new ProviderStateRequest( + "op-p", + new ProviderProfileId("ses-primary"), + ProviderRuntimeState.DISABLED, + "provider maintenance", + false), + actor)))); + } + + private static SuppressionRequest suppressionOf(TenantId tenantId) { + return new SuppressionRequest( + "op-s", + tenantId, + SuppressionScope.CONTACT_POINT, + SuppressionReason.ADMIN_BLOCK, + "c".repeat(64), + Optional.empty(), + false, + "reported abuse", + false); + } + + /** One operator use case, the authority it exercises, and how to call it as an actor. */ + private record OperatorCall( + String useCase, + NotificationAdminAuthority authority, + BiFunction call) { + + AdminOperationResult invoke(Fixture fixture, AdminActor actor) { + return call.apply(fixture, actor); + } + + @Override + public String toString() { + return useCase + " requires " + authority; + } + } + private static DeliveryAttemptSnapshot attemptOf(TenantId tenantId) { return new DeliveryAttemptSnapshot( new DeliveryAttemptId(UUID.fromString("00000000-0000-7000-8000-000000000011")), diff --git a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationSubmissionServiceTest.java b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationSubmissionServiceTest.java index 25040bf2..86b58924 100644 --- a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationSubmissionServiceTest.java +++ b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationSubmissionServiceTest.java @@ -11,6 +11,7 @@ import dev.caskeleton.application.notification.platform.api.NotificationReceipt; import dev.caskeleton.application.notification.platform.api.RequestStatus; import dev.caskeleton.application.notification.platform.api.TenantId; import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState; +import dev.caskeleton.application.notification.platform.api.delivery.SubmissionOutcome; import dev.caskeleton.application.notification.platform.api.error.IdempotencyConflictException; import dev.caskeleton.application.notification.platform.api.error.NotificationValidationException; import dev.caskeleton.application.notification.platform.api.routing.Channel; @@ -29,6 +30,7 @@ import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; /** @@ -242,19 +244,49 @@ class NotificationSubmissionServiceTest { assertThat(transactions.committed()).isEmpty(); } - @Test - void cancellationReportsExternalUncertaintyRatherThanClaimingTheMessageWasStopped() { + /** + * A job whose provider may already hold the message — an ambiguous attempt, or a submission the + * provider confirmed while the job is still open — is never reported as stopped. Without the + * follow-up flag the job is left as it is; with it the follow-up is canceled, and the result + * still says the external side effect is uncertain. + */ + @ParameterizedTest(name = "[{index}] ambiguousAttempt={0}, submission={1}, cancelFollowUps={3}") + @CsvSource( + textBlock = + """ + # ambiguousAttempt, submission, state before, cancelFollowUps, canceled, state after + true, AMBIGUOUS, RECONCILIATION_REQUIRED, false, 0, RECONCILIATION_REQUIRED + false, CONFIRMED_ACCEPTED, DISPATCHING, false, 0, DISPATCHING + true, AMBIGUOUS, RECONCILIATION_REQUIRED, true, 1, CANCELED + false, CONFIRMED_ACCEPTED, DISPATCHING, true, 1, CANCELED + """) + void cancellationReportsExternalUncertaintyRatherThanClaimingTheMessageWasStopped( + boolean ambiguousAttempt, + SubmissionOutcome submission, + RecipientDeliveryState before, + boolean cancelFollowUps, + int canceled, + RecipientDeliveryState after) { + // given + TenantId tenant = new TenantId("tenant-a"); var receipt = submit(PlatformFakes.plan("idem-6", Map.of())); - var job = requests.recipientsOf(new TenantId("tenant-a"), receipt.notificationId()).get(0); - requests.replace(withAmbiguousAttempt(job)); + var job = requests.recipientsOf(tenant, receipt.notificationId()).get(0); + requests.replace(withEvidence(job, before, submission, ambiguousAttempt)); + // when var result = - service.cancel(receipt.notificationId(), new CancelCommand("OPERATOR_REQUEST", false)); + service.cancel( + receipt.notificationId(), new CancelCommand("OPERATOR_REQUEST", cancelFollowUps)); - assertThat(result.externalSideEffectUncertain()).isTrue(); - assertThat(result.reasonCodes()).contains("EXTERNAL_SIDE_EFFECT_UNCERTAIN"); - // The provider will not un-send what it already accepted, and the result says so. - assertThat(result.canceledRecipients()).isZero(); + // then + assertThat( + List.of( + result.externalSideEffectUncertain(), + result.canceledRecipients(), + result.reasonCodes(), + requests.recipientsOf(tenant, receipt.notificationId()).get(0).state())) + .containsExactly( + true, canceled, List.of("EXTERNAL_SIDE_EFFECT_UNCERTAIN", "OPERATOR_REQUEST"), after); } @Test @@ -294,7 +326,11 @@ class NotificationSubmissionServiceTest { assertThat(NotificationRequestStatusPolicy.rollUp(List.of())).isEqualTo(RequestStatus.CREATED); } - private static RecipientDeliveryRecord withAmbiguousAttempt(RecipientDeliveryRecord job) { + private static RecipientDeliveryRecord withEvidence( + RecipientDeliveryRecord job, + RecipientDeliveryState state, + SubmissionOutcome submission, + boolean ambiguousAttempt) { return new RecipientDeliveryRecord( job.id(), job.notificationId(), @@ -304,11 +340,11 @@ class NotificationSubmissionServiceTest { job.timeZone(), job.routingPlan(), job.routeCursor(), - job.state(), - job.submissionOutcome(), + state, + submission, job.deliveryOutcome(), job.evidenceLevel(), - true, + ambiguousAttempt, job.duplicateRisk(), job.nextDispatchAt(), job.expiresAt(),