Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

security: unsafe chat markdown, constantize on params, LIKE wildcards, CSV formula injection (#1943)

David Gil3c8106ff3225
diff --git a/app/controllers/api/v1/transactions_controller.rb b/app/controllers/api/v1/transactions_controller.rb
index 46c9a32cd1..5ce2a5fba7 100644
--- a/app/controllers/api/v1/transactions_controller.rb
+++ b/app/controllers/api/v1/transactions_controller.rb
@@ -324,7 +324,9 @@ class Api::V1::TransactionsController < Api::V1::BaseController
end
def apply_search(query)
- search_term = "%#{params[:search]}%"
+ # Escape the caller's term so "%" and "_" match literally instead of
+ # acting as ILIKE wildcards, where a bare "%" returns everything.
+ search_term = "%#{ActiveRecord::Base.sanitize_sql_like(params[:search].to_s)}%"
query
.left_joins(:merchant)
diff --git a/app/controllers/import/mappings_controller.rb b/app/controllers/import/mappings_controller.rb
index f7347e40cc..32fa1b39bb 100644
--- a/app/controllers/import/mappings_controller.rb
+++ b/app/controllers/import/mappings_controller.rb
@@ -5,9 +5,9 @@ class Import::MappingsController < ApplicationController
before_action :require_import_editable!
def update
- mapping = @import.mappings.find(params[:id])
+ @mapping = @import.mappings.find(params[:id])
- mapping.update! \
+ @mapping.update! \
create_when_empty: create_when_empty,
mappable: mappable,
value: mapping_params[:value]
@@ -17,30 +17,25 @@ class Import::MappingsController < ApplicationController
private
def mapping_params
- params.require(:import_mapping).permit(:type, :key, :mappable_id, :mappable_type, :value)
+ params.require(:import_mapping).permit(:key, :mappable_id, :value)
end
def set_import
@import = Current.family.imports.find(params[:import_id])
end
+ # The mapping row already declares what it maps to, so neither the target
+ # class nor the mapping class comes from request params any more. Both used
+ # to reach `constantize`, which resolves any constant in the application
+ # and then had class methods and constants looked up on it (CWE-470).
def mappable
- return nil unless mappable_class.present?
+ target_class = @mapping.mappable_class
+ return nil unless target_class
- @mappable ||= mappable_class.find_by(id: mapping_params[:mappable_id], family: Current.family)
+ @mappable ||= target_class.find_by(id: mapping_params[:mappable_id], family: Current.family)
end
def create_when_empty
- return false unless mapping_class.present?
-
- mapping_params[:mappable_id] == mapping_class::CREATE_NEW_KEY
- end
-
- def mappable_class
- mapping_params[:mappable_type]&.constantize
- end
-
- def mapping_class
- mapping_params[:type]&.constantize
+ mapping_params[:mappable_id] == Import::Mapping::CREATE_NEW_KEY
end
end
diff --git a/app/controllers/reports_controller.rb b/app/controllers/reports_controller.rb
index 6972ceb811..de6a5a4f8f 100644
--- a/app/controllers/reports_controller.rb
+++ b/app/controllers/reports_controller.rb
@@ -981,6 +981,10 @@ class ReportsController < ApplicationController
def generate_transactions_csv
require "csv"
+ # Category names are user-supplied and this is the export the app points
+ # 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|
# Build header row: Category + Month columns + Total
month_headers = @export_data[:months].map { |m| m.strftime("%b %Y") }
@@ -992,7 +996,7 @@ class ReportsController < ApplicationController
csv << [ "INCOME" ] + Array.new(month_headers.length + 1, "")
@export_data[:income].each do |category_data|
- row = [ category_data[:category] ]
+ row = [ CsvSanitizer.sanitize(category_data[:category]) ]
# Add amounts for each month
@export_data[:months].each do |month|
@@ -1024,7 +1028,7 @@ class ReportsController < ApplicationController
csv << [ "EXPENSES" ] + Array.new(month_headers.length + 1, "")
@export_data[:expenses].each do |category_data|
- row = [ category_data[:category] ]
+ row = [ CsvSanitizer.sanitize(category_data[:category]) ]
# Add amounts for each month
@export_data[:months].each do |month|
diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb
index 356ddc32b8..2ab793c84c 100644
--- a/app/helpers/application_helper.rb
+++ b/app/helpers/application_helper.rb
@@ -253,8 +253,14 @@ module ApplicationHelper
def markdown(text)
return "" if text.blank?
+ # filter_html drops raw HTML present in the input. It is not redundant with
+ # the sanitize below: `div`, `span`, `class` and `style` have to stay on
+ # that allow-list for footnotes, code blocks and table alignment, so
+ # without this a chat message could ship `<div class="fixed inset-0">` and
+ # cover the app.
renderer = Redcarpet::Render::HTML.new(
hard_wrap: true,
+ filter_html: true,
link_attributes: { target: "_blank", rel: "noopener noreferrer" }
)
@@ -271,7 +277,16 @@ module ApplicationHelper
footnotes: true
)
- markdown.render(text).html_safe
+ # The second layer, for the markup the renderer itself produces: a markdown
+ # link carries whatever scheme the author wrote, so `[x](javascript:...)`
+ # survives filter_html and only the allow-list drops it (CWE-79). Every tag
+ # the extensions above generate has to be on it: `u` (underline), `q`
+ # (quote), `mark`, `del`, `sup`, and `style` for table column alignment.
+ sanitize(
+ markdown.render(text),
+ tags: %w[p br strong em u q a img ul ol li h1 h2 h3 h4 h5 h6 pre code blockquote table thead tbody tr th td span div sup sub del mark ins hr dl dt dd],
+ attributes: %w[href target rel class id src alt title style]
+ )
end
# Generate the callback URL for Enable Banking OAuth (used in views and controller).
diff --git a/app/models/account_import.rb b/app/models/account_import.rb
index 53ee51f1f4..4da872643d 100644
--- a/app/models/account_import.rb
+++ b/app/models/account_import.rb
@@ -5,7 +5,10 @@ class AccountImport < Import
transaction do
rows.each do |row|
mapping = mappings.account_types.find_by(key: row.entity_type)
- accountable_class = mapping.value.constantize
+ # The mapping value is user-supplied, so resolve it through the
+ # Accountable allow-list rather than constantize (CWE-470).
+ accountable_class = Accountable.from_type(mapping&.value)
+ raise ArgumentError, "Unsupported account type: #{mapping&.value.inspect}" unless accountable_class
account = family.accounts.build(
name: row.name,
diff --git a/app/models/family/data_exporter.rb b/app/models/family/data_exporter.rb
index 044ceed642..8b3837c145 100644
--- a/app/models/family/data_exporter.rb
+++ b/app/models/family/data_exporter.rb
@@ -61,8 +61,30 @@ class Family::DataExporter
TEXT
end
- def generate_accounts_csv
+ # Wraps a CSV writer so every row emitted is escaped against formula
+ # injection. Wrapping the writer rather than each call site means a column
+ # added later cannot go out unescaped by accident, which is exactly how the
+ # ticker and subtype columns were missed before.
+ class SanitizedCsv
+ def initialize(csv)
+ @csv = csv
+ end
+
+ def <<(row)
+ @csv << CsvSanitizer.sanitize_row(row)
+ end
+ end
+
+ private_constant :SanitizedCsv
+
+ def generate_sanitized_csv
CSV.generate do |csv|
+ yield SanitizedCsv.new(csv)
+ end
+ end
+
+ def generate_accounts_csv
+ generate_sanitized_csv do |csv|
csv << [ "id", "name", "type", "subtype", "balance", "currency", "created_at" ]
# Only export accounts belonging to this family
@@ -81,7 +103,7 @@ class Family::DataExporter
end
def generate_transactions_csv
- CSV.generate do |csv|
+ generate_sanitized_csv do |csv|
csv << TRANSACTIONS_CSV_HEADERS
# Only export transactions from accounts belonging to this family
@@ -108,7 +130,7 @@ class Family::DataExporter
end
def generate_trades_csv
- CSV.generate do |csv|
+ generate_sanitized_csv do |csv|
csv << [ "date", "account_name", "ticker", "quantity", "price", "amount", "currency" ]
# Only export trades from accounts belonging to this family
@@ -129,7 +151,7 @@ class Family::DataExporter
end
def generate_categories_csv
- CSV.generate do |csv|
+ generate_sanitized_csv do |csv|
csv << [ "name", "color", "parent_category", "lucide_icon" ]
# Only export categories belonging to this family
@@ -145,7 +167,7 @@ class Family::DataExporter
end
def generate_merchants_csv
- CSV.generate do |csv|
+ generate_sanitized_csv do |csv|
# Headers match MerchantImport's expected columns so the export round-trips
csv << [ "name", "color", "website_url" ]
@@ -161,7 +183,7 @@ class Family::DataExporter
end
def generate_rules_csv
- CSV.generate do |csv|
+ generate_sanitized_csv do |csv|
csv << [ "name", "resource_type", "active", "effective_date", "conditions", "actions", "group" ]
# Only export rules belonging to this family, in run order so an
diff --git a/app/views/import/mappings/_form.html.erb b/app/views/import/mappings/_form.html.erb
index 6bef825fc4..7426fd1b3f 100644
--- a/app/views/import/mappings/_form.html.erb
+++ b/app/views/import/mappings/_form.html.erb
@@ -9,7 +9,6 @@
<span><%= mapping.key.blank? ? "(unassigned)" : mapping.key %></span>
<% if mapping.mappable_class.present? %>
- <%= form.hidden_field :mappable_type, value: mapping.mappable_class, id: dom_id(mapping, :mappable_type) %>
<%= form.select :mappable_id,
mapping.selectable_values,
{ container_class: mapping.invalid? ? "border-red-500" : nil, include_blank: mapping.requires_selection? ? "Select an option" : "Leave unassigned", selected: mapping.create_when_empty? ? mapping.class::CREATE_NEW_KEY : mapping.mappable_id },
@@ -21,7 +20,6 @@
<% end %>
<%= form.hidden_field :key, value: mapping.key, id: dom_id(mapping, :key) %>
- <%= form.hidden_field :type, value: mapping.type, id: dom_id(mapping, :type) %>
<span class="justify-self-end">
<%= mapping.values_count %>
diff --git a/lib/csv_sanitizer.rb b/lib/csv_sanitizer.rb
new file mode 100644
index 0000000000..545e30ddba
--- /dev/null
+++ b/lib/csv_sanitizer.rb
@@ -0,0 +1,38 @@
+# Single source of truth for CSV formula-injection defence (CWE-1236).
+#
+# Values starting with =, +, -, @ execute as formulas when a spreadsheet opens
+# the file. \t, \r and \n are included because some parsers trim leading
+# whitespace-like characters before evaluating the cell, so a tab in front of
+# "=1+1" would still trigger one. Leading literal spaces are not treated as a
+# bypass by mainstream parsers today; extend the character class if that
+# changes.
+#
+# A plain signed number such as "-42.5" is left alone: it cannot run anything,
+# and escaping it would turn every negative amount into text.
+#
+# CSV only. Never apply this to JSON or NDJSON output: all.ndjson is the
+# lossless export/import round-trip.
+#
+# 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.
+module CsvSanitizer
+ FORMULA_TRIGGER = /\A[=+\-@\t\r\n]/
+ PLAIN_NUMBER = /\A[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?\z/
+
+ module_function
+
+ # Prefixes formula-triggering strings with a single quote so spreadsheets
+ # render them as literal text. Non-string values pass through unchanged.
+ def sanitize(value)
+ return value unless value.is_a?(String) && value.match?(FORMULA_TRIGGER)
+
+ value.match?(PLAIN_NUMBER) ? value : "'#{value}"
+ end
+
+ # Sanitizes a whole row. Prefer this over sanitizing chosen columns: picking
+ # fields by hand is how new user-controlled columns end up unescaped.
+ def sanitize_row(values)
+ Array(values).map { |value| sanitize(value) }
+ end
+end
diff --git a/test/controllers/api/v1/transactions_controller_test.rb b/test/controllers/api/v1/transactions_controller_test.rb
index 1b93023379..b538376e3b 100644
--- a/test/controllers/api/v1/transactions_controller_test.rb
+++ b/test/controllers/api/v1/transactions_controller_test.rb
@@ -214,6 +214,30 @@ class Api::V1::TransactionsControllerTest < ActionDispatch::IntegrationTest
assert_not_nil found_transaction, "Should find the coffee transaction"
end
+ # The search term is interpolated into an ILIKE pattern, so "%" and "_" from
+ # the caller act as wildcards instead of literals. Unescaped, a search for
+ # "%" matches every transaction in the family rather than the ones that
+ # actually contain a percent sign.
+ test "search treats LIKE wildcards in the term as literal characters" do
+ literal = @account.entries.create!(
+ name: "100% cotton",
+ amount: 5.50, currency: "USD", date: Date.current, entryable: Transaction.new
+ )
+ other = @account.entries.create!(
+ name: "Plain coffee",
+ amount: 5.50, currency: "USD", date: Date.current, entryable: Transaction.new
+ )
+
+ get api_v1_transactions_url,
+ params: { search: "%" },
+ headers: api_headers(@api_key)
+ assert_response :success
+
+ ids = JSON.parse(response.body)["transactions"].map { |t| t["id"] }
+ assert_includes ids, literal.transaction.id, "the transaction containing a literal % must match"
+ assert_not_includes ids, other.transaction.id, "a bare % must not match every transaction"
+ end
+
test "should search disabled account transactions" do
disabled_transaction = create_disabled_account_transaction(name: "Closed Account Coffee")
diff --git a/test/controllers/import/mappings_controller_test.rb b/test/controllers/import/mappings_controller_test.rb
index 91b335dfe0..794e4ada5b 100644
--- a/test/controllers/import/mappings_controller_test.rb
+++ b/test/controllers/import/mappings_controller_test.rb
@@ -26,4 +26,57 @@ class Import::MappingsControllerTest < ActionDispatch::IntegrationTest
assert_redirected_to import_confirm_path(@import)
end
+
+ # mappable_type and type used to reach `constantize` straight from request
+ # params, so any constant in the app could be resolved and have class methods
+ # called on it. The mapping row decides both now, whatever the request says.
+ test "ignores a mappable_type that is not an importable mapping target" do
+ mapping = import_mappings(:one)
+
+ assert_nothing_raised do
+ patch import_mapping_path(@import, mapping), params: {
+ import_mapping: {
+ mappable_type: "User",
+ mappable_id: users(:family_admin).id,
+ key: "Food"
+ }
+ }
+ end
+
+ assert_redirected_to import_confirm_path(@import)
+ assert_nil mapping.reload.mappable
+ end
+
+ test "ignores a mapping type that is not an importable mapping class" do
+ mapping = import_mappings(:one)
+
+ assert_nothing_raised do
+ patch import_mapping_path(@import, mapping), params: {
+ import_mapping: {
+ type: "Family",
+ mappable_type: "Category",
+ mappable_id: categories(:income).id,
+ key: "Food"
+ }
+ }
+ end
+
+ assert_redirected_to import_confirm_path(@import)
+ end
+
+ test "marks the mapping for creation when the picker asks for a new resource" do
+ mapping = import_mappings(:one)
+
+ patch import_mapping_path(@import, mapping), params: {
+ import_mapping: {
+ mappable_type: "Category",
+ mappable_id: Import::Mapping::CREATE_NEW_KEY,
+ key: "Food"
+ }
+ }
+
+ mapping.reload
+ assert mapping.create_when_empty, "the create-new sentinel must still set create_when_empty"
+ assert_nil mapping.mappable
+ end
end
diff --git a/test/controllers/reports_controller_test.rb b/test/controllers/reports_controller_test.rb
index 510e29cf47..ce2e7877d1 100644
--- a/test/controllers/reports_controller_test.rb
+++ b/test/controllers/reports_controller_test.rb
@@ -1044,6 +1044,39 @@ class ReportsControllerTest < ActionDispatch::IntegrationTest
assert_no_match(/#{Regexp.escape(I18n.t("reports.investment_performance.sells_count", count: 2))}/, response.body)
end
+ # The category column of the reports export is a user-supplied name, and this
+ # is the export the app points at Google Sheets.
+ test "transactions export escapes formula-triggering category names" do
+ malicious = "=SUM(A1)"
+ malicious_income = "@income"
+ account = @family.accounts.first
+
+ # One expense and one income, so both sections of the export are covered.
+ { malicious => 42.00, malicious_income => -500.00 }.each do |name, amount|
+ account.entries.create!(
+ name: "Payee",
+ date: Date.current.beginning_of_month + 3.days,
+ amount: amount,
+ currency: "USD",
+ entryable: Transaction.new(category: @family.categories.create!(name: name, color: "#123456"), kind: "standard")
+ )
+ end
+
+ get export_transactions_reports_path(
+ format: :csv,
+ period_type: :monthly,
+ start_date: Date.current.beginning_of_month,
+ end_date: Date.current.end_of_month
+ )
+
+ assert_response :ok
+ rows = CSV.parse(@response.body)
+ [ malicious, malicious_income ].each do |name|
+ assert rows.any? { |r| r.first == "'#{name}" }, "the #{name} category cell must be escaped"
+ assert_not rows.any? { |r| r.first == name }, "a raw #{name} must not lead a row"
+ end
+ 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 only
diff --git a/test/helpers/application_helper_test.rb b/test/helpers/application_helper_test.rb
index b20703108f..34cb13f43c 100644
--- a/test/helpers/application_helper_test.rb
+++ b/test/helpers/application_helper_test.rb
@@ -118,6 +118,92 @@ class ApplicationHelperTest < ActionView::TestCase
assert_equal [ "SGD", "USD", "EUR" ], currency_picker_options_for_family(family, extra: "EUR")
end
+ # `markdown` renders AI chat messages, and a user message is content the
+ # user typed. Redcarpet passes raw HTML through untouched, so without a
+ # filter this is stored XSS against anyone else in the family.
+ test "markdown strips script tags from user content" do
+ assert_no_match(/<script/i, markdown("<script>alert(1)</script>"))
+ end
+
+ test "markdown strips event handlers from user content" do
+ assert_no_match(/onerror/i, markdown('<img src=x onerror="alert(1)">'))
+ end
+
+ # Raw HTML in a chat message must not survive, and stripping tags is not
+ # enough on its own: div, span, class and style stay allow-listed for
+ # footnotes, code blocks and table alignment, so a bare allow-list would
+ # still let a message cover the app or lay an invisible link over it.
+ test "markdown drops raw HTML a user typed, layout tags included" do
+ assert_no_match(/<div/i, markdown('<div class="fixed inset-0 z-50 bg-black">covered</div>'))
+ assert_no_match(/position/i, markdown('<span style="position:fixed;inset:0">covered</span>'))
+ assert_no_match(/fixed inset-0/, markdown('<a href="https://evil.example" class="fixed inset-0">x</a>'))
+ assert_no_match(/evil\.example/, markdown('<img src="https://evil.example/track.gif">'))
+ end
+
+ # A markdown link is built by the renderer itself, so a javascript: or data:
+ # target survives filter_html and goes away only via the sanitize allow-list.
+ test "markdown strips dangerous URL schemes from the links it generates" do
+ assert_no_match(/javascript:/i, markdown("[click](javascript:alert(1))"))
+ assert_no_match(/javascript:/i, markdown("![x](javascript:alert(1))"))
+ assert_no_match(%r{data:text/html}i, markdown("[click](data:text/html;base64,PHNjcmlwdD4=)"))
+ assert_no_match(/data:/i, markdown("![x](data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=)"))
+ end
+
+ test "markdown keeps ordinary image and link targets" do
+ assert_match(%r{<img[^>]+src="https://example\.com/a\.png"}, markdown("![alt](https://example.com/a.png)"))
+ assert_match(%r{href="https://example\.com"}, markdown("[x](https://example.com)"))
+ end
+
+ test "markdown still renders the formatting the chat relies on" do
+ rendered = markdown("**bold** and `code` and [link](https://example.com)")
+
+ assert_match(/<strong>bold<\/strong>/, rendered)
+ assert_match(/<code>code<\/code>/, rendered)
+ assert_match(%r{href="https://example\.com"}, rendered)
+ end
+
+ test "markdown preserves underline formatting" do
+ assert_includes markdown("This is _underlined_"), "<u>underlined</u>"
+ end
+
+ test "markdown preserves inline quote formatting" do
+ assert_includes markdown('She said "hello"'), "<q>hello</q>"
+ end
+
+ test "markdown keeps the rest of the markup its extensions generate" do
+ rendered = markdown(<<~MD)
+ ==marked== ~~struck~~ x^2 note[^1]
+
+ | left | right |
+ |:-----|------:|
+ | a | b |
+
+ ```ruby
+ x
+ ```
+
+ [^1]: footnote
+ MD
+
+ assert_includes rendered, "<mark>marked</mark>"
+ assert_includes rendered, "<del>struck</del>"
+ assert_includes rendered, "<sup>2</sup>"
+ assert_match(%r{<sup id="fnref1"><a href="#fn1"[^>]*>1</a></sup>}, rendered)
+ assert_match(%r{<div class="footnotes">.*<li id="fn1">}m, rendered)
+ assert_match(%r{<th style="text-align:\s*left;?">left</th>}, rendered)
+ assert_match(%r{<td style="text-align:\s*right;?">b</td>}, rendered)
+ assert_includes rendered, '<code class="ruby">'
+ end
+
+ test "markdown renders images written as markdown" do
+ assert_match(%r{<img[^>]+src="https://example\.com/a\.png"}, markdown("![alt](https://example.com/a.png)"))
+ end
+
+ test "markdown returns an empty string for blank input" do
+ assert_equal "", markdown(nil)
+ assert_equal "", markdown("")
+ end
+
test "#mask_last4 masks all but the last 4 characters" do
assert_equal "•••7890", mask_last4("account-number-1234567890")
assert_equal "•••2345", mask_last4("12345")
diff --git a/test/lib/csv_sanitizer_test.rb b/test/lib/csv_sanitizer_test.rb
new file mode 100644
index 0000000000..15a758b6c7
--- /dev/null
+++ b/test/lib/csv_sanitizer_test.rb
@@ -0,0 +1,50 @@
+require "test_helper"
+
+class CsvSanitizerTest < ActiveSupport::TestCase
+ test "prefixes formula-triggering values so spreadsheets treat them as text" do
+ {
+ "=SUM(A1)" => "'=SUM(A1)",
+ "+cmd|calc" => "'+cmd|calc",
+ "-1+1" => "'-1+1",
+ "@evil" => "'@evil",
+ "\t=SUM(A1)" => "'\t=SUM(A1)",
+ "\r=SUM(A1)" => "'\r=SUM(A1)",
+ "\n=SUM(A1)" => "'\n=SUM(A1)"
+ }.each do |input, expected|
+ assert_equal expected, CsvSanitizer.sanitize(input), "failed for #{input.inspect}"
+ end
+ end
+
+ test "leaves ordinary values alone" do
+ [ "hello", "Groceries", "123", "a=b", "" ].each do |safe|
+ assert_equal safe, CsvSanitizer.sanitize(safe)
+ end
+ end
+
+ test "leaves plain numbers alone, signed ones included" do
+ [ "-42.5", "-1200.0", "+3", "-0.0001", "-1e3", "-7" ].each do |number|
+ assert_equal number, CsvSanitizer.sanitize(number), "failed for #{number.inspect}"
+ end
+ end
+
+ test "still escapes a value that only starts like a number" do
+ {
+ "-1+1" => "'-1+1",
+ "-2*cmd|' /C calc'!A0" => "'-2*cmd|' /C calc'!A0",
+ "+1)" => "'+1)",
+ "-42.5\n=1" => "'-42.5\n=1"
+ }.each do |input, expected|
+ assert_equal expected, CsvSanitizer.sanitize(input), "failed for #{input.inspect}"
+ end
+ end
+
+ test "passes non-string values through untouched" do
+ assert_nil CsvSanitizer.sanitize(nil)
+ assert_equal 42, CsvSanitizer.sanitize(42)
+ assert_equal BigDecimal("-1.5"), CsvSanitizer.sanitize(BigDecimal("-1.5"))
+ end
+
+ test "sanitizes every cell of a row" do
+ assert_equal [ "'=a", "b", nil, 3 ], CsvSanitizer.sanitize_row([ "=a", "b", nil, 3 ])
+ end
+end
diff --git a/test/models/account_import_test.rb b/test/models/account_import_test.rb
index c411484079..85e419da14 100644
--- a/test/models/account_import_test.rb
+++ b/test/models/account_import_test.rb
@@ -209,4 +209,24 @@ class AccountImportTest < ActiveSupport::TestCase
test "max_row_count is limited to 50" do
assert_equal 50, @import.max_row_count
end
+
+ # The accountable class came from a user-supplied mapping value straight
+ # through `constantize`, so any constant in the app could be instantiated
+ # and attached to an account.
+ test "import! refuses an account type that is not an accountable" do
+ @import.update!(
+ raw_file_str: "name,type,balance,currency\nSneaky,User,100.00,USD",
+ entity_type_col_label: "type",
+ name_col_label: "name",
+ amount_col_label: "balance",
+ currency_col_label: "currency"
+ )
+ @import.generate_rows_from_csv
+ @import.mappings.account_types.find_by(key: "User")&.update!(value: "User") ||
+ Import::AccountTypeMapping.create!(import: @import, key: "User", value: "User")
+
+ assert_no_difference "Account.count" do
+ assert_raises(ArgumentError) { @import.import! }
+ end
+ end
end
diff --git a/test/models/family/data_exporter_test.rb b/test/models/family/data_exporter_test.rb
index 8d2485f722..647ec26444 100644
--- a/test/models/family/data_exporter_test.rb
+++ b/test/models/family/data_exporter_test.rb
@@ -1291,6 +1291,114 @@ class Family::DataExporterTest < ActiveSupport::TestCase
end
end
+ # CSV formula injection (CWE-1236) -------------------------------------------
+ #
+ # These assert on the emitted CSV rather than on the helper. Sanitizing field
+ # by field is how fields get missed, so each generator is checked for the
+ # columns a user controls.
+
+ test "every CSV in the export escapes formula-triggering user content" do
+ security = Security.create!(ticker: "=SUM(A1)", name: "Formula Security", exchange_operating_mic: "XNAS")
+ account = @family.accounts.create!(
+ name: "@evil account",
+ accountable: Depository.new(subtype: "=cmd"),
+ balance: 500,
+ currency: "USD"
+ )
+ account.entries.create!(
+ date: Date.parse("2024-05-18"), amount: 1500, name: "Formula Trade", currency: "USD",
+ entryable: Trade.new(security: security, qty: 10, price: 150, currency: "USD")
+ )
+ category = @family.categories.create!(name: "+cmd|calc", color: "#123456", lucide_icon: "@icon")
+ account.entries.create!(
+ date: Date.parse("2024-05-19"), amount: 10, currency: "USD",
+ name: "=SUM(B1)", notes: "-1.5x leverage",
+ entryable: Transaction.new(category: category)
+ )
+ @family.merchants.create!(name: "-2+3", color: "#123456")
+ @family.rules.create!(
+ name: "@rule",
+ resource_type: "transaction",
+ actions: [ Rule::Action.new(action_type: "set_transaction_category", value: category.id) ]
+ )
+
+ Zip::File.open_buffer(@exporter.generate_export) do |zip|
+ accounts = CSV.parse(zip.read("accounts.csv"), headers: true)
+ row = accounts.find { |r| r["name"] == "'@evil account" }
+ assert row, "account name must be escaped"
+ assert_equal "'=cmd", row["subtype"], "account subtype must be escaped"
+
+ trades = CSV.parse(zip.read("trades.csv"), headers: true)
+ assert trades.any? { |r| r["ticker"] == "'=SUM(A1)" }, "trade ticker must be escaped"
+ assert_not trades.any? { |r| r["ticker"] == "=SUM(A1)" }, "raw formula ticker must not appear"
+
+ categories = CSV.parse(zip.read("categories.csv"), headers: true)
+ row = categories.find { |r| r["name"] == "'+cmd|calc" }
+ assert row, "category name must be escaped"
+ assert_equal "'@icon", row["lucide_icon"], "category lucide_icon must be escaped"
+
+ transactions = CSV.parse(zip.read("transactions.csv"), headers: true)
+ row = transactions.find { |r| r["name"] == "'=SUM(B1)" }
+ assert row, "transaction name must be escaped"
+ assert_equal "'-1.5x leverage", row["notes"], "transaction notes must be escaped"
+
+ merchants = CSV.parse(zip.read("merchants.csv"), headers: true)
+ assert merchants.any? { |r| r["name"] == "'-2+3" }, "merchant name must be escaped"
+
+ rules = CSV.parse(zip.read("rules.csv"), headers: true)
+ assert rules.any? { |r| r["name"] == "'@rule" }, "rule name must be escaped"
+ end
+ end
+
+ # A bare number cannot run anything, and escaping it would turn every income
+ # amount, negative balance and sale quantity into text in the spreadsheet.
+ test "CSV export leaves negative numbers as numbers" do
+ account = @family.accounts.create!(name: "Overdrawn", accountable: Depository.new, balance: -250.5, currency: "USD")
+ account.entries.create!(
+ date: Date.parse("2024-05-19"), amount: -1200, currency: "USD", name: "Salary",
+ entryable: Transaction.new
+ )
+ security = Security.create!(ticker: "SELLME", name: "Sold Security", exchange_operating_mic: "XNAS")
+ account.entries.create!(
+ date: Date.parse("2024-05-20"), amount: -300, name: "Sell", currency: "USD",
+ entryable: Trade.new(security: security, qty: -2, price: 150, currency: "USD")
+ )
+
+ Zip::File.open_buffer(@exporter.generate_export) do |zip|
+ accounts = CSV.parse(zip.read("accounts.csv"), headers: true)
+ assert_equal "-250.5", accounts.find { |r| r["name"] == "Overdrawn" }["balance"]
+
+ transactions = CSV.parse(zip.read("transactions.csv"), headers: true)
+ assert_equal "-1200.0", transactions.find { |r| r["name"] == "Salary" }["amount"]
+
+ trade = CSV.parse(zip.read("trades.csv"), headers: true).find { |r| r["ticker"] == "SELLME" }
+ assert_equal "-2.0", trade["quantity"]
+ assert_equal "-300.0", trade["amount"]
+ end
+ end
+
+ test "NDJSON keeps formula-prefixed values verbatim so export and import round-trip" do
+ name = "=SUM(A1)"
+ notes = "-1.5x leverage"
+ entry = @account.entries.create!(
+ date: Date.current, name: name, amount: 10, currency: "USD", notes: notes,
+ entryable: Transaction.new
+ )
+
+ Zip::File.open_buffer(@exporter.generate_export) do |zip|
+ line = zip.read("all.ndjson").each_line.find do |l|
+ parsed = JSON.parse(l)
+ parsed["type"] == "Transaction" && parsed.dig("data", "entry_id") == entry.id
+ end
+
+ assert line, "the transaction must be in all.ndjson"
+ data = JSON.parse(line)["data"]
+ assert_equal name, data["name"]
+ assert_equal notes, data["notes"]
+ end
+ end
+
+
private
def create_transaction_entry(account, amount:, date:, name:)
diff --git a/test/models/import_test.rb b/test/models/import_test.rb
index 89a9d898f5..bec5e5da42 100644
--- a/test/models/import_test.rb
+++ b/test/models/import_test.rb
@@ -233,4 +233,16 @@ class ImportTest < ActiveSupport::TestCase
assert_equal Date.new(2024, 5, 15), Date.strptime("15/05/24", import.date_format)
end
+
+ test "parse_csv_str keeps a quote that is part of the value" do
+ csv = Import.parse_csv_str("name\nO'Brien\n")
+
+ assert_equal "O'Brien", csv.first["name"]
+ end
+
+ test "parse_csv_str preserves a literal leading apostrophe before a formula marker" do
+ csv = Import.parse_csv_str("name\n'+44 Taxis\n+44 Taxis\n")
+
+ assert_equal [ "'+44 Taxis", "+44 Taxis" ], csv["name"]
+ end
end