The personal finance app for everyone (by everyone)
Ruby
fix: keep CSV formula escaping injective and consistent across export files (#4853)
Chris Werner Rau402ae5b62788
diff --git a/app/controllers/reports_controller.rb b/app/controllers/reports_controller.rbindex 32921319d3..97e63efd2c 100644--- a/app/controllers/reports_controller.rb+++ b/app/controllers/reports_controller.rb@@ -1254,7 +1254,7 @@ class ReportsController < ApplicationController# at Google Sheets, so the cells that carry them are escaped against# formula injection (CWE-1236). Only that column: the amount cells are# formatted money such as "-$42.00", which the escape would turn to text.- CSV.generate do |csv|+ CSV.generate(force_quotes: true) do |csv|# Build header row: Category + Month columns + Totalmonth_headers = @export_data[:months].map { |m| m.strftime("%b %Y") }header_row = [ "Category" ] + month_headers + [ "Total" ]diff --git a/app/models/family/data_exporter.rb b/app/models/family/data_exporter.rbindex b0bd29d610..b006e6496c 100644--- a/app/models/family/data_exporter.rb+++ b/app/models/family/data_exporter.rb@@ -78,7 +78,9 @@ class Family::DataExporterprivate_constant :SanitizedCsvdef generate_sanitized_csv- CSV.generate do |csv|+ # Every cell is quoted so a locale separator inside a value can never split+ # it into a second, unescaped cell.+ CSV.generate(force_quotes: true) do |csv|yield SanitizedCsv.new(csv)endend@@ -918,9 +920,9 @@ class Family::DataExportermerchant = split_operand_record(:merchants, split["merchant_id"])tags = Array(split["tag_ids"]).filter_map { |id| split_operand_record(:tags, id) }- row["category"] = category.name if category- row["merchant"] = merchant.name if merchant- row["tags"] = tags.map(&:name) if tags.any?+ row["category"] = operand_name(category.name) if category+ row["merchant"] = operand_name(merchant.name) if merchant+ row["tags"] = tags.map { |tag| operand_name(tag.name) } if tags.any?rowend@@ -938,7 +940,7 @@ class Family::DataExporterdef resolve_multi_tag_operand(value)ids = value.to_s.split(",")records = ids.map { |id| resolve_rule_operand_record(:tags, id, fallback_to_name: true) }- names = records.each_with_index.map { |record, i| record&.name || ids[i] }+ names = records.each_with_index.map { |record, i| record ? operand_name(record.name) : ids[i] }refs = records.compact.map { |record| rule_value_ref("Tag", record) }{@@ -957,7 +959,7 @@ class Family::DataExporterrecord = relation && resolve_rule_operand_record(relation, value, fallback_to_name: fallback_to_name){- value: record&.name || value,+ value: record ? operand_name(record.name) : value,value_ref: record ? rule_value_ref(type, record) : nil}end@@ -999,10 +1001,25 @@ class Family::DataExporterenddef serialize_conditions_for_csv(conditions)- conditions.where(parent_id: nil).map { |c| serialize_condition(c) }.to_json+ with_csv_operand_names { conditions.where(parent_id: nil).map { |c| serialize_condition(c) }.to_json }enddef serialize_actions_for_csv(actions)- actions.map { |a| serialize_action(a) }.to_json+ with_csv_operand_names { actions.map { |a| serialize_action(a) }.to_json }+ end++ # Category, merchant and tag names inside rule operands must read exactly like+ # the same names in categories.csv, merchants.csv and transactions.csv (which+ # are escaped), or an import creates a second record for the same name. Only+ # the CSV path does this; all.ndjson and value_ref keep the raw names.+ def with_csv_operand_names+ @csv_operand_names = true+ yield+ ensure+ @csv_operand_names = false+ end++ def operand_name(name)+ @csv_operand_names ? CsvSanitizer.sanitize(name) : nameendenddiff --git a/lib/csv_sanitizer.rb b/lib/csv_sanitizer.rbindex 545e30ddba..82e11e2d80 100644--- a/lib/csv_sanitizer.rb+++ b/lib/csv_sanitizer.rb@@ -15,9 +15,11 @@## Imports never undo the escape: a leading quote in an imported CSV may be the# user's own data ("'+44 Taxis"), and there is no telling it apart from one-# this module added.+# this module added. To keep the escape injective anyway, a value that already+# starts with apostrophes before a trigger gets one more, so `=x` and `'=x`+# export as `'=x` and `''=x` and never collapse into one name on re-import.module CsvSanitizer- FORMULA_TRIGGER = /\A[=+\-@\t\r\n]/+ FORMULA_TRIGGER = /\A'*[=+\-@\t\r\n]/PLAIN_NUMBER = /\A[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?\z/module_functiondiff --git a/test/controllers/reports_controller_test.rb b/test/controllers/reports_controller_test.rbindex 3074bbf2d5..1d0d6f2e8d 100644--- a/test/controllers/reports_controller_test.rb+++ b/test/controllers/reports_controller_test.rb@@ -1624,6 +1624,23 @@ class ReportsControllerTest < ActionDispatch::IntegrationTestendend+ test "transactions export quotes every cell so a separator inside a category name cannot split it" do+ category = @family.categories.create!(name: "Food;=1+1", color: "#000000")+ @family.accounts.first.entries.create!(+ name: "Payee", date: Date.current, amount: 25, currency: "USD",+ entryable: Transaction.new(category: category, kind: "standard")+ )++ get export_transactions_reports_path(+ format: :csv, period_type: :ytd,+ start_date: Date.current.beginning_of_year, end_date: Date.current+ )++ assert_response :ok+ assert_includes @response.body, %q("Food;=1+1")+ assert_includes CSV.parse(@response.body).flatten, "Food;=1+1"+ end+# The card was gated on `investment_accounts`, which is visible accounts# only (draft and active), while its realised-gains half is measured over# every account included in reports, disabled ones too. A family whose onlydiff --git a/test/lib/csv_sanitizer_test.rb b/test/lib/csv_sanitizer_test.rbindex 15a758b6c7..ee09bc9db7 100644--- a/test/lib/csv_sanitizer_test.rb+++ b/test/lib/csv_sanitizer_test.rb@@ -47,4 +47,19 @@ class CsvSanitizerTest < ActiveSupport::TestCasetest "sanitizes every cell of a row" doassert_equal [ "'=a", "b", nil, 3 ], CsvSanitizer.sanitize_row([ "=a", "b", nil, 3 ])end++ test "keeps the escape injective for values that already start with apostrophes" do+ {+ "=x" => "'=x",+ "'=x" => "''=x",+ "''-x" => "'''-x",+ "'plain" => "'plain",+ "'-42.5" => "''-42.5"+ }.each do |input, expected|+ assert_equal expected, CsvSanitizer.sanitize(input), "failed for #{input.inspect}"+ end++ inputs = [ "=x", "'=x", "''=x", "x", "'x" ]+ assert_equal inputs.size, inputs.map { |v| CsvSanitizer.sanitize(v) }.uniq.size+ endenddiff --git a/test/models/family/data_exporter_test.rb b/test/models/family/data_exporter_test.rbindex de7e5f59ed..da9f457c37 100644--- a/test/models/family/data_exporter_test.rb+++ b/test/models/family/data_exporter_test.rb@@ -192,15 +192,15 @@ class Family::DataExporterTest < ActiveSupport::TestCase# Check categories.csvcategories_csv = zip.read("categories.csv")- assert categories_csv.include?("name,color,parent_category,lucide_icon")+ assert categories_csv.include?(%q("name","color","parent_category","lucide_icon"))# Check merchants.csvmerchants_csv = zip.read("merchants.csv")- assert merchants_csv.include?("name,color,website_url")+ assert merchants_csv.include?(%q("name","color","website_url"))# Check rules.csvrules_csv = zip.read("rules.csv")- assert rules_csv.include?("name,resource_type,active,effective_date,conditions,actions,group")+ assert rules_csv.include?(%q("name","resource_type","active","effective_date","conditions","actions","group"))endend@@ -1556,6 +1556,100 @@ class Family::DataExporterTest < ActiveSupport::TestCaseendend+ test "quotes every field so a locale separator inside text cannot start an unguarded cell" do+ @account.entries.create!(+ name: "Rent;=1+1",+ notes: "a\t=1+1|@SUM(1)",+ amount: 5,+ currency: "USD",+ date: Date.parse("2024-05-16"),+ entryable: Transaction.new+ )++ Zip::File.open_buffer(@exporter.generate_export) do |zip|+ csv = zip.read("transactions.csv")+ assert_includes csv, %q("Rent;=1+1")+ assert_includes csv, %Q("a\t=1+1|@SUM(1)")+ assert csv.lines.first.start_with?(%q("date","account_name")), "header cells are quoted too"+ assert_equal "Rent;=1+1", CSV.parse(csv, headers: true).find { |row| row["name"].start_with?("Rent") }["name"]+ end+ end++ test "rule import keeps names that differ only by a leading apostrophe separate" do+ exported = nil+ Zip::File.open_buffer(@exporter.generate_export) { |zip| exported = CSV.parse(zip.read("rules.csv"), headers: true) }+ template = exported.find { |row| row["name"] == "Test Rule" }+ csv = CSV.generate do |out|+ out << exported.headers+ [ "=Rule", "'=Rule" ].each do |name|+ out << exported.headers.map { |header| header == "name" ? name : template[header] }+ end+ end++ import = @other_family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")+ import.generate_rows_from_csv+ assert_equal [ "'=Rule", "=Rule" ], import.rows.reload.map(&:name).sort+ end++ test "rules named with and without a leading apostrophe survive export and a committed import" do+ category = @family.categories.create!(name: "Rule Target", color: "#FF0000")+ other_category = @family.categories.create!(name: "Rule Other", color: "#00FF00")+ [ [ "=Rule", "first", category ], [ "'=Rule", "second", other_category ] ].each do |name, value, target|+ rule = @family.rules.build(name: name, resource_type: "transaction", active: true)+ rule.conditions.build(condition_type: "transaction_name", operator: "like", value: value)+ rule.actions.build(action_type: "set_transaction_category", value: target.id)+ rule.save!+ end++ csv = nil+ Zip::File.open_buffer(@exporter.generate_export) { |zip| csv = zip.read("rules.csv") }+ target_category = @other_family.categories.create!(name: "Rule Target", color: "#FF0000")+ @other_family.categories.create!(name: "Rule Other", color: "#00FF00")+ import = @other_family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")+ import.generate_rows_from_csv+ import.send(:import!)++ rules = @other_family.rules.where(name: [ "'=Rule", "''=Rule" ]).index_by(&:name)+ assert_equal [ "''=Rule", "'=Rule" ], rules.keys.sort+ assert_equal [ "first" ], rules["'=Rule"].conditions.map(&:value)+ assert_equal [ "second" ], rules["''=Rule"].conditions.map(&:value)+ assert_equal target_category.id, rules["'=Rule"].actions.first.value+ end++ test "rule operands spell escaped category names exactly as the other CSVs do" do+ budget = @family.categories.create!(name: "=Budget", color: "#FF0000")+ rule = @family.rules.build(name: "Budget Rule", resource_type: "transaction", active: true)+ rule.conditions.build(condition_type: "transaction_category", operator: "=", value: budget.id)+ rule.actions.build(action_type: "set_transaction_category", value: budget.id)+ rule.save!+ @account.entries.create!(+ name: "Budget purchase", amount: 9, currency: "USD", date: Date.parse("2024-05-16"),+ entryable: Transaction.new(category: budget)+ )++ files = {}+ ndjson = nil+ Zip::File.open_buffer(@exporter.generate_export) do |zip|+ %w[categories transactions rules].each { |name| files[name] = zip.read("#{name}.csv") }+ ndjson = zip.read("all.ndjson")+ end++ rule_row = CSV.parse(files["rules"], headers: true).find { |row| row["name"] == "Budget Rule" }+ assert_equal "'=Budget", JSON.parse(rule_row["conditions"]).first["value"]+ assert_equal "'=Budget", JSON.parse(rule_row["actions"]).first["value"]+ assert_includes ndjson, '"=Budget"', "all.ndjson keeps the raw name"++ [ [ "CategoryImport", "categories" ], [ "RuleImport", "rules" ] ].each do |type, file|+ import = @other_family.imports.create!(type: type, raw_file_str: files[file], col_sep: ",")+ import.generate_rows_from_csv+ import.send(:import!)+ end++ assert_equal 1, @other_family.categories.where(name: "'=Budget").count+ imported = @other_family.rules.find_by!(name: "Budget Rule")+ assert_equal "'=Budget", @other_family.categories.find(imported.actions.first.value).name+ end+# CSV formula injection (CWE-1236) -------------------------------------------## These assert on the emitted CSV rather than on the helper. Sanitizing field