diff --git a/.env.example b/.env.example index 09bb6b74..634a16c6 100644 --- a/.env.example +++ b/.env.example @@ -369,7 +369,10 @@ APP_NOTIFICATION_PLATFORM_PROVIDER_REQUEST_LOOKUP_HMAC_KEY= APP_NOTIFICATION_PLATFORM_CALLBACK_FINGERPRINT_HMAC_KEY= # The id each of those keys is active under — an identifier, not secret material, and required: # rotating the material without changing the id makes the new ciphertext indistinguishable from the -# old. Any stable string per purpose; change it whenever the matching key changes. +# old. Any stable string per purpose; change it whenever the matching key changes. The three lookup +# keys (CONTACT_LOOKUP_HMAC, PROVIDER_REQUEST_LOOKUP_HMAC, CALLBACK_FINGERPRINT_HMAC) are the +# exception: this version does not rotate them, so keep the key each runs on now; the id goes into +# no hash (docs/notification/at-rest-threat-model.md). APP_NOTIFICATION_PLATFORM_CONTACT_ENCRYPTION_KEY_ID= APP_NOTIFICATION_PLATFORM_CONTACT_LOOKUP_HMAC_KEY_ID= APP_NOTIFICATION_PLATFORM_CALLBACK_SIGNING_KEY_ID= diff --git a/docs/notification/at-rest-threat-model.md b/docs/notification/at-rest-threat-model.md index 5f0cec82..da7bdbaa 100644 --- a/docs/notification/at-rest-threat-model.md +++ b/docs/notification/at-rest-threat-model.md @@ -74,6 +74,9 @@ header는 앞에 붙이기만 하는 것이 아니라 **AAD**로 넘긴다. 그 설정 키는 `app.notification.platform.secrets` 아래에 있다(`notification.yml`). +아래 순서는 암호화 키의 순서다. 암호문은 자기를 만든 key id를 지니고, 읽는 쪽이 그 id로 옛 키를 찾기 때문에 듣는다. +조회 키 셋에는 쓰지 않는다. v1은 조회 키를 바꾸지 않는다(아래 「조회 키는 바꾸지 않는다」). + 1. 새 키 값과 새 key id를 같은 배포에서 바꾼다(예: `APP_NOTIFICATION_PLATFORM_PAYLOAD_ENCRYPTION_KEY`와 `APP_NOTIFICATION_PLATFORM_PAYLOAD_ENCRYPTION_KEY_ID`). 고정된 id는 교체를 앞 키와 구별할 수 없게 한다. 2. 같은 배포에서 밀려난 키 값을 `historical-keys.<목적>.<옛 id>` 아래에 둔다(예: @@ -82,6 +85,58 @@ header는 앞에 붙이기만 하는 것이 아니라 **AAD**로 넘긴다. 그 3. 옛 키로 쓴 행이 남아 있는 동안 옛 키를 그대로 둔다. `SettingsSecretMaterialProvider.keyById`는 모르는 id를 현재 키로 대신하지 않고 거부한다. 대신하면 이력의 모든 행이 읽을 때 인증 tag 실패가 된다. +### 조회 키는 바꾸지 않는다 + +v1은 조회 키 셋의 교체를 지원하지 않는다. 연락처 조회 HMAC(`CONTACT_LOOKUP_HMAC`), provider 요청 조회 +HMAC(`PROVIDER_REQUEST_LOOKUP_HMAC`), 콜백 fingerprint HMAC(`CALLBACK_FINGERPRINT_HMAC`)이다. + +조회 키는 값을 암호화하지 않는다. 값을 평문 없이 찾을 수 있게 hash(blind index)를 만든다. + +```text +주소 ─(활성 조회 키로 HMAC)─> fingerprint ─> 같은 fingerprint로 저장된 행을 찾는다 +``` + +행에는 hash만 있고, 어느 키로 만들었는지는 없다. 찾을 때도 활성 키로만 hash를 다시 만든다. 그래서 위 순서로 조회 +키를 바꾸면 옛 키는 아무도 읽지 않고, 바꾸기 전에 만든 hash가 모두 맞지 않는다. + +연락처 조회 HMAC을 바꾸면 세 가지가 함께 깨진다. + +1. 연락처가 둘이 된다. 접수가 옛 연락처를 찾지 못하고 같은 주소로 새 연락처(`UNVERIFIED`)를 만든다. 주소 하나의 + 상태가 두 행으로 갈린다. +2. 바꾸기 전 suppression이 맞지 않는다. 반송·신고로 쌓인 suppression은 옛 연락처의 fingerprint에 걸려 있다. 새 + 연락처로 보내는 발송은 그것을 찾지 못하고, 막힌 주소에 다시 보낸다. +3. 같은 요청이 다른 plan이 된다. plan에 새 연락처 id가 들어가 요청 지문이 바뀐다. 키를 준 재전송은 + `IDEMPOTENCY_CONFLICT`(422)로 거절되고, 키 없는 재전송은 두 번째 알림이 된다. + +다른 두 조회 키도 같다. + +- provider 요청 조회 HMAC을 바꾸면 바꾸기 전에 보낸 attempt의 callback이 그 attempt를 찾지 못한다. 그 메시지의 + 반송·신고는 짝 없는 event로 남고, 전달 상태와 suppression에 닿지 않는다. +- 콜백 fingerprint HMAC을 바꾸면 바꾸기 전에 받은 event가 provider event id 없이 다시 왔을 때 중복으로 보이지 않고 + 새 event로 한 번 더 쌓인다. + +기동이 막는 것: `historical-keys` 아래에 조회 키 목적의 옛 키가 하나라도 있으면(예: +`historical-keys.CONTACT_LOOKUP_HMAC.<옛 id>`) 플랫폼은 뜨기를 거부한다. 그 설정은 위 순서 2단계를 따른 신호이고, +조회는 그 키를 읽지 않는다. 거부 메시지가 이 절을 가리킨다. 거부되면 둘 중 하나다. + +- 조회 키를 바꾸려던 배포였으면 옛 키 값과 옛 id를 활성으로 되돌리고 `historical-keys`의 그 행을 지운다. 기동이 + 거부됐으므로 새 키로 만든 hash는 아직 없다. +- 이 검사 전에 새 조회 키로 이미 운영해 왔으면 되돌리지 않고 그 행만 지운다. 그 행은 아무도 읽지 않았다. 되돌리면 + 새 키로 만든 행이 찾아지지 않는다. 바꾸기 전 행은 이미 찾아지지 않고 있으니 바꾼 목적마다 아래를 확인한다. + - 연락처 조회 HMAC: `notification_contact_point`에서 `tenant_id`·`owner_ref`·`type`이 같고 `created_at`이 바꾼 + 시각 뒤인 행을 본다. 한 사람이 같은 종류의 연락처를 여럿 가질 수 있고 주소는 암호문이라, 그 행이 같은 주소의 + 둘째 행인지는 행만으로 가리지 못한다. 옛 연락처에만 걸린 suppression도 본다. + - provider 요청 조회 HMAC: `notifications` actuator의 `unmatchedProjections`(어느 attempt와도 짝이 맞지 않은 + event 수)가 바꾼 뒤 늘었는지 본다. + - 콜백 fingerprint HMAC: provider event id 없이 온 event가 바꾼 뒤 한 번 더 쌓였는지 본다. + +기동이 못 막는 것: 옛 키를 `historical-keys`에 두지 않고 키 값만 바꾸는 배포다. 행에 조회 키 id가 없어서 기동은 +무엇이 바뀌었는지 알 수 없다. 조회 키 값은 지금 쓰는 그대로 둔다. id는 hash에 들어가지 않아서, id만 바꾸면 찾기에는 +아무 일도 없다. + +조회 키가 드러나도 v1에는 바꾸는 절차가 없다. 드러난 키와 저장소를 함께 가진 사람은 주소를 하나씩 대어 보며 연락처를 +찾을 수 있다. blind index가 막던 일이다. 여러 키로 찾고 활성 키로 다시 색인하는 교체는 v1 뒤에 다룬다. + ## 결정의 이력 > 이력: 결정 당시(Wave 2) `NotificationJpaPersistenceFacade`는 아무도 import하지 않았다. 조립 루트의 component scan은 diff --git a/docs/notification/configuration-reference.md b/docs/notification/configuration-reference.md index a7212a7c..7fd3ae13 100644 --- a/docs/notification/configuration-reference.md +++ b/docs/notification/configuration-reference.md @@ -239,6 +239,13 @@ id는 교체를 바뀌기 전 키와 구별할 수 없게 만들어서, 그 전 id도 함께 바꾸고, 밀려난 키는 그 키로 쓴 데이터를 다시 암호화할 때까지 옛 id로 읽을 수 있게 둔다. 교체 순서는 [at-rest-threat-model.md](at-rest-threat-model.md)에 있다. +조회 키 셋(연락처 조회 HMAC, provider 요청 조회 HMAC, 콜백 fingerprint HMAC)은 이 순서로 바꾸지 않는다. v1은 이 +셋의 교체를 지원하지 않으니, 지금 쓰는 키 값을 그대로 둔다(id는 hash에 들어가지 않는다). 셋은 값을 암호화하지 않고 찾는 데 쓰는 hash를 +만들고, 행은 활성 키의 hash로만 찾는다. 그래서 바꾸면 옛 행이 찾아지지 않는다. 연락처 조회 HMAC이면 같은 주소가 +연락처 둘이 되고, 바꾸기 전 suppression이 새 연락처에 맞지 않아 막힌 주소에 다시 보내고, 같은 요청이 다른 plan이 된다. +`historical-keys` 아래에 이 셋의 옛 키를 두면 플랫폼은 뜨기를 거부한다. 무엇이 깨지는지와 거부됐을 때 할 일은 +[at-rest-threat-model.md](at-rest-threat-model.md) 「조회 키는 바꾸지 않는다」에 있다. + ## readiness 플랫폼은 `notifications` actuator 엔드포인트와 health indicator를 보탠다. provider 자격 증명이 거부됐을 때, 설정된 diff --git a/docs/registries/env-keys.yaml b/docs/registries/env-keys.yaml index 2922db59..f09073ae 100644 --- a/docs/registries/env-keys.yaml +++ b/docs/registries/env-keys.yaml @@ -4351,6 +4351,8 @@ env_keys: # 행 전체는 secrets-classification.yaml이 가진다. 바인딩 위치: # app.notification.platform.secrets.contact-lookup-hmac-key. 플랫폼이 기동할 때 값을 풀고, # 비었거나 32바이트보다 짧거나 다른 용도의 key와 같으면 기동을 거부한다. + # 교체 정책은 secrets-classification.yaml 행의 rotation_policy가 가진다(v1은 바꾸지 않는다, + # docs/notification/at-rest-threat-model.md 「조회 키는 바꾸지 않는다」). type: string default: null allowed_values: null @@ -4415,6 +4417,8 @@ env_keys: # 행 전체는 secrets-classification.yaml이 가진다. 바인딩 위치: # app.notification.platform.secrets.provider-request-lookup-hmac-key. 플랫폼이 기동할 때 값을 풀고, # 비었거나 32바이트보다 짧거나 다른 용도의 key와 같으면 기동을 거부한다. + # 교체 정책은 secrets-classification.yaml 행의 rotation_policy가 가진다(v1은 바꾸지 않는다, + # docs/notification/at-rest-threat-model.md 「조회 키는 바꾸지 않는다」). type: string default: null allowed_values: null @@ -4431,6 +4435,8 @@ env_keys: # 행 전체는 secrets-classification.yaml이 가진다. 바인딩 위치: # app.notification.platform.secrets.callback-fingerprint-hmac-key. 플랫폼이 기동할 때 값을 풀고, # 비었거나 32바이트보다 짧거나 다른 용도의 key와 같으면 기동을 거부한다. + # 교체 정책은 secrets-classification.yaml 행의 rotation_policy가 가진다(v1은 바꾸지 않는다, + # docs/notification/at-rest-threat-model.md 「조회 키는 바꾸지 않는다」). type: string default: null allowed_values: null @@ -4459,10 +4465,13 @@ env_keys: required_test: adapter-contract:notification-secret-material-required - name: APP_NOTIFICATION_PLATFORM_CONTACT_LOOKUP_HMAC_KEY_ID - # source: NTF-INT-007 — CONTACT_LOOKUP_HMAC key가 만드는 모든 envelope에 적는 id. + # source: NTF-INT-007 — CONTACT_LOOKUP_HMAC key의 id. 조회 hash는 envelope가 아니어서 이 id는 행에 적히지 않는다. # key 자료가 아니라 식별자라 public-config다. 자료 자체는 위의 # APP_NOTIFICATION_PLATFORM_CONTACT_LOOKUP_HMAC_KEY 행이다. 바인딩 위치: # app.notification.platform.secrets.active-key-ids.CONTACT_LOOKUP_HMAC. + # v1은 이 조회 키를 바꾸지 않는다. 조회는 활성 키의 hash로만 찾아, 바꾸면 옛 행이 찾아지지 않는다. + # historical-keys에 이 목적의 옛 키를 두면 기동을 거부한다(docs/notification/at-rest-threat-model.md + # 「조회 키는 바꾸지 않는다」). type: string default: null allowed_values: null @@ -4523,10 +4532,13 @@ env_keys: required_test: adapter-contract:notification-secret-material-required - name: APP_NOTIFICATION_PLATFORM_PROVIDER_REQUEST_LOOKUP_HMAC_KEY_ID - # source: NTF-INT-007 — PROVIDER_REQUEST_LOOKUP_HMAC key가 만드는 모든 envelope에 적는 id. + # source: NTF-INT-007 — PROVIDER_REQUEST_LOOKUP_HMAC key의 id. 조회 hash는 envelope가 아니어서 이 id는 행에 적히지 않는다. # key 자료가 아니라 식별자라 public-config다. 자료 자체는 위의 # APP_NOTIFICATION_PLATFORM_PROVIDER_REQUEST_LOOKUP_HMAC_KEY 행이다. 바인딩 위치: # app.notification.platform.secrets.active-key-ids.PROVIDER_REQUEST_LOOKUP_HMAC. + # v1은 이 조회 키를 바꾸지 않는다. 조회는 활성 키의 hash로만 찾아, 바꾸면 옛 행이 찾아지지 않는다. + # historical-keys에 이 목적의 옛 키를 두면 기동을 거부한다(docs/notification/at-rest-threat-model.md + # 「조회 키는 바꾸지 않는다」). type: string default: null allowed_values: null @@ -4539,10 +4551,13 @@ env_keys: required_test: adapter-contract:notification-secret-material-required - name: APP_NOTIFICATION_PLATFORM_CALLBACK_FINGERPRINT_HMAC_KEY_ID - # source: NTF-INT-007 — CALLBACK_FINGERPRINT_HMAC key가 만드는 모든 envelope에 적는 id. + # source: NTF-INT-007 — CALLBACK_FINGERPRINT_HMAC key의 id. 조회 hash는 envelope가 아니어서 이 id는 행에 적히지 않는다. # key 자료가 아니라 식별자라 public-config다. 자료 자체는 위의 # APP_NOTIFICATION_PLATFORM_CALLBACK_FINGERPRINT_HMAC_KEY 행이다. 바인딩 위치: # app.notification.platform.secrets.active-key-ids.CALLBACK_FINGERPRINT_HMAC. + # v1은 이 조회 키를 바꾸지 않는다. 조회는 활성 키의 hash로만 찾아, 바꾸면 옛 행이 찾아지지 않는다. + # historical-keys에 이 목적의 옛 키를 두면 기동을 거부한다(docs/notification/at-rest-threat-model.md + # 「조회 키는 바꾸지 않는다」). type: string default: null allowed_values: null diff --git a/docs/registries/secrets-classification.yaml b/docs/registries/secrets-classification.yaml index 354b4328..29de6b3d 100644 --- a/docs/registries/secrets-classification.yaml +++ b/docs/registries/secrets-classification.yaml @@ -23,6 +23,8 @@ # userinfo — URI의 사용자 정보 비밀번호(`scheme://user:****@host`). 접속 URI 행이다. # none — 가리지 않는다. # - `required_test`는 그 행의 약속을 지키는 app-bootstrap 시험 클래스 이름이다(같은 시험이 클래스가 있는지 본다). +# - `rotation_policy`는 그 값을 바꾸는 법이다. `not-rotated-v1`은 이 버전에서 바꾸지 않는다는 뜻이다. 행을 그 키로 +# 만든 hash로만 찾아서, 바꾸면 바꾸기 전 행이 모두 찾아지지 않는다. 알림 조회 키 셋이 이것이다. # - 이름 접미사는 보조 신호다 (feature-secrets-config-source-contract: "_TOKEN, _KEY, _PASSWORD"). # - public-config 항목은 env-keys.yaml에서 직접 정의되며 본 파일에는 reference row만 둠. @@ -246,9 +248,10 @@ secrets: # 연락처의 blind index. 조회에 평문이 필요 없게 한다. # purpose별 key 일곱 중 하나다. 모두 달라야 한다: 한 key를 여러 용도에 다시 쓰면 하나가 털릴 때 일곱이 모두 # 털린다. 플랫폼은 배포가 알아챘으리라 믿지 않고 기동할 때 구별을 강제한다. + # 조회 키라 v1에서 바꾸지 않는다(docs/notification/at-rest-threat-model.md 「조회 키는 바꾸지 않는다」). classification: secret source: secret-manager - rotation_policy: dual-read-restart-only + rotation_policy: not-rotated-v1 prod_default: null required_when: app.notification.platform.enabled=true dev_sentinel_prefix: __LOCAL_DEV_ @@ -306,9 +309,10 @@ secrets: # provider 쪽 식별자인 provider request id의 key 있는 hash. # purpose별 key 일곱 중 하나다. 모두 달라야 한다: 한 key를 여러 용도에 다시 쓰면 하나가 털릴 때 일곱이 모두 # 털린다. 플랫폼은 배포가 알아챘으리라 믿지 않고 기동할 때 구별을 강제한다. + # 조회 키라 v1에서 바꾸지 않는다(docs/notification/at-rest-threat-model.md 「조회 키는 바꾸지 않는다」). classification: secret source: secret-manager - rotation_policy: dual-read-restart-only + rotation_policy: not-rotated-v1 prod_default: null required_when: app.notification.platform.enabled=true dev_sentinel_prefix: __LOCAL_DEV_ @@ -321,9 +325,10 @@ secrets: # callback 본문의 key 있는 fingerprint. replay를 찾는 데 쓴다. # purpose별 key 일곱 중 하나다. 모두 달라야 한다: 한 key를 여러 용도에 다시 쓰면 하나가 털릴 때 일곱이 모두 # 털린다. 플랫폼은 배포가 알아챘으리라 믿지 않고 기동할 때 구별을 강제한다. + # 조회 키라 v1에서 바꾸지 않는다(docs/notification/at-rest-threat-model.md 「조회 키는 바꾸지 않는다」). classification: secret source: secret-manager - rotation_policy: dual-read-restart-only + rotation_policy: not-rotated-v1 prod_default: null required_when: app.notification.platform.enabled=true dev_sentinel_prefix: __LOCAL_DEV_ diff --git a/docs/upgrade/2026-11-notification-lookup-key-rotation.md b/docs/upgrade/2026-11-notification-lookup-key-rotation.md new file mode 100644 index 00000000..8acfb50e --- /dev/null +++ b/docs/upgrade/2026-11-notification-lookup-key-rotation.md @@ -0,0 +1,37 @@ +# 업그레이드 안내 — 2026-11 알림 조회 키의 옛 키 거부 + +- 범위: 알림 플랫폼의 secret 기동 검사(`NotificationPlatformSecretsConfig`)가 조회 키 셋의 옛 키를 거부하게 된 변경과 + 그 교체 문서. 설정 키 이름과 공개 타입은 그대로다. 기본 jar에는 이 경로가 없다. 알림 capability + (`:composition:notification-platform`)를 실은 서비스만 해당한다. +- 근거: 2026-11-23 리뷰 발견 REV-BE-0063. 조회 키는 행을 활성 키의 hash로만 찾는데, 교체 문서는 조회 키도 암호화 + 키와 같은 순서로 바꾼다고 읽혔다. 그 순서를 따르면 같은 주소가 연락처 둘이 되고, 바꾸기 전 suppression이 맞지 않고, + 같은 요청이 다른 plan이 된다. v1은 이 교체를 지원하지 않는다고 정했다(`docs/work/reference/decisions.md` 2.6절 + 「알림 조회 키 교체」). + +## 1. 누가 읽나 + +이 템플릿을 `upstream` remote로 두고 merge해 받는 파생 서비스가 읽는다. 특히 알림 capability를 켜고 +`app.notification.platform.secrets.historical-keys` 아래에 옛 키를 둔 서비스다. + +## 2. 바뀐 동작 + +### 2.1 2026-11-23 — 조회 키의 옛 키가 있으면 기동 거부 (따라 할 일 있음) + +| # | 바뀐 것 | 전에는 | 할 일 | 안 하면 | 해당 서비스 | +| --- | --- | --- | --- | --- | --- | +| 1 | `historical-keys.CONTACT_LOOKUP_HMAC`·`historical-keys.PROVIDER_REQUEST_LOOKUP_HMAC`·`historical-keys.CALLBACK_FINGERPRINT_HMAC` 아래에 키가 하나라도 있으면 플랫폼이 뜨기를 거부한다(`CapabilityStartupValidationException`). 메시지는 목적 이름과 `docs/notification/at-rest-threat-model.md` 「조회 키는 바꾸지 않는다」를 적고, 키 값은 적지 않는다. 다른 네 목적(연락처 암호화, 콜백 서명, provider 자격 증명, payload 암호화)의 옛 키는 전처럼 받는다 | 기동이 그 설정을 받아들였다. 조회는 그 키를 읽지 않으므로 아무 효과가 없었고, 같은 배포에서 활성 조회 키를 바꿨다면 바꾸기 전 행이 모두 찾아지지 않았다 | 조회 키를 바꾸는 배포가 처음 거부됐으면 그 목적의 옛 키 값과 옛 id를 활성(`APP_NOTIFICATION_PLATFORM_<목적>_KEY`·`_KEY_ID`)으로 되돌리고 `historical-keys`의 그 행을 지운다. 새 조회 키로 이미 운영해 왔으면 되돌리지 않고 `historical-keys`의 그 행만 지운다. 그 행은 아무도 읽지 않았으므로 동작은 그대로다. 되돌리면 새 키로 만든 행이 찾아지지 않는다. 그런 서비스에서는 바꾸기 전 행이 이미 찾아지지 않고 있으니 바꾼 목적마다 확인한다. 연락처 조회 HMAC은 `notification_contact_point`에서 `tenant_id`·`owner_ref`·`type`이 같고 바꾼 시각 뒤에 생긴 행(같은 주소의 둘째 행인지는 행만으로 가리지 못한다)과 옛 연락처에만 걸린 suppression, provider 요청 조회 HMAC은 `notifications` actuator의 `unmatchedProjections`가 늘었는지, 콜백 fingerprint HMAC은 provider event id 없이 온 event가 한 번 더 쌓였는지다(`docs/notification/at-rest-threat-model.md` 「조회 키는 바꾸지 않는다」). v1에는 다시 색인하는 이전이 없다 | 플랫폼이 뜨지 않는다 | 알림 capability를 켜고 조회 키 목적에 옛 키를 둔 서비스 | + +## 3. 바뀌지 않은 것 + +- 조회 hash를 만드는 계산(`AesGcmContactPointProtector`·`HmacProviderRequestIdHasher`·`AesGcmCallbackPayloadProtection`의 + fingerprint), 연락처·suppression 스키마, plan의 canonical encoding은 그대로다. +- 옛 키를 두지 않고 조회 키 값만 바꾸는 배포는 기동이 알 수 없다(행에 조회 키 id가 없다). 그것은 문서가 막는다. + 조회 키 값은 지금 쓰는 그대로 둔다. id는 hash에 들어가지 않는다. +- 암호화 키의 교체 순서(`docs/notification/at-rest-threat-model.md` 「키 교체 순서」 1~3단계)와 그 검사(빈 값, 짧은 키, + 겹친 키, 모르는 목적, 활성이자 옛 키인 id)는 그대로다. + +## 4. 되돌리는 법 + +기동 검사(`NotificationPlatformSecretsConfig`의 `LOOKUP_PURPOSES`)와 그 시험, 문서·레지스트리 주석을 함께 revert하고, 이 +문서에 되돌린 행을 더한다. 여러 키로 찾고 다시 색인하는 교체를 넣게 되면, 그 변경에서 이 검사를 지우고 교체 순서를 다시 +쓴다. diff --git a/docs/work/reference/decisions.md b/docs/work/reference/decisions.md index 421c38e6..9c272f76 100644 --- a/docs/work/reference/decisions.md +++ b/docs/work/reference/decisions.md @@ -187,6 +187,7 @@ | 빈 env 값 | 선택 숫자 설정의 빈 값은 "미설정". 오타·모르는 키 거부는 그대로 | 위임 | `1101` 15절 | | `APP_FLYWAY_ENABLED` | dev·prod에도 적용 | 위임 | `1101` 15절(r3-F) | | 전송 상한 기본값 | gRPC 스레드 32·큐 256·동시 100·deadline 10s·drain 2s, ledger `claimTtl` 5m·보존 24h, WebSocket `max-connections` 1000(초과 시 1013) | 위임 | `1101` 15절(03-06·03-09·03-10) | +| 알림 조회 키 교체 | v1은 조회 키 셋(`CONTACT_LOOKUP_HMAC`·`PROVIDER_REQUEST_LOOKUP_HMAC`·`CALLBACK_FINGERPRINT_HMAC`)의 교체를 지원하지 않는다. `historical-keys` 아래에 이 셋의 옛 키가 있으면 기동을 거부하고, 교체 문서는 이 셋을 바꾸지 않는다고 적는다. 행은 활성 키의 hash로만 찾아, 바꾸면 같은 주소가 연락처 둘이 되고 바꾸기 전 suppression이 맞지 않는다. 여러 키로 찾고 다시 색인하는 안(B)은 v1 뒤로, 문서만 고치는 안(C)은 버렸다 | 기본값(2026-11-23, review 허브가 고른 권하는 안, 자율 운영. 소유자가 정한 것이 아니고 뒤집을 수 있다) | review 허브 REV-BE-0063 요청(2026-11-23 17:44), `docs/upgrade/2026-11-notification-lookup-key-rotation.md` 2.1절 | ### 2.7 빌드·게이트·capability diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformSecretsConfig.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformSecretsConfig.java index cd0c0da9..18755360 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformSecretsConfig.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformSecretsConfig.java @@ -10,6 +10,7 @@ import dev.caskeleton.application.notification.platform.security.SecretPurpose; import java.time.Clock; import java.util.Base64; import java.util.EnumMap; +import java.util.EnumSet; import java.util.Map; import java.util.Objects; import java.util.Set; @@ -40,6 +41,11 @@ import org.springframework.core.env.Environment; * provider credential, so draining the previous generation — the thing historical keys exist for — * failed on the first in-flight attempt. * + *

