Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Stop backfill_encryption double-encoding json/jsonb columns (#2615)

Stephen Jolly27aa222ed3b8
diff --git a/lib/tasks/security_backfill.rake b/lib/tasks/security_backfill.rake
index ee2a261914..357a232fe3 100644
--- a/lib/tasks/security_backfill.rake
+++ b/lib/tasks/security_backfill.rake
@@ -1,6 +1,15 @@
# frozen_string_literal: true
namespace :security do
+ # Scope note: this task encrypts values that are still stored as PLAINTEXT.
+ # It cannot detect or repair rows that were double-encoded by the pre-fix
+ # version of this task (issue #2611): those decrypt "successfully" to a
+ # JSON-text String on a json/jsonb column, which is indistinguishable here
+ # from a legitimately stored string value, so mutating them automatically
+ # would risk mangling valid data. If your instance ran the backfill before
+ # the #2611 fix and provider payloads now decrypt to Strings (symptom:
+ # zero balances on every provider-linked account after a sync), run the
+ # manual recovery script in issue #2611 first, then re-run this task.
desc "Backfill encryption for sensitive fields (idempotent). Args: batch_size, dry_run"
task :backfill_encryption, [ :batch_size, :dry_run ] => :environment do |_, args|
raw_batch = args[:batch_size].presence || ENV["BATCH_SIZE"].presence || "100"
@@ -81,8 +90,11 @@ namespace :security do
# Skip if filter block returns false
next if block_given? && !filter_block.call(record)
- # Check if any field has data (use safe read to handle plaintext)
- next unless fields.any? { |f| safe_read_field(record, f).present? }
+ # Check if any field has data (use safe read to handle plaintext).
+ # Nil-check rather than present?: empty values ({}, [], "") are still
+ # plaintext that needs encrypting — present? skips them, leaving data
+ # the encrypted getters raise on once keys are live.
+ next unless fields.any? { |f| !safe_read_field(record, f).nil? }
next if dry_run
@@ -91,7 +103,7 @@ namespace :security do
plaintext_values = {}
fields.each do |field|
value = safe_read_field(record, field)
- plaintext_values[field] = value if value.present?
+ plaintext_values[field] = value unless value.nil?
end
next if plaintext_values.empty?
@@ -129,11 +141,25 @@ namespace :security do
# Safely read a field value, handling both encrypted and plaintext data.
# When encryption is configured but the value is plaintext, the getter
# raises ActiveRecord::Encryption::Errors::Decryption. In this case,
- # we fall back to reading the raw database value.
+ # we fall back to reading the raw database value. For json/jsonb columns
+ # the raw value is the JSON text, not the deserialized Array/Hash the
+ # encrypted setter expects, so parse it first — otherwise the backfill
+ # encrypts the JSON text itself and the column thereafter decrypts to a
+ # String, breaking every consumer of the payload.
def safe_read_field(record, field)
record.send(field)
rescue ActiveRecord::Encryption::Errors::Decryption
- record.read_attribute_before_type_cast(field)
+ raw = record.read_attribute_before_type_cast(field)
+ column = record.class.columns_hash[field.to_s]
+ if raw.is_a?(String) && [ :json, :jsonb ].include?(column&.type)
+ begin
+ JSON.parse(raw)
+ rescue JSON::ParserError
+ raw
+ end
+ else
+ raw
+ end
end
def backfill_sessions(batch_size, dry_run)
@@ -151,7 +177,7 @@ namespace :security do
# Re-save user_agent to trigger encryption (use safe read for plaintext)
user_agent_value = safe_read_field(session, :user_agent)
- if user_agent_value.present?
+ unless user_agent_value.nil?
# Use temporary instance to encrypt
encryptor = Session.new
encryptor.user_agent = user_agent_value
diff --git a/test/lib/tasks/security_backfill_test.rb b/test/lib/tasks/security_backfill_test.rb
new file mode 100644
index 0000000000..57258b6414
--- /dev/null
+++ b/test/lib/tasks/security_backfill_test.rb
@@ -0,0 +1,73 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class SecurityBackfillTest < ActiveSupport::TestCase
+ # Follows the suite convention (see test/encryption_verification_test.rb):
+ # runs only when explicit encryption keys are configured, e.g.
+ #
+ # ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY=test \
+ # ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY=test \
+ # ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT=test \
+ # bin/rails test test/lib/tasks/security_backfill_test.rb
+ setup do
+ skip "Encryption not configured" unless LunchflowAccount.encryption_ready?
+ Rails.application.load_tasks unless Rake::Task.task_defined?("security:backfill_encryption")
+ Rake::Task["security:backfill_encryption"].reenable
+ end
+
+ # Lunchflow is a representative provider model, chosen arbitrarily: the bug
+ # this guards against applies identically to every json/jsonb encrypts
+ # column the task touches (the Plaid/SimpleFin/Enable Banking/... raw
+ # payload columns), via the shared safe_read_field helper.
+ test "backfill preserves jsonb payload structure and string fields" do
+ item = LunchflowItem.new(family: families(:dylan_family), name: "Backfill Test", api_key: "seed")
+ item.save!(validate: false)
+ account = item.lunchflow_accounts.create!(
+ name: "Backfill Test Account", currency: "GBP", account_id: "backfill-test-1")
+
+ payload = [ { "id" => "tx-1", "amount" => -4.5, "currency" => "GBP", "date" => "2026-07-01" } ]
+
+ # Simulate rows written before encryption was enabled: bypass the encrypted
+ # setters and write plaintext values directly to the columns.
+ ActiveRecord::Base.connection.execute(ActiveRecord::Base.sanitize_sql([
+ "UPDATE lunchflow_accounts SET raw_transactions_payload = ?::jsonb WHERE id = ?",
+ payload.to_json, account.id ]))
+ ActiveRecord::Base.connection.execute(ActiveRecord::Base.sanitize_sql([
+ "UPDATE lunchflow_items SET api_key = ? WHERE id = ?", "plaintext-key", item.id ]))
+
+ capture_io { Rake::Task["security:backfill_encryption"].invoke("500", "false") }
+
+ account.reload
+ assert_kind_of Array, account.raw_transactions_payload,
+ "jsonb payload must decrypt to its original structure, not the JSON text"
+ assert_equal "tx-1", account.raw_transactions_payload.first["id"]
+ assert_equal "plaintext-key", item.reload.api_key
+
+ # The stored value is ciphertext, not plaintext jsonb
+ at_rest = account.read_attribute_before_type_cast(:raw_transactions_payload).to_s
+ refute_includes at_rest, "tx-1"
+ end
+
+ # Several payload columns default to {} — Rails presence checks treat empty
+ # Hash/Array as absent, so the backfill must gate on nil-ness or empty
+ # payloads stay plaintext and raise on every read once keys are live.
+ test "backfill encrypts empty json payloads" do
+ item = LunchflowItem.new(family: families(:dylan_family), name: "Backfill Empty Test", api_key: "seed")
+ item.save!(validate: false)
+ account = item.lunchflow_accounts.create!(
+ name: "Backfill Empty Test Account", currency: "GBP", account_id: "backfill-test-2")
+
+ # Plaintext empty payload, as left by a pre-encryption install
+ ActiveRecord::Base.connection.execute(ActiveRecord::Base.sanitize_sql([
+ "UPDATE lunchflow_accounts SET raw_payload = ?::jsonb WHERE id = ?", "{}", account.id ]))
+
+ capture_io { Rake::Task["security:backfill_encryption"].invoke("500", "false") }
+
+ account.reload
+ assert_equal({}, account.raw_payload,
+ "an empty payload must decrypt cleanly after the backfill, not remain plaintext")
+ assert_match(/"p":/, account.read_attribute_before_type_cast(:raw_payload).to_s,
+ "the stored value must be an encryption envelope, not plaintext {}")
+ end
+end