The personal finance app for everyone (by everyone)
Ruby
fix(insights): hide household totals once account access changes (#5203)
David Gil302757be6871
diff --git a/app/models/account.rb b/app/models/account.rbindex f52f189e39..6a568e6d1b 100644--- a/app/models/account.rb+++ b/app/models/account.rb@@ -138,6 +138,14 @@ class Account < ApplicationRecordSQL}+ # SHA-256 of a set of account ids, in id order, joined by commas. An+ # aggregate over no rows still yields one value, the hash of "". Insight+ # generators store it with a total and Insight.about_shared_accounts+ # recomputes it on read, so both share this one expression.+ ID_SET_DIGEST_SQL = Arel.sql(<<~SQL.squish)+ encode(sha256(convert_to(coalesce(string_agg(accounts.id::text, ',' ORDER BY accounts.id), ''), 'UTF8')), 'hex')+ SQL+# Accounts a user can write to (owned or shared with full_control)WRITABLE_BY_CONDITION = "accounts.owner_id = :uid OR (account_shares.user_id = :uid AND account_shares.permission = 'full_control')".freezediff --git a/app/models/insight.rb b/app/models/insight.rbindex 5c6200d6bc..0d6dc607bb 100644--- a/app/models/insight.rb+++ b/app/models/insight.rb@@ -56,6 +56,10 @@ class Insight < ApplicationRecord# 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.#+ # A total (metadata accounts_digest) names no single account, so it shows+ # only while its digest still matches the set every active member can open+ # now; otherwise its figures may include an account someone lost.+ ## 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, -> {@@ -67,7 +71,12 @@ class Insight < ApplicationRecordTHEN (insights.metadata->>'account_id')::uuidENDSQL+ current_digest = Account.accessible_by_all_active_members+ .where("accounts.family_id = insights.family_id")+ .select(Account::ID_SET_DIGEST_SQL)+where("NOT (insights.metadata ? 'account_id')").or(where(shared_account.arel.exists))+ .where("NOT (insights.metadata ? 'accounts_digest') OR insights.metadata->>'accounts_digest' = (#{current_digest.to_sql})").about_shared_recurring_transactions}diff --git a/app/models/insight/generator.rb b/app/models/insight/generator.rbindex cd291a2a3b..115b6df353 100644--- a/app/models/insight/generator.rb+++ b/app/models/insight/generator.rb@@ -67,11 +67,19 @@ class Insight::Generator# Totals have no single account that Insight.about_shared_accounts could# recheck on read, so an aggregate insight carries the account set it was- # computed from. When a share is granted or revoked the digest changes and- # the job rewrites the body (see GenerateInsightsJob#upsert_insights), so- # prose written from the old set does not outlive it.+ # computed from. Once access changes the feed hides it, and the next run+ # writes the new digest and rewrites the body (see+ # GenerateInsightsJob#upsert_insights), so prose written from the old set+ # does not outlive it.+ #+ # Hashed from the captured ids rather than the account rows, so an account+ # deleted after the figures were computed still counts. The ids are+ # aliased as accounts.id so the shared expression applies unchanged.def shared_accounts_digest- @shared_accounts_digest ||= Digest::SHA256.hexdigest(shared_account_ids.join(","))+ @shared_accounts_digest ||= Account.connection.select_value(Account.sanitize_sql_array([+ "SELECT #{Account::ID_SET_DIGEST_SQL} FROM unnest(?::uuid[]) AS accounts(id)",+ "{#{shared_account_ids.join(",")}}"+ ]))end# Recurring series follow the same rule, matchingdiff --git a/test/controllers/api/v1/insights_controller_test.rb b/test/controllers/api/v1/insights_controller_test.rbindex 83e179ec51..0f4697fed8 100644--- a/test/controllers/api/v1/insights_controller_test.rb+++ b/test/controllers/api/v1/insights_controller_test.rb@@ -1,6 +1,8 @@require "test_helper"class Api::V1::InsightsControllerTest < ActionDispatch::IntegrationTest+ include InsightTestHelper+setup do@user = users(:family_admin)@user.update!(preferences: @user.preferences.merge("preview_features_enabled" => true))@@ -33,6 +35,20 @@ class Api::V1::InsightsControllerTest < ActionDispatch::IntegrationTestassert_equal "Put idle cash to work", row.fetch("title")end+ test "hides a household total once access to its accounts changes" do+ total = household_total(@user.family)+ accounts(:depository).unshare_with!(users(:family_member))++ get api_v1_insights_url, headers: api_headers(@api_key)++ assert_response :success+ assert_not_includes response.parsed_body.fetch("insights").map { |insight| insight.fetch("id") }, total.id++ @api_key.update!(scopes: [ "read_write" ])+ patch acknowledge_api_v1_insight_url(total), headers: api_headers(@api_key)+ assert_response :not_found+ end+test "rejects requests without an API key" doget api_v1_insights_urldiff --git a/test/controllers/chats_controller_test.rb b/test/controllers/chats_controller_test.rbindex d1aa9d6c4c..62a3496024 100644--- a/test/controllers/chats_controller_test.rb+++ b/test/controllers/chats_controller_test.rb@@ -70,6 +70,20 @@ class ChatsControllerTest < ActionDispatch::IntegrationTestassert_no_match "Private holds a balance", response.bodyend+ test "new chat ignores a household total computed from accounts someone can no longer open" do+ insight = families(:dylan_family).insights.create!(+ insight_type: "savings_rate_change", priority: "medium", status: "active", title: "Savings",+ body: "Stale household total", metadata: { "accounts_digest" => "an-account-set-that-changed" },+ dedup_key: "savings_rate_change:stale", generated_at: Time.current+ )++ get new_chat_url(insight_id: insight.id)++ assert_response :success+ assert_select "textarea[name='chat[content]']", text: ""+ assert_no_match "Stale household total", response.body+ end+# Hidden from everyone, owner included, same as the feed.test "new chat ignores an insight about a private account for its owner too" doinsight = create_private_account_insightdiff --git a/test/jobs/deliver_insight_notification_job_test.rb b/test/jobs/deliver_insight_notification_job_test.rbindex dae764a45f..e6164561cd 100644--- a/test/jobs/deliver_insight_notification_job_test.rb+++ b/test/jobs/deliver_insight_notification_job_test.rb@@ -51,6 +51,13 @@ class DeliverInsightNotificationJobTest < ActiveJob::TestCaseDeliverInsightNotificationJob.perform_now(insight_id: @insight.id, push_subscription_id: @subscription.id)end+ test "does not push a household total computed from accounts someone can no longer open" do+ @insight.update!(metadata: @insight.metadata.merge("accounts_digest" => "an-account-set-that-changed"))+ 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/models/assistant/function/get_insights_test.rb b/test/models/assistant/function/get_insights_test.rbindex 5fb69a8045..140f3f6368 100644--- a/test/models/assistant/function/get_insights_test.rb+++ b/test/models/assistant/function/get_insights_test.rb@@ -1,6 +1,8 @@require "test_helper"class Assistant::Function::GetInsightsTest < ActiveSupport::TestCase+ include InsightTestHelper+setup do@user = users(:family_admin)@family = @user.family@@ -90,4 +92,16 @@ class Assistant::Function::GetInsightsTest < ActiveSupport::TestCaseassert_not_includes ids, insight.idend++ test "hides a household total once access to its accounts changes, acknowledged or not" do+ total = household_total(@family)+ acknowledged = household_total(@family, status: "dismissed", dedup_key: "savings_rate_change:old")++ accounts(:depository).unshare_with!(users(:family_member))++ assert_not_includes @fn.call[:insights].map { |i| i[:id] }, total.id+ included_ids = @fn.call("include_acknowledged" => true)[:insights].map { |i| i[:id] }+ assert_not_includes included_ids, total.id+ assert_not_includes included_ids, acknowledged.id+ endenddiff --git a/test/models/insight/generator_test.rb b/test/models/insight/generator_test.rbindex dcc86e7e27..0b0c143593 100644--- a/test/models/insight/generator_test.rb+++ b/test/models/insight/generator_test.rb@@ -1,6 +1,8 @@require "test_helper"class Insight::GeneratorTest < ActiveSupport::TestCase+ include InsightTestHelper+# Exposes the shared-account helpers the way a generator uses them: figures# first, the digest for the metadata afterwards.class ProbeGenerator < Insight::Generator@@ -29,4 +31,26 @@ class Insight::GeneratorTest < ActiveSupport::TestCaseassert_equal first_ids.sort, @generator.figure_account_ids.sortassert_equal Digest::SHA256.hexdigest(first_ids.sort.join(",")), @generator.digestend++ # Insight.about_shared_accounts recomputes this digest in SQL on every read;+ # rows written before it existed were hashed in Ruby, so both must agree.+ test "the digest matches the one first computed in Ruby" do+ assert_equal ruby_shared_accounts_digest(@family), @generator.digest+ end++ # The digest describes the ids the figures were computed from, not the+ # rows still there when it is taken.+ test "an account deleted after the figures still counts in the digest" do+ first_ids = @generator.figure_account_ids++ accounts(:depository).destroy!++ assert_equal Digest::SHA256.hexdigest(first_ids.sort.join(",")), @generator.digest+ end++ test "the digest of no shared account is the hash of an empty string" do+ AccountShare.where(account: @family.accounts).delete_all++ assert_equal Digest::SHA256.hexdigest(""), @generator.digest+ endenddiff --git a/test/models/insight_test.rb b/test/models/insight_test.rbindex 967bb8751c..2e1dcfd0b3 100644--- a/test/models/insight_test.rb+++ b/test/models/insight_test.rb@@ -1,6 +1,7 @@require "test_helper"class InsightTest < ActiveSupport::TestCase+ include InsightTestHelpersetup do@insight = insights(:spending_anomaly_dining)end@@ -189,6 +190,68 @@ class InsightTest < ActiveSupport::TestCaseassert_not_includes family.insights.visible, insightend+ # A total names no single account, so it carries the set it was computed+ # from. Once that set is no longer the one every active member can open, the+ # figures may come from an account someone lost, and the row hides until the+ # next run rewrites it.+ test "revoking a share hides a household total right away" do+ family = families(:dylan_family)+ total = household_total(family)+ assert_includes family.insights.visible, total++ accounts(:depository).unshare_with!(users(:family_member))++ assert_not_includes family.insights.visible, total+ assert_includes family.insights.visible, @insight, "a row without a digest is untouched"+ end++ test "restoring access shows the household total again as it was" do+ family = families(:dylan_family)+ total = household_total(family).tap(&:mark_read!)+ before = total.reload.attributes++ accounts(:depository).unshare_with!(users(:family_member))+ accounts(:depository).share_with!(users(:family_member))++ assert_includes family.insights.visible, total+ assert_equal before, total.reload.attributes, "hiding writes nothing"+ end++ test "a member leaving hides a household total" do+ family = families(:dylan_family)+ total = household_total(family)++ users(:family_member).deactivate++ assert_not_includes family.insights.visible, total+ end++ test "a member joining hides a household total" do+ family = families(:dylan_family)+ total = household_total(family)++ family.users.create!(email: "[email protected]", password: "password123!A", first_name: "New", last_name: "Member", role: "member")++ assert_not_includes family.insights.visible, total+ end++ test "an access change leaves an insight about a still shared account visible" do+ family = families(:dylan_family)+ per_account = idle_cash_insight(family, accounts(:depository))++ accounts(:credit_card).unshare_with!(users(:family_member))++ assert_includes family.insights.visible, per_account+ end++ test "a household total is checked against its own family's accounts" do+ total = household_total(families(:empty))++ accounts(:depository).unshare_with!(users(:family_member))++ assert_includes families(:empty).insights.visible, total+ end+privatedef subscription_audit_insight(family, series, account_id: nil)family.insights.create!(diff --git a/test/support/insight_test_helper.rb b/test/support/insight_test_helper.rbnew file mode 100644index 0000000000..27dcbf85c4--- /dev/null+++ b/test/support/insight_test_helper.rb@@ -0,0 +1,16 @@+module InsightTestHelper+ # The digest Insight::Generator stores on a total, computed the way it was+ # first written in Ruby, so tests check the SQL against an independent oracle.+ def ruby_shared_accounts_digest(family)+ Digest::SHA256.hexdigest(family.accounts.accessible_by_all_active_members.order(:id).pluck(:id).join(","))+ end++ # A household total computed from the accounts every member can open now.+ def household_total(family, status: "active", dedup_key: "savings_rate_change:current")+ family.insights.create!(+ insight_type: "savings_rate_change", priority: "medium", status: status, title: "Savings", body: "body",+ metadata: { "current_rate" => 40.0, "accounts_digest" => ruby_shared_accounts_digest(family) },+ dedup_key: dedup_key, generated_at: Time.current+ )+ end+end