Skip to content

feat(notifications): harden push relay credentials - #373

Merged
Quick104 merged 1 commit into
mainfrom
codex/push-relay-credential-lifecycle
Jul 10, 2026
Merged

Quick104 merged 1 commit into
mainfrom
codex/push-relay-credential-lifecycle

Conversation

@Quick104

@Quick104 Quick104 commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

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

  • add a shared relay credential lifecycle for registration, authenticated rotation, renewal, and legacy migration
  • rotate through /v1/deployments/rotate with a deterministic idempotency key so lost responses replay the same credential
  • renew proactively during the final week with deterministic per-deployment jitter, while retaining reactive token_expired recovery
  • persist relay URL, deployment ID, encrypted capability, expiration, key prefix, and re-registration status in one PostgreSQL transaction
  • auto-register only legacy rk_ credentials; rejected modern capabilities require explicit admin re-registration
  • restrict relay destinations to https://push.siloserver.org plus an exact operator-configured SILO_PUSH_RELAY_DEVELOPMENT_URL
  • update the admin UI to distinguish registration, rotation, and re-registration while showing safe expiration/renewal state
  • keep one delivery-attempt idempotency key across transport, renewal, and outbox retries

Verification

  • GOWORK=off go test -race ./internal/notifications ./internal/api/handlers ./internal/catalog
  • cd web && pnpm exec vitest run src/pages/admin-settings/NotificationsAdminSettings.test.tsx
  • cd web && pnpm run lint (0 errors; existing repository warnings only)
  • cd web && pnpm run format:check
  • make verify-local-paths
  • production frontend build completed during the dev image build

Live integration against the explicitly configured staging Worker origin:

  • deployed the branch to the development Silo Server
  • migrated the existing encrypted legacy relay credential through the admin registration endpoint
  • verified all credential fields were persisted together and the capability remained encrypted
  • sent an admin test notification to a real sandbox Apple device
  • delivery completed on the first attempt with relay HTTP 200

Risks and rollout

  • push.siloserver.org and production DNS are unchanged; production must not move to the Worker until the compatibility window is ready
  • staging/custom relay use requires the explicit development override; arbitrary HTTPS relay destinations are rejected
  • no Apple-client API changes are required
  • existing /api/v1 behavior remains additive-only

Part of #135

AI use disclosure

Implemented and verified with OpenAI Codex under human direction.

@coderabbitai

coderabbitai Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Push relay credential management now supports atomic storage, validated registration, rotation, renewal, synchronized sender retries, expanded admin API handling, and lifecycle-aware notification settings UI.

Changes

Push relay credential lifecycle

Layer / File(s) Summary
Atomic credential storage
internal/notifications/settings.go, internal/catalog/*, internal/api/handlers/admin_settings_checks_test.go
Push relay credentials are normalized and persisted atomically through encrypted batch writes and transactional server-setting upserts.
Relay registration, rotation, and renewal
internal/notifications/relay_credentials.go, internal/notifications/relay_credentials_test.go
Relay URL validation, credential requests, structured errors, deterministic idempotency, deployment checks, persistence, and re-registration state are implemented and tested.
Push delivery renewal and retry
internal/notifications/push_sender.go, internal/notifications/push_sender_test.go
Push delivery synchronizes credential renewal, handles expired capabilities, retries with renewed credentials, and preserves a stable idempotency key.
Admin registration and managed settings
internal/api/handlers/admin.go, internal/api/handlers/admin_apple_push.go, internal/api/handlers/*test.go
Admin registration supports registration and rotation, returns expiration metadata, maps relay errors, and blocks direct writes to managed relay fields.
Notification settings lifecycle UI
web/src/pages/admin-settings/NotificationsAdminSettings.tsx, web/src/pages/admin-settings/NotificationsAdminSettings.test.tsx
The UI displays credential metadata, expiration status, registration actions, and re-registration warnings.

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
Loading

Possibly related PRs

Suggested labels: v1

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 3.70% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is concise and accurately summarizes the main change: hardening push relay credential handling in notifications.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/push-relay-credential-lifecycle

Warning

Review ran into problems

🔥 Problems

Git: Failed to clone repository. Please run the @coderabbitai full review command to re-trigger a full review. If the issue persists, set path_filters to include or exclude specific files.


Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jul 10, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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, "")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

@Quick104
Quick104 merged commit d6d6a9f into main Jul 10, 2026
2 checks passed
@Quick104
Quick104 deleted the codex/push-relay-credential-lifecycle branch July 10, 2026 16:10

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
internal/notifications/settings.go (1)

169-212: 📐 Maintainability & Code Quality | 🔵 Trivial

Solid 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 credential fields are non-empty before persisting. A future bug that calls this with a zero-value/partial PushRelayCredential would 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 win

Hardcoded future expiry date is a test time-bomb.

"2026-08-10T00:00:00Z" (from makeForm, Line 38) drives the renewalStatus branch 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

renewMu is held for every send, not just during renewal.

Every call to send acquires renewMu for the full duration of prepareRelayCredential, 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 concurrent send (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 acquiring renewMu when 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

📥 Commits

Reviewing files that changed from the base of the PR and between e57faa1 and c784e15.

📒 Files selected for processing (13)
  • internal/api/handlers/admin.go
  • internal/api/handlers/admin_apple_push.go
  • internal/api/handlers/admin_apple_push_test.go
  • internal/api/handlers/admin_settings_checks_test.go
  • internal/catalog/encrypted_settings_repo.go
  • internal/catalog/server_settings_repo.go
  • internal/notifications/push_sender.go
  • internal/notifications/push_sender_test.go
  • internal/notifications/relay_credentials.go
  • internal/notifications/relay_credentials_test.go
  • internal/notifications/settings.go
  • web/src/pages/admin-settings/NotificationsAdminSettings.test.tsx
  • web/src/pages/admin-settings/NotificationsAdminSettings.tsx

Comment on lines 179 to +201
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)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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.

Suggested change
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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v1.0 Silo v1 scope - auto-adds to the Silo v1 project

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant