The personal finance app for everyone (by everyone)
Ruby
List and open only the imports whose statement the user can view (#5697)
David Gilad71b4bd917f
diff --git a/app/controllers/account_statements_controller.rb b/app/controllers/account_statements_controller.rbindex 94b93f1854..1c49dc97d0 100644--- a/app/controllers/account_statements_controller.rb+++ b/app/controllers/account_statements_controller.rb@@ -5,14 +5,11 @@ class AccountStatementsController < ApplicationControllerbefore_action :ensure_statement_manager!, only: %i[index create update destroy link unlink reject]def index- accessible_account_ids = Current.user.accessible_accounts.select(:id)account_statements = Current.family.account_statements.with_attached_original_file.includes(:account, :suggested_account)- visible_storage_scope = Current.family.account_statements- .where(account_id: nil)- .or(Current.family.account_statements.where(account_id: accessible_account_ids))- linked_statement_scope = account_statements.with_account.where(account_id: accessible_account_ids).by_period+ visible_storage_scope = Current.family.account_statements.viewable_by(Current.user)+ linked_statement_scope = account_statements.viewable_by(Current.user).with_account.by_period@unmatched_pagy, @unmatched_statements = pagy(account_statements.inbox.ordered, limit: safe_per_page, page_param: :unmatched_page)@linked_pagy, @linked_statements = pagy(linked_statement_scope, limit: safe_per_page, page_param: :linked_page)@@ -124,7 +121,7 @@ class AccountStatementsController < ApplicationControllerreturn if @statement.account && !require_account_permission!(@statement.account)redirect_path = @statement.account ? account_path(@statement.account, tab: "statements") : account_statements_path- if @statement.destroy+ if destroy_statementredirect_to redirect_path, notice: t("account_statements.destroy.success")elseredirect_back_or_to redirect_path, alert: t("account_statements.destroy.failure")@@ -132,6 +129,13 @@ class AccountStatementsController < ApplicationControllerendprivate+ # The foreign key refuses the DELETE when an import arrived after the+ # model's check for imports.+ def destroy_statement+ @statement.destroy+ rescue ActiveRecord::InvalidForeignKey+ false+ enddef set_statement@statement = Current.family.account_statementsdiff --git a/app/controllers/api/v1/imports_controller.rb b/app/controllers/api/v1/imports_controller.rbindex 93275837cf..8542baad1d 100644--- a/app/controllers/api/v1/imports_controller.rb+++ b/app/controllers/api/v1/imports_controller.rb@@ -11,8 +11,7 @@ class Api::V1::ImportsController < Api::V1::BaseControllerbefore_action :set_import, only: [ :rows ]def index- family = current_resource_owner.family- imports_query = family.imports.ordered+ imports_query = import_scope.ordered# Apply filtersif params[:status].present?@@ -215,7 +214,7 @@ class Api::V1::ImportsController < Api::V1::BaseControllerenddef import_scope- current_resource_owner.family.imports+ current_resource_owner.family.imports.viewable_by(current_resource_owner)enddef render_import_not_founddiff --git a/app/controllers/concerns/viewable_imports.rb b/app/controllers/concerns/viewable_imports.rbnew file mode 100644index 0000000000..ee753ba19d--- /dev/null+++ b/app/controllers/concerns/viewable_imports.rb@@ -0,0 +1,10 @@+# Imports belong to the family, but one made from a statement is as private as+# that statement. Import pages look imports up through here.+module ViewableImports+ extend ActiveSupport::Concern++ private+ def viewable_imports+ Current.family.imports.viewable_by(Current.user)+ end+enddiff --git a/app/controllers/import/cleans_controller.rb b/app/controllers/import/cleans_controller.rbindex 4b0b46c165..d5b1b02ae4 100644--- a/app/controllers/import/cleans_controller.rb+++ b/app/controllers/import/cleans_controller.rb@@ -1,4 +1,5 @@class Import::CleansController < ApplicationController+ include ViewableImportslayout "imports"before_action :set_import@@ -20,6 +21,6 @@ class Import::CleansController < ApplicationControllerprivatedef set_import- @import = Current.family.imports.find(params[:import_id])+ @import = viewable_imports.find(params[:import_id])endenddiff --git a/app/controllers/import/configurations_controller.rb b/app/controllers/import/configurations_controller.rbindex d71ae64bca..9d233d4bb8 100644--- a/app/controllers/import/configurations_controller.rb+++ b/app/controllers/import/configurations_controller.rb@@ -1,4 +1,5 @@class Import::ConfigurationsController < ApplicationController+ include ViewableImportsinclude ImportGuestGuardablelayout "imports"@@ -39,7 +40,7 @@ class Import::ConfigurationsController < ApplicationControllerprivatedef set_import- @import = Current.family.imports.find(params[:import_id])+ @import = viewable_imports.find(params[:import_id])end# Existing accounts a Monarch account can go into: the manual ones thisdiff --git a/app/controllers/import/confirms_controller.rb b/app/controllers/import/confirms_controller.rbindex 029a58469e..a3da71881d 100644--- a/app/controllers/import/confirms_controller.rb+++ b/app/controllers/import/confirms_controller.rb@@ -1,4 +1,5 @@class Import::ConfirmsController < ApplicationController+ include ViewableImportslayout "imports"before_action :set_import@@ -13,6 +14,6 @@ class Import::ConfirmsController < ApplicationControllerprivatedef set_import- @import = Current.family.imports.find(params[:import_id])+ @import = viewable_imports.find(params[:import_id])endenddiff --git a/app/controllers/import/mappings_controller.rb b/app/controllers/import/mappings_controller.rbindex 32fa1b39bb..90d1c2b59b 100644--- a/app/controllers/import/mappings_controller.rb+++ b/app/controllers/import/mappings_controller.rb@@ -1,4 +1,5 @@class Import::MappingsController < ApplicationController+ include ViewableImportsinclude ImportGuestGuardablebefore_action :set_import@@ -21,7 +22,7 @@ class Import::MappingsController < ApplicationControllerenddef set_import- @import = Current.family.imports.find(params[:import_id])+ @import = viewable_imports.find(params[:import_id])end# The mapping row already declares what it maps to, so neither the targetdiff --git a/app/controllers/import/qif_category_selections_controller.rb b/app/controllers/import/qif_category_selections_controller.rbindex 1bb0e6205d..220e7ba5cc 100644--- a/app/controllers/import/qif_category_selections_controller.rb+++ b/app/controllers/import/qif_category_selections_controller.rb@@ -1,4 +1,5 @@class Import::QifCategorySelectionsController < ApplicationController+ include ViewableImportsinclude ImportGuestGuardablelayout "imports"@@ -82,7 +83,7 @@ class Import::QifCategorySelectionsController < ApplicationControllerprivatedef set_import- @import = Current.family.imports.find(params[:import_id])+ @import = viewable_imports.find(params[:import_id])unless @import.is_a?(QifImport)redirect_to imports_path and returndiff --git a/app/controllers/import/rows_controller.rb b/app/controllers/import/rows_controller.rbindex 81233e552f..ee9babc938 100644--- a/app/controllers/import/rows_controller.rb+++ b/app/controllers/import/rows_controller.rb@@ -1,4 +1,5 @@class Import::RowsController < ApplicationController+ include ViewableImportsinclude ImportGuestGuardablebefore_action :set_import_row@@ -19,7 +20,7 @@ class Import::RowsController < ApplicationControllerenddef set_import_row- @import = Current.family.imports.find(params[:import_id])+ @import = viewable_imports.find(params[:import_id])@row = @import.rows.find(params[:id])endenddiff --git a/app/controllers/import/uploads_controller.rb b/app/controllers/import/uploads_controller.rbindex c2f660dd99..0ec1bae456 100644--- a/app/controllers/import/uploads_controller.rb+++ b/app/controllers/import/uploads_controller.rb@@ -1,4 +1,5 @@class Import::UploadsController < ApplicationController+ include ViewableImportsinclude ImportGuestGuardablelayout "imports"@@ -102,7 +103,7 @@ class Import::UploadsController < ApplicationControllerenddef set_import- @import = Current.family.imports.find(params[:import_id])+ @import = viewable_imports.find(params[:import_id])enddef handle_qif_uploaddiff --git a/app/controllers/imports_controller.rb b/app/controllers/imports_controller.rbindex cc7b2a3552..a33a000857 100644--- a/app/controllers/imports_controller.rb+++ b/app/controllers/imports_controller.rb@@ -1,4 +1,5 @@class ImportsController < ApplicationController+ include ViewableImportsinclude SettingsHelperbefore_action :set_import, only: %i[show update publish destroy revert apply_template cancel summary]@@ -66,7 +67,7 @@ class ImportsController < ApplicationControllerenddef index- @pagy, @imports = pagy(Current.family.imports.where(type: Import::TYPES).ordered, limit: safe_per_page)+ @pagy, @imports = pagy(viewable_imports.where(type: Import::TYPES).ordered, limit: safe_per_page)@breadcrumbs = [[ t("breadcrumbs.home"), root_path ],[ t("breadcrumbs.imports"), imports_path ]@@ -77,7 +78,7 @@ class ImportsController < ApplicationControllerenddef new- @pending_import = Current.family.imports.ordered.pending.first+ @pending_import = viewable_imports.ordered.pending.first@document_upload_extensions = document_upload_supported_extensionsend@@ -187,8 +188,7 @@ class ImportsController < ApplicationControllerprivatedef set_import- @import = Current.family.imports.includes(:account, :account_statement).find(params[:id])- raise ActiveRecord::RecordNotFound unless @import.viewable_by?(Current.user)+ @import = viewable_imports.includes(:account, :account_statement).find(params[:id])enddef import_paramsdiff --git a/app/models/account_statement.rb b/app/models/account_statement.rbindex e09fb23a5f..871ab90c2b 100644--- a/app/models/account_statement.rb+++ b/app/models/account_statement.rb@@ -34,7 +34,11 @@ class AccountStatement < ApplicationRecordbelongs_to :account, optional: truebelongs_to :suggested_account, class_name: "Account", optional: true- has_many :pdf_imports, -> { where(type: "PdfImport").ordered }, class_name: "PdfImport", dependent: :restrict_with_error+ # An import is as private as its statement, so a statement stays while any+ # import carries it. The foreign key refuses the DELETE too, for an import+ # committed after this check.+ has_many :imports, dependent: :restrict_with_error+ has_many :pdf_imports, -> { where(type: "PdfImport").ordered }, class_name: "PdfImport"has_one_attached :original_file, dependent: :purge_laterenum :source, { manual_upload: "manual_upload" }, validate: true, default: "manual_upload"diff --git a/app/models/assistant/function/import_bank_statement.rb b/app/models/assistant/function/import_bank_statement.rbindex 7f58847684..3338334f5b 100644--- a/app/models/assistant/function/import_bank_statement.rb+++ b/app/models/assistant/function/import_bank_statement.rb@@ -65,6 +65,17 @@ class Assistant::Function::ImportBankStatement < Assistant::Function}end+ # The web lets only those who can manage a statement act on its import, and+ # the import made here carries the statement, so the same rule applies.+ statement = pdf_import.account_statement+ if statement && !statement.manageable_by?(user)+ return {+ success: false,+ error: "statement_not_manageable",+ message: "You can view this statement but not import from it"+ }+ end+unless pdf_import.document_type == "bank_statement"return {success: false,@@ -131,10 +142,11 @@ class Assistant::Function::ImportBankStatement < Assistant::Function# Create a CSV from extracted transactionscsv_content = generate_csv(result[:transactions])- # Create a TransactionImport+ # The transactions come from the statement, so the import keeps its privacy.import = family.imports.create!(type: "TransactionImport",account: account,+ account_statement: statement,raw_file_str: csv_content,date_col_label: "date",amount_col_label: "amount",diff --git a/app/models/family/financial_data_reset.rb b/app/models/family/financial_data_reset.rbindex 5de104ad61..324896dae2 100644--- a/app/models/family/financial_data_reset.rb+++ b/app/models/family/financial_data_reset.rb@@ -119,9 +119,10 @@ class Family::FinancialDataResetscope(:budget_categories).destroy_allscope(:taggings).destroy_allscope(:family_merchant_associations).delete_all- scope(:account_statements).destroy_allscope(:family_exports).destroy_all+ # Imports first: a statement cannot be destroyed while an import carries it.scope(:imports).destroy_all+ scope(:account_statements).destroy_allscope(:import_sessions).destroy_allscope(:entries).destroy_allscope(:holdings).destroy_alldiff --git a/app/models/import.rb b/app/models/import.rbindex 346513c85a..9ccb4d390d 100644--- a/app/models/import.rb+++ b/app/models/import.rb@@ -90,6 +90,13 @@ class Import < ApplicationRecordscope :ordered, -> { order(created_at: :desc) }scope :ordered_by_sequence, -> { order(:sequence, :created_at) }+ # The imports +user+ may view. A statement-backed import is as private as its+ # statement; any other import is visible to the whole family.+ scope :viewable_by, ->(user) {+ family_imports = where(family_id: user.family_id)+ family_imports.where(account_statement_id: nil)+ .or(family_imports.where(account_statement_id: AccountStatement.viewable_by(user).select(:id)))+ }enum :status, {pending: "pending",@@ -501,10 +508,9 @@ class Import < ApplicationRecordFAMILY_CONFIG_TYPES.include?(type)end- # A statement-backed import is as private as its statement; any other import- # is visible to the whole family.+ # The viewable_by scope's rule for a single import.def viewable_by?(user)- account_statement.blank? || account_statement.viewable_by?(user)+ user.present? && self.class.viewable_by(user).exists?(id)end# Guests may view family configuration but not change it, so they may onlydiff --git a/db/migrate/20261124120000_restrict_statement_deletion_while_imports_carry_it.rb b/db/migrate/20261124120000_restrict_statement_deletion_while_imports_carry_it.rbnew file mode 100644index 0000000000..83e1fc834f--- /dev/null+++ b/db/migrate/20261124120000_restrict_statement_deletion_while_imports_carry_it.rb@@ -0,0 +1,23 @@+# An import with a statement is visible only to those who can view the+# statement. Nullifying the reference when the statement goes made the import+# visible to the whole family, and the model's check for imports cannot stop an+# import committed between that check and the DELETE. The database refuses the+# DELETE instead, and its foreign key locks serialize it with import creation.+#+# NO ACTION rather than RESTRICT: both refuse the DELETE, but only NO ACTION+# raises the foreign key violation Rails reports as InvalidForeignKey.+#+# The new key is added NOT VALID, so the ACCESS EXCLUSIVE lock on imports lasts+# only for the swap. It is enforced on new rows and deletes at once; the next+# migration validates the existing rows under a lock that lets writes through.+class RestrictStatementDeletionWhileImportsCarryIt < ActiveRecord::Migration[8.1]+ def up+ remove_foreign_key :imports, :account_statements+ add_foreign_key :imports, :account_statements, validate: false+ end++ def down+ remove_foreign_key :imports, :account_statements+ add_foreign_key :imports, :account_statements, on_delete: :nullify+ end+enddiff --git a/db/migrate/20261124120100_validate_imports_account_statement_foreign_key.rb b/db/migrate/20261124120100_validate_imports_account_statement_foreign_key.rbnew file mode 100644index 0000000000..c56e294050--- /dev/null+++ b/db/migrate/20261124120100_validate_imports_account_statement_foreign_key.rb@@ -0,0 +1,15 @@+# Validates the key the previous migration added NOT VALID. VALIDATE CONSTRAINT+# takes SHARE UPDATE EXCLUSIVE on imports, so imports keep being written while+# the existing rows are checked.+class ValidateImportsAccountStatementForeignKey < ActiveRecord::Migration[8.1]+ def up+ validate_foreign_key :imports, :account_statements+ end++ # Postgres cannot mark a validated key NOT VALID again; re-adding it NOT VALID+ # restores the state the previous migration left.+ def down+ remove_foreign_key :imports, :account_statements+ add_foreign_key :imports, :account_statements, validate: false+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex e0c1eaba9f..088e60b8a1 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -10,7 +10,7 @@## It's strongly recommended that you check this file into your version control system.-ActiveRecord::Schema[8.1].define(version: 2026_11_23_220100) do+ActiveRecord::Schema[8.1].define(version: 2026_11_24_120100) do# These are extensions that must be enabled in order to support this databaseenable_extension "pg_catalog.plpgsql"enable_extension "pgcrypto"@@ -3270,7 +3270,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_23_220100) doadd_foreign_key "import_sessions", "families"add_foreign_key "import_source_mappings", "families"add_foreign_key "import_source_mappings", "import_sessions", column: ["import_session_id", "family_id"], primary_key: ["id", "family_id"], name: "fk_import_source_mappings_session_family", on_delete: :cascade- add_foreign_key "imports", "account_statements", on_delete: :nullify+ add_foreign_key "imports", "account_statements"add_foreign_key "imports", "families"add_foreign_key "imports", "import_sessions", column: ["import_session_id", "family_id"], primary_key: ["id", "family_id"], name: "fk_imports_session_family", on_delete: :cascadeadd_foreign_key "indexa_capital_accounts", "indexa_capital_items"diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yamlindex 7b66b997d7..2c65cc07ba 100644--- a/docs/api/openapi.yaml+++ b/docs/api/openapi.yaml@@ -8194,7 +8194,9 @@ paths:"/api/v1/imports":get:summary: List imports- description: List all imports for the user's family with pagination and filtering.+ description: List the family's imports the user can view, with pagination and+ filtering. An import made from an account statement is as private as that+ statement, so it is left out for users who cannot view the statement.tags:- Importssecurity:@@ -8533,6 +8535,7 @@ paths:summary: Retrieve an importdescription: Retrieve detailed information about a specific import, includingconfiguration, row statistics, and SureImport readback verification when available.+ An import made from an account statement the user cannot view returns 404.tags:- Importssecurity:@@ -8545,7 +8548,8 @@ paths:schema:"$ref": "#/components/schemas/ImportResponse"'404':- description: import not found+ description: import not found, or made from a statement the user cannot+ viewcontent:application/json:schema:@@ -8561,7 +8565,8 @@ paths:get:summary: List import row diagnosticsdescription: List sanitized import rows with validation errors and mapping resolution- state.+ state. An import made from an account statement the user cannot view returns+ 404.tags:- Importssecurity:@@ -8599,7 +8604,8 @@ paths:schema:"$ref": "#/components/schemas/ErrorResponse"'404':- description: import not found+ description: import not found, or made from a statement the user cannot+ viewcontent:application/json:schema:diff --git a/spec/requests/api/v1/imports_spec.rb b/spec/requests/api/v1/imports_spec.rbindex 1d3982b749..3139db452c 100644--- a/spec/requests/api/v1/imports_spec.rb+++ b/spec/requests/api/v1/imports_spec.rb@@ -86,7 +86,7 @@ RSpec.describe 'API V1 Imports', type: :request dopath '/api/v1/imports' doget 'List imports' do- description 'List all imports for the user\'s family with pagination and filtering.'+ description 'List the family\'s imports the user can view, with pagination and filtering. An import made from an account statement is as private as that statement, so it is left out for users who cannot view the statement.'tags 'Imports'security [ { apiKeyAuth: [] } ]produces 'application/json'@@ -320,7 +320,7 @@ RSpec.describe 'API V1 Imports', type: :request doparameter name: :id, in: :path, type: :string, required: true, description: 'Import ID'get 'Retrieve an import' do- description 'Retrieve detailed information about a specific import, including configuration, row statistics, and SureImport readback verification when available.'+ description 'Retrieve detailed information about a specific import, including configuration, row statistics, and SureImport readback verification when available. An import made from an account statement the user cannot view returns 404.'tags 'Imports'security [ { apiKeyAuth: [] } ]produces 'application/json'@@ -333,7 +333,7 @@ RSpec.describe 'API V1 Imports', type: :request dorun_test!end- response '404', 'import not found' do+ response '404', 'import not found, or made from a statement the user cannot view' doschema '$ref' => '#/components/schemas/ErrorResponse'let(:id) { SecureRandom.uuid }@@ -347,7 +347,7 @@ RSpec.describe 'API V1 Imports', type: :request doparameter name: :id, in: :path, type: :string, required: true, description: 'Import ID'get 'List import row diagnostics' do- description 'List sanitized import rows with validation errors and mapping resolution state.'+ description 'List sanitized import rows with validation errors and mapping resolution state. An import made from an account statement the user cannot view returns 404.'tags 'Imports'security [ { apiKeyAuth: [] } ]produces 'application/json'@@ -380,7 +380,7 @@ RSpec.describe 'API V1 Imports', type: :request dorun_test!end- response '404', 'import not found' do+ response '404', 'import not found, or made from a statement the user cannot view' doschema '$ref' => '#/components/schemas/ErrorResponse'let(:id) { SecureRandom.uuid }diff --git a/test/controllers/account_statements_controller_test.rb b/test/controllers/account_statements_controller_test.rbindex 3450b2b3e9..c96e0baf53 100644--- a/test/controllers/account_statements_controller_test.rb+++ b/test/controllers/account_statements_controller_test.rb@@ -501,6 +501,40 @@ class AccountStatementsControllerTest < ActionDispatch::IntegrationTestassert_equal I18n.t("account_statements.destroy.failure"), flash[:alert]end+ test "destroy keeps a statement that an import still carries" do+ statement = AccountStatement.create_from_upload!(+ family: @account.family,+ account: @account,+ file: uploaded_file(filename: "statement.csv", content_type: "text/csv", content: "date,amount\n2024-01-01,1\n")+ )+ import = TransactionImport.create!(family: @account.family, account: @account, account_statement: statement)++ assert_no_difference "AccountStatement.count" do+ delete account_statement_url(statement)+ end++ assert_redirected_to account_url(@account, tab: "statements")+ assert_equal I18n.t("account_statements.destroy.failure"), flash[:alert]+ assert_equal statement.id, import.reload.account_statement_id+ end++ test "destroy reports failure when the database refuses the delete" do+ statement = AccountStatement.create_from_upload!(+ family: @account.family,+ account: @account,+ file: uploaded_file(filename: "statement.csv", content_type: "text/csv", content: "date,amount\n2024-01-01,1\n")+ )+ # An import committed between the model's check and the DELETE.+ AccountStatement.any_instance.stubs(:destroy).raises(ActiveRecord::InvalidForeignKey)++ assert_no_difference "AccountStatement.count" do+ delete account_statement_url(statement)+ end++ assert_redirected_to account_url(@account, tab: "statements")+ assert_equal I18n.t("account_statements.destroy.failure"), flash[:alert]+ end+test "statement vault lists linked statements by period and the inbox by upload" dofebruary = statement_for(account: @account, month: Date.new(2024, 2, 1), name: "february")april = statement_for(account: @account, month: Date.new(2024, 4, 1), name: "april")diff --git a/test/controllers/api/v1/imports_controller_test.rb b/test/controllers/api/v1/imports_controller_test.rbindex 223eacb058..977917dfd4 100644--- a/test/controllers/api/v1/imports_controller_test.rb+++ b/test/controllers/api/v1/imports_controller_test.rb@@ -248,6 +248,70 @@ class Api::V1::ImportsControllerTest < ActionDispatch::IntegrationTestassert_equal "not_found", json_response["error"]end+ test "should not list an import of a statement the member cannot view" do+ member_key = read_only_key_for(users(:family_member))+ private_import = pdf_import_with_row(account: accounts(:investment))+ shared_import = pdf_import_with_row(account: accounts(:depository))++ get api_v1_imports_url, params: { per_page: 100 }, headers: api_headers(member_key)++ assert_response :success+ json_response = JSON.parse(response.body)+ listed_ids = json_response["data"].map { |import| import["id"] }+ assert_not_includes listed_ids, private_import.id+ assert_includes listed_ids, shared_import.id+ assert_includes listed_ids, @diagnostic_import.id+ assert_equal listed_ids.size, json_response["meta"]["total_count"]+ end++ test "should not show an import of a statement the member cannot view" do+ member_key = read_only_key_for(users(:family_member))+ private_import = pdf_import_with_row(account: accounts(:investment))++ get api_v1_import_url(private_import), headers: api_headers(member_key)++ assert_response :not_found+ assert_equal "not_found", JSON.parse(response.body)["error"]++ get api_v1_import_url(private_import), headers: api_headers(@read_only_api_key)+ assert_response :success+ end++ test "should not list rows of an import of a statement the member cannot view" do+ member_key = read_only_key_for(users(:family_member))+ private_import = pdf_import_with_row(account: accounts(:investment))+ shared_import = pdf_import_with_row(account: accounts(:depository))++ get rows_api_v1_import_url(private_import), headers: api_headers(member_key)++ assert_response :not_found+ assert_equal "not_found", JSON.parse(response.body)["error"]++ get rows_api_v1_import_url(shared_import), headers: api_headers(member_key)+ assert_response :success+ assert_equal [ "Statement line" ], JSON.parse(response.body)["data"].map { |row| row.dig("fields", "name") }++ get rows_api_v1_import_url(private_import), headers: api_headers(@read_only_api_key)+ assert_response :success+ assert_equal 1, JSON.parse(response.body)["data"].size+ end++ test "should hide an unlinked statement import from a guest" do+ guest = @family.users.create!(+ first_name: "Guest", last_name: "Viewer", email: "guest-#{SecureRandom.hex(4)}@example.com",+ password: "password", role: "guest", onboarded_at: Time.current+ )+ guest_key = read_only_key_for(guest)+ unlinked_import = pdf_import_with_row(account: nil)++ get api_v1_imports_url, params: { per_page: 100 }, headers: api_headers(guest_key)+ assert_response :success+ assert_not_includes JSON.parse(response.body)["data"].map { |import| import["id"] }, unlinked_import.id++ get rows_api_v1_import_url(unlinked_import), headers: api_headers(guest_key)+ assert_response :not_found+ end+test "should require authentication for import row diagnostics" doget rows_api_v1_import_url(@diagnostic_import)@@ -1500,4 +1564,29 @@ class Api::V1::ImportsControllerTest < ActionDispatch::IntegrationTestdef api_headers(api_key){ "X-Api-Key" => api_key.plain_key }end++ def read_only_key_for(user)+ ApiKey.create!(+ user: user,+ name: "Read-Only Key",+ scopes: [ "read" ],+ source: "web",+ display_key: "test_ro_#{SecureRandom.hex(8)}"+ ).tap { |key| Redis.new.del("api_rate_limit:#{key.id}") }+ end++ def pdf_import_with_row(account:)+ statement = AccountStatement.create_from_upload!(+ family: @family,+ account: account,+ file: uploaded_file(+ filename: "statement-#{SecureRandom.hex(4)}.pdf",+ content_type: "application/pdf",+ content: file_fixture("imports/sample_bank_statement.pdf").binread + SecureRandom.hex(8)+ )+ )+ PdfImport.create_from_statement!(statement: statement).tap do |import|+ import.rows.create!(source_row_number: 1, date: "01-15-2024", amount: "-42.00", currency: "USD", name: "Statement line")+ end+ endenddiff --git a/test/controllers/imports_controller_test.rb b/test/controllers/imports_controller_test.rbindex 021ac0f8e5..886a7f2af7 100644--- a/test/controllers/imports_controller_test.rb+++ b/test/controllers/imports_controller_test.rb@@ -446,6 +446,51 @@ class ImportsControllerTest < ActionDispatch::IntegrationTestassert_response :not_foundend+ test "import pages hide a statement backed pdf import for an inaccessible statement" do+ statement = AccountStatement.create_from_upload!(+ family: @user.family,+ account: accounts(:investment),+ file: uploaded_file(+ filename: "statement.pdf",+ content_type: "application/pdf",+ content: file_fixture("imports/sample_bank_statement.pdf").binread+ )+ )+ pdf_import = PdfImport.create_from_statement!(statement: statement)+ row = pdf_import.rows.create!(source_row_number: 1, date: "01-15-2024", amount: "-42.00", currency: "USD", name: "Statement line")++ sign_in users(:family_member)++ get imports_url+ assert_response :success+ assert_select "#" + dom_id(pdf_import), count: 0+ assert_select "#" + dom_id(imports(:transaction)), count: 1++ get new_import_url+ assert_response :success+ assert_select "a[href='#{import_path(pdf_import)}']", count: 0++ [+ import_row_path(pdf_import, row),+ import_clean_path(pdf_import),+ import_confirm_path(pdf_import),+ import_upload_path(pdf_import),+ import_configuration_path(pdf_import),+ import_qif_category_selection_path(pdf_import)+ ].each do |path|+ get path+ assert_response :not_found, path+ end++ patch import_row_path(pdf_import, row), params: { import_row: { name: "Changed" } }+ assert_response :not_found+ mapping = Import::CategoryMapping.create!(import: pdf_import, key: "Groceries")+ patch import_mapping_path(pdf_import, mapping), params: { import_mapping: { mappable_id: categories(:food_and_drink).id } }+ assert_response :not_found+ assert_equal "Statement line", row.reload.name+ assert_nil mapping.reload.mappable+ end+test "read only shared user cannot publish statement backed pdf import" doaccount = accounts(:credit_card)statement = AccountStatement.create_from_upload!(diff --git a/test/migrations/restrict_statement_deletion_while_imports_carry_it_migration_test.rb b/test/migrations/restrict_statement_deletion_while_imports_carry_it_migration_test.rbnew file mode 100644index 0000000000..daab3ab8a2--- /dev/null+++ b/test/migrations/restrict_statement_deletion_while_imports_carry_it_migration_test.rb@@ -0,0 +1,91 @@+# frozen_string_literal: true++require "test_helper"+require Rails.root.join("db/migrate/20261124120000_restrict_statement_deletion_while_imports_carry_it")+require Rails.root.join("db/migrate/20261124120100_validate_imports_account_statement_foreign_key")++class RestrictStatementDeletionWhileImportsCarryItMigrationTest < ActiveSupport::TestCase+ # Each test starts from the foreign key an installation has before both+ # migrations. DDL is transactional in Postgres, so the change is rolled back+ # with the rest of the test.+ setup do+ validation.down+ restriction.down+ @statement = AccountStatement.create_from_upload!(+ family: families(:dylan_family),+ account: accounts(:depository),+ file: uploaded_file(filename: "statement.csv", content_type: "text/csv", content: "date,amount\n2024-01-01,1\n")+ )+ @import = TransactionImport.create!(family: @statement.family, account: @statement.account, account_statement: @statement)+ end++ test "the key added not valid already refuses to delete a statement an import carries" do+ restriction.up++ assert_not foreign_key_validated?+ assert_statement_deletion_refused+ end++ test "the database refuses to delete a statement an import carries once the key is validated" do+ restriction.up+ validation.up++ assert foreign_key_validated?+ assert_statement_deletion_refused+ end++ test "rolling back the validation leaves the key not valid and still enforced" do+ restriction.up+ validation.up+ validation.down++ assert_not foreign_key_validated?+ assert_statement_deletion_refused+ end++ test "rolling back both nullifies the import's statement again" do+ restriction.up+ validation.up+ validation.down+ restriction.down++ assert foreign_key_validated?+ AccountStatement.where(id: @statement.id).delete_all++ assert_nil @import.reload.account_statement_id+ end++ test "a statement without imports can still be deleted" do+ restriction.up+ validation.up+ @import.destroy!++ assert_difference -> { AccountStatement.count }, -1 do+ @statement.destroy!+ end+ end++ private+ def restriction+ @restriction ||= RestrictStatementDeletionWhileImportsCarryIt.new.tap { |m| m.verbose = false }+ end++ def validation+ @validation ||= ValidateImportsAccountStatementForeignKey.new.tap { |m| m.verbose = false }+ end++ def foreign_key_validated?+ ActiveRecord::Base.connection.select_value(<<~SQL)+ SELECT convalidated FROM pg_constraint+ WHERE contype = 'f' AND conrelid = 'imports'::regclass AND confrelid = 'account_statements'::regclass+ SQL+ end++ # A savepoint, so the refused DELETE leaves the test's transaction usable.+ def assert_statement_deletion_refused+ assert_raises(ActiveRecord::InvalidForeignKey) do+ AccountStatement.transaction(requires_new: true) { AccountStatement.where(id: @statement.id).delete_all }+ end+ assert_equal @statement.id, @import.reload.account_statement_id+ end+enddiff --git a/test/models/account_statement_import_concurrency_test.rb b/test/models/account_statement_import_concurrency_test.rbnew file mode 100644index 0000000000..e2908eb1e7--- /dev/null+++ b/test/models/account_statement_import_concurrency_test.rb@@ -0,0 +1,122 @@+require "test_helper"+require "timeout"++# An import is as private as its statement, so deleting a statement must never+# leave an import without it. The model checks for imports before the DELETE,+# with no lock, so an import committed in between is caught only by the foreign+# key: its lock on the statement row makes the DELETE and the INSERT wait for+# each other, whichever comes first.+#+# Real threads on real connections, so this needs real commits.+class AccountStatementImportConcurrencyTest < ActiveSupport::TestCase+ self.use_transactional_tests = false++ setup do+ @family = families(:dylan_family)+ @account = accounts(:depository)+ @statement = AccountStatement.create_from_upload!(+ family: @family,+ account: @account,+ file: uploaded_file(filename: "statement-#{SecureRandom.hex(4)}.csv", content_type: "text/csv",+ content: "date,amount\n2024-01-01,#{SecureRandom.hex(4)}\n")+ )+ @threads = []+ end++ teardown do+ # Each test has already read its threads' outcomes; join re-raises them.+ @threads.each do |thread|+ thread.join(10)+ rescue StandardError+ nil+ ensure+ thread.kill if thread.alive?+ end+ Import.where(account_statement_id: @statement.id).destroy_all+ if AccountStatement.exists?(@statement.id)+ @statement.original_file.purge+ AccountStatement.where(id: @statement.id).delete_all+ end+ end++ test "a statement deleted while an import for it is being created stays, and so does the import's reference" do+ inserted = Queue.new+ release = Queue.new+ import_id = Queue.new+ creator = in_thread do+ Import.transaction do+ import_id << TransactionImport.create!(family: @family, account: @account, account_statement: @statement).id+ inserted << true+ release.pop+ end+ end+ Timeout.timeout(10) { inserted.pop }++ deleter_pid = Queue.new+ deleter = in_thread do |connection|+ deleter_pid << connection.select_value("SELECT pg_backend_pid()")+ AccountStatement.find(@statement.id).destroy+ end++ assert_waits_on_lock deleter, Timeout.timeout(10) { deleter_pid.pop }+ release << true+ assert creator.join(10)+ assert_raises(ActiveRecord::InvalidForeignKey) { deleter.value }++ assert AccountStatement.exists?(@statement.id)+ assert_equal @statement.id, Import.find(import_id.pop).account_statement_id+ end++ test "an import created while its statement is being deleted is refused" do+ deleted = Queue.new+ release = Queue.new+ deleter = in_thread do+ AccountStatement.transaction do+ AccountStatement.find(@statement.id).destroy!+ deleted << true+ release.pop+ end+ end+ Timeout.timeout(10) { deleted.pop }++ creator_pid = Queue.new+ creator = in_thread do |connection|+ creator_pid << connection.select_value("SELECT pg_backend_pid()")+ TransactionImport.create!(family: @family, account: @account, account_statement: @statement)+ end++ assert_waits_on_lock creator, Timeout.timeout(10) { creator_pid.pop }+ release << true+ assert deleter.join(10)+ assert_raises(ActiveRecord::InvalidForeignKey) { creator.value }++ assert_not AccountStatement.exists?(@statement.id)+ assert_not Import.exists?(account_statement_id: @statement.id)+ end++ private+ # Thread#value re-raises what the block raised, so each test asserts on+ # the outcome of its own connection.+ def in_thread(&block)+ thread = Thread.new do+ ActiveRecord::Base.connection_pool.with_connection(&block)+ end+ thread.report_on_exception = false+ @threads << thread+ thread+ end++ # The thread cannot finish while the other transaction is open, and+ # Postgres reports the wait as soon as it starts.+ def assert_waits_on_lock(thread, pid)+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 10+ loop do+ flunk "finished without waiting for the other transaction" if thread.join(0.01)+ wait_event_type = ActiveRecord::Base.connection.select_value(+ "SELECT wait_event_type FROM pg_stat_activity WHERE pid = #{Integer(pid)}"+ )+ break if wait_event_type == "Lock"+ flunk "never waited on the other transaction's lock" if Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline+ end+ end+enddiff --git a/test/models/account_statement_test.rb b/test/models/account_statement_test.rbindex 5ec0695c1a..295b4897ed 100644--- a/test/models/account_statement_test.rb+++ b/test/models/account_statement_test.rb@@ -1222,6 +1222,29 @@ class AccountStatementTest < ActiveSupport::TestCaseassert_equal [ march, start_only, end_only, unread ], @account.account_statements.by_period.to_aend+ test "viewable_by lists exactly the statements viewable_by? accepts" do+ guest = @family.users.create!(first_name: "Guest", last_name: "Viewer", email: "guest-#{SecureRandom.hex(4)}@example.com",+ password: "password", role: "guest", onboarded_at: Time.current)+ accounts(:credit_card).share_with!(guest)+ statements = [ accounts(:investment), accounts(:depository), accounts(:credit_card), nil ].each_with_index.map do |account, index|+ create_statement(account: account, month: Date.new(2024, index + 1, 1), content: "viewable-#{index}")+ end+ other_family = families(:empty)+ statements << AccountStatement.create_from_upload!(+ family: other_family,+ account: nil,+ file: uploaded_file(filename: "other.csv", content_type: "text/csv", content: "date,amount\n2024-01-01,1\nother\n")+ )++ [ users(:family_admin), users(:family_member), guest, users(:empty) ].each do |user|+ expected = statements.select { |statement| statement.viewable_by?(user) }.map(&:id).sort+ actual = AccountStatement.viewable_by(user).where(id: statements.map(&:id)).pluck(:id).sort++ assert_equal expected, actual, "for #{user.role} #{user.email}"+ end+ assert_equal [ statements[2].id ], AccountStatement.viewable_by(guest).where(id: statements.map(&:id)).pluck(:id)+ end+privatedef upload_card_statement(account:, text: CARD_STATEMENT_TEXT)diff --git a/test/models/account_test.rb b/test/models/account_test.rbindex 8a16b3a1e4..9ceff4ceb0 100644--- a/test/models/account_test.rb+++ b/test/models/account_test.rb@@ -797,6 +797,20 @@ class AccountTest < ActiveSupport::TestCaseassert_nil statement.match_confidenceend+ test "destroying an account keeps a statement an import carries, and the import keeps it" do+ statement = AccountStatement.create_from_upload!(+ family: @family,+ account: @account,+ file: uploaded_file(filename: "statement.csv", content_type: "text/csv", content: "date,amount\n2024-01-01,1\n")+ )+ import = TransactionImport.create!(family: @family, account: @account, account_statement: statement)++ @account.destroy!++ assert_nil statement.reload.account_id+ assert_equal statement.id, import.reload.account_statement_id+ end+test "rolled back account destroy keeps linked statements unchanged" dostatement = AccountStatement.create_from_upload!(family: @family,diff --git a/test/models/assistant/function/import_bank_statement_test.rb b/test/models/assistant/function/import_bank_statement_test.rbindex 5faf68d25d..de709a937e 100644--- a/test/models/assistant/function/import_bank_statement_test.rb+++ b/test/models/assistant/function/import_bank_statement_test.rb@@ -114,18 +114,8 @@ class Assistant::Function::ImportBankStatementTest < ActiveSupport::TestCase# the statement is neither sent to the model nor summarised back.test "an import of a statement the user cannot view is not found" domember = users(:family_member)- statement = AccountStatement.create_from_upload!(- family: member.family,- account: accounts(:investment),- file: uploaded_file(- filename: "statement.pdf",- content_type: "application/pdf",- content: file_fixture("imports/sample_bank_statement.pdf").binread- )- )- pdf_import = PdfImport.create_from_statement!(statement: statement)- pdf_import.update!(document_type: "bank_statement")- assert_not statement.viewable_by?(member)+ pdf_import = statement_import_on(accounts(:investment))+ assert_not pdf_import.account_statement.viewable_by?(member)use_ai_routesProvider::Registry.expects(:preferred_llm_provider).never@@ -135,4 +125,57 @@ class Assistant::Function::ImportBankStatementTest < ActiveSupport::TestCaseassert_equal "PDF import not found", result[:error]end++ # The web lets only those who can manage a statement act on its import, so+ # the tool does not turn a statement someone can only read into an import.+ test "an import of a statement the user can only read is refused before any extraction" do+ member = users(:family_member)+ pdf_import = statement_import_on(accounts(:credit_card))+ assert pdf_import.account_statement.viewable_by?(member)+ assert_not pdf_import.account_statement.manageable_by?(member)+ use_ai_routes+ Provider::Registry.expects(:preferred_llm_provider).never++ assert_no_difference -> { Import.count } do+ result = Assistant::Function::ImportBankStatement.new(member).call(+ "pdf_import_id" => pdf_import.id, "account_id" => accounts(:depository).id+ )++ assert_equal "statement_not_manageable", result[:error]+ end+ end++ # The transactions come from the statement, so the import made from them is+ # as private as the statement.+ test "the import made from a statement keeps that statement's privacy" do+ pdf_import = statement_import_on(accounts(:investment))+ use_ai_routes+ provider = mock("llm_provider")+ Provider::Registry.stubs(:preferred_llm_provider).returns(provider)+ provider.stubs(:extract_bank_statement).returns(+ OpenStruct.new(success?: true, data: { transactions: [ { date: "2026-10-01", amount: "-5.0", name: "Coffee" } ] })+ )++ result = @fn.call("pdf_import_id" => pdf_import.id, "account_id" => accounts(:depository).id)++ assert result[:success], result.inspect+ import = Import.find(result[:import_id])+ assert_equal pdf_import.account_statement, import.account_statement+ assert import.viewable_by?(@user)+ assert_not import.viewable_by?(users(:family_member)), "another member can read a private statement's transactions"+ end++ private+ def statement_import_on(account)+ statement = AccountStatement.create_from_upload!(+ family: account.family,+ account: account,+ file: uploaded_file(+ filename: "statement.pdf",+ content_type: "application/pdf",+ content: file_fixture("imports/sample_bank_statement.pdf").binread+ )+ )+ PdfImport.create_from_statement!(statement: statement).tap { |import| import.update!(document_type: "bank_statement") }+ endenddiff --git a/test/models/family/financial_data_reset_test.rb b/test/models/family/financial_data_reset_test.rbindex c59f9e0cbe..64728fb63b 100644--- a/test/models/family/financial_data_reset_test.rb+++ b/test/models/family/financial_data_reset_test.rb@@ -267,7 +267,9 @@ class Family::FinancialDataResetTest < ActiveSupport::TestCasebudgeted_spending: 50,currency: family.currency)- import = family.imports.create!(type: "TransactionImport", status: "pending")+ account_statement = create_account_statement!(family: family, account: account, label: label)+ # The import carries the statement, as the assistant's statement import does.+ import = family.imports.create!(type: "TransactionImport", status: "pending", account_statement: account_statement)import_row = import.rows.create!(source_row_number: 1,date: Date.current.strftime(import.date_format),@@ -278,7 +280,6 @@ class Family::FinancialDataResetTest < ActiveSupport::TestCaseimport_mapping = Import::AccountMapping.create!(import: import, key: "#{label} Checking", mappable: account)family_export = family.family_exports.create!(status: "completed")family_export.export_file.attach(io: StringIO.new("zip"), filename: "#{safe_label}.zip", content_type: "application/zip")- account_statement = create_account_statement!(family: family, account: account, label: label)plaid_item = family.plaid_items.create!(name: "#{label} Plaid Item",plaid_id: "plaid_item_#{safe_label}_#{family.id.delete("-")}",diff --git a/test/models/family_test.rb b/test/models/family_test.rbindex 58dfc8d5a8..56902daaa7 100644--- a/test/models/family_test.rb+++ b/test/models/family_test.rb@@ -8,6 +8,24 @@ class FamilyTest < ActiveSupport::TestCase@syncable = families(:dylan_family)end+ # The foreign key refuses to delete a statement an import carries, so a+ # family's imports must go before its statements.+ test "destroys a family whose import carries a statement" do+ family = Family.create!(name: "Statements", currency: "USD")+ statement = AccountStatement.create_from_upload!(+ family: family,+ account: nil,+ file: uploaded_file(filename: "statement.csv", content_type: "text/csv", content: "date,amount\n2024-01-01,1\n")+ )+ import = TransactionImport.create!(family: family, account_statement: statement)++ family.destroy!++ assert_not Family.exists?(family.id)+ assert_not AccountStatement.exists?(statement.id)+ assert_not Import.exists?(import.id)+ end+test "missing_data_provider? is false under the keyless securities fallback" dofamily = Family.create!(name: "Fallback", currency: "USD")account = family.accounts.create!(name: "Brokerage", currency: "USD", balance: 0, accountable: Investment.new)diff --git a/test/models/import_test.rb b/test/models/import_test.rbindex 2473ccd0ce..7216e67ac5 100644--- a/test/models/import_test.rb+++ b/test/models/import_test.rb@@ -270,15 +270,53 @@ class ImportTest < ActiveSupport::TestCasemember = users(:family_member)assert TransactionImport.create!(family: member.family).viewable_by?(member)- statement = AccountStatement.create_from_upload!(- family: member.family,- account: accounts(:investment),- file: uploaded_file(filename: "statement.pdf", content_type: "application/pdf",- content: file_fixture("imports/sample_bank_statement.pdf").binread)- )- pdf_import = PdfImport.create_from_statement!(statement: statement)+ pdf_import = PdfImport.create_from_statement!(statement: statement_on(accounts(:investment)))assert pdf_import.viewable_by?(users(:family_admin))assert_not pdf_import.viewable_by?(member)+ assert_not pdf_import.viewable_by?(nil)end++ test "viewable_by hides an import whose statement the user cannot view" do+ family = families(:dylan_family)+ guest = family.users.create!(first_name: "Guest", last_name: "Viewer", email: "guest-#{SecureRandom.hex(4)}@example.com",+ password: "password", role: "guest", onboarded_at: Time.current)+ plain = TransactionImport.create!(family: family)+ plain_on_private_account = TransactionImport.create!(family: family, account: accounts(:investment))+ on_private_account = PdfImport.create_from_statement!(statement: statement_on(accounts(:investment)))+ on_shared_account = PdfImport.create_from_statement!(statement: statement_on(accounts(:depository)))+ unlinked = PdfImport.create_from_statement!(statement: statement_on(nil))+ other_family = TransactionImport.create!(family: families(:empty))+ all = [ plain, plain_on_private_account, on_private_account, on_shared_account, unlinked, other_family ]++ visible = ->(user) { Import.viewable_by(user).where(id: all.map(&:id)).pluck(:id).sort }++ assert_equal [ plain, plain_on_private_account, on_private_account, on_shared_account, unlinked ].map(&:id).sort, visible.(users(:family_admin))+ assert_equal [ plain, plain_on_private_account, on_shared_account, unlinked ].map(&:id).sort, visible.(users(:family_member))+ assert_equal [ plain, plain_on_private_account ].map(&:id).sort, visible.(guest)+ assert_equal [ other_family.id ], visible.(users(:empty))+ end++ test "a statement cannot be deleted while an import carries it, so the import stays private" do+ member = users(:family_member)+ statement = statement_on(accounts(:investment))+ pdf_import = PdfImport.create_from_statement!(statement: statement)+ transaction_import = TransactionImport.create!(family: statement.family, account: accounts(:investment), account_statement: statement)+ pdf_import.destroy!++ assert_not statement.reload.destroy+ assert AccountStatement.exists?(statement.id)+ assert_equal statement.id, transaction_import.reload.account_statement_id+ assert_not Import.viewable_by(member).exists?(transaction_import.id)+ end++ private+ def statement_on(account)+ AccountStatement.create_from_upload!(+ family: families(:dylan_family),+ account: account,+ file: uploaded_file(filename: "statement-#{SecureRandom.hex(4)}.pdf", content_type: "application/pdf",+ content: file_fixture("imports/sample_bank_statement.pdf").binread + SecureRandom.hex(8))+ )+ endend