The personal finance app for everyone (by everyone)
Ruby
fix(insights): keep private and unshared accounts out of the shared feed (#4061)
GFR4a1e6574a4c4
diff --git a/app/controllers/insights_controller.rb b/app/controllers/insights_controller.rbindex 0fec7a7226..88c0051c8b 100644--- a/app/controllers/insights_controller.rb+++ b/app/controllers/insights_controller.rb@@ -11,7 +11,7 @@ class InsightsController < ApplicationController# hits this GET before the user actually navigates, so skip the write# for prefetch requests or badges would clear on hover.unless prefetch_request?- Current.family.insights.active.update_all(status: "read", read_at: Time.current, updated_at: Time.current)+ Current.family.insights.visible.active.update_all(status: "read", read_at: Time.current, updated_at: Time.current)endend@@ -54,7 +54,9 @@ class InsightsController < ApplicationControllerprivatedef set_insight- @insight = Current.family.insights.find(params[:id])+ # Not `visible`: unacknowledge targets acknowledged rows. The account+ # check still applies, so a hidden row can't be changed by id.+ @insight = Current.family.insights.about_shared_accounts.find(params[:id])enddef load_feeddiff --git a/app/jobs/deliver_insight_notification_job.rb b/app/jobs/deliver_insight_notification_job.rbindex 7dc1966c86..f6793e7aa3 100644--- a/app/jobs/deliver_insight_notification_job.rb+++ b/app/jobs/deliver_insight_notification_job.rb@@ -26,6 +26,9 @@ class DeliverInsightNotificationJob < ApplicationJobreturn unless subscription.user.family_id == insight.family_idreturn unless subscription.eligible? && subscription.user.preview_features_enabled?return unless insight.priority_high? && insight.active?+ # The account it names may have stopped being shared with everyone+ # since the insight was generated; the feed hides it, so no push either.+ return unless Insight.about_shared_accounts.exists?(insight.id)PushSubscription::Delivery.new(subscription).call do |client|I18n.with_locale(insight.family.locale) dodiff --git a/app/jobs/generate_insights_job.rb b/app/jobs/generate_insights_job.rbindex 31c7dd20b9..231726e8ad 100644--- a/app/jobs/generate_insights_job.rb+++ b/app/jobs/generate_insights_job.rb@@ -82,10 +82,11 @@ class GenerateInsightsJob < ApplicationJob# A visible insight whose generator ran successfully but did not re-emit# its dedup_key has had its condition clear — hide it. Types whose# generator crashed are left untouched so a transient failure can't wipe- # out healthy insights.+ # out healthy insights. By status rather than `visible`, so a row hidden+ # because its account is no longer shared with everyone expires too.def expire_stale_insights(family, result)family.insights- .visible+ .where(status: %w[active read]).where(insight_type: result.succeeded_types).where.not(dedup_key: result.insights.map(&:dedup_key)).update_all(status: "expired", updated_at: Time.current)diff --git a/app/models/account.rb b/app/models/account.rbindex 1a5ab35dc9..e1422cb400 100644--- a/app/models/account.rb+++ b/app/models/account.rb@@ -73,6 +73,26 @@ class Account < ApplicationRecord.distinct}+ # Accounts every active member of the account's family can access (owned or+ # shared with them), the same test as accessible_by applied to all of them.+ # Family-wide surfaces such as the insights feed name accounts and amounts+ # to everyone, so they draw only from this set.+ scope :accessible_by_all_active_members, -> {+ where(<<~SQL.squish)+ NOT EXISTS (+ SELECT 1 FROM users+ WHERE users.family_id = accounts.family_id+ AND users.active = TRUE+ AND users.id IS DISTINCT FROM accounts.owner_id+ AND NOT EXISTS (+ SELECT 1 FROM account_shares+ WHERE account_shares.account_id = accounts.id+ AND account_shares.user_id = users.id+ )+ )+ SQL+ }+# Accounts a user can write to (owned or shared with full_control)scope :writable_by, ->(user) {left_joins(:account_shares)diff --git a/app/models/assistant/function/get_insights.rb b/app/models/assistant/function/get_insights.rbindex 16508ab4cd..d129a517ec 100644--- a/app/models/assistant/function/get_insights.rb+++ b/app/models/assistant/function/get_insights.rb@@ -49,12 +49,13 @@ class Assistant::Function::GetInsights < Assistant::Functionend# Insights are family-scoped by design (the nightly generator runs per- # family, not per user), so there is no per-account visibility filter here.- # That matches the web feed exactly: InsightsController serves- # Current.family.insights to every member, so this tool exposes nothing the- # /insights page does not already show the same user.+ # family, not per user), so there is no per-viewer filter here. That matches+ # the web feed exactly: InsightsController serves Current.family.insights to+ # every member, so this tool exposes nothing the /insights page does not+ # already show the same user. Acknowledged rows go through the same+ # about_shared_accounts check the feed's `visible` scope applies.def call(params = {})- scope = params["include_acknowledged"] ? family.insights.where.not(status: :expired) : family.insights.visible+ scope = params["include_acknowledged"] ? family.insights.where.not(status: :expired).about_shared_accounts : family.insights.visiblescope = scope.where(insight_type: params["insight_type"]) if params["insight_type"].present?limit = params["limit"].present? ? params["limit"].to_i.clamp(1, MAX_LIMIT) : DEFAULT_LIMITdiff --git a/app/models/insight.rb b/app/models/insight.rbindex 15969f13e5..a880f59a8a 100644--- a/app/models/insight.rb+++ b/app/models/insight.rb@@ -43,7 +43,30 @@ class Insight < ApplicationRecordvalidates :dedup_key, uniqueness: { scope: :family_id }# Everything the user hasn't acknowledged; what the feed renders.- scope :visible, -> { where(status: [ :active, :read ]) }+ scope :visible, -> { where(status: [ :active, :read ]).about_shared_accounts }++ # The feed is shared by the whole family, so an insight that names an+ # account (metadata account_id) shows only while every active member can+ # see that account. Generators already skip other accounts; this read-time+ # check also covers rows written before access changed (a share revoked, a+ # member joined, the account moved, hidden or deleted), which would+ # otherwise stay in the feed until the next nightly run expires them.+ # Nothing is written, so the row reappears as it was if access is restored.+ #+ # The id is cast to uuid (not the column to text) so the lookup stays a+ # primary-key probe; the CASE keeps a malformed value from raising.+ scope :about_shared_accounts, -> {+ shared_account = Account.visible.accessible_by_all_active_members+ .where("accounts.family_id = insights.family_id")+ .where(<<~SQL.squish)+ accounts.id = CASE+ WHEN insights.metadata->>'account_id' ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'+ THEN (insights.metadata->>'account_id')::uuid+ END+ SQL+ where("NOT (insights.metadata ? 'account_id')").or(where(shared_account.arel.exists))+ }+scope :ordered, -> {order(Arel.sql("CASE insights.priority WHEN 'high' THEN 0 WHEN 'medium' THEN 1 ELSE 2 END")).order(generated_at: :desc)diff --git a/app/models/insight/generators/idle_cash_generator.rb b/app/models/insight/generators/idle_cash_generator.rbindex 651e6b5bb3..499b8b6970 100644--- a/app/models/insight/generators/idle_cash_generator.rb+++ b/app/models/insight/generators/idle_cash_generator.rb@@ -34,8 +34,11 @@ class Insight::Generators::IdleCashGenerator < Insight::Generatorprivate# Ordered so the pick is stable between runs — an unordered relation could# nudge a different pair of accounts each night, churning the feed.+ #+ # The feed is shared by the whole family and the insight names the account+ # and its balance, so only accounts every active member can see qualify.def idle_accounts- family.accounts.visible+ family.accounts.visible.accessible_by_all_active_members.where(accountable_type: "Depository", currency: family.currency).where("balance >= ?", MIN_BALANCE).where.not(id: Entry.where("date >= ?", IDLE_DAYS.days.ago.to_date).select(:account_id))diff --git a/app/views/layouts/shared/_insights_button.html.erb b/app/views/layouts/shared/_insights_button.html.erbindex 8ff37bbeff..2342b7039a 100644--- a/app/views/layouts/shared/_insights_button.html.erb+++ b/app/views/layouts/shared/_insights_button.html.erb@@ -20,6 +20,6 @@as: :span,html_class: "size-full items-center justify-center") %>- <%= render "layouts/shared/insights_badge", count: Current.family.insights.active.count %>+ <%= render "layouts/shared/insights_badge", count: Current.family.insights.visible.active.count %><% end %><% end %>diff --git a/test/controllers/insights_controller_test.rb b/test/controllers/insights_controller_test.rbindex fd9c571f28..03543924de 100644--- a/test/controllers/insights_controller_test.rb+++ b/test/controllers/insights_controller_test.rb@@ -242,6 +242,22 @@ class InsightsControllerTest < ActionDispatch::IntegrationTestassert other_insight.reload.active?end+ test "an insight about an account not everyone can see is neither shown nor changed" do+ hidden = @user.family.insights.create!(+ insight_type: "idle_cash", priority: "low", status: "active", title: "Idle cash in Private",+ body: "Body", metadata: { "account_id" => accounts(:connected).id },+ dedup_key: "idle_cash:private:2026-07", generated_at: Time.current+ )++ get insights_url+ assert_no_match "Idle cash in Private", response.body+ assert hidden.reload.active?, "viewing the feed does not mark a hidden row read"++ patch acknowledge_insight_url(hidden), as: :turbo_stream+ assert_response :not_found+ assert hidden.reload.active?+ end+test "refresh enqueues insight generation for the family" doassert_enqueued_with(job: GenerateInsightsJob, args: [ { family_id: @user.family_id } ]) dopost refresh_insights_urldiff --git a/test/jobs/deliver_insight_notification_job_test.rb b/test/jobs/deliver_insight_notification_job_test.rbindex 55d18bbb12..2513029513 100644--- a/test/jobs/deliver_insight_notification_job_test.rb+++ b/test/jobs/deliver_insight_notification_job_test.rb@@ -44,6 +44,13 @@ class DeliverInsightNotificationJobTest < ActiveJob::TestCase)end+ test "does not push an insight whose account is no longer shared with everyone" do+ @insight.update!(metadata: @insight.metadata.merge("account_id" => accounts(:connected).id))+ Apns::Client.expects(:new).never++ DeliverInsightNotificationJob.perform_now(insight_id: @insight.id, push_subscription_id: @subscription.id)+ end+test "localizes notifications using the family locale" do@insight.family.update!(locale: "de")response = stub(ok?: true)diff --git a/test/jobs/generate_insights_job_test.rb b/test/jobs/generate_insights_job_test.rbindex 328070e14a..0f7e7b7ad6 100644--- a/test/jobs/generate_insights_job_test.rb+++ b/test/jobs/generate_insights_job_test.rb@@ -281,6 +281,20 @@ class GenerateInsightsJobTest < ActiveJob::TestCaseassert_nil insight.read_atend+ test "expires an insight hidden because its account is no longer shared with everyone" do+ insight = @family.insights.create!(+ insight_type: "idle_cash", priority: "low", status: "active", title: "Idle", body: "body",+ metadata: { "account_id" => accounts(:connected).id }, dedup_key: "idle_cash:private",+ generated_at: Time.current+ )+ assert_not @family.insights.visible.exists?(id: insight.id), "precondition: the row must be hidden, not just stale"+ stub_generated([], succeeded_types: [ "idle_cash" ])++ GenerateInsightsJob.perform_now(family_id: @family.id)++ assert insight.reload.expired?, "a hidden row whose condition cleared must not come back stale once access returns"+ end+privatedef enable_preview_features(family)family.users.each { |user| set_preview_features(user, true) }@@ -312,7 +326,7 @@ class GenerateInsightsJobTest < ActiveJob::TestCasetitle: title,template_key: "idle_cash",facts: { account: "Test Checking", balance: "$#{(display_balance || balance).to_i}", idle_days: 60 },- metadata: { account_id: "test-account", balance: balance },+ metadata: { account_id: accounts(:depository).id, balance: balance },currency: "USD",period_start: nil,period_end: nil,diff --git a/test/models/assistant/function/get_insights_test.rb b/test/models/assistant/function/get_insights_test.rbindex c5aee3f6fd..5fb69a8045 100644--- a/test/models/assistant/function/get_insights_test.rb+++ b/test/models/assistant/function/get_insights_test.rb@@ -78,4 +78,16 @@ class Assistant::Function::GetInsightsTest < ActiveSupport::TestCaseassert_empty result[:insights]end++ test "include_acknowledged still hides insights about accounts not everyone can see" do+ insight = @family.insights.create!(+ insight_type: "idle_cash", priority: "low", status: "dismissed", title: "Idle", body: "body",+ metadata: { "account_id" => accounts(:connected).id }, dedup_key: "idle_cash:private",+ generated_at: Time.current+ )++ ids = @fn.call("include_acknowledged" => true)[:insights].map { |i| i[:id] }++ assert_not_includes ids, insight.id+ endenddiff --git a/test/models/insight/generators/idle_cash_generator_test.rb b/test/models/insight/generators/idle_cash_generator_test.rbnew file mode 100644index 0000000000..e17a9ed7cf--- /dev/null+++ b/test/models/insight/generators/idle_cash_generator_test.rb@@ -0,0 +1,31 @@+require "test_helper"++class Insight::Generators::IdleCashGeneratorTest < ActiveSupport::TestCase+ setup do+ @family = families(:dylan_family)+ # Both are untouched Depository accounts with 5,000 USD: `depository` is+ # shared with family_member, `connected` is private to family_admin.+ @shared = accounts(:depository)+ @private = accounts(:connected)+ Entry.where(account: [ @shared, @private ]).delete_all+ end++ test "nudges about an idle account every active member can see" do+ assert_includes nudged_account_ids, @shared.id+ end++ test "skips an account that is private to one member" do+ assert_not_includes nudged_account_ids, @private.id+ end++ test "an inactive member does not hide an account from the feed" do+ users(:family_member).update_columns(active: false)++ assert_includes nudged_account_ids, @private.id+ end++ private+ def nudged_account_ids+ Insight::Generators::IdleCashGenerator.new(@family).generate.map { |insight| insight.metadata[:account_id] }+ end+enddiff --git a/test/models/insight_test.rb b/test/models/insight_test.rbindex a40484c239..d91619b794 100644--- a/test/models/insight_test.rb+++ b/test/models/insight_test.rb@@ -99,4 +99,79 @@ class InsightTest < ActiveSupport::TestCaseassert_not insight.valid?assert insight.errors[:insight_type].any?end++ test "visible hides an insight about an account a member cannot see" do+ family = families(:dylan_family)+ shared = idle_cash_insight(family, accounts(:depository))+ private_one = idle_cash_insight(family, accounts(:connected))+ gone = idle_cash_insight(family, Struct.new(:id).new(SecureRandom.uuid))++ visible = family.insights.visible++ assert_includes visible, shared+ assert_not_includes visible, private_one+ assert_not_includes visible, gone, "an insight about a deleted account is hidden too"+ assert_includes visible, @insight, "insights without an account are untouched"+ assert private_one.reload.active?, "hiding writes nothing; the row returns as it was"+ end++ test "revoking a share hides an insight about that account right away" do+ family = families(:dylan_family)+ insight = idle_cash_insight(family, accounts(:depository))++ accounts(:depository).unshare_with!(users(:family_member))++ assert_not_includes family.insights.visible, insight+ end++ test "a member joining without access hides an insight about the account" do+ family = families(:dylan_family)+ insight = idle_cash_insight(family, accounts(:depository))++ family.users.create!(email: "[email protected]", password: "password123!A", first_name: "New", last_name: "Member", role: "member")++ assert_not_includes family.insights.visible, insight+ end++ test "an inactive member does not hide an insight" do+ family = families(:dylan_family)+ insight = idle_cash_insight(family, accounts(:connected))++ users(:family_member).update_columns(active: false)++ assert_includes family.insights.visible, insight+ end++ test "an insight about another family's account id is hidden" do+ family = families(:dylan_family)+ insight = idle_cash_insight(family, accounts(:connected))+ insight.update_columns(family_id: families(:empty).id)++ assert_not_includes families(:empty).insights.visible, insight+ end++ test "a malformed account id hides the insight instead of raising" do+ family = families(:dylan_family)+ insight = idle_cash_insight(family, Struct.new(:id).new("not-a-uuid"))++ assert_not_includes family.insights.visible.to_a, insight+ end++ test "an insight about an account pending deletion is hidden" do+ family = families(:dylan_family)+ insight = idle_cash_insight(family, accounts(:depository))++ accounts(:depository).update_columns(status: "pending_deletion")++ assert_not_includes family.insights.visible, insight+ end++ private+ def idle_cash_insight(family, account)+ family.insights.create!(+ insight_type: "idle_cash", priority: "low", status: "active", title: "Idle", body: "body",+ metadata: { "account_id" => account.id }, dedup_key: "idle_cash:#{account.id}",+ generated_at: Time.current+ )+ endend