Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Add hosted iOS push diagnostics and delivery safeguards (#3541)

Juan José Matad46b383267ac
diff --git a/app/controllers/admin/system_health_controller.rb b/app/controllers/admin/system_health_controller.rb
index ab4fc1f1c3..b442d7f062 100644
--- a/app/controllers/admin/system_health_controller.rb
+++ b/app/controllers/admin/system_health_controller.rb
@@ -2,12 +2,22 @@
module Admin
class SystemHealthController < Admin::BaseController
+ before_action :require_hosted_push, only: :send_test_push
+
# Bypass the per-request memo / cross-request cache that the layout
# banner uses. An operator landing on this page (often right after
# restarting the worker) wants to confirm the current state, not a
# snapshot up to `SidekiqHealth::CACHE_TTL` old. Also makes the page
# work in managed mode, where `current_sidekiq_health` is nil.
def show
+ tabs = %w[background_jobs ai]
+ @active_tab = params[:tab].presence_in(tabs) || "background_jobs"
+ if Apns::Client.hosted? && @active_tab == "background_jobs"
+ @push_notification_test = PushNotificationTest.new(Current.user)
+ @push_disabled_reason = @push_notification_test.disabled_reason
+ @latest_push_test = @push_notification_test.latest
+ @push_test_results = @latest_push_test ? @push_notification_test.results(@latest_push_test) : []
+ end
SidekiqHealth.expire_cache!
@health = SidekiqHealth.new
ai_tab = params[:tab] == "ai"
@@ -26,5 +36,16 @@ module Admin
WorkerAiHealth.request_check!
redirect_to admin_system_health_path(tab: "ai"), notice: t(".queued")
end
+
+ def send_test_push
+ result = PushNotificationTest.new(Current.user).request!
+ flash[result == :queued ? :notice : :alert] = t("admin.system_health.push_notifications.messages.#{result}")
+ redirect_to admin_system_health_path(tab: "background_jobs", anchor: "push-notifications"), status: :see_other
+ end
+
+ private
+ def require_hosted_push
+ head :not_found unless Apns::Client.hosted?
+ end
end
end
diff --git a/app/controllers/api/v1/push_subscriptions_controller.rb b/app/controllers/api/v1/push_subscriptions_controller.rb
index dcf4b85324..e3a054873c 100644
--- a/app/controllers/api/v1/push_subscriptions_controller.rb
+++ b/app/controllers/api/v1/push_subscriptions_controller.rb
@@ -2,6 +2,7 @@
class Api::V1::PushSubscriptionsController < Api::V1::BaseController
before_action :ensure_write_scope
+ before_action :require_hosted_push
def create
subscription = PushSubscription.register_for!(user: current_resource_owner,
@@ -23,6 +24,13 @@ class Api::V1::PushSubscriptionsController < Api::V1::BaseController
end
private
+ def require_hosted_push
+ return if Apns::Client.hosted?
+
+ render json: { error: "feature_disabled", message: "Push notifications are available only in hosted mode" },
+ status: :forbidden
+ end
+
def ensure_write_scope
authorize_scope!(:write)
end
diff --git a/app/jobs/deliver_insight_notification_job.rb b/app/jobs/deliver_insight_notification_job.rb
index 225b494110..7dc1966c86 100644
--- a/app/jobs/deliver_insight_notification_job.rb
+++ b/app/jobs/deliver_insight_notification_job.rb
@@ -3,14 +3,14 @@
class DeliverInsightNotificationJob < ApplicationJob
queue_as :scheduled
- retry_on StandardError, wait: :polynomially_longer, attempts: 5
+ retry_on Apns::Client::TransientError, wait: :polynomially_longer, attempts: 5
discard_on ActiveRecord::RecordNotFound
def self.enqueue_for(insight)
- return unless Apns::Client.configured?
+ return unless Apns::Client.available? && insight.priority_high? && insight.active?
insight.family.users.includes(:push_subscriptions).find_each do |user|
- next unless user.preview_features_enabled?
+ next unless user.active? && user.preview_features_enabled?
user.push_subscriptions.recent.find_each do |subscription|
perform_later(insight_id: insight.id, push_subscription_id: subscription.id)
@@ -19,41 +19,23 @@ class DeliverInsightNotificationJob < ApplicationJob
end
def perform(insight_id:, push_subscription_id:)
+ return unless Apns::Client.available?
+
insight = Insight.find(insight_id)
subscription = PushSubscription.find(push_subscription_id)
return unless subscription.user.family_id == insight.family_id
-
- response = I18n.with_locale(insight.family.locale) do
- Apns::Client.new(environment: subscription.environment).deliver(
- token: subscription.token,
- title: I18n.t("insights.notification.title"),
- body: I18n.t("insights.notification.body"),
- insight_id: insight.id
- )
- end
- return if response.ok?
-
- if invalid_token_response?(response)
- subscription.destroy!
- return
+ return unless subscription.eligible? && subscription.user.preview_features_enabled?
+ return unless insight.priority_high? && insight.active?
+
+ PushSubscription::Delivery.new(subscription).call do |client|
+ I18n.with_locale(insight.family.locale) do
+ client.deliver(
+ token: subscription.token,
+ title: I18n.t("insights.notification.title"),
+ body: I18n.t("insights.notification.body"),
+ insight_id: insight.id
+ )
+ end
end
-
- raise "APNs rejected notification with status #{response.status}: #{response.body.inspect}"
- rescue => e
- DebugLogEntry.capture(
- category: "insights",
- level: "error",
- message: "Failed to deliver insight notification: #{e.class}: #{e.message}",
- source: "DeliverInsightNotificationJob",
- family: insight&.family,
- metadata: { insight_id: insight_id, push_subscription_id: push_subscription_id }
- )
- raise
end
-
- private
- def invalid_token_response?(response)
- response.status == "410" ||
- (response.status == "400" && response.body.is_a?(Hash) && response.body["reason"] == "BadDeviceToken")
- end
end
diff --git a/app/jobs/deliver_test_push_notification_job.rb b/app/jobs/deliver_test_push_notification_job.rb
new file mode 100644
index 0000000000..bede2ba1d1
--- /dev/null
+++ b/app/jobs/deliver_test_push_notification_job.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+
+class DeliverTestPushNotificationJob < ApplicationJob
+ queue_as :scheduled
+ # The request is already in the shared cache; no uncommitted database row is
+ # needed by the worker. Surface enqueue failures while the request is handled.
+ self.enqueue_after_transaction_commit = false
+ sidekiq_options lock: :until_executed, on_conflict: :log
+
+ retry_on Apns::Client::TransientError, wait: :polynomially_longer, attempts: 5 do |job, _error|
+ arguments = job.arguments.first.symbolize_keys
+ if (user = User.find_by(id: arguments[:user_id]))
+ PushNotificationTest.new(user).record(arguments[:request_id], arguments[:push_subscription_id], :failed)
+ end
+ end
+ discard_on ActiveRecord::RecordNotFound
+
+ def perform(user_id:, request_id:, push_subscription_id:)
+ user = User.find(user_id)
+ PushNotificationTest.new(user).deliver(request_id: request_id, push_subscription_id: push_subscription_id)
+ end
+end
diff --git a/app/models/push_notification_test.rb b/app/models/push_notification_test.rb
new file mode 100644
index 0000000000..0a9faa0d75
--- /dev/null
+++ b/app/models/push_notification_test.rb
@@ -0,0 +1,121 @@
+# frozen_string_literal: true
+
+# Short-lived operator diagnostics, like WorkerAiHealth. Production web and
+# Sidekiq must use the same Redis cache. This is not an insight delivery ledger.
+class PushNotificationTest
+ RETENTION = 24.hours
+ SEND_WINDOW = 15.minutes
+ COOLDOWN = 30.seconds
+ TERMINAL_STATUSES = %w[accepted skipped rejected unregistered failed enqueue_failed].freeze
+
+ attr_reader :user
+
+ def initialize(user, cache: Rails.cache)
+ @user = user
+ @cache = cache
+ end
+
+ def disabled_reason
+ return :hosted_only unless Apns::Client.hosted?
+ return :ineligible unless user.active? && user.super_admin?
+ return :no_devices unless user.push_subscriptions.recent.exists?
+ return :disabled if ENV["APNS_ENABLED"] == "false"
+ return :not_configured unless Apns::Client.configured?
+ request = latest
+ :cooldown if request && request[:created_at] > COOLDOWN.ago
+ end
+
+ def latest
+ @cache.read(latest_key)
+ end
+
+ def results(request)
+ request[:subscriptions].map do |subscription|
+ result = @cache.read(result_key(request[:id], subscription[:id]))
+ result = nil if result && !TERMINAL_STATUSES.include?(result[:status]) && request[:created_at] < SEND_WINDOW.ago
+ status = request[:created_at] < SEND_WINDOW.ago ? "expired" : "queued"
+ subscription.merge(result || { status: status, checked_at: nil })
+ end
+ end
+
+ def request!
+ # Serialize double-clicks across web processes for this account.
+ user.with_lock do
+ reason = disabled_reason
+ return reason if reason
+
+ subscriptions = user.push_subscriptions.recent.order(:id).map { |s| { id: s.id, environment: s.environment } }
+ return :no_devices if subscriptions.empty?
+
+ request = { id: SecureRandom.uuid, created_at: Time.current, subscriptions: subscriptions }
+ return :storage_unavailable unless @cache.write(request_key(request[:id]), request, expires_in: RETENTION)
+ return :storage_unavailable unless @cache.write(latest_key, request, expires_in: RETENTION)
+
+ queued = 0
+ subscriptions.each do |subscription|
+ begin
+ job = DeliverTestPushNotificationJob.perform_later(
+ user_id: user.id, request_id: request[:id], push_subscription_id: subscription[:id]
+ )
+ if job
+ queued += 1
+ else
+ record(request[:id], subscription[:id], :enqueue_failed)
+ end
+ rescue ActiveJob::EnqueueError, Redis::BaseError, RedisClient::Error
+ record(request[:id], subscription[:id], :enqueue_failed)
+ end
+ end
+ queued.positive? ? :queued : :enqueue_failed
+ end
+ end
+
+ def deliver(request_id:, push_subscription_id:)
+ request = @cache.read(request_key(request_id))
+ return unless request && request[:subscriptions].any? { |s| s[:id] == push_subscription_id }
+
+ # Each device has its own result key: one worker cannot overwrite another
+ # device's outcome. Terminal results suppress ordinary job replays.
+ previous = @cache.read(result_key(request_id, push_subscription_id))
+ return if previous && TERMINAL_STATUSES.include?(previous[:status])
+
+ subscription = user.push_subscriptions.find_by(id: push_subscription_id)
+ unless Apns::Client.available? && user.active? && user.super_admin? &&
+ subscription&.eligible? && request[:created_at] > SEND_WINDOW.ago
+ return record(request_id, push_subscription_id, :skipped)
+ end
+
+ result = PushSubscription::Delivery.new(subscription).call do |client|
+ I18n.with_locale(user.locale.presence || user.family.locale) do
+ client.deliver_test(
+ token: subscription.token,
+ title: I18n.t("admin.system_health.push_notification.title"),
+ body: I18n.t("admin.system_health.push_notification.body"),
+ request_id: request_id
+ )
+ end
+ end
+ record(request_id, push_subscription_id, result)
+ rescue Apns::Client::TransientError
+ record(request_id, push_subscription_id, :retrying)
+ raise
+ end
+
+ def record(request_id, subscription_id, status)
+ @cache.write(result_key(request_id, subscription_id),
+ { status: status.to_s, checked_at: Time.current }, expires_in: RETENTION)
+ end
+
+ private
+ def latest_key
+ "push_notification_test/v1/#{user.id}/latest"
+ end
+
+ def request_key(request_id)
+ "push_notification_test/v1/#{user.id}/#{request_id}"
+ end
+
+ def result_key(request_id, subscription_id)
+ "#{request_key(request_id)}/#{subscription_id}"
+ end
+end
diff --git a/app/models/push_subscription.rb b/app/models/push_subscription.rb
index b22fded197..38a7af887e 100644
--- a/app/models/push_subscription.rb
+++ b/app/models/push_subscription.rb
@@ -7,8 +7,11 @@ class PushSubscription < ApplicationRecord
normalizes :token, with: ->(token) { token.downcase }
+ # Keep hexadecimal tokens below PostgreSQL's B-tree entry limit for the
+ # unique lower(token) index, even when the value cannot be compressed.
validates :token, presence: true, uniqueness: { case_sensitive: false },
- format: { with: /\A[0-9a-f]{64,200}\z/i }
+ length: { maximum: 2048 },
+ format: { with: /\A(?:[0-9a-f]{2})+\z/i }
validates :platform, inclusion: { in: %w[ios] }
validates :last_registered_at, presence: true
@@ -50,4 +53,23 @@ class PushSubscription < ApplicationRecord
end
scope :recent, -> { where("last_registered_at > ?", 90.days.ago) }
+
+ def eligible?
+ user.active? && last_registered_at > 90.days.ago
+ end
+
+ # A response may arrive after the app has registered again. Only remove the
+ # exact registration sent, and respect APNs' invalidation timestamp when given.
+ def invalidate_if_unchanged!(response)
+ return unless response.status.to_i == 410
+
+ timestamp = response.body.is_a?(Hash) && response.body["timestamp"]
+ if timestamp
+ return unless timestamp.is_a?(Numeric) && timestamp.positive? && timestamp.finite?
+ return if last_registered_at.to_f * 1000 > timestamp
+ end
+
+ self.class.where(id: id, token: token, environment: environment,
+ last_registered_at: last_registered_at).delete_all
+ end
end
diff --git a/app/models/push_subscription/delivery.rb b/app/models/push_subscription/delivery.rb
new file mode 100644
index 0000000000..111e9d87e6
--- /dev/null
+++ b/app/models/push_subscription/delivery.rb
@@ -0,0 +1,48 @@
+# frozen_string_literal: true
+
+# Shared response handling for financial alerts and explicit admin diagnostics.
+class PushSubscription::Delivery
+ def initialize(subscription)
+ @subscription = subscription
+ end
+
+ def call
+ return :skipped unless Apns::Client.available? && @subscription.eligible?
+
+ response = yield Apns::Client.new(environment: @subscription.environment)
+ return :accepted if response.ok?
+
+ status = response.status.to_i
+ if status == 429 || (500..599).cover?(status)
+ raise Apns::Client::TransientError, "APNs temporarily rejected the request (#{status})"
+ end
+
+ record_failure(status)
+ if status == 410
+ @subscription.invalidate_if_unchanged!(response)
+ :unregistered
+ else
+ # BadDeviceToken can mean the environment is wrong. Preserve the record
+ # for diagnosis and renewal rather than deleting every 400 response.
+ :rejected
+ end
+ rescue Apns::Client::UnavailableError
+ :skipped
+ rescue Apns::Client::ConfigurationError
+ record_failure(:configuration)
+ :failed
+ rescue Apns::Client::TransientError
+ record_failure(:transient)
+ raise
+ end
+
+ private
+ def record_failure(code)
+ DebugLogEntry.capture(
+ category: "push_notifications", level: "error",
+ message: "Push delivery failed (#{code})", source: self.class.name,
+ user: @subscription.user, family: @subscription.user.family,
+ metadata: { push_subscription_id: @subscription.id, environment: @subscription.environment, failure_code: code }
+ )
+ end
+end
diff --git a/app/services/apns/client.rb b/app/services/apns/client.rb
index 0b2d93f8f8..c8c5d627af 100644
--- a/app/services/apns/client.rb
+++ b/app/services/apns/client.rb
@@ -8,6 +8,18 @@ module Apns
class Client
REQUIRED_ENV_KEYS = %w[APNS_KEY_ID APNS_TEAM_ID APNS_BUNDLE_ID APNS_PRIVATE_KEY_BASE64].freeze
+ UnavailableError = Class.new(StandardError)
+ ConfigurationError = Class.new(StandardError)
+ TransientError = Class.new(StandardError)
+
+ def self.hosted?
+ Rails.application.config.app_mode.managed?
+ end
+
+ def self.available?
+ hosted? && ENV["APNS_ENABLED"] != "false" && configured?
+ end
+
def self.configured?
REQUIRED_ENV_KEYS.all? { |key| ENV[key].present? }
end
@@ -17,28 +29,47 @@ module Apns
end
def deliver(token:, title:, body:, insight_id:)
- raise "APNs credentials are not configured" unless self.class.configured?
-
- connection = build_connection
- notification = Apnotic::Notification.new(token)
- notification.alert = { title: title, body: body }
- notification.sound = "default"
- notification.topic = ENV.fetch("APNS_BUNDLE_ID")
- notification.push_type = "alert"
- notification.apns_collapse_id = "insight-#{insight_id}"
- notification.custom_payload = { insight_id: insight_id, destination: "insights" }
-
- connection.push(notification).tap do |response|
- raise "APNs request timed out" unless response
- end
- ensure
- connection&.close
+ push(token: token, title: title, body: body,
+ payload: { insight_id: insight_id, destination: "insights" },
+ collapse_id: "insight-#{insight_id}", expires_at: 1.hour.from_now)
+ end
+
+ def deliver_test(token:, title:, body:, request_id:)
+ push(token: token, title: title, body: body,
+ payload: { notification_type: "test", destination: "overview" },
+ collapse_id: "test-#{request_id}", expires_at: 5.minutes.from_now)
end
private
+
+ def push(token:, title:, body:, payload:, collapse_id:, expires_at:)
+ raise UnavailableError, "Push delivery is unavailable" unless self.class.available?
+
+ connection = build_connection
+ notification = Apnotic::Notification.new(token)
+ notification.alert = { title: title, body: body }
+ notification.sound = "default"
+ notification.topic = ENV.fetch("APNS_BUNDLE_ID")
+ notification.push_type = "alert"
+ notification.apns_collapse_id = collapse_id
+ notification.expiration = expires_at.to_i
+ notification.custom_payload = payload
+
+ connection.push(notification, timeout: 10).tap do |response|
+ raise TransientError, "APNs request timed out" unless response
+ end
+ rescue ArgumentError, OpenSSL::PKey::PKeyError
+ raise ConfigurationError, "APNs signing configuration is invalid"
+ rescue IOError, SystemCallError, Timeout::Error, SocketError, NetHttp2::AsyncRequestTimeout, OpenSSL::SSL::SSLError
+ raise TransientError, "APNs connection failed"
+ ensure
+ connection&.close
+ end
+
def build_connection
options = {
auth_method: :token,
+ connect_timeout: 10,
cert_path: StringIO.new(Base64.strict_decode64(ENV.fetch("APNS_PRIVATE_KEY_BASE64"))),
key_id: ENV.fetch("APNS_KEY_ID"),
team_id: ENV.fetch("APNS_TEAM_ID")
diff --git a/app/views/admin/system_health/_background_jobs.html.erb b/app/views/admin/system_health/_background_jobs.html.erb
index 72af867fd0..ccf45adbef 100644
--- a/app/views/admin/system_health/_background_jobs.html.erb
+++ b/app/views/admin/system_health/_background_jobs.html.erb
@@ -100,4 +100,8 @@
</table>
<% end %>
</div>
+ <% if push_notification_test %>
+ <%= render "push_notifications", disabled_reason: push_disabled_reason,
+ latest_test: latest_push_test, results: push_test_results %>
+ <% end %>
</div>
diff --git a/app/views/admin/system_health/_push_notifications.html.erb b/app/views/admin/system_health/_push_notifications.html.erb
new file mode 100644
index 0000000000..e28a50babd
--- /dev/null
+++ b/app/views/admin/system_health/_push_notifications.html.erb
@@ -0,0 +1,58 @@
+<section id="push-notifications" class="bg-container rounded-xl shadow-border-xs p-4 space-y-4" data-testid="push-notification-status" aria-labelledby="push-notifications-title">
+ <div class="flex flex-wrap items-center justify-between gap-3">
+ <div class="space-y-1">
+ <h2 id="push-notifications-title" class="text-lg font-semibold text-primary"><%= t("admin.system_health.push_notifications.title") %></h2>
+ <% if latest_test %>
+ <p class="text-sm text-secondary"><%= t("admin.system_health.push_notifications.requested_at", time: l(latest_test[:created_at], format: :long)) %></p>
+ <% end %>
+ </div>
+ <%= render DS::Button.new(
+ href: send_test_push_admin_system_health_path,
+ method: :post,
+ variant: :outline,
+ size: :sm,
+ icon: "bell-ring",
+ text: t("admin.system_health.push_notifications.send_test"),
+ disabled: disabled_reason.present?,
+ class: "disabled:opacity-50",
+ aria: { describedby: "push-notification-help" },
+ data: { turbo_submits_with: t("admin.system_health.push_notifications.queueing") }
+ ) %>
+ </div>
+
+ <p id="push-notification-help" class="text-sm text-secondary">
+ <%= t("admin.system_health.push_notifications.messages.#{disabled_reason || :ready}") %>
+ </p>
+
+ <% if latest_test %>
+ <div class="space-y-3">
+ <p class="text-sm text-secondary"><%= t("admin.system_health.push_notifications.result_help") %></p>
+ <div class="overflow-x-auto">
+ <table class="w-full text-sm text-left">
+ <thead>
+ <tr class="border-b border-primary text-secondary">
+ <% %w[device environment status checked_at].each do |column| %>
+ <th scope="col" class="py-2 font-medium"><%= t("admin.system_health.push_notifications.columns.#{column}") %></th>
+ <% end %>
+ </tr>
+ </thead>
+ <tbody>
+ <% results.each_with_index do |result, index| %>
+ <tr class="border-b border-primary text-primary">
+ <th scope="row" class="py-2 font-medium"><%= t("admin.system_health.push_notifications.device", number: index + 1) %></th>
+ <td class="py-2"><%= t("admin.system_health.push_notifications.environments.#{result[:environment]}") %></td>
+ <td class="py-2"><%= t("admin.system_health.push_notifications.statuses.#{result[:status]}") %></td>
+ <td class="py-2"><%= result[:checked_at] ? l(result[:checked_at], format: :long) : t("admin.system_health.push_notifications.pending") %></td>
+ </tr>
+ <% end %>
+ </tbody>
+ </table>
+ </div>
+ <%= render DS::Button.new(
+ href: admin_system_health_path(tab: "background_jobs", anchor: "push-notifications"), method: :get,
+ variant: :outline, size: :sm, icon: "refresh-cw",
+ text: t("admin.system_health.push_notifications.refresh")
+ ) %>
+ </div>
+ <% end %>
+</section>
diff --git a/app/views/admin/system_health/show.html.erb b/app/views/admin/system_health/show.html.erb
index 148decd6ce..ad753d991c 100644
--- a/app/views/admin/system_health/show.html.erb
+++ b/app/views/admin/system_health/show.html.erb
@@ -1,7 +1,7 @@
<%= content_for :page_title, t(".title") %>
<%= render DS::Tabs.new(
- active_tab: params[:tab].presence_in(%w[background_jobs ai]) || "background_jobs",
+ active_tab: @active_tab,
url_param_key: "tab",
navigate_on_change: true,
testid: "system-health-tabs"
@@ -12,7 +12,9 @@
<% end %>
<% tabs.with_panel(tab_id: "background_jobs") do %>
- <%= render "background_jobs", health: @health %>
+ <%= render "background_jobs", health: @health, push_notification_test: @push_notification_test,
+ push_disabled_reason: @push_disabled_reason, latest_push_test: @latest_push_test,
+ push_test_results: @push_test_results %>
<% end %>
<% tabs.with_panel(tab_id: "ai") do %>
diff --git a/config/locales/views/admin/system_health/de.yml b/config/locales/views/admin/system_health/de.yml
index f6346bb2dd..0fc2e69353 100644
--- a/config/locales/views/admin/system_health/de.yml
+++ b/config/locales/views/admin/system_health/de.yml
@@ -2,6 +2,47 @@
de:
admin:
system_health:
+ push_notifications:
+ send_test: "Testbenachrichtigung senden"
+ queueing: "Wird eingereiht…"
+ title: "Push-Benachrichtigungen"
+ requested_at: "Letzter Test angefordert am %{time}"
+ result_help: "Die Annahme durch APNs bestätigt nicht die Zustellung auf deinem Gerät. Aktualisiere die Ergebnisse, um den Worker-Status zu sehen. Ergebnisse werden 24 Stunden gespeichert."
+ device: "Gerät %{number}"
+ pending: "Ausstehend"
+ refresh: "Ergebnisse aktualisieren"
+ columns:
+ device: "Gerät"
+ environment: "APNs-Umgebung"
+ status: "Ergebnis"
+ checked_at: "Letzte Aktualisierung"
+ environments:
+ sandbox: "Sandbox"
+ production: "Produktion"
+ messages:
+ enqueue_failed: "Der Test konnte nicht eingereiht werden. Prüfe Sidekiq und aktualisiere die Ergebnisse unten."
+ ready: "Sende eine Testbenachrichtigung an die für dein Konto registrierten, aktivierten iOS-Geräte."
+ queued: "Testbenachrichtigung eingereiht. Aktualisiere die Ergebnisse unten, um den Status zu prüfen."
+ hosted_only: "Push-Benachrichtigungen sind nur im gehosteten Modus verfügbar."
+ ineligible: "Nur ein aktiver Super-Admin kann eine Testbenachrichtigung senden."
+ no_devices: "Aktiviere Push-Benachrichtigungen in der Sure-iOS-App für dieses Konto, um einen Test zu senden."
+ disabled: "Der Betreiber hat den Push-Versand deaktiviert."
+ not_configured: "Die APNs-Zugangsdaten sind nicht konfiguriert."
+ cooldown: "Bitte warte 30 Sekunden, bevor du einen weiteren Test sendest."
+ storage_unavailable: "Die Testanfrage konnte nicht gespeichert werden. Prüfe die Konfiguration des gemeinsamen Caches."
+ statuses:
+ queued: "Eingereiht"
+ accepted: "Von APNs angenommen"
+ skipped: "Übersprungen: nicht mehr berechtigt"
+ rejected: "Von APNs abgelehnt; Push-Debug-Protokolle prüfen"
+ unregistered: "Geräteregistrierung ist nicht mehr gültig"
+ retrying: "Vorübergehender Fehler; erneuter Versuch"
+ failed: "Fehlgeschlagen; Push-Debug-Protokolle prüfen"
+ enqueue_failed: "Einreihen fehlgeschlagen; Sidekiq prüfen"
+ expired: "Ohne abschließendes Ergebnis abgelaufen"
+ push_notification:
+ title: "Sure-Testbenachrichtigung"
+ body: "Dies ist eine Testbenachrichtigung für dein Sure-Konto."
verify_worker_ai:
queued: Die Worker-Prüfung wurde in die Warteschlange gestellt. Das Ergebnis erscheint unten, sobald ein Worker-Prozess die Prüfung übernimmt – normalerweise innerhalb weniger Sekunden.
show:
diff --git a/config/locales/views/admin/system_health/en.yml b/config/locales/views/admin/system_health/en.yml
index 19d56be4c5..6526f7aad8 100644
--- a/config/locales/views/admin/system_health/en.yml
+++ b/config/locales/views/admin/system_health/en.yml
@@ -2,6 +2,47 @@
en:
admin:
system_health:
+ push_notifications:
+ send_test: "Send test push notification"
+ queueing: "Queueing…"
+ title: "Push notifications"
+ requested_at: "Latest test requested at %{time}"
+ result_help: "APNs acceptance does not confirm delivery to your device. Refresh to see worker results. Results are retained for 24 hours."
+ device: "Device %{number}"
+ pending: "Pending"
+ refresh: "Refresh results"
+ columns:
+ device: "Device"
+ environment: "APNs environment"
+ status: "Result"
+ checked_at: "Last update"
+ environments:
+ sandbox: "Sandbox"
+ production: "Production"
+ messages:
+ enqueue_failed: "The test could not be queued. Check Sidekiq and refresh the results below."
+ ready: "Send a test notification to the enabled iOS devices registered to your account."
+ queued: "Test notification queued. Refresh the results below to check its status."
+ hosted_only: "Push notifications are available only in hosted mode."
+ ineligible: "Only an active super-admin can send a test notification."
+ no_devices: "Enable push notifications in the Sure iOS app for this account to send a test."
+ disabled: "Push delivery has been disabled by the operator."
+ not_configured: "APNs credentials are not configured."
+ cooldown: "Please wait 30 seconds before sending another test."
+ storage_unavailable: "The test request could not be saved. Check the shared cache configuration."
+ statuses:
+ queued: "Queued"
+ accepted: "Accepted by APNs"
+ skipped: "Skipped: no longer eligible"
+ rejected: "Rejected by APNs; check push debug logs"
+ unregistered: "Device registration is no longer valid"
+ retrying: "Retrying a temporary failure"
+ failed: "Failed; check push debug logs"
+ enqueue_failed: "Could not enqueue; check Sidekiq"
+ expired: "Expired without a final result"
+ push_notification:
+ title: "Sure test notification"
+ body: "This is a test push notification for your Sure account."
verify_worker_ai:
queued: "Worker check queued. It will appear below once a worker process picks it up, usually within a few seconds."
show:
diff --git a/config/locales/views/admin/system_health/fr.yml b/config/locales/views/admin/system_health/fr.yml
index f9dca6f815..b259fbb2c6 100644
--- a/config/locales/views/admin/system_health/fr.yml
+++ b/config/locales/views/admin/system_health/fr.yml
@@ -2,6 +2,47 @@
fr:
admin:
system_health:
+ push_notifications:
+ send_test: "Envoyer une notification de test"
+ queueing: "Mise en file…"
+ title: "Notifications push"
+ requested_at: "Dernier test demandé le %{time}"
+ result_help: "L’acceptation par APNs ne confirme pas la réception sur votre appareil. Actualisez pour voir les résultats du worker. Les résultats sont conservés pendant 24 heures."
+ device: "Appareil %{number}"
+ pending: "En attente"
+ refresh: "Actualiser les résultats"
+ columns:
+ device: "Appareil"
+ environment: "Environnement APNs"
+ status: "Résultat"
+ checked_at: "Dernière mise à jour"
+ environments:
+ sandbox: "Sandbox"
+ production: "Production"
+ messages:
+ enqueue_failed: "Le test n’a pas pu être mis en file. Vérifiez Sidekiq et actualisez les résultats ci-dessous."
+ ready: "Envoyez une notification de test aux appareils iOS activés et enregistrés pour votre compte."
+ queued: "Notification de test mise en file. Actualisez les résultats ci-dessous pour consulter son état."
+ hosted_only: "Les notifications push sont disponibles uniquement en mode hébergé."
+ ineligible: "Seul un super-administrateur actif peut envoyer une notification de test."
+ no_devices: "Activez les notifications push dans l’application iOS Sure pour ce compte afin d’envoyer un test."
+ disabled: "L’opérateur a désactivé l’envoi des notifications push."
+ not_configured: "Les identifiants APNs ne sont pas configurés."
+ cooldown: "Veuillez patienter 30 secondes avant d’envoyer un autre test."
+ storage_unavailable: "La demande de test n’a pas pu être enregistrée. Vérifiez la configuration du cache partagé."
+ statuses:
+ queued: "En file"
+ accepted: "Accepté par APNs"
+ skipped: "Ignoré : plus éligible"
+ rejected: "Rejeté par APNs ; consultez les journaux push"
+ unregistered: "L’enregistrement de l’appareil n’est plus valide"
+ retrying: "Nouvelle tentative après une erreur temporaire"
+ failed: "Échec ; consultez les journaux push"
+ enqueue_failed: "Mise en file impossible ; vérifiez Sidekiq"
+ expired: "Expiré sans résultat final"
+ push_notification:
+ title: "Notification de test Sure"
+ body: "Ceci est une notification push de test pour votre compte Sure."
show:
ai:
adapters:
diff --git a/config/locales/views/admin/system_health/pt-PT.yml b/config/locales/views/admin/system_health/pt-PT.yml
index dfccd11562..c692162463 100644
--- a/config/locales/views/admin/system_health/pt-PT.yml
+++ b/config/locales/views/admin/system_health/pt-PT.yml
@@ -2,6 +2,47 @@
pt-PT:
admin:
system_health:
+ push_notifications:
+ send_test: "Enviar notificação de teste"
+ queueing: "A colocar em fila…"
+ title: "Notificações push"
+ requested_at: "Último teste pedido em %{time}"
+ result_help: "A aceitação pelo APNs não confirma a entrega no dispositivo. Atualize para ver os resultados do worker. Os resultados são guardados durante 24 horas."
+ device: "Dispositivo %{number}"
+ pending: "Pendente"
+ refresh: "Atualizar resultados"
+ columns:
+ device: "Dispositivo"
+ environment: "Ambiente APNs"
+ status: "Resultado"
+ checked_at: "Última atualização"
+ environments:
+ sandbox: "Sandbox"
+ production: "Produção"
+ messages:
+ enqueue_failed: "Não foi possível colocar o teste em fila. Verifique o Sidekiq e atualize os resultados abaixo."
+ ready: "Envie uma notificação de teste para os dispositivos iOS ativados e registados na sua conta."
+ queued: "Notificação de teste em fila. Atualize os resultados abaixo para consultar o estado."
+ hosted_only: "As notificações push estão disponíveis apenas no modo alojado."
+ ineligible: "Apenas um superadministrador ativo pode enviar uma notificação de teste."
+ no_devices: "Ative as notificações push na aplicação iOS Sure para esta conta para enviar um teste."
+ disabled: "O operador desativou o envio de notificações push."
+ not_configured: "As credenciais APNs não estão configuradas."
+ cooldown: "Aguarde 30 segundos antes de enviar outro teste."
+ storage_unavailable: "Não foi possível guardar o pedido de teste. Verifique a configuração da cache partilhada."
+ statuses:
+ queued: "Em fila"
+ accepted: "Aceite pelo APNs"
+ skipped: "Ignorado: já não é elegível"
+ rejected: "Rejeitado pelo APNs; consulte os registos push"
+ unregistered: "O registo do dispositivo já não é válido"
+ retrying: "A repetir após um erro temporário"
+ failed: "Falhou; consulte os registos push"
+ enqueue_failed: "Não foi possível colocar em fila; verifique o Sidekiq"
+ expired: "Expirou sem resultado final"
+ push_notification:
+ title: "Notificação de teste Sure"
+ body: "Esta é uma notificação push de teste para a sua conta Sure."
show:
title: Estado do sistema
tabs:
diff --git a/config/routes.rb b/config/routes.rb
index 14d59a3e20..390bcae496 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -998,6 +998,7 @@ Rails.application.routes.draw do
# so name it explicitly.
resource :system_health, only: :show, controller: "system_health" do
post :verify_worker_ai
+ post :send_test_push
end
end
diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml
index 2a222cefbd..a495f5bd6f 100644
--- a/docs/api/openapi.yaml
+++ b/docs/api/openapi.yaml
@@ -353,6 +353,8 @@ components:
properties:
token:
type: string
+ maxLength: 2048
+ pattern: "^(?:[0-9a-fA-F]{2})+$"
environment:
type: string
enum:
@@ -6364,12 +6366,20 @@ paths:
"/api/v1/push_subscriptions":
post:
summary: Register an APNs device token
+ description: Available only in hosted (managed) mode. Requires write scope.
tags:
- Push Subscriptions
security:
- apiKeyAuth: []
parameters: []
responses:
+ '403':
+ description: push unavailable in self-hosted mode or insufficient write
+ scope
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
'201':
description: token registered
content:
@@ -6397,11 +6407,19 @@ paths:
type: string
delete:
summary: Unregister an APNs device token
+ description: Available only in hosted (managed) mode. Requires write scope.
tags:
- Push Subscriptions
security:
- apiKeyAuth: []
responses:
+ '403':
+ description: push unavailable in self-hosted mode or insufficient write
+ scope
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
'204':
description: token unregistered
"/api/v1/recurring_transactions":
diff --git a/docs/hosting/push-notifications.md b/docs/hosting/push-notifications.md
new file mode 100644
index 0000000000..c8b4802cd6
--- /dev/null
+++ b/docs/hosting/push-notifications.md
@@ -0,0 +1,90 @@
+# Hosted iOS push notifications
+
+Native push notifications are supported only in hosted mode, which Rails calls
+`managed`. `SELF_HOSTED=true` or `SELF_HOSTING_ENABLED=true` disables registration,
+unregistration, diagnostic controls, and APNs delivery. Existing tokens and
+configured Apple credentials do not override that restriction.
+
+## Server and worker configuration
+
+Set the following in the deployment secret store for both Rails web processes
+and Sidekiq workers:
+
+| Variable | Purpose |
+| --- | --- |
+| `APNS_KEY_ID` | Apple APNs signing key ID |
+| `APNS_TEAM_ID` | Apple Developer team owning the app |
+| `APNS_BUNDLE_ID` | Official iOS app topic: `am.sure.insights` |
+| `APNS_PRIVATE_KEY_BASE64` | Base64-encoded APNs `.p8` private key; keep server-side |
+| `APNS_ENABLED` | Set to `false` to stop push delivery after web/worker processes load the updated environment; defaults to enabled when configured |
+| `REDIS_URL` | Shared Redis for Sidekiq and Rails diagnostic cache |
+
+Base64 does not encrypt the signing key. Do not embed it in the iOS app, logs, or
+repository. Configure the same shared Rails Redis cache on web and worker
+processes; a process-local memory/null cache cannot coordinate these diagnostics.
+Workers must consume the existing `scheduled` queue and reach the sandbox and
+production APNs endpoints over HTTP/2/TLS. No additional gem or database migration
+is needed for the System Health diagnostic.
+
+Verify Push Notifications is enabled for the app's Apple App ID. Inspect the
+entitlements of the signed development and TestFlight artifacts, and verify their
+APNs environments. Registrations select `sandbox` or `production` per device.
+
+## Send a diagnostic notification
+
+1. Sign into the Sure iOS app with the same hosted account as the super-admin
+ signed into the web app, and enable push notifications.
+2. Open **System Health → Background jobs → Push notifications** in the web app.
+3. Select **Send test push notification**. This sends only to that account's
+ recently registered iOS devices; no recipient can be selected in the request.
+4. Select **Refresh results** to see each device's outcome. Results remain for
+ 24 hours. **Accepted by APNs** confirms Apple's acceptance, not presentation
+ on the device. Confirm the alert on a development device and a TestFlight build.
+
+The button is disabled when there is no current registration, APNs is unconfigured,
+delivery is disabled, or another test was requested in the last 30 seconds. A
+registration currently counts as enabled until it is removed or becomes stale;
+iOS permission changes must be synchronized by the app. This server-side state
+cannot prove the current device permission while the device is offline.
+
+Tests run through Sidekiq, one job per device, with generic localized text and no
+financial information. They do not create an insight or require insight preview
+access. Requests older than 15 minutes are skipped. Ordinary job replays reuse a
+terminal diagnostic result; this short-lived cache is not an exactly-once delivery
+guarantee. A lost cache entry prevents a diagnostic send rather than inventing a
+recipient from stale arguments.
+
+## Outcomes and troubleshooting
+
+- **Queued / retrying:** check worker availability and the `scheduled` queue.
+- **Skipped:** eligibility, ownership, role, mode, configuration, or freshness
+ changed after the test was requested.
+- **Rejected by APNs:** check the `push_notifications` category in Debug logs.
+ Verify bundle ID, key/team, and device environment; `BadDeviceToken` may indicate
+ an environment mismatch. Raw tokens and APNs response bodies are not recorded.
+- **Device registration is no longer valid:** the worker received APNs `410`.
+ Removal is conditional on the registration not being renewed in the meantime.
+- **Could not enqueue:** check Sidekiq/Redis availability and submit again after
+ the cooldown. No device send occurred for that result.
+- **Expired without a final result:** the request outlived the send window without
+ a completed outcome; check worker connectivity and request a fresh test.
+
+Only temporary connection errors, HTTP 429, and HTTP 5xx responses receive the
+explicit bounded retry policy. Configuration and other APNs rejections are surfaced
+for operator correction. Each send has connection and response timeouts, and test
+notifications expire at APNs after five minutes.
+
+Normal insight notifications require an active user, current registration, preview
+opt-in, and a high-priority active insight at execution time. The diagnostic checks
+active super-admin status and device ownership again in the worker. Disabling
+push delivery stops both paths, while registration remains available in hosted mode
+so a temporary delivery outage does not prevent token renewal.
+
+## Remaining release work
+
+The Swift app still needs periodic registration renewal (Rails currently excludes
+registrations older than 90 days), account-bound lifecycle recovery, visible
+registration error state, and navigation for insight/test notification taps.
+Durable insight delivery tracking and recovery across enqueue failures are a
+separate implementation step. Provisioning and live sandbox/TestFlight acceptance
+must be completed before declaring push delivery ready for rollout.
diff --git a/docs/images/system-health-push-notifications.png b/docs/images/system-health-push-notifications.png
new file mode 100644
index 0000000000..3e6f1212e2
Binary files /dev/null and b/docs/images/system-health-push-notifications.png differ
diff --git a/docs/ios-push-notification-plan.md b/docs/ios-push-notification-plan.md
new file mode 100644
index 0000000000..2fad7b4aad
--- /dev/null
+++ b/docs/ios-push-notification-plan.md
@@ -0,0 +1,125 @@
+# iOS push notification implementation plan
+
+Prepared September 11, 2026. This is a source review and proposed implementation sequence, not confirmation that production push delivery is configured or working.
+
+Reviewed Rails checkout `38be19fa7d385ab9b344bbab367c6f63a4b6c24a` and [swift-sure](https://github.com/sure-admin/swift-sure/tree/1d51fc447b7e0225f559cac9119ba67295a5ca6f) at `1d51fc447b7e0225f559cac9119ba67295a5ca6f`.
+
+## Existing foundation
+
+| Area | Already implemented |
+| --- | --- |
+| Rails registration | `PushSubscription`, authenticated `POST /api/v1/push_subscriptions` and owner-scoped `DELETE /api/v1/push_subscriptions/:id`; OAuth and API keys supported, writes require write scope. |
+| Rails delivery | `Apns::Client` uses the existing Apnotic dependency, token authentication, sandbox/production routing, generic localized alert copy, and an insight collapse ID. |
+| Trigger | `GenerateInsightsJob` enqueues notifications for new and resurfaced insights; daily generation runs at 06:00 UTC, with manual refresh also able to trigger generation. |
+| Eligibility | Enqueue requires configured APNs credentials, user preview opt-in, and a subscription registered within 90 days. Delivery checks family membership. |
+| Swift | Permission prompt, APNs delegate callbacks, token formatting, registration API client, persisted subscription state, and logout/server-change cleanup with deferred retries. |
+| Tests/docs | Rails API and APNs tests, OpenAPI documentation, and Swift notification lifecycle/API tests already exist. |
+
+The initial release should finish and validate this insight notification path. Keep additional events, such as rule matches, completed assistant replies, or provider reconnect requests, as a later extension with explicit product scope.
+
+## 1. Establish the deployment and notification contract
+
+**Owners: backend, iOS, operations.**
+
+- Start with direct APNs delivery from the Sure-operated Rails deployment to the official iOS app, bundle ID `am.sure.insights`.
+- Define the initial policy as opt-in, high-priority insights only, matching the current Swift label “Notify urgent insights.” Today generation enqueues every new/resurfaced insight regardless of priority. Preview access and notification consent are separate controls.
+- Define whether the preference applies to a device or all of a user's devices; preserve the existing per-device behavior for the first release. Add an explicit server-side enabled state if subscriptions will remain after opt-out.
+- Preserve the existing payload fields `insight_id` and `destination: "insights"`. Keep balances, transaction descriptions, and insight prose out of lock-screen text. Resolve details through the authenticated API.
+- Specify the behavior when preview access, write scope, server support, or APNs configuration is unavailable. The app should distinguish permission granted, registration pending, enabled, and unavailable.
+- Document that the current trigger is scheduled/manual insight generation. If urgent means prompt detection after financial changes, add a separate, debounced post-sync generation requirement; the current nightly schedule does not provide that guarantee.
+
+**Deployment restriction (confirmed):** all native push functionality is hosted-only. The Rails configuration names this mode `managed`; use `Rails.application.config.app_mode.managed?`. Self-hosted deployments must not expose the push section or support subscription endpoints or delivery, even if APNs credentials or old subscription rows exist. Enforce this at API/admin entry points, enqueueing, and worker/transport execution. No self-hosted app configuration or push relay is in scope. Swift must treat the API's `feature_disabled` response as unavailable and avoid presenting push as enabled for that connection.
+
+**Exit criterion:** agreed event policy, deployment support matrix, compatible payload and API behavior, including hosted-only rejection.
+
+## 2. Verify Apple provisioning and server configuration
+
+**Owner: operations, with iOS support.**
+
+- Enable Push Notifications for the official App ID and verify the signed development and distribution artifacts carry the correct entitlement. The source entitlement says `development`; inspect the actual exported TestFlight artifact before assuming its environment.
+- Provision an APNs token-authentication key for the appropriate team, topic, and environments. Configure `APNS_KEY_ID`, `APNS_TEAM_ID`, `APNS_BUNDLE_ID=am.sure.insights`, and `APNS_PRIVATE_KEY_BASE64` in the server/worker secret store. Base64 is encoding, not encryption; the private key stays server-side.
+- Verify workers consume the existing `scheduled` queue and can reach APNs over HTTP/2/TLS. Confirm the insight schedule is loaded.
+- Add Rails hosting documentation and example variable names without secret values. Validate malformed/missing configuration and expose a safe operational health result and explicit delivery kill switch.
+- Use the System Health test-push action described below for smoke notifications to the logged-in super-admin's enabled devices in sandbox and production. Validate a real TestFlight device as well as development; inspect both APNs acceptance and device presentation.
+
+Apple references: [app registration](https://developer.apple.com/documentation/usernotifications/registering-your-app-with-apns), [APNs connections](https://developer.apple.com/documentation/usernotifications/establishing-a-connection-to-apns), and [request format](https://developer.apple.com/documentation/usernotifications/sending-notification-requests-to-apns).
+
+**Exit criterion:** verified sandbox and TestFlight delivery with documented credential ownership and rotation.
+
+## 3. Repair registration freshness and account lifecycle
+
+**Owners: iOS and backend.**
+
+- Fix the confirmed freshness mismatch: Swift skips POST when the token/server/environment is unchanged, but Rails stops sending after `last_registered_at` is 90 days old. Persist the last successful server refresh and renew on authenticated foreground/launch at a defined interval, for example daily. Serialize concurrent renewals and retry transient failures without repeatedly prompting for permission.
+- Keep requesting the current token from APNs on launch. Handle token rotation, a server-deleted subscription, and returning after a long absence. Refresh notification authorization when returning from Settings.
+- Bind persisted subscription and cleanup state to authenticated account identity as well as server URL. Current Swift records are server-bound; test switching users on the same server, especially when logout cleanup failed.
+- Define safe ownership transfer or recovery for an existing token. Rails currently rejects a token belonging to another user. Do not remove owner checks or silently transfer a token merely to resolve that conflict. An installation-bound credential/revocation mechanism can support recovery and removal without retaining old login credentials.
+- Make opt-out/logout disable delivery durably when online. Define offline behavior honestly: cleanup cannot reach the server while disconnected. Retain pending revocation state, associate subscriptions with a revocable installation/session where appropriate, and ensure old-account alerts cannot open data under the next account.
+- Review token identity constraints using environment and configured topic, and replace the current 64–200-character assumption with variable-length token handling plus a defensible request-size limit. Apple explicitly says [not to hard-code token size](https://developer.apple.com/documentation/UIKit/UIApplicationDelegate/application%28_%3AdidRegisterForRemoteNotificationsWithDeviceToken%3A%29?language=objc).
+
+**Exit criterion:** an unchanged token stays active beyond 90 days; rotation, reinstall, opt-out, and same-host/cross-host account transitions recover without cross-user delivery.
+
+## 4. Make delivery eligibility and retries reliable
+
+**Owner: backend.**
+
+- Recheck eligibility immediately before sending: active user, family membership, preview access, current subscription/consent, high priority, and a still-relevant insight. Existing execution only rechecks family membership. Reuse the insight API's authorization policy and audit any account-visibility restrictions before adding account-specific events.
+- Add durable per-event/per-subscription delivery records and record the event alongside the insight change, then dispatch after commit with reconciliation for missed enqueueing. Today persistence and enqueueing are separate, so a failure between them can lose an alert.
+- Identify an insight occurrence/revision explicitly: deduplicating forever on insight ID would suppress legitimate resurfacing; `generated_at` is refreshed on unchanged insights and is not a reliable event version. Use a unique database key for occurrence plus subscription and record attempts, APNs acceptance, failure category, and timestamps.
+- Keep the existing `NotificationDelivery` model for rule-email deduplication; its required rule/transaction associations do not fit insight push delivery. Add a focused push record instead of overloading it.
+- Classify responses: retry network failures, throttling, and transient server errors with bounded backoff; surface configuration/authentication/payload failures without repeatedly retrying unchanged invalid requests. Treat `BadDeviceToken` as a possible environment mismatch as well as invalid registration.
+- Process `410 Unregistered` conditionally using APNs' invalidation timestamp and the token/registration version sent, so a delayed response cannot remove a freshly registered subscription. See [Apple response semantics](https://developer.apple.com/documentation/usernotifications/handling-notification-responses-from-apns).
+- Set an explicit expiration policy and collapse behavior for stale/superseded insights. Recognize that a collapse ID is not exactly-once delivery; an ambiguous timeout can still produce duplicates. Measure APNs acceptance separately from device delivery or user opens.
+- Use sanitized `DebugLogEntry.capture` diagnostics and metrics for queued, accepted, rejected, retried, expired, and invalidated notifications. Preserve token/secret filtering. Consider bounded connection reuse after correctness is established; the current client opens a connection per send.
+
+**Exit criterion:** retries and repeated generation do not cause routine duplicate alerts; missed jobs can be recovered; revoked access prevents queued sends; APNs faults are diagnosable.
+
+## 5. Finish the Swift notification experience
+
+**Owner: iOS.**
+
+- Implement consumption of `pendingInsightID`: the delegate currently persists it, but no app navigation code reads it. Route to Overview/Insights, refresh through the authenticated API, and reveal the referenced insight.
+- Handle foreground, background, and cold-start taps; defer navigation while sign-in completes. If the insight is unavailable, expired, or unauthorized, show a safe fallback. Bind pending navigation to the originating connection/account and clear it on logout or connection changes.
+- Display registration failures and pending/retry state. Currently `registrationError` is persisted but no UI reads it, and enabling can report success even when the server registration failed.
+- Implement permission-denied guidance and Settings return handling. Preserve generic lock-screen copy and decide foreground banner/sound behavior explicitly.
+
+**Exit criterion:** a tap reaches the appropriate authorized content from every app state, and the notification setting reflects actual registration state.
+
+## 6. Add a System Health test-push button
+
+**Owner: backend, with iOS support for the test payload. User-requested scope; hosted (`managed`) mode only.**
+
+- In hosted mode, add a **Push notifications** section within **Background jobs** at `/admin/system_health?tab=background_jobs#push-notifications` with a **Send test push notification** button. Match the AI tab's description/action layout and existing `DS::Button` outline, small-size styling; keep the existing two tabs and use localized strings, functional design tokens, and the existing icon API. No design-system stylesheet changes are needed.
+- The button sends only to the super-admin account currently logged into the web app. Resolve the recipient exclusively from `Current.user`; fan out to that user's eligible iOS subscriptions, never to other super-admins or family members. Do not accept a recipient user ID or arbitrary device token from the request.
+- Render a genuinely disabled button when that super-admin has no enabled, current push subscriptions. Show explanatory text such as “Enable push notifications in the Sure iOS app for this account to send a test.” Use a shared server-side eligibility predicate incorporating subscription freshness, revocation, and any explicit consent state introduced by this plan. Preview opt-in alone does not mean push is enabled. The server can report only the latest registered authorization state; synchronize permission changes through the Swift lifecycle work.
+- Hide the entire push section in self-hosted mode and reject direct test-push POSTs. Also disable sending when APNs is unconfigured or the delivery kill switch is active, with a distinct explanation. Recheck all conditions server-side on submission; a disabled button alone does not enforce eligibility.
+- Add a CSRF-protected `POST /admin/system_health/send_test_push` action to `Admin::SystemHealthController`, retaining `Admin::BaseController`'s super-admin authorization. Keep the controller thin and enqueue a dedicated test delivery job through Active Job/Sidekiq on the existing `scheduled` queue. Follow the asynchronous `verify_worker_ai` action's redirect/queued-feedback pattern; the AI tab's GET-based “Run checks again” control is a visual reference, not the HTTP method for sending a notification.
+- Pass the initiating user's ID and eligible subscription IDs to the delivery workflow, then recheck active super-admin status, subscription ownership, consent/freshness, and delivery availability when the job runs. A logout-driven revocation, role change, or opt-out after clicking must prevent the queued send.
+- Send a generic localized diagnostic alert, for example “Sure test notification” / “Push notifications are working for your account.” Reuse the APNs transport, environment selection, retry handling, and sanitized delivery tracking. Give each test request its own identifier, with per-subscription retry deduplication and brief protection against accidental repeated clicks.
+- The diagnostic must not require, generate, or mutate a financial insight. Extend the transport's current required `insight_id` interface with an explicit test payload; tapping it should safely open the app's Overview. Insight priority and insight preview gates apply to financial alerts, not this explicit super-admin diagnostic; registered push consent remains required.
+- Title the section **Push notifications** and show **Latest test requested at …** when a test exists. Immediately show **Test notification queued**, then expose the current user's latest test result with per-device APNs acceptance/failure or skipped status and a timestamp. Do not label queueing or APNs acceptance as confirmed device delivery. Render sanitized errors without tokens or credentials.
+
+**Acceptance coverage:** enabled and disabled button states; missing configuration and kill switch; unauthenticated/non-super-admin rejection; no eligible device; current-user-only fan-out even when other super-admins/family members have subscriptions; forged recipient parameters; enqueueing without synchronous APNs calls; revocation/role/ownership changes before execution; partial device failures; safe payload/tap behavior; and accessible localized status messages. Add focused Minitest controller/job tests and a system test for the critical button flow.
+
+**Exit criterion:** an opted-in super-admin can queue a test from System Health and inspect its outcome; an account without push enabled cannot send through either the UI or direct POST.
+
+## 7. Validate and release in stages
+
+**Owners: backend and iOS, with operations for acceptance.**
+
+- Backend coverage: registration renewal/concurrency, owner isolation, read-only scope rejection, variable-length tokens, stale subscriptions, revoked consent/preview, deactivated users, family changes, stale insight events, duplicate jobs, transient/permanent APNs responses, and invalidation/renewal races.
+- Swift coverage: unchanged-token renewal with an injected clock, token rotation, permission changes, failed registration recovery, same-host account changes after failed cleanup, host isolation, and notification navigation across launch/authentication states.
+- Contract coverage: retain existing POST 201 and DELETE 204 behavior unless a coordinated version change is necessary. Update Minitest behavioral tests with the repository's `X-Api-Key` pattern, documentation-only rswag specs/shared schemas, and regenerate OpenAPI. Validate runtime OAuth interoperability through the Swift/auth integration coverage.
+- Before implementation PRs, run all required Rails checks: full Minitest, applicable system tests, Ruby and ERB lint, Biome, and Brakeman. Run the Swift repository's iOS/macOS/watch test destinations and signed device acceptance tests.
+- Roll out to internal preview users first, then a small TestFlight cohort. Verify opt-out and kill-switch behavior before expanding. Monitor queue latency, acceptance/error rates, registration freshness, and duplicate reports.
+- Expand event types only after this path is stable. Introduce a versioned typed payload and shared delivery policy when the second event is selected; each event needs recipient rules, preference controls, authorized navigation, and its own deduplication semantics.
+
+**Suggested work packages:** (1) deployment contract and runbook; (2) registration/lifecycle fixes across both repositories; (3) Rails delivery policy and durable dispatch; (4) Swift routing/status UI; (5) System Health test-push section/action using the shared eligibility and delivery infrastructure; (6) end-to-end acceptance and staged rollout. After the contract is agreed, registration, delivery, and UI implementation can progress independently against it.
+
+## Implementation progress
+
+The first Rails milestone adds hosted-only API/admin/worker/transport guards, the System Health test-push action, per-device Sidekiq diagnostics, high-priority/send-time insight eligibility checks, shared APNs error handling, registration-safe invalidation, bounded token input, and a [hosting runbook](hosting/push-notifications.md).
+
+Diagnostic results use the existing shared Rails cache pattern with 24-hour retention; they are not the durable insight event/delivery ledger described in step 4. The Swift lifecycle/navigation changes, durable insight dispatch, Apple provisioning, and live device acceptance remain follow-up work. The test payload safely omits an insight ID; explicit Overview navigation requires the planned Swift update.
+
+The original planning review did not inspect production credentials or signed app artifacts or send a live push. Implementation verification is reported separately.
diff --git a/spec/requests/api/v1/push_subscriptions_spec.rb b/spec/requests/api/v1/push_subscriptions_spec.rb
index 7e127f3ae8..fecbf970a8 100644
--- a/spec/requests/api/v1/push_subscriptions_spec.rb
+++ b/spec/requests/api/v1/push_subscriptions_spec.rb
@@ -3,6 +3,8 @@
require "swagger_helper"
RSpec.describe "API V1 Push Subscriptions", type: :request do
+ before { allow(Rails.application.config).to receive(:app_mode).and_return("managed".inquiry) }
+
let(:family) { Family.create!(name: "API Family") }
let(:user) do
family.users.create!(email: "[email protected]", password: "password123", ai_enabled: true)
@@ -15,6 +17,7 @@ RSpec.describe "API V1 Push Subscriptions", type: :request do
path "/api/v1/push_subscriptions" do
post "Register an APNs device token" do
+ description "Available only in hosted (managed) mode. Requires write scope."
tags "Push Subscriptions"
security [ { apiKeyAuth: [] } ]
consumes "application/json"
@@ -22,6 +25,12 @@ RSpec.describe "API V1 Push Subscriptions", type: :request do
parameter name: :subscription, in: :body, required: true, schema: { "$ref" => "#/components/schemas/PushSubscriptionRegistration" }
let(:subscription) { { token: "ab" * 32, environment: "sandbox", platform: "ios" } }
+ response "403", "push unavailable in self-hosted mode or insufficient write scope" do
+ before { allow(Rails.application.config).to receive(:app_mode).and_return("self_hosted".inquiry) }
+ schema "$ref" => "#/components/schemas/ErrorResponse"
+ run_test!
+ end
+
response "201", "token registered" do
schema "$ref" => "#/components/schemas/PushSubscription"
run_test!
@@ -51,9 +60,17 @@ RSpec.describe "API V1 Push Subscriptions", type: :request do
let(:id) { subscription.id }
delete "Unregister an APNs device token" do
+ description "Available only in hosted (managed) mode. Requires write scope."
tags "Push Subscriptions"
security [ { apiKeyAuth: [] } ]
+ response "403", "push unavailable in self-hosted mode or insufficient write scope" do
+ before { allow(Rails.application.config).to receive(:app_mode).and_return("self_hosted".inquiry) }
+ produces "application/json"
+ schema "$ref" => "#/components/schemas/ErrorResponse"
+ run_test!
+ end
+
response "204", "token unregistered" do
run_test!
end
diff --git a/spec/swagger_helper.rb b/spec/swagger_helper.rb
index 1ea884f996..059bc27d5b 100644
--- a/spec/swagger_helper.rb
+++ b/spec/swagger_helper.rb
@@ -248,7 +248,8 @@ RSpec.configure do |config|
PushSubscriptionRegistration: {
type: :object, required: %w[token environment platform],
properties: {
- token: { type: :string }, environment: { type: :string, enum: %w[sandbox production] },
+ token: { type: :string, maxLength: 2048, pattern: "^(?:[0-9a-fA-F]{2})+$" },
+ environment: { type: :string, enum: %w[sandbox production] },
platform: { type: :string, enum: %w[ios] },
device_key: { type: :string, pattern: '^[0-9a-f]{64}$', description: 'Optional 256-bit installation secret, unique per server and kept in device secure storage. Required proof to replace another user’s registration for this device. Never returned.' }
}
diff --git a/test/controllers/admin/system_health_push_notifications_test.rb b/test/controllers/admin/system_health_push_notifications_test.rb
new file mode 100644
index 0000000000..e9f771ae34
--- /dev/null
+++ b/test/controllers/admin/system_health_push_notifications_test.rb
@@ -0,0 +1,112 @@
+require "test_helper"
+
+class Admin::SystemHealthPushNotificationsTest < ActionDispatch::IntegrationTest
+ setup do
+ Rails.application.config.stubs(:app_mode).returns("managed".inquiry)
+ Apns::Client.stubs(:configured?).returns(true)
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+ @user = users(:sure_support_staff)
+ sign_in @user
+ end
+
+ test "button is disabled until this super admin registers a device" do
+ get admin_system_health_url(tab: "background_jobs")
+ assert_response :success
+ assert_select "button[role='tab']", count: 2
+ assert_select "button[disabled][aria-describedby='push-notification-help']", text: "Send test push notification"
+ assert_match "Enable push notifications in the Sure iOS app", response.body
+
+ register_device
+ get admin_system_health_url(tab: "background_jobs")
+ assert_select "form[action='#{send_test_push_admin_system_health_path}'][method='post'] button:not([disabled])", text: "Send test push notification"
+ end
+
+ test "queues for the current account ignoring forged recipient parameters" do
+ subscription = register_device
+ other_user = users(:family_admin)
+ Apns::Client.expects(:new).never
+ assert_enqueued_with(job: DeliverTestPushNotificationJob, args: ->(args) {
+ args.first[:user_id] == @user.id && args.first[:push_subscription_id] == subscription.id
+ }) do
+ post send_test_push_admin_system_health_url, params: { user_id: other_user.id, token: "cd" * 32 }
+ end
+ assert_redirected_to admin_system_health_path(tab: "background_jobs", anchor: "push-notifications")
+ assert_match "queued", flash[:notice]
+ follow_redirect!
+ assert_select "h2", text: "Push notifications"
+ assert_match "Latest test requested at", response.body
+ assert_select "td", text: "Queued"
+ assert_match "does not confirm delivery", response.body
+ end
+
+ test "direct post is rejected without an enabled device" do
+ assert_no_enqueued_jobs only: DeliverTestPushNotificationJob do
+ post send_test_push_admin_system_health_url
+ end
+ assert_match "Enable push notifications", flash[:alert]
+ end
+
+ test "self hosted mode hides the section and rejects the post even with credentials and a device" do
+ register_device
+ Rails.application.config.stubs(:app_mode).returns("self_hosted".inquiry)
+ get admin_system_health_url(tab: "background_jobs")
+ assert_response :success
+ assert_select "button[role='tab']", text: "Push notifications", count: 0
+ assert_select "[data-testid='push-notification-status']", count: 0
+ assert_no_enqueued_jobs only: DeliverTestPushNotificationJob do
+ post send_test_push_admin_system_health_url
+ end
+ assert_response :not_found
+ end
+
+ test "APNs configuration and kill switch disable the control and direct post" do
+ register_device
+ Apns::Client.stubs(:configured?).returns(false)
+ get admin_system_health_url(tab: "background_jobs")
+ assert_select "button[disabled]", text: "Send test push notification"
+ assert_match "APNs credentials are not configured", response.body
+ assert_no_enqueued_jobs only: DeliverTestPushNotificationJob do
+ post send_test_push_admin_system_health_url
+ end
+ Apns::Client.stubs(:configured?).returns(true)
+ ClimateControl.modify("APNS_ENABLED" => "false") do
+ get admin_system_health_url(tab: "background_jobs")
+ assert_select "button[disabled]", text: "Send test push notification"
+ assert_no_enqueued_jobs only: DeliverTestPushNotificationJob do
+ post send_test_push_admin_system_health_url
+ end
+ assert_match "disabled by the operator", flash[:alert]
+ end
+ end
+
+ test "ordinary admins cannot send diagnostic pushes" do
+ sign_in users(:family_admin)
+ assert_no_enqueued_jobs only: DeliverTestPushNotificationJob do
+ post send_test_push_admin_system_health_url
+ end
+ assert_redirected_to root_path
+ end
+
+ test "unauthenticated requests cannot send diagnostic pushes" do
+ reset!
+ assert_no_enqueued_jobs only: DeliverTestPushNotificationJob do
+ post send_test_push_admin_system_health_url
+ end
+ assert_redirected_to new_session_path
+ end
+
+ test "all system health locales include the notification labels and outcomes" do
+ %i[en de fr pt-PT].each do |locale|
+ %w[title requested_at send_test messages.no_devices messages.queued statuses.accepted statuses.failed].each do |key|
+ assert_kind_of String, I18n.t("admin.system_health.push_notifications.#{key}", locale: locale, time: "2026-09-12", fallback: false, raise: true)
+ end
+ end
+ end
+
+ private
+ def register_device
+ @user.push_subscriptions.create!(
+ token: "ab" * 32, environment: "sandbox", platform: "ios", last_registered_at: Time.current
+ )
+ end
+end
diff --git a/test/controllers/api/v1/push_subscriptions_controller_test.rb b/test/controllers/api/v1/push_subscriptions_controller_test.rb
index dec0201237..682f9749f0 100644
--- a/test/controllers/api/v1/push_subscriptions_controller_test.rb
+++ b/test/controllers/api/v1/push_subscriptions_controller_test.rb
@@ -2,6 +2,7 @@ require "test_helper"
class Api::V1::PushSubscriptionsControllerTest < ActionDispatch::IntegrationTest
setup do
+ Rails.application.config.stubs(:app_mode).returns("managed".inquiry)
@user = users(:family_admin)
key = ApiKey.generate_secure_key
@api_key = ApiKey.create!(
@@ -136,6 +137,20 @@ class Api::V1::PushSubscriptionsControllerTest < ActionDispatch::IntegrationTest
assert_response :no_content
end
+ test "requires write scope to remove a token" do
+ @api_key.update!(scopes: [ "read" ])
+ subscription = @user.push_subscriptions.create!(
+ token: @token, environment: "sandbox", platform: "ios", last_registered_at: Time.current
+ )
+
+ assert_no_difference "PushSubscription.count" do
+ delete api_v1_push_subscription_url(subscription), headers: @headers
+ end
+
+ assert_response :forbidden
+ assert PushSubscription.exists?(subscription.id)
+ end
+
test "does not remove another user's token" do
subscription = users(:empty).push_subscriptions.create!(
token: @token,
@@ -195,4 +210,77 @@ class Api::V1::PushSubscriptionsControllerTest < ActionDispatch::IntegrationTest
assert_equal old.id, response.parsed_body["id"]
assert_equal Digest::SHA256.hexdigest("cd" * 32), old.reload.device_key_digest
end
+
+ test "self hosted mode rejects registration even when APNs is configured" do
+ Rails.application.config.stubs(:app_mode).returns("self_hosted".inquiry)
+ Apns::Client.stubs(:configured?).returns(true)
+ assert_no_difference "PushSubscription.count" do
+ post api_v1_push_subscriptions_url,
+ params: { token: @token, environment: "sandbox", platform: "ios" }, headers: @headers, as: :json
+ end
+ assert_response :forbidden
+ assert_equal "feature_disabled", response.parsed_body["error"]
+ end
+
+ test "self hosted mode rejects unregistering subscriptions" do
+ subscription = @user.push_subscriptions.create!(
+ token: @token, environment: "sandbox", platform: "ios", last_registered_at: Time.current
+ )
+ Rails.application.config.stubs(:app_mode).returns("self_hosted".inquiry)
+ assert_no_difference "PushSubscription.count" do
+ delete api_v1_push_subscription_url(subscription), headers: @headers
+ end
+ assert_response :forbidden
+ assert_equal "feature_disabled", response.parsed_body["error"]
+ end
+
+ test "accepts variable length byte tokens but rejects oversized and incomplete bytes" do
+ [ "ab" * 16, "ab" * 128 ].each do |token|
+ post api_v1_push_subscriptions_url,
+ params: { token: token, environment: "sandbox", platform: "ios" }, headers: @headers, as: :json
+ assert_response :created
+ end
+ [ "ab" * 1025, "abc" ].each do |token|
+ post api_v1_push_subscriptions_url,
+ params: { token: token, environment: "sandbox", platform: "ios" }, headers: @headers, as: :json
+ assert_response :unprocessable_entity
+ end
+ end
+
+ test "persists a maximum length token without relying on index compression" do
+ device_token = SecureRandom.hex(1024)
+
+ assert_difference "PushSubscription.count", 1 do
+ post api_v1_push_subscriptions_url,
+ params: { token: device_token, environment: "sandbox", platform: "ios" }, headers: @headers, as: :json
+ end
+
+ assert_response :created
+ assert_equal device_token, @user.push_subscriptions.find(response.parsed_body["id"]).token
+ end
+
+ test "rejects tokens exceeding the index limit with a validation response" do
+ assert_no_difference "PushSubscription.count" do
+ post api_v1_push_subscriptions_url,
+ params: { token: SecureRandom.hex(2048), environment: "sandbox", platform: "ios" },
+ headers: @headers, as: :json
+ end
+
+ assert_response :unprocessable_entity
+ assert_equal "validation_error", response.parsed_body["error"]
+ end
+
+ test "renews a stale registration without changing its identity" do
+ subscription = @user.push_subscriptions.create!(
+ token: @token, environment: "sandbox", platform: "ios", last_registered_at: 91.days.ago
+ )
+ freeze_time do
+ post api_v1_push_subscriptions_url,
+ params: { token: @token, environment: "sandbox", platform: "ios" }, headers: @headers, as: :json
+ assert_response :created
+ assert_equal subscription.id, response.parsed_body["id"]
+ assert_equal Time.current, subscription.reload.last_registered_at
+ assert subscription.eligible?
+ end
+ end
end
diff --git a/test/jobs/deliver_insight_notification_job_test.rb b/test/jobs/deliver_insight_notification_job_test.rb
index 218dfb1c1c..55d18bbb12 100644
--- a/test/jobs/deliver_insight_notification_job_test.rb
+++ b/test/jobs/deliver_insight_notification_job_test.rb
@@ -2,8 +2,12 @@ require "test_helper"
class DeliverInsightNotificationJobTest < ActiveJob::TestCase
setup do
+ Rails.application.config.stubs(:app_mode).returns("managed".inquiry)
+ Apns::Client.stubs(:configured?).returns(true)
@insight = insights(:cash_flow_warning)
- @subscription = @insight.family.users.first.push_subscriptions.create!(
+ user = @insight.family.users.first
+ user.update!(preferences: user.preferences.merge("preview_features_enabled" => true))
+ @subscription = user.push_subscriptions.create!(
token: "ab" * 32,
environment: "sandbox",
platform: "ios",
@@ -84,4 +88,39 @@ class DeliverInsightNotificationJobTest < ActiveJob::TestCase
push_subscription_id: other_subscription.id
)
end
+
+ test "self hosted mode prevents enqueueing and execution of old jobs" do
+ Rails.application.config.stubs(:app_mode).returns("self_hosted".inquiry)
+ Apns::Client.expects(:new).never
+ assert_no_enqueued_jobs do
+ DeliverInsightNotificationJob.enqueue_for(@insight)
+ DeliverInsightNotificationJob.perform_now(insight_id: @insight.id, push_subscription_id: @subscription.id)
+ end
+ end
+
+ test "preview opt out after enqueueing prevents delivery" do
+ @subscription.user.update!(preferences: { "preview_features_enabled" => false })
+ Apns::Client.expects(:new).never
+ DeliverInsightNotificationJob.perform_now(insight_id: @insight.id, push_subscription_id: @subscription.id)
+ end
+
+ test "stale registrations and inactive users cannot receive insight pushes" do
+ @subscription.update!(last_registered_at: 91.days.ago)
+ Apns::Client.expects(:new).never
+ DeliverInsightNotificationJob.perform_now(insight_id: @insight.id, push_subscription_id: @subscription.id)
+ @subscription.update!(last_registered_at: Time.current)
+ @subscription.user.update_column(:active, false)
+ DeliverInsightNotificationJob.perform_now(insight_id: @insight.id, push_subscription_id: @subscription.id)
+ end
+
+ test "low priority and already read insights cannot enqueue or deliver" do
+ Apns::Client.expects(:new).never
+ [ { priority: "low" }, { priority: "high", status: "read" }, { status: "expired" }, { status: "acknowledged" } ].each do |attributes|
+ @insight.update!(attributes)
+ assert_no_enqueued_jobs do
+ DeliverInsightNotificationJob.enqueue_for(@insight)
+ DeliverInsightNotificationJob.perform_now(insight_id: @insight.id, push_subscription_id: @subscription.id)
+ end
+ end
+ end
end
diff --git a/test/jobs/generate_insights_job_test.rb b/test/jobs/generate_insights_job_test.rb
index 144138d0bd..acbfca20fd 100644
--- a/test/jobs/generate_insights_job_test.rb
+++ b/test/jobs/generate_insights_job_test.rb
@@ -89,7 +89,8 @@ class GenerateInsightsJobTest < ActiveJob::TestCase
assert_equal 5000.0, insight.metadata["balance"]
end
- test "enqueues notifications for newly created insights" do
+ test "enqueues notifications for newly created high priority insights" do
+ Rails.application.config.stubs(:app_mode).returns("managed".inquiry)
opted_in_user, opted_out_user = @family.users.to_a
set_preview_features(opted_out_user, false)
subscription = opted_in_user.push_subscriptions.create!(
@@ -105,7 +106,7 @@ class GenerateInsightsJobTest < ActiveJob::TestCase
last_registered_at: Time.current
)
Apns::Client.stubs(:configured?).returns(true)
- stub_generated([ generated_insight ])
+ stub_generated([ generated_insight(priority: "high") ])
assert_enqueued_jobs 1, only: DeliverInsightNotificationJob do
assert_enqueued_with(
@@ -289,10 +290,10 @@ class GenerateInsightsJobTest < ActiveJob::TestCase
# display_balance changes only the formatted facts, leaving metadata (the
# material-change signal) untouched — mirrors a balance drifting slightly
# between runs without crossing a bucket boundary.
- def generated_insight(balance: 5000.0, display_balance: nil, title: "Idle cash in Test Checking")
+ def generated_insight(balance: 5000.0, display_balance: nil, priority: "low", title: "Idle cash in Test Checking")
Insight::Generator::GeneratedInsight.new(
insight_type: "idle_cash",
- priority: "low",
+ priority: priority,
title: title,
template_key: "idle_cash",
facts: { account: "Test Checking", balance: "$#{(display_balance || balance).to_i}", idle_days: 60 },
diff --git a/test/models/push_notification_test_test.rb b/test/models/push_notification_test_test.rb
new file mode 100644
index 0000000000..90f54530cc
--- /dev/null
+++ b/test/models/push_notification_test_test.rb
@@ -0,0 +1,183 @@
+require "test_helper"
+
+class PushNotificationTestTest < ActiveJob::TestCase
+ setup do
+ Rails.application.config.stubs(:app_mode).returns("managed".inquiry)
+ Apns::Client.stubs(:configured?).returns(true)
+ @cache = ActiveSupport::Cache::MemoryStore.new
+ Rails.stubs(:cache).returns(@cache)
+ @user = users(:sure_support_staff)
+ @subscription = @user.push_subscriptions.create!(
+ token: "ab" * 32, environment: "sandbox", platform: "ios", last_registered_at: Time.current
+ )
+ @test = PushNotificationTest.new(@user)
+ end
+
+ test "queues only this super admin's recent devices and limits repeated clicks" do
+ users(:family_admin).push_subscriptions.create!(
+ token: "cd" * 32, environment: "production", platform: "ios", last_registered_at: Time.current
+ )
+ @user.push_subscriptions.create!(
+ token: "ef" * 32, environment: "production", platform: "ios", last_registered_at: 91.days.ago
+ )
+ Apns::Client.expects(:new).never
+
+ assert_enqueued_jobs 1, only: DeliverTestPushNotificationJob do
+ assert_equal :queued, @test.request!
+ assert_equal :cooldown, @test.request!
+ end
+ assert_enqueued_with(job: DeliverTestPushNotificationJob, args: [ {
+ user_id: @user.id, request_id: @test.latest[:id], push_subscription_id: @subscription.id
+ } ])
+ assert_equal [ "queued" ], @test.results(@test.latest).pluck(:status)
+ end
+
+ test "does not require an insight or preview opt in" do
+ @user.update!(preferences: @user.preferences.merge("preview_features_enabled" => false))
+ @test.request!
+ client = mock
+ Apns::Client.expects(:new).with(environment: "sandbox").returns(client)
+ client.expects(:deliver_test).with(
+ token: @subscription.token, title: "Sure test notification",
+ body: "This is a test push notification for your Sure account.", request_id: @test.latest[:id]
+ ).returns(stub(ok?: true))
+
+ assert_no_difference "Insight.count" do
+ deliver
+ deliver # An ordinary queue replay does not send a second alert.
+ end
+ assert_equal "accepted", result_status
+ end
+
+ test "localizes the test alert for the initiating user" do
+ @user.update!(locale: "de")
+ @test.request!
+ Apns::Client.any_instance.expects(:deliver_test).with(
+ token: @subscription.token, title: "Sure-Testbenachrichtigung",
+ body: "Dies ist eine Testbenachrichtigung für dein Sure-Konto.", request_id: @test.latest[:id]
+ ).returns(stub(ok?: true))
+ deliver
+ assert_equal "accepted", result_status
+ end
+
+ test "skips a device removed after queueing" do
+ @test.request!
+ @subscription.destroy!
+ Apns::Client.expects(:new).never
+ deliver
+ assert_equal "skipped", result_status
+ end
+
+ test "skips a device transferred to another user after queueing" do
+ @test.request!
+ @subscription.update!(user: users(:family_admin))
+ Apns::Client.expects(:new).never
+ deliver
+ assert_equal "skipped", result_status
+ end
+
+ test "skips a stale registration after queueing" do
+ @test.request!
+ @subscription.update!(last_registered_at: 91.days.ago)
+ Apns::Client.expects(:new).never
+ deliver
+ assert_equal "skipped", result_status
+ end
+
+ test "role or active status changes prevent delivery" do
+ @test.request!
+ @user.update_columns(role: "admin")
+ Apns::Client.expects(:new).never
+ deliver
+ assert_equal "skipped", result_status
+ @user.update_columns(role: "super_admin", active: false)
+ assert_equal :ineligible, @test.disabled_reason
+ end
+
+ test "host mode is rechecked by the worker and at request time" do
+ @test.request!
+ Rails.application.config.stubs(:app_mode).returns("self_hosted".inquiry)
+ assert_equal :hosted_only, @test.request!
+ Apns::Client.expects(:new).never
+ deliver
+ assert_equal "skipped", result_status
+ end
+
+ test "kill switch disables new and queued test notifications" do
+ @test.request!
+ ClimateControl.modify("APNS_ENABLED" => "false") do
+ assert_equal :disabled, @test.request!
+ Apns::Client.expects(:new).never
+ deliver
+ assert_equal "skipped", result_status
+ end
+ end
+
+ test "unconfigured APNs and missing devices cannot enqueue" do
+ Apns::Client.stubs(:configured?).returns(false)
+ assert_no_enqueued_jobs do
+ assert_equal :not_configured, @test.request!
+ @subscription.destroy!
+ assert_equal :no_devices, @test.request!
+ end
+ end
+
+ test "expired requests and forged subscriptions cannot send" do
+ @test.request!
+ Apns::Client.expects(:new).never
+ @test.deliver(request_id: SecureRandom.uuid, push_subscription_id: @subscription.id)
+ @test.deliver(request_id: @test.latest[:id], push_subscription_id: SecureRandom.uuid)
+ travel 16.minutes do
+ assert_equal "expired", result_status
+ deliver
+ assert_equal "skipped", result_status
+ end
+ end
+
+ test "a cache failure does not enqueue a request the worker cannot find" do
+ @cache.stubs(:write).returns(false)
+ assert_no_enqueued_jobs do
+ assert_equal :storage_unavailable, @test.request!
+ end
+ end
+
+ test "records enqueue failure per device" do
+ [ ActiveJob::EnqueueError, Redis::BaseError, RedisClient::CannotConnectError ].each do |error_class|
+ @cache.clear
+ DeliverTestPushNotificationJob.stubs(:perform_later).raises(error_class)
+ assert_equal :enqueue_failed, @test.request!
+ assert_equal "enqueue_failed", result_status
+ end
+ end
+
+ test "results are isolated between users and devices" do
+ second = @user.push_subscriptions.create!(
+ token: "cd" * 32, environment: "production", platform: "ios", last_registered_at: Time.current
+ )
+ @test.request!
+ @test.record(@test.latest[:id], @subscription.id, :accepted)
+ @test.record(@test.latest[:id], second.id, :failed)
+ assert_equal %w[accepted failed], @test.results(@test.latest).pluck(:status).sort
+ assert_nil PushNotificationTest.new(users(:family_admin)).latest
+ end
+
+ test "transient errors retry without reporting success" do
+ @test.request!
+ Apns::Client.any_instance.stubs(:deliver_test).returns(stub(ok?: false, status: "503"))
+ assert_enqueued_with(job: DeliverTestPushNotificationJob) do
+ deliver
+ end
+ assert_equal "retrying", result_status
+ end
+
+ private
+ def deliver
+ DeliverTestPushNotificationJob.perform_now(
+ user_id: @user.id, request_id: @test.latest[:id], push_subscription_id: @subscription.id
+ )
+ end
+
+ def result_status
+ @test.results(@test.latest).first[:status]
+ end
+end
diff --git a/test/models/push_subscription/delivery_test.rb b/test/models/push_subscription/delivery_test.rb
new file mode 100644
index 0000000000..0a288a93fd
--- /dev/null
+++ b/test/models/push_subscription/delivery_test.rb
@@ -0,0 +1,63 @@
+require "test_helper"
+
+class PushSubscription::DeliveryTest < ActiveSupport::TestCase
+ setup do
+ Rails.application.config.stubs(:app_mode).returns("managed".inquiry)
+ Apns::Client.stubs(:configured?).returns(true)
+ @subscription = users(:sure_support_staff).push_subscriptions.create!(
+ token: "ab" * 32, environment: "sandbox", platform: "ios", last_registered_at: 1.minute.ago
+ )
+ end
+
+ test "retries throttling and transient server failures" do
+ %w[429 500 503].each do |status|
+ assert_raises(Apns::Client::TransientError) { deliver(status) }
+ end
+ end
+
+ test "permanent errors preserve the subscription and redact response details" do
+ %w[400 403 413].each do |status|
+ assert_equal :rejected, deliver(status, { "reason" => @subscription.token })
+ end
+ assert PushSubscription.exists?(@subscription.id)
+ refute_includes DebugLogEntry.last.message, @subscription.token
+ refute_includes DebugLogEntry.last.metadata.to_json, @subscription.token
+ end
+
+ test "invalidates an unchanged unregistered token" do
+ assert_difference "PushSubscription.count", -1 do
+ assert_equal :unregistered, deliver("410", { "timestamp" => Time.current.to_i * 1000 })
+ end
+ end
+
+ test "a response predating registration cannot invalidate the token" do
+ assert_no_difference "PushSubscription.count" do
+ deliver("410", { "timestamp" => 2.minutes.ago.to_i * 1000 })
+ end
+ end
+
+ test "renewal while APNs is responding is preserved" do
+ original = @subscription
+ PushSubscription.find(original.id).update!(last_registered_at: Time.current)
+ assert_no_difference "PushSubscription.count" do
+ deliver("410", { "timestamp" => Time.current.to_i * 1000 })
+ end
+ end
+
+ test "malformed invalidation timestamp cannot remove a token" do
+ assert_no_difference "PushSubscription.count" do
+ deliver("410", { "timestamp" => "invalid" })
+ end
+ end
+
+ test "self hosted mode never constructs a transport even when configured" do
+ Rails.application.config.stubs(:app_mode).returns("self_hosted".inquiry)
+ Apns::Client.expects(:new).never
+ assert_equal :skipped, deliver("200")
+ end
+
+ private
+ def deliver(status, body = {})
+ PushSubscription::Delivery.new(@subscription).call { stub(ok?: status == "200", status: status, body: body) }
+ end
+end
diff --git a/test/services/apns/client_test.rb b/test/services/apns/client_test.rb
index 4be17954d0..86006561dd 100644
--- a/test/services/apns/client_test.rb
+++ b/test/services/apns/client_test.rb
@@ -2,7 +2,9 @@ require "test_helper"
class Apns::ClientTest < ActiveSupport::TestCase
setup do
+ Rails.application.config.stubs(:app_mode).returns("managed".inquiry)
@environment = {
+ "APNS_ENABLED" => nil,
"APNS_KEY_ID" => "key-id",
"APNS_TEAM_ID" => "team-id",
"APNS_BUNDLE_ID" => "com.example.sure",
@@ -19,7 +21,8 @@ class Apns::ClientTest < ActiveSupport::TestCase
options[:team_id] == "team-id" &&
options[:cert_path].read == "private-key"
end.returns(connection)
- connection.expects(:push).with do |notification|
+ connection.expects(:push).with do |notification, options|
+ options == { timeout: 10 } &&
notification.topic == "com.example.sure" &&
notification.push_type == "alert" &&
notification.custom_payload == { insight_id: "insight-id", destination: "insights" }
@@ -37,4 +40,66 @@ class Apns::ClientTest < ActiveSupport::TestCase
assert result.ok?
end
end
+
+ test "sends a bounded production diagnostic without an insight ID" do
+ connection = mock
+ Apnotic::Connection.expects(:new).returns(connection)
+ connection.expects(:push).with do |notification, options|
+ notification.custom_payload == { notification_type: "test", destination: "overview" } &&
+ notification.apns_collapse_id == "test-request-id" &&
+ notification.expiration == 5.minutes.from_now.to_i && options == { timeout: 10 }
+ end.returns(stub(ok?: true))
+ connection.expects(:close)
+ freeze_time do
+ ClimateControl.modify(@environment) do
+ Apns::Client.new(environment: "production").deliver_test(
+ token: "ab" * 32, title: "Test", body: "Test notification", request_id: "request-id"
+ )
+ end
+ end
+ end
+
+ test "configured credentials never permit direct sends from self hosted mode" do
+ Rails.application.config.stubs(:app_mode).returns("self_hosted".inquiry)
+ Apnotic::Connection.expects(:development).never
+ Apnotic::Connection.expects(:new).never
+ ClimateControl.modify(@environment) do
+ assert Apns::Client.configured?
+ refute Apns::Client.available?
+ assert_raises(Apns::Client::UnavailableError) do
+ Apns::Client.new(environment: "sandbox").deliver_test(
+ token: "ab" * 32, title: "Test", body: "Test", request_id: "request-id"
+ )
+ end
+ end
+ end
+
+ test "kill switch and absent credentials prevent direct delivery" do
+ Apnotic::Connection.expects(:new).never
+ ClimateControl.modify(@environment.merge("APNS_ENABLED" => "false")) do
+ refute Apns::Client.available?
+ assert_raises(Apns::Client::UnavailableError) do
+ Apns::Client.new(environment: "production").deliver_test(
+ token: "ab" * 32, title: "Test", body: "Test", request_id: "request-id"
+ )
+ end
+ end
+ ClimateControl.modify(@environment.merge("APNS_KEY_ID" => nil)) do
+ refute Apns::Client.available?
+ end
+ end
+
+ test "a timeout is retryable and closes the connection" do
+ connection = mock
+ Apnotic::Connection.expects(:new).returns(connection)
+ connection.expects(:push).returns(nil)
+ connection.expects(:close)
+ ClimateControl.modify(@environment) do
+ assert_raises(Apns::Client::TransientError) do
+ Apns::Client.new(environment: "production").deliver_test(
+ token: "ab" * 32, title: "Test", body: "Test", request_id: "request-id"
+ )
+ end
+ end
+ end
end
diff --git a/test/system/admin/system_health_test.rb b/test/system/admin/system_health_test.rb
index cdd4c41cc1..d50e29d946 100644
--- a/test/system/admin/system_health_test.rb
+++ b/test/system/admin/system_health_test.rb
@@ -1,6 +1,8 @@
require "application_system_test_case"
class Admin::SystemHealthTest < ApplicationSystemTestCase
+ include ActiveJob::TestHelper
+
setup do
sign_in users(:sure_support_staff)
Setting.stubs(:llm_provider).returns("openai")
@@ -37,6 +39,42 @@ class Admin::SystemHealthTest < ApplicationSystemTestCase
end
end
+ test "hosted super admin enables the test button by registering an iOS device" do
+ Rails.application.config.stubs(:app_mode).returns("managed".inquiry)
+ Apns::Client.stubs(:configured?).returns(true)
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+ visit admin_system_health_path
+ assert_selector "button[role='tab']", count: 2
+ assert_selector "button[role='tab'][aria-selected='true']", text: "Background jobs"
+ assert_selector "h2", text: "Push notifications"
+ assert_button "Send test push notification", disabled: true
+ assert_text "Enable push notifications in the Sure iOS app"
+
+ user = users(:sure_support_staff)
+ user.push_subscriptions.create!(
+ token: "ab" * 32, environment: "sandbox", platform: "ios", last_registered_at: Time.current
+ )
+ visit admin_system_health_path(tab: "background_jobs")
+ assert_button "Send test push notification", disabled: false
+ Apns::Client.expects(:new).never
+ assert_enqueued_jobs 1, only: DeliverTestPushNotificationJob do
+ click_button "Send test push notification"
+ assert_text "Test notification queued"
+ end
+ assert_text "Queued"
+ assert_button "Send test push notification", disabled: true
+ Apns::Client.unstub(:new)
+ Apns::Client.any_instance.stubs(:deliver_test).returns(stub(ok?: true))
+ perform_enqueued_jobs only: DeliverTestPushNotificationJob
+ travel 31.seconds do
+ visit admin_system_health_path(tab: "background_jobs")
+ assert_text "Latest test requested at"
+ assert_text "Accepted by APNs"
+ assert_button "Send test push notification", disabled: false
+ page.save_screenshot(Rails.root.join("tmp", "system-health-background-push-notifications.png"))
+ end
+ end
+
private
def probe_result(status)
AiHealth::Probe::Result.new(