fix(notification)!: 운영자 연산의 거절을 클라이언트 오류로 답하고 reconcile의 존재 노출을 막는다 #106

Merged
donghyeon.kang merged 6 commits from fix/notification-admin-refusal-carriers into main 2026-11-23 14:57:01 +00:00
19 changed files with 965 additions and 173 deletions
+2 -1
View File
@@ -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: 378
# types: 379
dev.caskeleton.adapter.outbound.notification.NotificationConfig
dev.caskeleton.adapter.outbound.notification.NotificationRoutesSettings
dev.caskeleton.adapter.outbound.notification.core.FailOpenNotificationProvider
@@ -100,6 +100,7 @@ dev.caskeleton.application.notification.platform.admin.AdminAuthorizationGuard
dev.caskeleton.application.notification.platform.admin.AdminOperationClaim
dev.caskeleton.application.notification.platform.admin.AdminOperationResult
dev.caskeleton.application.notification.platform.admin.AdminOperationStorePort
dev.caskeleton.application.notification.platform.admin.AdminTargetNotFoundException
dev.caskeleton.application.notification.platform.admin.ChangeProviderStateCommand
dev.caskeleton.application.notification.platform.admin.ChangeProviderStateUseCase
dev.caskeleton.application.notification.platform.admin.ChangeSuppressionCommand
+22 -5
View File
@@ -51,11 +51,28 @@ redrive는 `NotificationId`와 `RecipientDeliveryId`를 유지하고, 새 `Deliv
- 확인은 두 겹이다. permission은 전송의 호출자가 이 연산을 부를 수 있는지다(`@RequiresPermission`). authority와
tenant 범위는 command의 `AdminActor`가 쥐고, 연산이 건드리는 delivery의 tenant와 대조한다.
- 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를 건너뛴다.
- 아래 거절은 모두 운영자 입력이라 서버 오류가 아니다. 거절 예외는 `ApiErrorCarrier`라서 실패를 답하는 전송(web·GraphQL·gRPC)이
아래 code(`NotificationAdminErrorCode`)로 답하고 서버 오류로 남기지 않는다. 예외의 descriptor는 알림 code 목록 값이라
응답 code와 다르다. 전송마다의 모양은 `docs/upgrade/2026-11-notification-admin-refusals.md` 2.1절이다. 이 표 밖의 거절
(provider 상태 연산에서 runtime이 받아들이지 않은 변경, 없는 profile)은 아직 500과 ERROR 로그다.
| 거절 | code | web | retryable | 운영자가 할 일 |
|---|---|---|---|---|
| authority가 없다. tenant 범위 운영자가 provider 상태를 바꾸려 했다 | `ADMIN_ACCESS_DENIED` | 403 | false | authority를 받거나 tenant 범위 없는 운영자에게 맡긴다 |
| redrive의 attempt id가 없거나 그 attempt가 운영자 tenant 밖이다. reconcile 묶음에 그런 id가 하나라도 있다 | `DELIVERY_ATTEMPT_NOT_FOUND` | 404 | false | id를 확인한다. reconcile은 묶음 전체가 거절되니 그 id를 빼고 다시 보낸다 |
| suppression이 운영자 tenant 밖의 tenant를 골랐다 | `ADMIN_TARGET_NOT_FOUND` | 404 | false | tenant를 확인한다 |
| 모호한 attempt를 중복 위험 승인 없이 redrive했다 | `DUPLICATE_RISK_APPROVAL_REQUIRED` | 409 | false | 중복 위험을 받아들이면 승인을 붙여 다시 보낸다 |
| operation id가 전에 다른 요청에 쓰였다 | `ADMIN_OPERATION_CONFLICT` | 422 | false | 새 operation id를 쓴다 |
| 같은 operation id·같은 요청을 다른 호출자가 아직 처리하고 있다 | `ADMIN_OPERATION_IN_PROGRESS` | 409 | false | 기다렸다가 같은 id·같은 요청을 다시 보낸다. 끝났으면 저장된 결과가 온다. 오래 가면 아래처럼 새 id를 쓴다 |
- authority는 대상을 읽기 전에 본다. 그래서 403은 대상에 대해 아무것도 알려 주지 않는다. tenant 밖의 대상은 authority
거절이 아니라 없는 대상과 같은 404다. redrive와 reconcile은 없는 attempt와 남의 tenant attempt가 같은 답이라 다른 tenant에
그 id가 있는지 알 수 없다.
- reconcile은 provider를 부르기 전에 묶음의 id를 모두 본다. 하나라도 없거나 운영자 tenant 밖이면 묶음 전체를 거절하고
아무것도 묻지 않는다(dry run도 같다). 그래서 처리 수(`affected`)는 묶음의 id 수와 같다. 보존 기간이 지나 지워진 attempt
id가 섞인 묶음도 거절된다.
- provider 호출 중에 프로세스가 멈춘 reconcile의 operation id는 claim이 끝나지 않아(claim에 만료가 없다) 계속 진행 중으로
답한다. 그 묶음은 새 operation id로 보낸다. 그래서 진행 중은 retryable이 false다.
- 모든 연산은 운영자가 준 operation id로 멱등이다. 같은 id·같은 요청은 저장된 결과를 돌려주고, 같은 id·다른 요청은
충돌이다. 대상 확인(tenant·중복 위험)과 claim과 쓰기는 한 쓰기 트랜잭션에서 커밋한다. reconcile만 대상 확인을 읽기
트랜잭션에서 하고, provider 호출은 트랜잭션 밖에서 하며, claim과 결과를 따로 커밋한다.
@@ -34,6 +34,10 @@
- `ReconcileDeliveriesUseCase`는 묶음 안의 없는 attempt id를 그대로 건너뛴다.
- suppression·reconcile·provider 상태 연산은 남의 tenant 대상을 전처럼 `AdminAccessDeniedException`으로 거절한다.
authority가 없을 때의 답도 네 연산 모두 그대로다.
- 2026-11-23에 위 두 줄의 일부가 낡았다. reconcile의 없는 id와 남의 tenant attempt, suppression의 남의 tenant의 답과,
authority 없음의 응답(예외는 그대로 `AdminAccessDeniedException`, 이제 403)은
`docs/upgrade/2026-11-notification-admin-refusals.md` 2.1절이 대신한다. provider 상태 연산이 tenant 범위 운영자를
`AdminAccessDeniedException`으로 거절하는 것은 그대로다(이제 403).
- 오류 code 목록(`NotificationFailureCode`)과 템플릿 오류 code registry(`docs/registries/error-codes.yaml`)는 그대로다.
not-found 코드는 그 목록이 아니라 전송이 읽는 `NotificationAdminErrorCode`에 두었다. 새 예외의 descriptor는 있는
값(`VALIDATION_FAILED`, `INVALID_PAYLOAD`)이라 descriptor code와 응답 code가 다르다.
@@ -0,0 +1,63 @@
# 업그레이드 안내 — 2026-11 알림 운영자 연산의 거절
- 범위: 알림 운영자 연산 넷(`RedriveDeliveryUseCase`·`ReconcileDeliveriesUseCase`·`ChangeSuppressionUseCase`·
`ChangeProviderStateUseCase`)이 운영자 입력을 거절할 때 전송이 내는 답과, reconcile이 없는 attempt id와 남의 tenant
attempt를 다루는 규칙을 바꾼 변경. 설정 키는 그대로다. 공개 타입이
하나 늘었고(`AdminTargetNotFoundException`), 공개 메서드 `AdminAuthorizationGuard.requireTenant`의 인자가 하나 줄었다.
템플릿은 이 연산을 부르는 전송을 싣지 않는다. 알림 capability(`:composition:notification-platform`)를 싣고 이 연산에
전송(운영자 화면, admin endpoint)을 연 서비스만 해당한다.
- 근거: 2026-11-23 리뷰 발견 REV-BE-0058과 REV-BE-0059. 운영자 실수는 클라이언트 탓이라 carrier로 답하고, 남의 것은 없는 것과 같은 404로
답한다는 것은 `docs/manual/06-errors.md` 「판단: 어떤 예외 타입으로 던지나」와 `docs/manual/07-authorization.md`
「객체 단위 권한」이 이미 약속했다. 거절마다 status를 고른 것과 reconcile 묶음을 통째로 거절하는 것은 review 허브의
권하는 안이고 소유자 결정이 아니다
(`docs/work/reference/decisions.md` 2.3절).
## 1. 누가 읽나
이 템플릿을 `upstream` remote로 두고 merge해 받는 파생 서비스가 읽는다. 특히 알림 운영자 연산을 부르는 전송을 연 서비스다.
## 2. 바뀐 동작
### 2.1 2026-11-23 — 거절 다섯을 클라이언트 오류로, reconcile의 없는·남의 id를 404 하나로 (따라 할 일 있음)
거절마다 답하는 code다. code는 `application-notification`의 `NotificationAdminErrorCode`다.
| code | 거절 | 예외 | status | category | retryable |
| --- | --- | --- | --- | --- | --- |
| `ADMIN_ACCESS_DENIED` | 운영자에게 연산의 authority가 없다. 또는 tenant 범위 운영자가 provider 상태를 바꾸려 했다 | `AdminAccessDeniedException` | 403 | `AUTHZ` | false |
| `ADMIN_TARGET_NOT_FOUND` | suppression이 운영자 tenant 밖의 tenant를 골랐다 | `AdminTargetNotFoundException`(새 타입) | 404 | `NOT_FOUND` | false |
| `DUPLICATE_RISK_APPROVAL_REQUIRED` | 모호한 attempt의 redrive가 중복 위험 승인 없이 왔다 | `DuplicateRiskApprovalRequiredException` | 409 | `CONFLICT` | false |
| `ADMIN_OPERATION_CONFLICT` | operation id가 전에 다른 요청에 쓰였다 | 공개되지 않은 타입(`RuntimeException`) | 422 | `VALIDATION` | false |
| `ADMIN_OPERATION_IN_PROGRESS` | 같은 operation id·같은 요청을 다른 호출자가 아직 처리하고 있다 | 공개되지 않은 타입(`RuntimeException`) | 409 | `CONFLICT` | false |
| # | 바뀐 것 | 전에는 | 할 일 | 안 하면 | 해당 서비스 |
| --- | --- | --- | --- | --- | --- |
| 1 | 위 다섯 예외가 `ApiErrorCarrier`를 구현한다. 실패를 답하는 공용 처리기가 위 code로 답한다. web은 위 status와 error 본문(code·category·category별 고정 문구·retryable)이고, 서버 오류 로그와 span 오류를 남기지 않는다. 다섯 모두 retryable false라 `Retry-After` 헤더도 없다. GraphQL은 errors의 code가 위 code이고 category는 `AUTHORIZATION`(403)·`BUSINESS`(404·409)·`REQUEST`(422)다. 실패 자신이 carrier라서 등록 매핑보다 먼저 답한다. resolver observation은 전처럼 던진 예외를 오류로 센다(`graphql.outcome=ERROR`와 span 오류). gRPC는 `PERMISSION_DENIED`(403)·`NOT_FOUND`(404)·`ABORTED`(409)·`INVALID_ARGUMENT`(422)와 trailer `error-code`·`error-category`·`error-retryable`이고 서버 오류 로그를 남기지 않는다. STOMP `@MessageMapping`이 던진 실패는 전처럼 frame을 보내지 않고 ERROR 로그만 사라진다. 예외 타입·메시지·descriptor(알림 code 목록 값)는 그대로다 | carrier가 아니어서 공용 처리기가 서버 오류로 다뤘다. web은 500 `INTERNAL_ERROR`와 ERROR 로그·span 오류, gRPC는 `INTERNAL`, GraphQL은 이 타입(또는 상위 타입)을 등록한 매핑이 없으면 `INTERNAL_ERROR`였다. STOMP는 frame 없이 ERROR 로그를 남겼다. 운영자 실수가 5xx 경보를 울렸다 | 500·`INTERNAL`을 거절로 읽던 운영자 화면·모니터링을 위 code로 바꾼다. `ADMIN_OPERATION_IN_PROGRESS`는 기다렸다가 같은 요청을 다시 보낸다(첫 요청이 끝났으면 저장된 결과가 온다). claim에 만료가 없어서 provider 호출 중에 프로세스가 멈춘 reconcile의 id는 끝나지 않는다. 그래서 retryable이 false이고, 오래 가면 새 operation id로 보낸다. retryable을 보고 자동으로 다시 보내는 공용 재시도는 이 code를 다시 보내지 않는다. `ADMIN_OPERATION_CONFLICT`는 다시 보내지 않고 새 operation id를 쓴다. GraphQL에 `GraphQlExceptionResolver`로 이 예외나 상위 타입(`NotificationException`, `RuntimeException` 등)을 등록해 자기 code로 답하던 서비스는 그 매핑이 더 쓰이지 않는다(`docs/work/reference/decisions.md` 2.3절 「GraphQL 판정 순서」). 자기 code가 필요하면 이 예외를 감싼 자기 예외로 던지고 그 타입을 등록한다. web `@ExceptionHandler`와 이 예외를 직접 잡던 코드는 그대로 동작한다 | 운영자 화면이 이 code를 모르면 거절을 처리하지 못한다. 5xx만 세던 경보 규칙은 이 거절을 더 보지 않는다. GraphQL의 등록 매핑에 기대던 분기는 code가 바뀌어 깨진다 | 알림 운영자 연산 전송을 연 서비스 |
| 2 | suppression이 운영자 tenant 밖의 tenant를 고르면 `AdminTargetNotFoundException`이다. 이 예외는 상태를 싣지 않는다. 거절은 그 tenant의 어떤 것도 읽지 않아서, 답으로 그 tenant가 무엇을 가졌는지 알 수 없다 | `AdminAccessDeniedException`(`required()`는 `SUPPRESS`)이었다. 운영자에게 authority가 없을 때와 같은 예외였다 | 이 경우를 `AdminAccessDeniedException`으로 잡던 코드를 `AdminTargetNotFoundException`으로 바꾼다. `AdminAccessDeniedException`은 이제 authority가 없을 때와 tenant 범위 운영자의 provider 상태 변경에만 난다. 공용 처리기에 맡겼다면 고칠 코드는 없다(web 응답이 404로 바뀐다) | 그 catch가 이 예외를 놓쳐 공용 처리기로 간다. 서비스가 만든 거절 응답 대신 `ADMIN_TARGET_NOT_FOUND`(web은 404)가 나간다 | 알림 운영자 연산 전송을 연 서비스 |
| 3 | `AdminAuthorizationGuard.requireTenant(AdminActor, TenantId)`가 authority 인자를 받지 않는다. tenant 밖이면 `AdminTargetNotFoundException`을 던진다 | `requireTenant(AdminActor, TenantId, NotificationAdminAuthority)`가 그 authority를 실은 `AdminAccessDeniedException`을 던졌다 | 이 guard를 자기 연산에 쓰는 서비스는 셋째 인자를 지우고, 거절을 잡던 곳은 2행대로 바꾼다 | 컴파일이 실패한다 | 이 guard를 직접 부르는 서비스 |
| 4 | reconcile 묶음에 없는 attempt id나 운영자 tenant 밖의 attempt가 하나라도 있으면 provider를 부르기 전에 묶음 전체를 `DeliveryAttemptNotFoundException`(404 `DELIVERY_ATTEMPT_NOT_FOUND`, redrive와 같은 답)으로 거절한다. dry run도 같다. operation id를 claim하지 않고 audit도 남기지 않는다. 없는 id와 남의 tenant id가 같은 답이라 다른 tenant에 그 attempt가 있는지 알 수 없다. 통과한 묶음의 처리 수(`affected`)는 묶음의 id 수와 같다. 이 판정은 operation id claim보다 먼저라, 끝난 operation id를 다시 보내도(replay) 먼저 지난다. 그 사이 attempt가 지워졌으면 저장된 결과 대신 이 404다(redrive도 같다) | 없는 id는 건너뛰고도 처리 수에 셌다(dry run은 id 수를 그대로 답했다). 남의 tenant attempt는 `AdminAccessDeniedException(RECONCILE)`이라 web에서 500이었다. 그래서 tenant 범위 운영자가 id를 넣어 보는 것만으로 남의 tenant에 그 attempt가 있는지 알 수 있었다 | 보존 기간이 지나 지워진 attempt id를 섞어 보내던 운영자 도구는 그 id를 빼고 다시 보낸다. 답은 어느 id인지 알려 주지 않으니 묶음을 나눠 보내 찾는다. reconcile의 남의 tenant 거절을 `AdminAccessDeniedException`으로 잡던 코드는 `DeliveryAttemptNotFoundException`으로 바꾼다 | 지워진 id 하나가 묶음 전체를 막는다. 그 catch가 이 예외를 놓쳐 공용 처리기로 가고 `DELIVERY_ATTEMPT_NOT_FOUND`(web은 404)가 나간다 | 알림 운영자 연산 전송을 연 서비스 |
## 3. 바뀌지 않은 것
- redrive의 없는 attempt id와 남의 tenant attempt는 전처럼 404 `DELIVERY_ATTEMPT_NOT_FOUND`다
(`docs/upgrade/2026-11-notification-admin-redrive.md` 2.1절).
- authority는 대상을 읽기 전에 본다. 그래서 403은 대상에 대해 아무것도 알려 주지 않는다.
- reconcile 묶음에 같은 id를 두 번 넣으면 전처럼 그 id를 두 번 처리하고 두 번 센다.
- 같은 operation id·같은 요청은 전처럼 저장된 결과를 돌려준다.
- carrier가 아닌 실패는 공용 처리기가 전처럼 500으로 답한다(web `GlobalExceptionHandler`). 운영자 연산에서도 2.1절이 다루지
않은 거절은 그대로다. provider 상태 연산이 runtime이 받아들이지 않은 변경(`ProviderConfigurationException`)이나 없는 profile을
받으면 전처럼 500과 ERROR 로그다.
- 오류 code 목록(`NotificationFailureCode`)과 템플릿 오류 code registry(`docs/registries/error-codes.yaml`)는 그대로다.
응답 code는 전송이 읽는 `NotificationAdminErrorCode`에 두었다. 예외의 descriptor는 알림 code 목록 값이라
descriptor code와 응답 code가 다르다.
- 같은 operation id를 다른 요청에 쓴 거절이 409가 아니라 422인 것은 같은 멱등 키·다른 요청을 422로 답하는 규칙을
따랐다(`docs/manual/06-errors.md` 「판단: 어떤 예외 타입으로 던지나」). operation id가 이 연산의 멱등 키다.
## 4. 되돌리는 법
다섯 예외의 carrier 구현, `NotificationAdminErrorCode`의 다섯 행, `AdminTargetNotFoundException`, `requireTenant`의 인자,
reconcile의 묶음 판정, 문서와 API surface 기준선 행을 함께 revert하고, 이 문서에 되돌린 행을 더한다. operation id 재사용만 409로 바꾸려면
`ADMIN_OPERATION_CONFLICT`를 `(409, Category.CONFLICT, false)`로 바꾸고, 시험 행, 그 enum 상수와
`AdminOperationConflictException`의 Javadoc, 이 문서·`docs/web/http-contract.md` 4절·`docs/notification/operations.md`·
`docs/work/reference/decisions.md` 2.3절의 422를 409로 고친다. 진행 중을 retryable true로 바꾸려면 claim에 만료가 먼저
있어야 한다.
+9 -3
View File
@@ -15,7 +15,8 @@
- 헤더 규칙(3절): `WebMvcRequestIdFilterTest`, `CorsSecurityFilterIntegrationTest`
- web 전용 코드(4절): `TransportErrorHandlingTest`, `IdempotencyKeyHeaderTest`, web-advanced
`WebAdvancedErrorMappingTest`, 알림 기능 코드는 web-notification의 `NotificationAdminRefusalHttpAnswerTest`
(`DELIVERY_ATTEMPT_NOT_FOUND`)와 `NotificationSubmissionControllerTest`(`IDEMPOTENCY_CONFLICT`)
(운영자 연산 거절: `DELIVERY_ATTEMPT_NOT_FOUND`·`ADMIN_*`·`DUPLICATE_RISK_APPROVAL_REQUIRED`)와
`NotificationSubmissionControllerTest`(`IDEMPOTENCY_CONFLICT`)
## 1. Envelope 키 존재 규칙
@@ -191,7 +192,7 @@ CORS가 켜져 있으면(`app.cors.enabled=true`) cross-origin 실제 응답의
## 4. web 전용 오류 코드
`OperationalError`(`docs/registries/error-codes.yaml`) 밖의 코드다. HTTP 어댑터가 내는 코드와, 기능 leaf의 enum이 내고
HTTP가 그대로 답하는 코드(`DELIVERY_ATTEMPT_NOT_FOUND`, `IDEMPOTENCY_CONFLICT`)가 있다.
HTTP가 그대로 답하는 코드(알림 운영자 연산 거절, `IDEMPOTENCY_CONFLICT`)가 있다.
| 코드 | status | category | `retryable` | `Retry-After` | 언제 |
| --- | --- | --- | --- | --- | --- |
@@ -200,7 +201,12 @@ HTTP가 그대로 답하는 코드(`DELIVERY_ATTEMPT_NOT_FOUND`, `IDEMPOTENCY_CO
| `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`) |
| `DELIVERY_ATTEMPT_NOT_FOUND` | 404 | `NOT_FOUND` | `false` | 없음 | 알림 운영자 redrive(`RedriveDeliveryUseCase`)가 받은 attempt나 reconcile(`ReconcileDeliveriesUseCase`) 묶음의 attempt 하나가 없거나 운영자 tenant 밖이다. 둘을 가르지 않는다. reconcile은 provider를 부르기 전에 묶음 전체를 거절한다. 코드는 `application-notification`의 `NotificationAdminErrorCode`라 실패를 답하는 전송(web·GraphQL·gRPC)이 같은 코드로 답한다. 템플릿은 이 연산의 전송을 싣지 않는다(`docs/notification/operations.md`) |
| `ADMIN_ACCESS_DENIED` | 403 | `AUTHZ` | `false` | 없음 | 알림 운영자 연산에서 운영자에게 그 연산의 authority가 없거나, tenant 범위 운영자가 provider 상태를 바꾸려 했다. authority는 대상을 읽기 전에 보므로 대상에 대해 알려 주지 않는다. 코드는 `application-notification`의 `NotificationAdminErrorCode`다(아래 운영자 연산 행 모두 같다). 템플릿은 이 연산의 전송을 싣지 않는다(`docs/notification/operations.md`) |
| `ADMIN_TARGET_NOT_FOUND` | 404 | `NOT_FOUND` | `false` | 없음 | 알림 운영자 suppression이 운영자 tenant 밖의 tenant를 골랐다. 권한 거절(403)이 아니라 없는 대상과 같은 404라 그 tenant가 무엇을 가졌는지 알려 주지 않는다 |
| `DUPLICATE_RISK_APPROVAL_REQUIRED` | 409 | `CONFLICT` | `false` | 없음 | 이미 사용자에게 닿았을 수 있는 attempt의 redrive가 중복 위험 승인 없이 왔다. 같은 요청은 다시 거절된다. 승인을 붙여 보낸다 |
| `ADMIN_OPERATION_CONFLICT` | 422 | `VALIDATION` | `false` | 없음 | 알림 운영자 연산의 operation id(그 연산의 멱등 키)가 전에 다른 요청에 쓰였다. 같은 멱등 키·다른 요청이라 409가 아니다(`docs/manual/06-errors.md`). 새 operation id를 쓴다 |
| `ADMIN_OPERATION_IN_PROGRESS` | 409 | `CONFLICT` | `false` | 없음 | 같은 operation id·같은 요청을 다른 호출자가 아직 처리하고 있다. 기다렸다가 같은 요청을 다시 보내면 끝난 결과가 온다. 다만 claim에 만료가 없어서 provider 호출 중에 프로세스가 멈춘 reconcile의 id는 끝나지 않는다. 그래서 2절의 `IDEMPOTENT_IN_FLIGHT`(lease가 지나면 409가 끝난다)와 달리 retryable이 `false`이고 `Retry-After`도 없다. 오래 가면 새 operation id를 쓴다 |
| `IDEMPOTENCY_CONFLICT` | 422 | `VALIDATION` | `false` | 없음 | 알림 제출(`POST /notifications`)이 본문의 `idempotencyKey`를 이미 다른 알림에 쓴 키로 받았다. 견주는 것은 본문이 아니라 알림 plan 지문이다. 2절의 `Idempotency-Key` 헤더와는 다른 키라 `IDEMPOTENT_REQUEST_MISMATCH`가 아니다. 다시 보내지 않는다. 새 알림이면 새 키를 쓴다. 코드는 `application-notification`의 `NotificationSubmissionErrorCode`라 실패를 답하는 전송(web·GraphQL·gRPC)이 같은 코드로 답한다(`docs/manual/05-idempotency.md` 「executor를 쓰지 않는 중복 판정 둘」) |
- 컨트롤러 파라미터 제약 위반(`@RequestParam @Max(10)`)은 요청 본문 위반과 같은
+3 -1
View File
@@ -111,8 +111,10 @@
| 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절 |
| 알림 redrive의 없는·남의 attempt | 없는 attempt id와 운영자 tenant 밖의 attempt를 같은 404 carrier(`DeliveryAttemptNotFoundException`, code `DELIVERY_ATTEMPT_NOT_FOUND`) 하나로 답한다. 권한 거절(403)로 바꾸는 안과 문서만 500으로 고치는 안은 버렸다. 알림 code 목록(`NotificationFailureCode`)과 템플릿 registry는 넓히지 않는다. 다른 운영자 연산의 tenant 거절은 그대로다(2026-11-23에 아래 「알림 운영자 연산의 거절」·「알림 reconcile의 없는·남의 attempt」 행이 바꿨다) | 기본값(2026-11-22, review 허브가 고른 권하는 안, 자율 운영. 소유자가 정한 것이 아니고 뒤집을 수 있다) | review 허브 REV-BE-0039 정정(2026-11-22 12:51), `docs/upgrade/2026-11-notification-admin-redrive.md` 2.1절 |
| 알림 제출의 같은 키·다른 plan | 알림 제출이 이미 다른 plan에 쓴 `idempotencyKey`를 받으면 422 carrier(`IdempotencyConflictException`, code `IDEMPOTENCY_CONFLICT`, category `VALIDATION`, retryable false)로 답한다. code는 기능 enum `NotificationSubmissionErrorCode`에 둔다. executor의 `IDEMPOTENT_REQUEST_MISMATCH`를 다시 쓰는 안과 web-notification에만 처리기를 두는 안은 버렸다. `NotificationException` 전체를 carrier로 만들지 않는다(서버 쪽 실패까지 4xx가 된다). 알림 code 목록(`NotificationFailureCode`)과 템플릿 registry는 넓히지 않는다 | 기본값(2026-11-22, review 허브가 고른 권하는 안, 자율 운영. 소유자가 정한 것이 아니고 뒤집을 수 있다) | review 허브 REV-BE-0054 요청(2026-11-22 12:58), `docs/upgrade/2026-11-notification-idempotency-conflict.md` 2.1절 |
| 알림 운영자 연산의 거절 | 운영자 입력 거절 다섯을 carrier로 답한다. code는 기능 enum `NotificationAdminErrorCode`다: authority 없음 403 `ADMIN_ACCESS_DENIED`, suppression의 tenant 밖 대상 404 `ADMIN_TARGET_NOT_FOUND`(권한 거절이 아니라 없는 대상과 같은 답), 중복 위험 승인 없음 409 `DUPLICATE_RISK_APPROVAL_REQUIRED`, operation id 재사용 422 `ADMIN_OPERATION_CONFLICT`, 같은 id 진행 중 409 `ADMIN_OPERATION_IN_PROGRESS`(retryable false, `Retry-After` 없음: claim에 만료가 없어 provider 호출 중 멈춘 reconcile의 id는 끝나지 않는다. 다시 보내도 되는지는 code가 알린다). 요청의 표는 재사용을 409로 적었지만, 같은 멱등 키·다른 요청은 422라는 `docs/manual/06-errors.md` 판단 표와 executor 선례(`IDEMPOTENT_REQUEST_MISMATCH`)를 따라 422로 했다. 문서만 500으로 고치는 안과 web 처리기에서 이름으로 잡는 안은 버렸다. 알림 code 목록(`NotificationFailureCode`)과 템플릿 registry는 넓히지 않는다 | 기본값(2026-11-23, review 허브가 고른 권하는 안, 자율 운영. 422는 백엔드 개발자가 매뉴얼에 맞췄고 review가 2026-11-23에 확정했다(요청 표가 판단 표보다 먼저 쓰였다). 소유자가 정한 것이 아니고 뒤집을 수 있다) | review 허브 REV-BE-0058 요청(2026-11-23 09:40), `docs/upgrade/2026-11-notification-admin-refusals.md` 2.1절 |
| 알림 reconcile의 없는·남의 attempt | reconcile 묶음에 없는 attempt id나 운영자 tenant 밖의 attempt가 하나라도 있으면 provider를 부르기 전에 묶음 전체를 redrive와 같은 404 carrier(`DeliveryAttemptNotFoundException`)로 거절한다. dry run도 같다. 처리 수는 묶음의 id 수다. 대가로 보존 기간이 지나 지워진 id가 섞인 묶음도 거절된다. 없는 id와 남의 id를 둘 다 건너뛰고 있는 것만 세는 안(「남의 id가 있으면 아무것도 안 바꾼다」가 깨지고 오타가 성공으로 보인다)과 지금대로 두는 안(존재가 드러난다)은 버렸다 | 기본값(2026-11-23, review 허브가 고른 권하는 안, 자율 운영. 소유자가 정한 것이 아니고 뒤집을 수 있다) | review 허브 REV-BE-0059 요청(2026-11-23 09:40), `docs/upgrade/2026-11-notification-admin-refusals.md` 2.1절 4행 |
| 오류 코드 로그 레벨 | `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 총괄 세션 전달 |
@@ -6,41 +6,74 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
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.ChangeSuppressionCommand;
import dev.caskeleton.application.notification.platform.admin.ChangeSuppressionUseCase;
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.ReconcileDeliveriesCommand;
import dev.caskeleton.application.notification.platform.admin.ReconcileDeliveriesUseCase;
import dev.caskeleton.application.notification.platform.admin.ReconcileRequest;
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.SuppressionRequest;
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.callback.DeliveryAttemptSnapshot;
import dev.caskeleton.application.notification.platform.callback.ProviderEventProjectionService;
import dev.caskeleton.application.notification.platform.callback.StandardDeliveryProjector;
import dev.caskeleton.application.notification.platform.callback.testkit.InMemoryProviderEventLedger;
import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestRecord;
import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryRecord;
import dev.caskeleton.application.notification.platform.dispatch.ReconciliationGatewayPort;
import dev.caskeleton.application.notification.platform.dispatch.ReconciliationService;
import dev.caskeleton.application.notification.platform.dispatch.SuppressionSideEffect;
import dev.caskeleton.application.notification.platform.dispatch.SyntheticEventFingerprint;
import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryContactPointStore;
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.dispatch.testkit.Sha256ProviderRequestIdHasher;
import dev.caskeleton.application.notification.platform.observation.NotificationMetricsPort;
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.ReconciliationResult;
import dev.caskeleton.application.transaction.testkit.DirectTransactionPort;
import dev.caskeleton.shared.error.Category;
import dev.caskeleton.shared.error.ClientErrorMessages;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.slf4j.LoggerFactory;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MockMvc;
@@ -51,41 +84,78 @@ 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.
* What an HTTP caller sees when a notification operator operation refuses a request.
*
* <p>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.
* would write: it hands the command to the real use cases over the notification fakes and lets the
* failure reach the real {@link GlobalExceptionHandler}. The use cases' own tables (claims, audit,
* provider calls) are {@code NotificationAdminUseCasesTest}; this one is the answer on the wire.
*
* <p>Every refusal here answers the operator's own input — a missing authority, a target out of
* reach, an unapproved duplicate risk, a reused or busy operation id — so none is answered or
* recorded as a server failure.
*/
class NotificationAdminRefusalHttpAnswerTest {
private static final Clock CLOCK =
Clock.fixed(Instant.parse("2026-11-23T00:00:00Z"), ZoneOffset.UTC);
private static final TenantId TENANT_A = new TenantId("tenant-a");
private static final TenantId TENANT_B = new TenantId("tenant-b");
private static final AdminActor TENANT_B_OPERATOR =
new AdminActor(
"operator-b",
Set.of(NotificationAdminAuthority.REDRIVE),
Optional.of(new TenantId("tenant-b")));
EnumSet.of(
NotificationAdminAuthority.REDRIVE,
NotificationAdminAuthority.RECONCILE,
NotificationAdminAuthority.SUPPRESS),
Optional.of(TENANT_B));
private static final String UNKNOWN_ATTEMPT = "00000000-0000-7000-8000-000000000099";
// A body without a field reads as null, so a success answer fails the comparison by its values.
private static final Configuration LENIENT_JSON =
Configuration.defaultConfiguration().addOptions(Option.SUPPRESS_EXCEPTIONS);
private static final String ANSWER_FIELDS =
"[status, success, error code, category, message, retryable, Retry-After, handler log lines,"
+ " span error codes]";
private final InMemoryNotificationRequestStore requests = new InMemoryNotificationRequestStore();
private final InMemoryDeliveryAttemptStore attempts = new InMemoryDeliveryAttemptStore(requests);
private final InMemoryRecipientQueue recipients = new InMemoryRecipientQueue(requests, CLOCK);
private final InMemoryAdminOperationStore operations = new InMemoryAdminOperationStore();
private final RecordingNotificationAudit audit = new RecordingNotificationAudit();
private final DirectTransactionPort transactions = new DirectTransactionPort();
private final List<String> spanErrorCodes = new ArrayList<>();
private final AtomicInteger providerCalls = new AtomicInteger();
private ProviderCall duringProviderCall = () -> {};
private AdminActor actor = TENANT_B_OPERATOR;
private final MockMvc mvc =
MockMvcBuilders.standaloneSetup(
new RedriveProbe(
new OperatorProbe(
new RedriveDeliveryUseCase(
new AdminAuthorizationGuard(),
new DuplicateRiskGuard(),
attempts,
new InMemoryRecipientQueue(requests, CLOCK),
new InMemoryAdminOperationStore(),
recipients,
operations,
audit,
new DirectTransactionPort(),
CLOCK)))
transactions,
CLOCK),
new ReconcileDeliveriesUseCase(
new AdminAuthorizationGuard(),
attempts,
reconciliation(),
operations,
audit,
transactions,
CLOCK),
new ChangeSuppressionUseCase(
new AdminAuthorizationGuard(),
new InMemorySuppressionStore(),
operations,
audit,
transactions,
UUID::randomUUID,
CLOCK),
() -> actor))
.setControllerAdvice(
new GlobalExceptionHandler((error, code) -> spanErrorCodes.add(code)))
.build();
@@ -100,58 +170,218 @@ class NotificationAdminRefusalHttpAnswerTest {
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<ILoggingEvent> handlerLog = new ListAppender<>();
handlerLog.start();
handlerLogger.addAppender(handlerLog);
String attemptId = "foreign".equals(target) ? storedAttemptOf(TENANT_A) : UNKNOWN_ATTEMPT;
// 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();
}
List<Object> answer =
answerRecordingServerFailures(
() -> redrive(attemptId, "op-rd-http", "provider outage", true, dryRun));
// then
String body = response.getContentAsString();
assertThat(
List.<Object>of(
response.getStatus(),
JsonPath.<Boolean>read(body, "$.success"),
JsonPath.<String>read(body, "$.error.code"),
JsonPath.<String>read(body, "$.error.category"),
JsonPath.<String>read(body, "$.error.message"),
JsonPath.<Boolean>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]")
assertThat(List.of(answer, audit.events().size()))
.as("[%s, audit events]", ANSWER_FIELDS)
.containsExactly(notFound(NotificationAdminErrorCode.DELIVERY_ATTEMPT_NOT_FOUND.code()), 0);
}
/**
* One reconcile batch beside an attempt of the operator's own tenant names an id no attempt has,
* or an attempt of another tenant. Both refuse the whole batch with the answer a redrive gives,
* before any provider is asked, so the answer does not tell which ids exist elsewhere.
*/
@ParameterizedTest(name = "{0} attempt beside an own one, dryRun={1}")
@CsvSource({"unknown, false", "unknown, true", "foreign, false", "foreign, true"})
void aReconcileNamingAnUnreachableAttemptAnswersOneNotFoundForTheWholeBatch(
String target, boolean dryRun) throws Exception {
// given
String ownAttempt = storedAttemptOf(TENANT_B);
String unreachable = "foreign".equals(target) ? storedAttemptOf(TENANT_A) : UNKNOWN_ATTEMPT;
// when
List<Object> answer =
answerRecordingServerFailures(
() -> reconcile(List.of(ownAttempt, unreachable), dryRun, "op-rc-http"));
// then
assertThat(List.of(answer, providerCalls.get(), audit.events().size()))
.as("[%s, provider calls, audit events]", ANSWER_FIELDS)
.containsExactly(
404,
notFound(NotificationAdminErrorCode.DELIVERY_ATTEMPT_NOT_FOUND.code()), 0, 0);
}
/**
* Each refusal answers its own status and code with the category's fixed message, and the handler
* records none as a server failure. A missing authority (403) and a target outside the operator's
* tenant (404) are different answers. None is retryable: a busy operation id may never be
* released, so it is the code, not the flag, that tells an operator to send it again later.
*/
@ParameterizedTest(name = "{0}")
@MethodSource("refusals")
void eachOperatorRefusalAnswersItsOwnClientErrorAndRecordsNoServerFailure(Refusal refusal)
throws Exception {
// given
String ownAttempt = storedAttemptOf(TENANT_B);
// when
List<Object> answer = answerRecordingServerFailures(() -> refusal.send(this, ownAttempt));
// then
assertThat(answer)
.as(ANSWER_FIELDS)
.containsExactly(
refusal.status(),
false,
"DELIVERY_ATTEMPT_NOT_FOUND",
"NOT_FOUND",
ClientErrorMessages.of(NotificationAdminErrorCode.DELIVERY_ATTEMPT_NOT_FOUND),
false,
0,
refusal.code(),
refusal.category().name(),
ClientErrorMessages.of(refusal.category()),
refusal.retryable(),
null,
0,
List.of());
}
/** Stores a FAILED delivery of tenant-a and its attempt, and returns the attempt id. */
private String storedAttemptOfTenantA() {
private static Stream<Refusal> refusals() {
return Stream.of(
new Refusal(
"an operator without the authority",
(test, attempt) -> {
test.actor =
new AdminActor(
"operator-b",
EnumSet.complementOf(EnumSet.of(NotificationAdminAuthority.REDRIVE)),
Optional.of(TENANT_B));
return test.redrive(attempt, "op-no-authority", "provider outage", true, false);
},
403,
"ADMIN_ACCESS_DENIED",
Category.AUTHZ,
false),
new Refusal(
"a suppression in another tenant",
(test, attempt) -> test.suppress(TENANT_A),
404,
"ADMIN_TARGET_NOT_FOUND",
Category.NOT_FOUND,
false),
new Refusal(
"a redrive of an ambiguous attempt without the duplicate-risk approval",
(test, attempt) ->
test.redrive(attempt, "op-unapproved", "provider outage", false, false),
409,
"DUPLICATE_RISK_APPROVAL_REQUIRED",
Category.CONFLICT,
false),
new Refusal(
"an operation id reused for another request",
(test, attempt) -> {
test.redrive(attempt, "op-reused", "provider outage", true, false);
return test.redrive(attempt, "op-reused", "another reason", true, false);
},
422,
"ADMIN_OPERATION_CONFLICT",
Category.VALIDATION,
false),
new Refusal(
"an operation id another caller still holds",
(test, attempt) -> test.reconcileAgainWhileItsProviderCallRuns(attempt),
409,
"ADMIN_OPERATION_IN_PROGRESS",
Category.CONFLICT,
false));
}
/** The answer of a 404 with {@code code}, recorded as no server failure. */
private static List<Object> notFound(String code) {
return Arrays.asList(
404,
false,
code,
Category.NOT_FOUND.name(),
ClientErrorMessages.of(Category.NOT_FOUND),
false,
null,
0,
List.of());
}
/**
* Sends a reconcile and, while its provider call runs — the operation id claimed, no result yet —
* sends the same request again, as a second operator would. Returns the second answer.
*/
private MockHttpServletResponse reconcileAgainWhileItsProviderCallRuns(String attemptId)
throws Exception {
AtomicReference<MockHttpServletResponse> second = new AtomicReference<>();
duringProviderCall = () -> second.set(reconcile(List.of(attemptId), false, "op-held"));
reconcile(List.of(attemptId), false, "op-held");
return second.get();
}
/**
* The wire answer of what {@code send} sent — status, the envelope's success and error fields,
* the {@code Retry-After} header — followed by what the handler recorded as a server failure: its
* log lines and span error codes.
*/
private List<Object> answerRecordingServerFailures(Request send) throws Exception {
Logger handlerLogger = (Logger) LoggerFactory.getLogger(GlobalExceptionHandler.class);
ListAppender<ILoggingEvent> handlerLog = new ListAppender<>();
handlerLog.start();
handlerLogger.addAppender(handlerLog);
MockHttpServletResponse response;
try {
response = send.send();
} finally {
handlerLogger.detachAppender(handlerLog);
handlerLog.stop();
}
DocumentContext body = JsonPath.using(LENIENT_JSON).parse(response.getContentAsString());
return Arrays.asList(
response.getStatus(),
body.read("$.success"),
body.read("$.error.code"),
body.read("$.error.category"),
body.read("$.error.message"),
body.read("$.error.retryable"),
response.getHeader("Retry-After"),
handlerLog.list.size(),
List.copyOf(spanErrorCodes));
}
private MockHttpServletResponse redrive(
String attemptId, String operationId, String reason, boolean approve, boolean dryRun)
throws Exception {
return mvc.perform(
post("/operator/redrives/{attemptId}", attemptId)
.param("operationId", operationId)
.param("reason", reason)
.param("approveDuplicateRisk", String.valueOf(approve))
.param("dryRun", String.valueOf(dryRun)))
.andReturn()
.getResponse();
}
private MockHttpServletResponse reconcile(
List<String> attemptIds, boolean dryRun, String operationId) throws Exception {
return mvc.perform(
post("/operator/reconciliations")
.param("attemptId", attemptIds.toArray(String[]::new))
.param("operationId", operationId)
.param("dryRun", String.valueOf(dryRun)))
.andReturn()
.getResponse();
}
private MockHttpServletResponse suppress(TenantId tenantId) throws Exception {
return mvc.perform(post("/operator/suppressions/{tenantId}", tenantId.value()))
.andReturn()
.getResponse();
}
/**
* Stores a FAILED delivery of {@code tenantId} and its attempt, ambiguous as a dispatching
* attempt is, and returns the attempt id.
*/
private String storedAttemptOf(TenantId tenantId) {
NotificationRequestRecord request =
NotificationRows.request(new TenantId("tenant-a"), "idem-a", CLOCK.instant());
NotificationRows.request(tenantId, "idem-" + tenantId.value(), CLOCK.instant());
RecipientDeliveryRecord job =
NotificationRows.job(
request,
@@ -173,28 +403,167 @@ class NotificationAdminRefusalHttpAnswerTest {
.toString();
}
/** The operator transport a service would write, as a tenant-b operator. */
/**
* Reconciliation over the test's stores. Its provider answers every attempt unsupported, counts
* the calls, and runs {@link #duringProviderCall} inside each one.
*/
private ReconciliationService reconciliation() {
NotificationMetricsPort metrics =
new NotificationMetricsPort() {
@Override
public void increment(String metricName, Map<String, String> tags) {}
@Override
public void record(String metricName, Map<String, String> tags, Duration value) {}
@Override
public void gauge(String metricName, Map<String, String> tags, double value) {}
};
InMemoryProviderEventLedger ledger =
new InMemoryProviderEventLedger(attempts, new Sha256ProviderRequestIdHasher());
return new ReconciliationService(
attempts,
recipients,
new ReconciliationGatewayPort() {
@Override
public boolean supports(ProviderProfileId profileId) {
return true;
}
@Override
public ReconciliationResult reconcile(DeliveryAttemptSnapshot attempt) {
providerCalls.incrementAndGet();
try {
duringProviderCall.run();
} catch (Exception failure) {
throw new IllegalStateException("the request sent during the provider call", failure);
}
return new ReconciliationResult.Unsupported();
}
},
ledger,
new ProviderEventProjectionService(
ledger,
new StandardDeliveryProjector(),
attempts,
attempts,
new SuppressionSideEffect(
new InMemoryContactPointStore(CLOCK),
new InMemorySuppressionStore(),
UUID::randomUUID,
CLOCK),
transactions,
metrics),
audit,
metrics,
new SyntheticEventFingerprint(),
transactions,
CLOCK);
}
/** A request this test sends. */
@FunctionalInterface
private interface Request {
MockHttpServletResponse send() throws Exception;
}
/** What the provider does while it is asked. */
@FunctionalInterface
private interface ProviderCall {
void run() throws Exception;
}
/** One refusal: how to send it, given an attempt of the operator's tenant, and its answer. */
private record Refusal(
String name, Sender sender, int status, String code, Category category, boolean retryable) {
MockHttpServletResponse send(NotificationAdminRefusalHttpAnswerTest test, String attemptId)
throws Exception {
return sender.send(test, attemptId);
}
@Override
public String toString() {
return name;
}
}
@FunctionalInterface
private interface Sender {
MockHttpServletResponse send(NotificationAdminRefusalHttpAnswerTest test, String attemptId)
throws Exception;
}
/** The operator transport a service would write, acting as the test's current actor. */
@RestController
static final class RedriveProbe {
static final class OperatorProbe {
private final RedriveDeliveryUseCase redrive;
private final ReconcileDeliveriesUseCase reconcile;
private final ChangeSuppressionUseCase suppression;
private final Supplier<AdminActor> actor;
RedriveProbe(RedriveDeliveryUseCase redrive) {
OperatorProbe(
RedriveDeliveryUseCase redrive,
ReconcileDeliveriesUseCase reconcile,
ChangeSuppressionUseCase suppression,
Supplier<AdminActor> actor) {
this.redrive = redrive;
this.reconcile = reconcile;
this.suppression = suppression;
this.actor = actor;
}
@PostMapping("/operator/redrives/{attemptId}")
String redrive(
@PathVariable("attemptId") String attemptId, @RequestParam("dryRun") boolean dryRun) {
Map<String, Integer> redrive(
@PathVariable("attemptId") String attemptId,
@RequestParam("operationId") String operationId,
@RequestParam("reason") String reason,
@RequestParam("approveDuplicateRisk") boolean approve,
@RequestParam("dryRun") boolean dryRun) {
RedriveRequest request =
new RedriveRequest(
"op-rd-http",
operationId,
new DeliveryAttemptId(UUID.fromString(attemptId)),
"provider outage",
true,
reason,
approve,
dryRun);
redrive.handle(new RedriveDeliveryCommand(request, TENANT_B_OPERATOR));
return "redriven";
return Map.of(
"affected", redrive.handle(new RedriveDeliveryCommand(request, actor.get())).affected());
}
@PostMapping("/operator/reconciliations")
Map<String, Integer> reconcile(
@RequestParam("attemptId") List<String> attemptIds,
@RequestParam("operationId") String operationId,
@RequestParam("dryRun") boolean dryRun) {
ReconcileRequest request =
new ReconcileRequest(
operationId,
attemptIds.stream().map(id -> new DeliveryAttemptId(UUID.fromString(id))).toList(),
"stuck attempt",
dryRun);
return Map.of(
"affected",
reconcile.handle(new ReconcileDeliveriesCommand(request, actor.get())).affected());
}
@PostMapping("/operator/suppressions/{tenantId}")
Map<String, Integer> suppress(@PathVariable("tenantId") String tenantId) {
SuppressionRequest request =
new SuppressionRequest(
"op-s-http",
new TenantId(tenantId),
SuppressionScope.CONTACT_POINT,
SuppressionReason.ADMIN_BLOCK,
"c".repeat(64),
Optional.empty(),
false,
"reported abuse",
false);
return Map.of(
"affected",
suppression.handle(new ChangeSuppressionCommand(request, actor.get())).affected());
}
}
}
@@ -4,16 +4,24 @@ import dev.caskeleton.application.notification.platform.api.error.FailureCategor
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 an operator action is refused: the actor lacks the authority, or the target is
* outside the actor's tenant scope.
* Raised when an operator action is refused for the actor: it lacks the authority the action
* exercises, or the action changes state every tenant shares and the actor is bound to one tenant.
*
* <p>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.
* <p>The actor is the caller, so this is the caller's failure, not a server fault: a transport
* answers {@link NotificationAdminErrorCode#ADMIN_ACCESS_DENIED} (403) and logs no server failure.
* The authority is checked before any target is read, so the refusal says nothing about targets. A
* target outside the actor's tenant is a different answer, the one a missing target gets: {@link
* AdminTargetNotFoundException} for a suppression's tenant, {@link
* DeliveryAttemptNotFoundException} for an attempt a redrive or a reconcile batch names.
*
* <p>The {@linkplain #descriptor() descriptor} keeps the closed notification registry ({@code
* VALIDATION_FAILED}, {@code AUTHORIZATION}); the code on the wire is {@link #errorCode()}.
*/
public class AdminAccessDeniedException extends NotificationException {
public class AdminAccessDeniedException extends NotificationException implements ApiErrorCarrier {
private static final long serialVersionUID = 1L;
@@ -30,4 +38,9 @@ public class AdminAccessDeniedException extends NotificationException {
public NotificationAdminAuthority required() {
return required;
}
@Override
public ApiErrorCode errorCode() {
return NotificationAdminErrorCode.ADMIN_ACCESS_DENIED;
}
}
@@ -31,18 +31,17 @@ public final class AdminAuthorizationGuard {
}
/**
* Require that the actor may act on a tenant.
* Require that the actor may act on a tenant, or answer the tenant as a target that does not
* exist.
*
* <p>An actor with no tenant is a global operator; one bound to a tenant may only act inside it.
*
* @param authority the authority being exercised, which the refusal names; it used to name {@code
* SUPPRESS} whatever the operation was
* Another tenant is refused with {@link AdminTargetNotFoundException} (404), not as missing
* authority: the actor may hold the authority, and the answer must not tell what another tenant
* holds.
*/
public void requireTenant(
AdminActor actor, TenantId tenantId, NotificationAdminAuthority authority) {
Objects.requireNonNull(authority, "authority");
public void requireTenant(AdminActor actor, TenantId tenantId) {
if (!mayActOn(actor, tenantId)) {
throw new AdminAccessDeniedException(authority);
throw new AdminTargetNotFoundException();
}
}
@@ -50,8 +49,8 @@ public final class AdminAuthorizationGuard {
* Whether the actor's tenant scope covers a tenant: a global operator's covers every tenant, a
* tenant-bound one's only its own.
*
* <p>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.
* <p>For an operation that reads its target first and answers one outside the scope as it answers
* one that does not exist, with its own not-found exception.
*/
public boolean mayActOn(AdminActor actor, TenantId tenantId) {
Objects.requireNonNull(actor, "actor");
@@ -1,11 +1,25 @@
package dev.caskeleton.application.notification.platform.admin;
/** One admin operation id was reused for a different command. */
final class AdminOperationConflictException extends RuntimeException {
import dev.caskeleton.shared.error.ApiErrorCarrier;
import dev.caskeleton.shared.error.ApiErrorCode;
/**
* One admin operation id was reused for a different command.
*
* <p>The operation id is the operator's idempotency key, so this is the caller's mistake, not a
* server fault: a transport answers {@link NotificationAdminErrorCode#ADMIN_OPERATION_CONFLICT}
* (422) and logs no server failure.
*/
final class AdminOperationConflictException extends RuntimeException implements ApiErrorCarrier {
private static final long serialVersionUID = 1L;
AdminOperationConflictException(String operationId) {
super("admin operation id was reused for a different command: " + operationId);
}
@Override
public ApiErrorCode errorCode() {
return NotificationAdminErrorCode.ADMIN_OPERATION_CONFLICT;
}
}
@@ -1,11 +1,26 @@
package dev.caskeleton.application.notification.platform.admin;
/** The same admin operation id is currently held by another caller. */
final class AdminOperationInProgressException extends RuntimeException {
import dev.caskeleton.shared.error.ApiErrorCarrier;
import dev.caskeleton.shared.error.ApiErrorCode;
/**
* The same admin operation id is currently held by another caller.
*
* <p>Nothing is wrong with the request, it arrived while the first one runs: a transport answers
* {@link NotificationAdminErrorCode#ADMIN_OPERATION_IN_PROGRESS} (409) and logs no server failure.
* The same request sent again after the first finishes answers its stored result. The code is not
* retryable, because an id whose holder stopped stays held (see the code).
*/
final class AdminOperationInProgressException extends RuntimeException implements ApiErrorCarrier {
private static final long serialVersionUID = 1L;
AdminOperationInProgressException(String operationId) {
super("admin operation is already in progress: " + operationId);
}
@Override
public ApiErrorCode errorCode() {
return NotificationAdminErrorCode.ADMIN_OPERATION_IN_PROGRESS;
}
}
@@ -0,0 +1,38 @@
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 an operator action names a tenant outside the actor's tenant scope, such as a
* tenant-bound operator adding or lifting a suppression of another tenant.
*
* <p>The tenant is the operator's input, so this is the caller's failure, not a server fault: a
* transport answers {@link NotificationAdminErrorCode#ADMIN_TARGET_NOT_FOUND} (404) and logs no
* server failure. The refusal reads nothing of the named tenant and holds no state of its own, so
* neither the answer nor the exception tells what that tenant holds, or that it exists.
*
* <p>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 AdminTargetNotFoundException extends NotificationException
implements ApiErrorCarrier {
private static final long serialVersionUID = 1L;
public AdminTargetNotFoundException() {
super(
NotificationFailureDescriptor.preDispatch(
NotificationFailureCode.VALIDATION_FAILED, FailureCategory.INVALID_PAYLOAD));
}
@Override
public ApiErrorCode errorCode() {
return NotificationAdminErrorCode.ADMIN_TARGET_NOT_FOUND;
}
}
@@ -73,7 +73,7 @@ public class ChangeSuppressionUseCase
SuppressionRequest request = change.request();
AdminActor actor = change.actor();
authorization.require(actor, NotificationAdminAuthority.SUPPRESS);
authorization.requireTenant(actor, request.tenantId(), NotificationAdminAuthority.SUPPRESS);
authorization.requireTenant(actor, request.tenantId());
if (request.dryRun()) {
return new AdminOperationResult(
@@ -8,10 +8,11 @@ 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.
* Raised when a redrive, or any id of a reconcile batch, 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. A reconcile batch is refused whole,
* before any provider is asked.
*
* <p>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
@@ -4,13 +4,22 @@ import dev.caskeleton.application.notification.platform.api.error.FailureCategor
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 an operator tries to redrive an ambiguous attempt without accepting the duplicate
* risk. The platform cannot tell whether the first submission reached the user, so the decision has
* to be recorded as a human one.
*
* <p>The request conflicts with the attempt's state, which the operator can resolve by approving: a
* transport answers {@link NotificationAdminErrorCode#DUPLICATE_RISK_APPROVAL_REQUIRED} (409) and
* logs no server failure. The {@linkplain #descriptor() descriptor} keeps the closed notification
* registry ({@code VALIDATION_FAILED}, {@code AMBIGUOUS_SUBMISSION}); the code on the wire is
* {@link #errorCode()}.
*/
public class DuplicateRiskApprovalRequiredException extends NotificationException {
public class DuplicateRiskApprovalRequiredException extends NotificationException
implements ApiErrorCarrier {
private static final long serialVersionUID = 1L;
@@ -19,4 +28,9 @@ public class DuplicateRiskApprovalRequiredException extends NotificationExceptio
NotificationFailureDescriptor.preDispatch(
NotificationFailureCode.VALIDATION_FAILED, FailureCategory.AMBIGUOUS_SUBMISSION));
}
@Override
public ApiErrorCode errorCode() {
return NotificationAdminErrorCode.DUPLICATE_RISK_APPROVAL_REQUIRED;
}
}
@@ -6,17 +6,58 @@ import dev.caskeleton.shared.error.Category;
/**
* Codes the notification operator operations answer a transport with.
*
* <p>Each refusal below is the operator's own input — an authority they do not hold, a target out
* of their reach, an unapproved duplicate risk, a reused or busy operation id — so each is a client
* error, not a server fault. A refusal with no code here, such as a provider state change the
* runtime does not accept, is still answered as a server failure.
*
* <p>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.
* tags, ledger rows, audit — and has no code for most of these. A transport answers with this code
* instead, read through {@link dev.caskeleton.shared.error.ApiErrorCarrier}, so each transport that
* answers a failure (web, GraphQL, gRPC) answers the same code 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.
* The operator lacks the authority the operation exercises, or the operation changes state every
* tenant shares and the operator is bound to one tenant.
*/
DELIVERY_ATTEMPT_NOT_FOUND(404, Category.NOT_FOUND, false);
ADMIN_ACCESS_DENIED(403, Category.AUTHZ, false),
/**
* The operation named a tenant outside the operator's tenant scope. It is answered as a target
* that does not exist, so the answer does not tell what the other tenant holds.
*/
ADMIN_TARGET_NOT_FOUND(404, Category.NOT_FOUND, false),
/**
* A redrive or a reconcile batch 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),
/**
* A redrive of an attempt that may already have reached the user did not accept the duplicate
* risk. The same request is refused again; it succeeds only with the approval.
*/
DUPLICATE_RISK_APPROVAL_REQUIRED(409, Category.CONFLICT, false),
/**
* The operation id was used before for a different request. Like a reused idempotency key, it is
* the caller's mistake rather than a state conflict, and sending it again fails again.
*/
ADMIN_OPERATION_CONFLICT(422, Category.VALIDATION, false),
/**
* Another caller holds the same operation id for the same request and has not finished. Sending
* the same request again once it finishes answers its result.
*
* <p>Not retryable: the claim has no expiry, so a reconcile whose process stopped during its
* provider calls holds its operation id for good, and a client retrying on its own would never
* stop. An operator sends the request again after a while, and under a new operation id if it
* stays busy.
*/
ADMIN_OPERATION_IN_PROGRESS(409, Category.CONFLICT, false);
private final int httpStatus;
private final Category category;
@@ -21,9 +21,12 @@ import java.util.Optional;
/**
* Asks providers, on an operator's request, what happened to a bounded batch of attempts.
*
* <p>Every attempt is checked against the operator's tenant scope before any is touched, so a batch
* with one foreign id changes none. An id with no attempt behind it is left to reconciliation,
* which does nothing with it.
* <p>Every attempt id is checked before any provider is asked. An id no attempt has and an attempt
* outside the operator's tenant scope get one answer for the whole batch, the one a redrive gives:
* {@link DeliveryAttemptNotFoundException}. A tenant-scoped operator cannot tell which ids exist in
* other tenants, a batch with one such id changes nothing and claims no operation id, and the
* result counts one per id the batch names. The price: a batch that names an attempt already
* removed by retention is refused whole, and is sent again without that id.
*
* <p>The provider calls run with no transaction open: each one asks over the network, and inside a
* write transaction it held a pooled connection for as long as the provider took, once per attempt.
@@ -78,17 +81,19 @@ public class ReconcileDeliveriesUseCase
ReconcileRequest request = batch.request();
AdminActor actor = batch.actor();
authorization.require(actor, NotificationAdminAuthority.RECONCILE);
// Read in a read transaction of its own: the providers are asked with none open, so the tenant
// check cannot share the boundary the answers are recorded in.
// Read in a read transaction of its own: the providers are asked with none open, so the
// existence and tenant check cannot share the boundary the answers are recorded in.
transactions.inRead(
() -> {
for (DeliveryAttemptId attemptId : request.attemptIds()) {
attempts
.snapshot(attemptId)
.ifPresent(
attempt ->
authorization.requireTenant(
actor, attempt.tenantId(), NotificationAdminAuthority.RECONCILE));
boolean unreachable =
attempts
.snapshot(attemptId)
.filter(attempt -> authorization.mayActOn(actor, attempt.tenantId()))
.isEmpty();
if (unreachable) {
throw new DeliveryAttemptNotFoundException();
}
}
return null;
});
@@ -1,7 +1,9 @@
package dev.caskeleton.application.notification.platform.admin;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.application.notification.platform.api.TenantId;
import java.util.Optional;
@@ -24,23 +26,29 @@ class AdminAuthorizationGuardTest {
}
@Test
void tenantScopedActorCannotCrossTenantBoundary() {
AdminActor actor =
new AdminActor(
"operator-1",
Set.of(NotificationAdminAuthority.SUPPRESS),
Optional.of(new TenantId("tenant-a")));
void tenantScopedActorMayActInsideItsOwnTenant() {
AdminActor actor = tenantAOperator();
assertThatCode(
() ->
guard.requireTenant(
actor, new TenantId("tenant-a"), NotificationAdminAuthority.SUPPRESS))
assertThatCode(() -> guard.requireTenant(actor, new TenantId("tenant-a")))
.doesNotThrowAnyException();
assertThatThrownBy(
() ->
guard.requireTenant(
actor, new TenantId("tenant-b"), NotificationAdminAuthority.SUPPRESS))
.isInstanceOf(AdminAccessDeniedException.class);
}
/** Another tenant is answered as a target that does not exist, not as a missing authority. */
@Test
void tenantScopedActorCannotCrossTenantBoundary() {
// given
AdminActor actor = tenantAOperator();
// when
Throwable failure = catchThrowable(() -> guard.requireTenant(actor, new TenantId("tenant-b")));
// then
assertThat(failure)
.isInstanceOfSatisfying(
AdminTargetNotFoundException.class,
notFound ->
assertThat(notFound.errorCode())
.isEqualTo(NotificationAdminErrorCode.ADMIN_TARGET_NOT_FOUND));
}
@Test
@@ -49,10 +57,14 @@ class AdminAuthorizationGuardTest {
new AdminActor(
"global-operator", Set.of(NotificationAdminAuthority.SUPPRESS), Optional.empty());
assertThatCode(
() ->
guard.requireTenant(
global, new TenantId("tenant-b"), NotificationAdminAuthority.SUPPRESS))
assertThatCode(() -> guard.requireTenant(global, new TenantId("tenant-b")))
.doesNotThrowAnyException();
}
private static AdminActor tenantAOperator() {
return new AdminActor(
"operator-1",
Set.of(NotificationAdminAuthority.SUPPRESS),
Optional.of(new TenantId("tenant-a")));
}
}
@@ -46,12 +46,14 @@ import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
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;
import org.junit.jupiter.params.provider.ValueSource;
/**
* The four operator-plane use cases, each its own entrypoint with its own permission (round9 review
@@ -134,34 +136,6 @@ class NotificationAdminUseCasesTest {
assertThat(fixture.runtime.calls).isZero();
}
@Test
void aTenantScopedOperatorCannotReconcileAnotherTenantsAttempt() {
// given
Fixture fixture = new Fixture();
DeliveryAttemptSnapshot foreign = attemptOf(new TenantId("tenant-a"));
AttemptSnapshots.store(
fixture.requests, fixture.attempts, foreign, RecipientDeliveryState.DISPATCHING);
AdminActor tenantB =
new AdminActor(
"operator-b",
Set.of(NotificationAdminAuthority.RECONCILE),
Optional.of(new TenantId("tenant-b")));
ReconcileRequest request =
new ReconcileRequest("op-r", List.of(foreign.attemptId()), "stuck attempt", false);
// when
Throwable failure =
catchThrowable(
() -> fixture.reconcile.handle(new ReconcileDeliveriesCommand(request, tenantB)));
// then
assertThat(failure)
.isInstanceOfSatisfying(
AdminAccessDeniedException.class,
denied ->
assertThat(denied.required()).isEqualTo(NotificationAdminAuthority.RECONCILE));
}
@Test
void aTenantScopedOperatorCannotChangeAGlobalProviderState() {
// given
@@ -232,6 +206,151 @@ class NotificationAdminUseCasesTest {
.containsExactly(false);
}
/**
* The attempt ids are the operator's input. A batch naming an id no attempt has, or an attempt
* outside the operator's tenant scope, is refused whole before any provider is asked, with the
* answer a redrive gives: a skipped id would be counted as reconciled, and a refusal for the
* foreign id alone would tell a tenant-scoped operator which ids exist in other tenants.
*/
@ParameterizedTest(name = "{0}")
@MethodSource("unreachableReconciles")
void aReconcileBatchNamingAnUnknownOrForeignAttemptIsNotFoundAndAsksNoProvider(
UnreachableReconcile reconcile) {
// given
AtomicInteger providerCalls = new AtomicInteger();
Fixture fixture = new Fixture(countingProvider(providerCalls));
DeliveryAttemptSnapshot own = attemptOf(new TenantId("tenant-b"), 2);
DeliveryAttemptSnapshot foreign = attemptOf(new TenantId("tenant-a"));
AttemptSnapshots.store(
fixture.requests, fixture.attempts, own, RecipientDeliveryState.DISPATCHING);
AttemptSnapshots.store(
fixture.requests, fixture.attempts, foreign, RecipientDeliveryState.DISPATCHING);
AdminActor operator =
new AdminActor(
"operator-b", Set.of(NotificationAdminAuthority.RECONCILE), reconcile.scope());
ReconcileRequest request =
new ReconcileRequest(
"op-rc-unreachable",
List.of(own.attemptId(), reconcile.target(foreign)),
"stuck attempt",
reconcile.dryRun());
AtomicReference<AdminOperationResult> answered = new AtomicReference<>();
// when
Throwable failure =
catchThrowable(
() ->
answered.set(
fixture.reconcile.handle(new ReconcileDeliveriesCommand(request, operator))));
// then
assertThat(
List.<Object>of(
failure == null ? "no failure" : failure.getClass(),
carrierCode(failure),
answered.get() == null ? "no result" : "affected " + answered.get().affected(),
providerCalls.get(),
fixture.operations.claims,
fixture.audit.events().size()))
.as("[failure, carrier code, result, provider calls, claims, audit events]")
.containsExactly(
DeliveryAttemptNotFoundException.class,
"DELIVERY_ATTEMPT_NOT_FOUND",
"no result",
0,
0,
0);
}
private static Stream<UnreachableReconcile> unreachableReconciles() {
Optional<TenantId> tenantB = Optional.of(new TenantId("tenant-b"));
Optional<TenantId> global = Optional.empty();
return Stream.of(
new UnreachableReconcile("tenant operator, unknown id, reconcile", tenantB, false, false),
new UnreachableReconcile("tenant operator, unknown id, dry run", tenantB, false, true),
new UnreachableReconcile("tenant operator, foreign id, reconcile", tenantB, true, false),
new UnreachableReconcile("tenant operator, foreign id, dry run", tenantB, true, true),
new UnreachableReconcile("global operator, unknown id, reconcile", global, false, false),
new UnreachableReconcile("global operator, unknown id, dry run", global, false, true));
}
/**
* The authority is checked before any attempt of the batch is read: an operator without it is
* refused for that, whether the batch names an id no attempt has or another tenant's attempt, so
* the refusal does not tell which ids exist.
*/
@ParameterizedTest(name = "foreign attempt={0}")
@ValueSource(booleans = {false, true})
void aReconcileWithoutTheAuthorityIsRefusedBeforeItsAttemptsAreLookedUp(boolean foreign) {
// given
AtomicInteger providerCalls = new AtomicInteger();
Fixture fixture = new Fixture(countingProvider(providerCalls));
DeliveryAttemptSnapshot foreignAttempt = attemptOf(new TenantId("tenant-a"));
AttemptSnapshots.store(
fixture.requests, fixture.attempts, foreignAttempt, RecipientDeliveryState.DISPATCHING);
AdminActor withoutReconcile =
new AdminActor(
"operator-b",
EnumSet.complementOf(EnumSet.of(NotificationAdminAuthority.RECONCILE)),
Optional.of(new TenantId("tenant-b")));
ReconcileRequest request =
new ReconcileRequest(
"op-rc-no-authority",
List.of(foreign ? foreignAttempt.attemptId() : UNKNOWN_ATTEMPT),
"stuck attempt",
false);
// when
Throwable failure =
catchThrowable(
() ->
fixture.reconcile.handle(
new ReconcileDeliveriesCommand(request, withoutReconcile)));
// then
assertThat(failure)
.as("refused with AdminAccessDeniedException(RECONCILE), not answered as unreachable")
.isInstanceOfSatisfying(
AdminAccessDeniedException.class,
denied ->
assertThat(
List.<Object>of(
denied.required(), providerCalls.get(), fixture.operations.claims))
.as("[required authority, provider calls, claims]")
.containsExactly(NotificationAdminAuthority.RECONCILE, 0, 0));
}
/** A batch the operator may act on in full reports one affected attempt per id it named. */
@ParameterizedTest(name = "dryRun={0}")
@ValueSource(booleans = {false, true})
void aReconcileOfReachableAttemptsReportsEveryIdItNamed(boolean dryRun) {
// given
AtomicInteger providerCalls = new AtomicInteger();
Fixture fixture = new Fixture(countingProvider(providerCalls));
TenantId tenantB = new TenantId("tenant-b");
DeliveryAttemptSnapshot first = attemptOf(tenantB);
DeliveryAttemptSnapshot second = attemptOf(tenantB, 2);
AttemptSnapshots.store(
fixture.requests, fixture.attempts, first, RecipientDeliveryState.DISPATCHING);
AttemptSnapshots.store(
fixture.requests, fixture.attempts, second, RecipientDeliveryState.DISPATCHING);
AdminActor operator =
new AdminActor(
"operator-b", Set.of(NotificationAdminAuthority.RECONCILE), Optional.of(tenantB));
ReconcileRequest request =
new ReconcileRequest(
"op-rc-own", List.of(first.attemptId(), second.attemptId()), "stuck attempt", dryRun);
// when
AdminOperationResult result =
fixture.reconcile.handle(new ReconcileDeliveriesCommand(request, operator));
// then
assertThat(List.of(result.affected(), providerCalls.get()))
.as("[affected, provider calls]")
.containsExactly(2, dryRun ? 0 : 2);
}
@Test
void redriveReturnsTheDeliveryToTheQueueUnderItsClaim() {
// given
@@ -389,6 +508,10 @@ class NotificationAdminUseCasesTest {
.containsExactly(call.authority(), 0));
}
/**
* Another tenant is answered as a target that does not exist, not as a missing authority: the
* operator holds {@code SUPPRESS}, and the answer must not tell what tenant-a holds.
*/
@Test
void aTenantScopedOperatorCannotSuppressAnotherTenantsContactPoint() {
// given
@@ -409,19 +532,20 @@ class NotificationAdminUseCasesTest {
// then
assertThat(failure)
.as("refused with AdminAccessDeniedException(SUPPRESS)")
.as("answered AdminTargetNotFoundException")
.isInstanceOfSatisfying(
AdminAccessDeniedException.class,
denied ->
AdminTargetNotFoundException.class,
notFound ->
assertThat(
List.of(
denied.required(),
List.<Object>of(
notFound.errorCode(),
fixture
.suppressions
.activeFor(tenantA, "c".repeat(64), CLOCK.instant())
.size(),
fixture.operations.claims))
.containsExactly(NotificationAdminAuthority.SUPPRESS, 0, 0));
.as("[code, active suppressions of tenant-a, claims]")
.containsExactly(NotificationAdminErrorCode.ADMIN_TARGET_NOT_FOUND, 0, 0));
}
/**
@@ -633,6 +757,47 @@ class NotificationAdminUseCasesTest {
}
}
/**
* A reconcile batch of the stored attempt of tenant-b and one the operator cannot reach: the
* operator's tenant scope, whether that one is the stored attempt of tenant-a or an id no attempt
* has, and whether it is a dry run.
*/
private record UnreachableReconcile(
String name, Optional<TenantId> scope, boolean foreign, boolean dryRun) {
DeliveryAttemptId target(DeliveryAttemptSnapshot foreignAttempt) {
return foreign ? foreignAttempt.attemptId() : UNKNOWN_ATTEMPT;
}
@Override
public String toString() {
return name;
}
}
/** The code of the first carrier in {@code failure}'s cause chain, or {@code "no code"}. */
private static String carrierCode(Throwable failure) {
return ApiErrorCarrier.firstIn(failure)
.map(carrier -> ((ApiErrorCarrier) carrier).errorCode().code())
.orElse("no code");
}
/** A provider that supports every profile, answers unsupported, and counts its calls. */
private static ReconciliationGatewayPort countingProvider(AtomicInteger calls) {
return new ReconciliationGatewayPort() {
@Override
public boolean supports(ProviderProfileId profileId) {
return true;
}
@Override
public ReconciliationResult reconcile(DeliveryAttemptSnapshot attempt) {
calls.incrementAndGet();
return new ReconciliationResult.Unsupported();
}
};
}
/** One operator use case, the authority it exercises, and how to call it as an actor. */
private record OperatorCall(
String useCase,
@@ -650,10 +815,19 @@ class NotificationAdminUseCasesTest {
}
private static DeliveryAttemptSnapshot attemptOf(TenantId tenantId) {
return attemptOf(tenantId, 1);
}
/**
* An ambiguous attempt of {@code tenantId}. {@code serial} picks its ids — the attempt's ends in
* {@code <serial>1}, the delivery's in {@code <serial>2}, the notification's in {@code <serial>3}
* — so two serials are two stored deliveries.
*/
private static DeliveryAttemptSnapshot attemptOf(TenantId tenantId, int serial) {
return new DeliveryAttemptSnapshot(
new DeliveryAttemptId(UUID.fromString("00000000-0000-7000-8000-000000000011")),
new RecipientDeliveryId(UUID.fromString("00000000-0000-7000-8000-000000000012")),
new NotificationId(UUID.fromString("00000000-0000-7000-8000-000000000013")),
new DeliveryAttemptId(UUID.fromString(idOf(serial, 1))),
new RecipientDeliveryId(UUID.fromString(idOf(serial, 2))),
new NotificationId(UUID.fromString(idOf(serial, 3))),
tenantId,
1,
Channel.EMAIL,
@@ -672,6 +846,10 @@ class NotificationAdminUseCasesTest {
Optional.empty());
}
private static String idOf(int serial, int part) {
return String.format("00000000-0000-7000-8000-%012d", serial * 10 + part);
}
private static final class Fixture {
private final InMemoryNotificationRequestStore requests =
new InMemoryNotificationRequestStore();