Repository navigation
feat(notifications): harden push relay credentials - #373
Conversation
📝 WalkthroughWalkthroughPush relay credential management now supports atomic storage, validated registration, rotation, renewal, synchronized sender retries, expanded admin API handling, and lifecycle-aware notification settings UI. ChangesPush relay credential lifecycle
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant AdminUI
participant AdminApplePushHandler
participant PushRelay
participant Settings
AdminUI->>AdminApplePushHandler: Register or rotate relay credential
AdminApplePushHandler->>PushRelay: POST register or rotate
PushRelay-->>AdminApplePushHandler: Credential and expiration
AdminApplePushHandler->>Settings: Persist credential fields
AdminApplePushHandler-->>AdminUI: Registration result and metadata
Possibly related PRs
Suggested labels: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Warning Review ran into problems🔥 ProblemsGit: Failed to clone repository. Please run the Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c784e15190
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| } | ||
|
|
||
| func RenewRelayCredential(ctx context.Context, settings *Settings, client RelayHTTPDoer, current PushRelayCredential) (RelayCredentialResult, error) { | ||
| result, err := RequestRelayCredential(ctx, client, current.RelayURL, relayRenewPath, current.APIKey, "") |
There was a problem hiding this comment.
Add stable idempotency to renewals
When a token_expired send path or proactive refresh renews a capability, this call omits the Idempotency-Key. If the relay successfully mints the renewed credential but the response or subsequent persistence is lost, the outbox retry still uses the old stored capability and cannot replay the same renewal; depending on relay invalidation semantics it can mint another credential or reject the old one, leaving Apple pushes stuck on an expired credential until manual re-registration. Use a deterministic renewal key, similar to rotation, for the same deployment/capability generation.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (3)
internal/notifications/settings.go (1)
169-212: 📐 Maintainability & Code Quality | 🔵 TrivialSolid atomic-write design.
Refusing non-batch-capable readers and writing all identity fields plus invalidating caches in one shot correctly upholds the "atomic unit" invariant described in the comment.
One low-cost defensive improvement worth considering: there's no validation that
credentialfields are non-empty before persisting. A future bug that calls this with a zero-value/partialPushRelayCredentialwould silently wipe a working relay credential with empty strings. Since there is currently no legitimate case for persisting an empty credential, a guard against blank required fields (RelayURL,DeploymentID,APIKey,KeyPrefix) would prevent accidental data loss from future call sites.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/notifications/settings.go` around lines 169 - 212, Add validation at the start of Settings.UpdatePushRelayCredential to reject credentials with blank RelayURL, DeploymentID, APIKey, or KeyPrefix, returning a clear error before any persistence occurs; preserve the existing atomic SetMany and cache invalidation behavior for valid credentials.web/src/pages/admin-settings/NotificationsAdminSettings.test.tsx (1)
114-116: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winHardcoded future expiry date is a test time-bomb.
"2026-08-10T00:00:00Z"(frommakeForm, Line 38) drives therenewalStatusbranch that renders "Silo renews automatically" (Line 116). Once that date passes,expiration.getTime() <= Date.now()flips true and the test will start asserting text that the component no longer renders, breaking this test with no code change.♻️ Proposed fix
- case "notifications.push_relay_expires_at": - return "2026-08-10T00:00:00Z"; + case "notifications.push_relay_expires_at": + return new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString();🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/admin-settings/NotificationsAdminSettings.test.tsx` around lines 114 - 116, Replace the hardcoded expiry in makeForm with a dynamically future date, such as one derived from the current time, so the renewalStatus branch consistently renders “Silo renews automatically” regardless of when the test runs; update the fixture while preserving the existing assertions in NotificationsAdminSettings tests.internal/notifications/push_sender.go (1)
203-233: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win
renewMuis held for every send, not just during renewal.Every call to
sendacquiresrenewMufor the full duration ofprepareRelayCredential, including the steady-state case where no renewal is due. Since legacy-key registration and proactive renewal (Lines 216-217, 223) perform network round-trips to the relay while holding this lock, every other concurrentsend(even ones that don't need renewal) is blocked until that round-trip completes. During the weekly renewal window this serializes the entire push-delivery pipeline for as long as the relay call takes.Consider a fast-path check outside the lock (mirroring the double-check already used in
renewRelayCapability), only acquiringrenewMuwhen an actual network call is required:current := LoadPushRelayCredential(ctx, s.settings) // ...normalize/validate... if !IsLegacyPushRelayKey(current.APIKey) && !current.ReregistrationRequired && !RelayCredentialNeedsRenewal(s.now(), current.ExpiresAt, current.DeploymentID) { return current, nil // no lock needed } s.renewMu.Lock() defer s.renewMu.Unlock() // re-check current state under the lock before renewing🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/notifications/push_sender.go` around lines 203 - 233, Refactor prepareRelayCredential so renewMu is not held during steady-state sends: perform normalization and credential validation first, return immediately when the credential is neither legacy nor due for renewal, then acquire renewMu only for registration or renewal. After locking, reload and re-check the credential state before making any network call, preserving the existing handling for ReregistrationRequired, RegisterRelayCredential, and RenewRelayCredential.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/notifications/push_sender.go`:
- Around line 179-201: Update pushSender.send so the retry result from
sendWithCapability after renewRelayCapability is checked for HTTP 401, and call
markReregistrationRequired with the renewed credential before returning it;
preserve the existing behavior for all other responses and ensure the renewed
result is returned unchanged.
---
Nitpick comments:
In `@internal/notifications/push_sender.go`:
- Around line 203-233: Refactor prepareRelayCredential so renewMu is not held
during steady-state sends: perform normalization and credential validation
first, return immediately when the credential is neither legacy nor due for
renewal, then acquire renewMu only for registration or renewal. After locking,
reload and re-check the credential state before making any network call,
preserving the existing handling for ReregistrationRequired,
RegisterRelayCredential, and RenewRelayCredential.
In `@internal/notifications/settings.go`:
- Around line 169-212: Add validation at the start of
Settings.UpdatePushRelayCredential to reject credentials with blank RelayURL,
DeploymentID, APIKey, or KeyPrefix, returning a clear error before any
persistence occurs; preserve the existing atomic SetMany and cache invalidation
behavior for valid credentials.
In `@web/src/pages/admin-settings/NotificationsAdminSettings.test.tsx`:
- Around line 114-116: Replace the hardcoded expiry in makeForm with a
dynamically future date, such as one derived from the current time, so the
renewalStatus branch consistently renders “Silo renews automatically” regardless
of when the test runs; update the fixture while preserving the existing
assertions in NotificationsAdminSettings tests.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 46a9ecae-dad7-48c0-a225-81fcf07526c0
📒 Files selected for processing (13)
internal/api/handlers/admin.gointernal/api/handlers/admin_apple_push.gointernal/api/handlers/admin_apple_push_test.gointernal/api/handlers/admin_settings_checks_test.gointernal/catalog/encrypted_settings_repo.gointernal/catalog/server_settings_repo.gointernal/notifications/push_sender.gointernal/notifications/push_sender_test.gointernal/notifications/relay_credentials.gointernal/notifications/relay_credentials_test.gointernal/notifications/settings.goweb/src/pages/admin-settings/NotificationsAdminSettings.test.tsxweb/src/pages/admin-settings/NotificationsAdminSettings.tsx
| func (s *pushSender) send(ctx context.Context, attempt PushDeliveryAttempt, device *PushDevice, token string) pushSendResult { | ||
| apiKey := s.settings.PushRelayAPIKey(ctx) | ||
| if apiKey == "" { | ||
| return pushSendResult{Message: "push relay API key not configured", UpstreamReason: "relay_api_key_missing"} | ||
| credential, err := s.prepareRelayCredential(ctx) | ||
| if err != nil { | ||
| return pushSendResult{HTTPStatus: http.StatusServiceUnavailable, Message: err.Error(), UpstreamReason: "relay_credential_unavailable"} | ||
| } | ||
| result := s.sendWithCapability(ctx, attempt, device, token, credential.RelayURL, credential.APIKey) | ||
| if result.HTTPStatus != http.StatusUnauthorized || result.UpstreamReason != "token_expired" { | ||
| if result.HTTPStatus == http.StatusUnauthorized { | ||
| _ = s.markReregistrationRequired(ctx, credential) | ||
| } | ||
| return result | ||
| } | ||
|
|
||
| renewed, err := s.renewRelayCapability(ctx, credential.APIKey) | ||
| if err != nil { | ||
| return pushSendResult{ | ||
| HTTPStatus: http.StatusServiceUnavailable, | ||
| UpstreamReason: "relay_renewal_failed", | ||
| Message: "push relay capability renewal failed", | ||
| } | ||
| } | ||
| return s.sendWithCapability(ctx, attempt, device, token, renewed.RelayURL, renewed.APIKey) | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Second post-renewal 401 doesn't mark re-registration.
If renewRelayCapability succeeds but the freshly renewed credential is itself immediately rejected with 401 on the retry (Line 200), the result is just returned — markReregistrationRequired is only called for the first send's 401 (Line 187), not for this final one. This silently drops the signal that the relay is rejecting even a freshly minted capability, so the deployment stays "healthy" from the admin's perspective until the credential's real expiry is hit again.
🐛 Proposed fix
- renewed, err := s.renewRelayCapability(ctx, credential.APIKey)
- if err != nil {
- return pushSendResult{
- HTTPStatus: http.StatusServiceUnavailable,
- UpstreamReason: "relay_renewal_failed",
- Message: "push relay capability renewal failed",
- }
- }
- return s.sendWithCapability(ctx, attempt, device, token, renewed.RelayURL, renewed.APIKey)
+ renewed, err := s.renewRelayCapability(ctx, credential.APIKey)
+ if err != nil {
+ return pushSendResult{
+ HTTPStatus: http.StatusServiceUnavailable,
+ UpstreamReason: "relay_renewal_failed",
+ Message: "push relay capability renewal failed",
+ }
+ }
+ finalResult := s.sendWithCapability(ctx, attempt, device, token, renewed.RelayURL, renewed.APIKey)
+ if finalResult.HTTPStatus == http.StatusUnauthorized {
+ _ = s.markReregistrationRequired(ctx, renewed)
+ }
+ return finalResult📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| func (s *pushSender) send(ctx context.Context, attempt PushDeliveryAttempt, device *PushDevice, token string) pushSendResult { | |
| apiKey := s.settings.PushRelayAPIKey(ctx) | |
| if apiKey == "" { | |
| return pushSendResult{Message: "push relay API key not configured", UpstreamReason: "relay_api_key_missing"} | |
| credential, err := s.prepareRelayCredential(ctx) | |
| if err != nil { | |
| return pushSendResult{HTTPStatus: http.StatusServiceUnavailable, Message: err.Error(), UpstreamReason: "relay_credential_unavailable"} | |
| } | |
| result := s.sendWithCapability(ctx, attempt, device, token, credential.RelayURL, credential.APIKey) | |
| if result.HTTPStatus != http.StatusUnauthorized || result.UpstreamReason != "token_expired" { | |
| if result.HTTPStatus == http.StatusUnauthorized { | |
| _ = s.markReregistrationRequired(ctx, credential) | |
| } | |
| return result | |
| } | |
| renewed, err := s.renewRelayCapability(ctx, credential.APIKey) | |
| if err != nil { | |
| return pushSendResult{ | |
| HTTPStatus: http.StatusServiceUnavailable, | |
| UpstreamReason: "relay_renewal_failed", | |
| Message: "push relay capability renewal failed", | |
| } | |
| } | |
| return s.sendWithCapability(ctx, attempt, device, token, renewed.RelayURL, renewed.APIKey) | |
| } | |
| func (s *pushSender) send(ctx context.Context, attempt PushDeliveryAttempt, device *PushDevice, token string) pushSendResult { | |
| credential, err := s.prepareRelayCredential(ctx) | |
| if err != nil { | |
| return pushSendResult{HTTPStatus: http.StatusServiceUnavailable, Message: err.Error(), UpstreamReason: "relay_credential_unavailable"} | |
| } | |
| result := s.sendWithCapability(ctx, attempt, device, token, credential.RelayURL, credential.APIKey) | |
| if result.HTTPStatus != http.StatusUnauthorized || result.UpstreamReason != "token_expired" { | |
| if result.HTTPStatus == http.StatusUnauthorized { | |
| _ = s.markReregistrationRequired(ctx, credential) | |
| } | |
| return result | |
| } | |
| renewed, err := s.renewRelayCapability(ctx, credential.APIKey) | |
| if err != nil { | |
| return pushSendResult{ | |
| HTTPStatus: http.StatusServiceUnavailable, | |
| UpstreamReason: "relay_renewal_failed", | |
| Message: "push relay capability renewal failed", | |
| } | |
| } | |
| finalResult := s.sendWithCapability(ctx, attempt, device, token, renewed.RelayURL, renewed.APIKey) | |
| if finalResult.HTTPStatus == http.StatusUnauthorized { | |
| _ = s.markReregistrationRequired(ctx, renewed) | |
| } | |
| return finalResult | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/notifications/push_sender.go` around lines 179 - 201, Update
pushSender.send so the retry result from sendWithCapability after
renewRelayCapability is checked for HTTP 401, and call
markReregistrationRequired with the renewed credential before returning it;
preserve the existing behavior for all other responses and ensure the renewed
result is returned unchanged.
Problem
Silo's Apple push relay integration could register capabilities, but credential rotation still created a new anonymous deployment, renewal was reactive-only, and sequential settings writes could leave mismatched credential state after partial failure. Legacy
rk_credentials also need a safe migration path before the hosted relay moves to the Worker.Approach
/v1/deployments/rotatewith a deterministic idempotency key so lost responses replay the same credentialtoken_expiredrecoveryrk_credentials; rejected modern capabilities require explicit admin re-registrationhttps://push.siloserver.orgplus an exact operator-configuredSILO_PUSH_RELAY_DEVELOPMENT_URLVerification
GOWORK=off go test -race ./internal/notifications ./internal/api/handlers ./internal/catalogcd web && pnpm exec vitest run src/pages/admin-settings/NotificationsAdminSettings.test.tsxcd web && pnpm run lint(0 errors; existing repository warnings only)cd web && pnpm run format:checkmake verify-local-pathsLive integration against the explicitly configured staging Worker origin:
Risks and rollout
push.siloserver.organd production DNS are unchanged; production must not move to the Worker until the compatibility window is ready/api/v1behavior remains additive-onlyPart of #135
AI use disclosure
Implemented and verified with OpenAI Codex under human direction.