Three purposes take no retired keys at all: the lookup keys, {@code LOOKUP_PURPOSES}. Each + * hashes a value under the active key and finds rows by that hash, and nothing asks for a retired + * one, so the rotation sequence that keeps an encryption key readable keeps nothing findable for + * them. Startup refuses a retired lookup key instead of accepting a rotation that only looks done. + * *

What is demanded follows what is switched on. Every purpose was required of every deployment, * so an SMTP-only platform with callbacks off had to provision and rotate a provider credential and * two callback keys that nothing could reach — and a key that exists and is never used is a key @@ -194,6 +200,9 @@ class NotificationPlatformSecretsConfig { * under one purpose regardless of what they served made the historical map worse than empty: a * retired provider credential resolved, failed its purpose check, and the drain it was kept for * failed on the first in-flight attempt. + * + *

A retired lookup key is refused rather than kept, because nothing would read it ({@code + * LOOKUP_PURPOSES}). */ private static Map historical(NotificationSecretsSettings settings) { Map historical = new java.util.LinkedHashMap<>(); @@ -202,6 +211,19 @@ class NotificationPlatformSecretsConfig { .forEach( (purposeName, keys) -> { SecretPurpose purpose = purposeOf(purposeName); + if (LOOKUP_PURPOSES.contains(purpose) && !keys.isEmpty()) { + // The purpose and the section that says not to rotate it, never an id or a value: + // the ids are not secret, but the message has nothing to say about any one of them. + throw new CapabilityStartupValidationException( + "historical notification secrets are declared under " + + purpose + + ", a lookup key this version cannot rotate: rows are found by a hash" + + " under the active key only, so a retired one is never read and every" + + " row hashed before the change stops being found. Remove the historical" + + " entry, and if this deployment changes the active key, restore the" + + " previous key and id; see docs/notification/at-rest-threat-model.md," + + " 「조회 키는 바꾸지 않는다」"); + } keys.forEach( (keyId, base64) -> { if (settings.activeKeyIds().containsValue(keyId)) { @@ -309,4 +331,30 @@ class NotificationPlatformSecretsConfig { /** The shortest key any purpose here accepts: 256 bits. */ private static final int MINIMUM_KEY_BYTES = 32; + + /** + * The purposes whose key only computes the index rows are found by, and which therefore cannot be + * rotated in this version. + * + *

A contact point is found by the keyed hash of its address ({@code + * AesGcmContactPointProtector.fingerprint}), a delivery attempt by the keyed hash of the + * provider's request id ({@code HmacProviderRequestIdHasher}), and a callback event without a + * provider event id by its keyed fingerprint ({@code AesGcmCallbackPayloadProtection + * .fingerprint}). All three hash under {@code activeKey} and look the hash up; no row records + * which key made it and nothing calls {@code keyById} for these purposes. Rotating one changes + * every hash at once: the same address becomes a second contact point that its earlier + * suppressions do not reach and whose id makes a repeated request a different plan, callbacks for + * attempts sent before the change no longer find them, and a redelivered event no longer reads as + * a duplicate. + * + *

So a retired key under one of these is refused at startup rather than kept. Its presence + * means the operator followed the rotation sequence for encryption keys, which this platform + * would otherwise have accepted as a rotation done. Looking rows up under retired keys too and + * re-indexing them under the active one is after v1; when it exists this set goes. + */ + private static final Set LOOKUP_PURPOSES = + EnumSet.of( + SecretPurpose.CONTACT_LOOKUP_HMAC, + SecretPurpose.PROVIDER_REQUEST_LOOKUP_HMAC, + SecretPurpose.CALLBACK_FINGERPRINT_HMAC); } diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationSecretsValidationTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationSecretsValidationTest.java index f8ec7e2b..182ae34e 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationSecretsValidationTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationSecretsValidationTest.java @@ -3,8 +3,11 @@ package dev.caskeleton.adapter.outbound.notification.platform.autoconfigure; 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.adapter.outbound.notification.platform.autoconfigure.NotificationPlatformSecretsConfig.NotificationSecretsSettings; +import dev.caskeleton.adapter.outbound.support.CapabilityStartupValidationException; +import dev.caskeleton.application.notification.platform.security.SecretKeyMaterial; import dev.caskeleton.application.notification.platform.security.SecretPurpose; import java.util.Base64; import java.util.LinkedHashMap; @@ -12,6 +15,8 @@ import java.util.List; import java.util.Map; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; /** * What the platform accepts as key material at startup. @@ -162,6 +167,87 @@ class NotificationSecretsValidationTest { .isEqualTo(SecretPurpose.PROVIDER_CREDENTIAL); } + /** + * A retired lookup key is refused, and the refusal names the section that says lookup keys are + * not rotated. + * + *

Each of these purposes hashes under the active key and finds rows by the hash; nothing asks + * for a retired one. So the sequence that keeps an encryption key readable — new key and id + * active, the old one under {@code historical-keys} — changes every hash and keeps nothing + * findable: the same address becomes a second contact point that its earlier suppressions do not + * reach. Startup used to accept that configuration as a rotation done. + */ + @ParameterizedTest + @EnumSource( + value = SecretPurpose.class, + names = {"CONTACT_LOOKUP_HMAC", "PROVIDER_REQUEST_LOOKUP_HMAC", "CALLBACK_FINGERPRINT_HMAC"}) + void aRetiredLookupKeyIsRefusedNamingTheSectionThatSaysNotToRotateIt(SecretPurpose purpose) { + // given + NotificationSecretsSettings retired = + settingsWithHistory(Map.of(purpose.name(), Map.of("lookup-2026-01", key((byte) 0x99)))); + + // when + Throwable refused = + catchThrowable( + () -> config.notificationSecretMaterialProvider(everyCapabilityOn(), retired)); + + // then + assertThat(refused) + .as( + "a retired %s key was accepted, so a rotation nothing can look up under passed", + purpose) + .isInstanceOf(CapabilityStartupValidationException.class) + .hasMessageContainingAll( + "declared under " + purpose, + "docs/notification/at-rest-threat-model.md", + "「조회 키는 바꾸지 않는다」"); + } + + /** + * A lookup purpose named with nothing under it is not a retired key, and startup accepts it. The + * refusal is for a key that would never be read, not for the heading. + */ + @Test + void aLookupPurposeDeclaredWithNoRetiredKeysIsAccepted() { + // given + NotificationSecretsSettings emptyBlock = + settingsWithHistory(Map.of("CONTACT_LOOKUP_HMAC", Map.of())); + + // when + SecretKeyMaterial active = + config + .notificationSecretMaterialProvider(everyCapabilityOn(), emptyBlock) + .activeKey(SecretPurpose.CONTACT_LOOKUP_HMAC); + + // then + assertThat(active.keyId()).isEqualTo("contact-mac-2026-08"); + } + + /** + * Every purpose that is not a lookup key still accepts a retired key and resolves it by id under + * the purpose it served. The two tests split the enum between them, so a new purpose lands in + * this one until someone decides it is a lookup key. + */ + @ParameterizedTest + @EnumSource( + value = SecretPurpose.class, + mode = EnumSource.Mode.EXCLUDE, + names = {"CONTACT_LOOKUP_HMAC", "PROVIDER_REQUEST_LOOKUP_HMAC", "CALLBACK_FINGERPRINT_HMAC"}) + void aRetiredKeyForAPurposeOtherThanLookupIsStillAccepted(SecretPurpose purpose) { + // given + NotificationSecretsSettings retired = + settingsWithHistory(Map.of(purpose.name(), Map.of("retired-2026-01", key((byte) 0x99)))); + + // when + SecretKeyMaterial kept = + config + .notificationSecretMaterialProvider(everyCapabilityOn(), retired) + .keyById("retired-2026-01"); + + // then + assertThat(kept.purpose()).isEqualTo(purpose); + } + @Test @DisplayName("a retired key filed under a purpose this platform does not issue is refused") void anUnknownHistoricalPurposeIsRefused() { @@ -207,7 +293,7 @@ class NotificationSecretsValidationTest { } @Test - @DisplayName("no rejection carries the material it rejected") + @DisplayName("어떤 기동 거부도 거부한 키 값을 싣지 않는다") void noRejectionCarriesTheMaterialItRejected() { String weak = Base64.getEncoder().encodeToString(new byte[8]); String malformed = "not base64!!"; @@ -241,7 +327,15 @@ class NotificationSecretsValidationTest { config.notificationSecretMaterialProvider( everyCapabilityOn(), settingsWithHistory( - Map.of("PAYLOAD_ENCRYPTION", Map.of("payload-2026-01", weak))))))) { + Map.of("PAYLOAD_ENCRYPTION", Map.of("payload-2026-01", weak))))), + catchOf( + () -> + config.notificationSecretMaterialProvider( + everyCapabilityOn(), + settingsWithHistory( + Map.of( + "CONTACT_LOOKUP_HMAC", + Map.of("lookup-2026-01", key((byte) 0x99)))))))) { if (failure == null) { continue; } @@ -254,8 +348,10 @@ class NotificationSecretsValidationTest { .doesNotContain(malformed) .doesNotContain(key((byte) 0x11)) .doesNotContain(key((byte) 0x55)) + .doesNotContain(key((byte) 0x99)) .doesNotContain("1111111111") - .doesNotContain("5555555555"); + .doesNotContain("5555555555") + .doesNotContain("9999999999"); } } diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/security/AesGcmContactPointProtectorContractTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/security/AesGcmContactPointProtectorContractTest.java new file mode 100644 index 00000000..74272e32 --- /dev/null +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/security/AesGcmContactPointProtectorContractTest.java @@ -0,0 +1,30 @@ +package dev.caskeleton.adapter.outbound.notification.platform.security; + +import dev.caskeleton.application.notification.platform.security.ContactPointProtector; +import dev.caskeleton.application.notification.platform.security.SecretKeyMaterial; +import dev.caskeleton.application.notification.platform.security.SecretPurpose; +import dev.caskeleton.application.notification.platform.security.testkit.ContactPointProtectorContract; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Map; + +/** The AES-GCM protector held to the same fingerprint contract as the keyed fake. */ +class AesGcmContactPointProtectorContractTest extends ContactPointProtectorContract { + + @Override + protected ContactPointProtector protectorUnderLookupKey(String lookupKey) { + byte[] encryption = new byte[32]; + Arrays.fill(encryption, (byte) 0x11); + // The name itself, padded to 32 bytes: the same name gives the same material, two names give + // two, and neither is the encryption key, which the protector refuses to share. + byte[] lookup = Arrays.copyOf(("lookup:" + lookupKey).getBytes(StandardCharsets.UTF_8), 32); + return new AesGcmContactPointProtector( + new SettingsSecretMaterialProvider( + Map.of( + SecretPurpose.CONTACT_ENCRYPTION, + new SecretKeyMaterial("enc-1", SecretPurpose.CONTACT_ENCRYPTION, encryption), + SecretPurpose.CONTACT_LOOKUP_HMAC, + new SecretKeyMaterial(lookupKey, SecretPurpose.CONTACT_LOOKUP_HMAC, lookup)), + Map.of())); + } +} diff --git a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCaseTest.java b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCaseTest.java index 1f390de5..c3201b4d 100644 --- a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCaseTest.java +++ b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCaseTest.java @@ -3,6 +3,7 @@ package dev.caskeleton.application.notification.platform.dispatch; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; +import dev.caskeleton.application.notification.platform.api.ContactPointSelector; import dev.caskeleton.application.notification.platform.api.DeduplicationAction; import dev.caskeleton.application.notification.platform.api.DeduplicationSpec; import dev.caskeleton.application.notification.platform.api.NotificationAcceptance; @@ -14,7 +15,6 @@ import dev.caskeleton.application.notification.platform.api.RequestStatus; import dev.caskeleton.application.notification.platform.api.error.IdempotencyConflictException; import dev.caskeleton.application.notification.platform.api.routing.Channel; import dev.caskeleton.application.notification.platform.api.routing.ExplicitChannel; -import dev.caskeleton.application.notification.platform.contact.ContactPointValue; 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; @@ -22,9 +22,8 @@ import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemor import dev.caskeleton.application.notification.platform.port.in.AcceptNotificationCommand; import dev.caskeleton.application.notification.platform.port.in.SubmitNotificationCommand; import dev.caskeleton.application.notification.platform.port.in.SubmitNotificationUseCase; -import dev.caskeleton.application.notification.platform.security.AccessContext; import dev.caskeleton.application.notification.platform.security.ContactPointProtector; -import dev.caskeleton.application.notification.platform.security.ProtectedContactPoint; +import dev.caskeleton.application.notification.platform.security.testkit.KeyedContactPointProtector; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import dev.caskeleton.shared.error.ApiErrorCarrier; import dev.caskeleton.shared.error.Category; @@ -302,6 +301,53 @@ class AcceptNotificationApplicationUseCaseTest { .containsExactly(first.notificationId(), 1, path.missedLookups(), path.lostInserts()); } + /** + * The limit v1 keeps rather than fixes: changing only the lookup key registers the same address a + * second time. + * + *

Registration finds an address by its keyed fingerprint under the active lookup key and + * nothing else, so after the change the stored contact point is not found and a new one is made. + * Suppressions held by the first do not reach the second, and the second's id makes the same + * request a different plan with a different derived key. v1 does not support this rotation: + * startup refuses a retired lookup key and the rotation sequence says not to change one. + * + *

This test is reversed by lookup under retired keys (REV-BE-0063 option B, after v1): when + * registration also looks an address up under the previous key, the second acceptance reuses the + * first contact point and these counts become one each. + */ + @Test + void changingOnlyTheLookupKeyRegistersTheSameAddressAgainUntilLookupUnderRetiredKeysExists() { + // given + CapturingSubmit submit = new CapturingSubmit(); + InMemoryContactPointStore contactPoints = + new InMemoryContactPointStore(Clock.fixed(NOW, ZoneOffset.UTC)); + PlatformFakes.SequentialIds ids = new PlatformFakes.SequentialIds(); + AcceptNotificationCommand command = + command(Map.of("amount", new NotificationVariable.TextValue("10"))); + accept(submit, contactPoints, ids, new KeyedContactPointProtector("lookup-2026-01")) + .handle(command); + AcceptNotificationApplicationUseCase afterTheChange = + accept(submit, contactPoints, ids, new KeyedContactPointProtector("lookup-2026-08")); + + // when + afterTheChange.handle(command); + + // then + assertThat( + List.of( + (long) contactPoints.rows().size(), + submit.plans.stream() + .map(plan -> plan.recipients().getFirst().contactPoints().getFirst()) + .map(ContactPointSelector::contactPointId) + .distinct() + .count(), + submit.plans.stream().map(NotificationPlan::idempotencyKey).distinct().count())) + .as( + "[contact points for one address, contact point ids in the two plans, derived keys]" + + " — one each once lookup under retired keys exists") + .containsExactly(2L, 2L, 2L); + } + /** What each insert that lost the key to the stored request would have stored. */ private static List lostInserts(RealSubmission chain) { return chain.requests.lostInserts.stream().map(NotificationRequestRecord::acceptance).toList(); @@ -449,28 +495,26 @@ class AcceptNotificationApplicationUseCaseTest { "billing"); } + /** Acceptance over a capturing submit, sharing the store and ids with another acceptance. */ + private static AcceptNotificationApplicationUseCase accept( + CapturingSubmit submit, + InMemoryContactPointStore contactPoints, + PlatformFakes.SequentialIds ids, + ContactPointProtector protector) { + return new AcceptNotificationApplicationUseCase( + submit, + contactPoints, + protector, + PlatformFakes.tenant("tenant-a"), + ids, + PlatformFakes.fingerprints(), + new DirectTransactionPort(), + Clock.fixed(NOW, ZoneOffset.UTC), + DEFAULT_LOCALE); + } + private static ContactPointProtector protector() { - return new ContactPointProtector() { - @Override - public ProtectedContactPoint protect(ContactPointValue value) { - return new ProtectedContactPoint( - value.type(), - "test-key", - new byte[] {1}, - value.serialized().getBytes(java.nio.charset.StandardCharsets.UTF_8), - fingerprint(value)); - } - - @Override - public ContactPointValue reveal(ProtectedContactPoint value, AccessContext context) { - throw new UnsupportedOperationException("not used"); - } - - @Override - public String fingerprint(ContactPointValue value) { - return "fp:" + value.normalized(); - } - }; + return new KeyedContactPointProtector("fp"); } private static final class CapturingSubmit implements SubmitNotificationUseCase { diff --git a/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/security/testkit/KeyedContactPointProtectorTest.java b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/security/testkit/KeyedContactPointProtectorTest.java new file mode 100644 index 00000000..13aaffad --- /dev/null +++ b/src/application/notification/src/test/java/dev/caskeleton/application/notification/platform/security/testkit/KeyedContactPointProtectorTest.java @@ -0,0 +1,12 @@ +package dev.caskeleton.application.notification.platform.security.testkit; + +import dev.caskeleton.application.notification.platform.security.ContactPointProtector; + +/** The keyed fake held to the same fingerprint contract as the AES-GCM adapter. */ +class KeyedContactPointProtectorTest extends ContactPointProtectorContract { + + @Override + protected ContactPointProtector protectorUnderLookupKey(String lookupKey) { + return new KeyedContactPointProtector(lookupKey); + } +} diff --git a/src/application/notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/security/testkit/ContactPointProtectorContract.java b/src/application/notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/security/testkit/ContactPointProtectorContract.java new file mode 100644 index 00000000..2e494383 --- /dev/null +++ b/src/application/notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/security/testkit/ContactPointProtectorContract.java @@ -0,0 +1,69 @@ +package dev.caskeleton.application.notification.platform.security.testkit; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.notification.platform.contact.ContactPointValue; +import dev.caskeleton.application.notification.platform.contact.EmailAddress; +import dev.caskeleton.application.notification.platform.security.ContactPointProtector; +import dev.caskeleton.application.notification.platform.security.ProtectedContactPoint; +import org.junit.jupiter.api.Test; + +/** + * What every {@link ContactPointProtector} promises about its fingerprint, run against the keyed + * fake and the AES-GCM adapter alike. + * + *

The fingerprint is the keyed value a contact point is found, deduplicated and suppressed by + * ({@link ContactPointProtector#fingerprint}). So it is the same for the same value under the same + * lookup key, including across two protectors built from that key; the fingerprint {@code protect} + * stores is the one a later lookup computes; and the same value under another lookup key has + * another fingerprint. The last is why v1 does not rotate the lookup key: nothing finds a contact + * point by a fingerprint under a retired one. + */ +public abstract class ContactPointProtectorContract { + + private static final ContactPointValue ADDRESS = EmailAddress.parse("person@example.com"); + + /** + * A protector under the named lookup key. + * + * @param lookupKey names the lookup key; the same name gives the same key material + * @return a new protector + */ + protected abstract ContactPointProtector protectorUnderLookupKey(String lookupKey); + + @Test + void theSameValueUnderTheSameLookupKeyHasOneFingerprint() { + // given + String first = protectorUnderLookupKey("lookup-a").fingerprint(ADDRESS); + + // when + String second = protectorUnderLookupKey("lookup-a").fingerprint(ADDRESS); + + // then + assertThat(second).isEqualTo(first); + } + + @Test + void theFingerprintProtectStoresIsTheOneALookupComputes() { + // given + ContactPointProtector protector = protectorUnderLookupKey("lookup-a"); + + // when + ProtectedContactPoint stored = protector.protect(ADDRESS); + + // then + assertThat(stored.lookupHmac()).isEqualTo(protector.fingerprint(ADDRESS)); + } + + @Test + void theSameValueUnderAnotherLookupKeyHasAnotherFingerprint() { + // given + String before = protectorUnderLookupKey("lookup-a").fingerprint(ADDRESS); + + // when + String after = protectorUnderLookupKey("lookup-b").fingerprint(ADDRESS); + + // then + assertThat(after).isNotEqualTo(before); + } +} diff --git a/src/application/notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/security/testkit/KeyedContactPointProtector.java b/src/application/notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/security/testkit/KeyedContactPointProtector.java new file mode 100644 index 00000000..e8e9e891 --- /dev/null +++ b/src/application/notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/security/testkit/KeyedContactPointProtector.java @@ -0,0 +1,58 @@ +package dev.caskeleton.application.notification.platform.security.testkit; + +import dev.caskeleton.application.notification.platform.contact.ContactPointValue; +import dev.caskeleton.application.notification.platform.security.AccessContext; +import dev.caskeleton.application.notification.platform.security.ContactPointProtector; +import dev.caskeleton.application.notification.platform.security.ProtectedContactPoint; +import java.nio.charset.StandardCharsets; +import java.util.Objects; + +/** + * In-memory {@link ContactPointProtector} whose fingerprint is keyed the way the real one is. + * + *

The fingerprint depends on the lookup key this fake was built with, the contact kind and the + * identity form of the value, and on nothing else. So the same address under the same lookup key is + * one contact point, and under another lookup key it is a different one — the property a use case + * test needs to show what changing a lookup key does. It is held to {@link + * ContactPointProtectorContract} with the AES-GCM adapter. + * + *

It protects nothing: the "ciphertext" is the serialized value in clear under the key id {@code + * test-key}. It does not reveal. No test that takes it reveals a contact point, the contract has no + * case for it, and the adapter refuses every context but the unaudited dispatch path, which a fake + * that answered every context would hide. + */ +public final class KeyedContactPointProtector implements ContactPointProtector { + + private final String lookupKey; + + /** + * A protector under one lookup key. + * + * @param lookupKey names the lookup key; the same name gives the same fingerprints + */ + public KeyedContactPointProtector(String lookupKey) { + this.lookupKey = Objects.requireNonNull(lookupKey, "lookupKey"); + } + + @Override + public ProtectedContactPoint protect(ContactPointValue value) { + Objects.requireNonNull(value, "value"); + return new ProtectedContactPoint( + value.type(), + "test-key", + new byte[] {1}, + value.serialized().getBytes(StandardCharsets.UTF_8), + fingerprint(value)); + } + + @Override + public ContactPointValue reveal(ProtectedContactPoint protectedValue, AccessContext context) { + throw new UnsupportedOperationException("this fake does not reveal"); + } + + @Override + public String fingerprint(ContactPointValue value) { + Objects.requireNonNull(value, "value"); + return lookupKey + ":" + value.type().name() + ":" + value.normalized(); + } +} diff --git a/src/bootstrap/notification-platform/src/main/resources/config/module-defaults/notification.yml b/src/bootstrap/notification-platform/src/main/resources/config/module-defaults/notification.yml index d12a9bde..fb5dcb04 100644 --- a/src/bootstrap/notification-platform/src/main/resources/config/module-defaults/notification.yml +++ b/src/bootstrap/notification-platform/src/main/resources/config/module-defaults/notification.yml @@ -184,11 +184,16 @@ app: payload-encryption-key: ${APP_NOTIFICATION_PLATFORM_PAYLOAD_ENCRYPTION_KEY:} provider-request-lookup-hmac-key: ${APP_NOTIFICATION_PLATFORM_PROVIDER_REQUEST_LOOKUP_HMAC_KEY:} callback-fingerprint-hmac-key: ${APP_NOTIFICATION_PLATFORM_CALLBACK_FINGERPRINT_HMAC_KEY:} - # The id written into every envelope this key produces, one per purpose, keyed by the - # purpose's own name. Not secret — an id identifies key material without revealing it — but - # required all the same, and with no default on purpose: a constant id makes a rotation - # indistinguishable from the key it replaced, so nothing could decrypt what was written - # before it. Change the id in the same deployment that changes the material. + # The id each key is active under, one per purpose, keyed by the purpose's own name. An + # encryption key writes it into every envelope it produces; a lookup key writes it nowhere, + # because a lookup hash is not an envelope. Not secret — an id identifies key material + # without revealing it — but required all the same, and with no default on purpose: a + # constant id makes a rotation indistinguishable from the key it replaced, so nothing could + # decrypt what was written before it. Change the id in the same deployment that changes the material — except for + # the three lookup keys (CONTACT_LOOKUP_HMAC, PROVIDER_REQUEST_LOOKUP_HMAC, + # CALLBACK_FINGERPRINT_HMAC), which this version does not rotate at all: rows are found by a + # hash under the active key only, so keep the material each runs on now; the id goes into + # no hash. active-key-ids: CONTACT_ENCRYPTION: ${APP_NOTIFICATION_PLATFORM_CONTACT_ENCRYPTION_KEY_ID:} CONTACT_LOOKUP_HMAC: ${APP_NOTIFICATION_PLATFORM_CONTACT_LOOKUP_HMAC_KEY_ID:} @@ -202,7 +207,8 @@ app: # not recoverable from an id, and every consumer that resolves a key by id refuses one # carrying the wrong purpose, so a retired key filed under the wrong heading resolves and # is then rejected. Unset until a first rotation; a deployment that has never rotated needs - # none. See docs/notification/at-rest-threat-model.md for the rotation sequence. + # none. A retired lookup key is refused at startup, because nothing would read it. See + # docs/notification/at-rest-threat-model.md for the rotation sequence. historical-keys: {} # R0 compatibility provider gates. These booleans are the properties the provider