Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Encrypting plaid and Plaid EU as declared settings (#4992)

Mark F92abc3ac6fe2
diff --git a/app/models/setting.rb b/app/models/setting.rb
index 6454ecdab5..60b1167783 100644
--- a/app/models/setting.rb
+++ b/app/models/setting.rb
@@ -125,6 +125,10 @@ class Setting < RailsSettings::Base
field :chimnie_api_key, type: :string, default: ENV["CHIMNIE_API_KEY"]
field :terrascoutx_api_key, type: :string, default: ENV["TERRASCOUTX_API_KEY"]
+ # Instance-wide Plaid credentials; provider configuration handles ENV fallback.
+ field :plaid_secret, type: :string
+ field :plaid_eu_secret, type: :string
+
# Transparent encryption for API key fields. The `field` macro defines the
# raw getter/setter on the class. By prepending this module we intercept
# reads (decrypt) and writes (encrypt) while `super` delegates to the
@@ -148,6 +152,8 @@ class Setting < RailsSettings::Base
anthropic_access_token
jev_api_key
external_assistant_token
+ plaid_secret
+ plaid_eu_secret
].freeze
ENCRYPTED_FIELDS.each do |field_name|
diff --git a/db/migrate/20261113130000_promote_plaid_secrets_to_declared_settings.rb b/db/migrate/20261113130000_promote_plaid_secrets_to_declared_settings.rb
new file mode 100644
index 0000000000..5b073b8e8c
--- /dev/null
+++ b/db/migrate/20261113130000_promote_plaid_secrets_to_declared_settings.rb
@@ -0,0 +1,56 @@
+# frozen_string_literal: true
+
+class PromotePlaidSecretsToDeclaredSettings < ActiveRecord::Migration[8.1]
+ class MigrationSetting < ActiveRecord::Base
+ self.table_name = "settings"
+ self.filter_attributes += [ :value ]
+ serialize :value, coder: YAML
+ end
+
+ class ConversionError < StandardError; end
+
+ def up
+ MigrationSetting.transaction(requires_new: true) do
+ %w[plaid_secret plaid_eu_secret].each do |key|
+ source = MigrationSetting.lock.find_by(var: "dynamic:#{key}")
+ next unless source
+
+ if MigrationSetting.exists?(var: key)
+ raise ConversionError, "Both legacy and declared #{key} settings exist; resolve the conflict before upgrading"
+ end
+
+ plaintext = source.value
+ unless plaintext.nil? || plaintext.is_a?(String)
+ raise ConversionError, "Legacy #{key} is not a plaintext string; conversion requires operator review"
+ end
+
+ # Match the declared settings format without depending on future Setting accessors.
+ ciphertext = plaintext.blank? ? plaintext : encryptor.encrypt_and_sign(plaintext)
+ write = proc { source.update!(var: key, value: ciphertext) }
+ MigrationSetting.logger ? MigrationSetting.logger.silence(&write) : write.call
+ end
+
+ Setting.clear_cache
+ end
+ rescue ConversionError
+ raise
+ rescue StandardError => error
+ raise ConversionError, "Plaid secret conversion failed (#{error.class}); original settings were preserved", cause: nil
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration, "Do not restore provider secrets to plaintext; restore a protected pre-upgrade backup instead"
+ end
+
+ private
+
+ def encryptor
+ @encryptor ||= begin
+ secret_key_base = Rails.application.secret_key_base
+ raise ConversionError, "SECRET_KEY_BASE is required to convert Plaid secrets" if secret_key_base.blank?
+
+ key = ActiveSupport::KeyGenerator.new(secret_key_base).generate_key("setting_encryption", 32)
+ ActiveSupport::MessageEncryptor.new(key)
+ end
+ end
+end
diff --git a/docs/hosting/encryption.md b/docs/hosting/encryption.md
index 11da955c82..d365d7785c 100644
--- a/docs/hosting/encryption.md
+++ b/docs/hosting/encryption.md
@@ -101,6 +101,29 @@ bin/rails "security:rotate_setting_secrets[0]" # writes
unset OLD_SECRET_KEY_BASE
```
+Re-enter any key the task lists under `not_decryptable`.
+
+## Upgrading Plaid instance credentials
+
+Plaid and Plaid EU instance secrets now use the same declared encrypted settings
+as AI and market-data keys. Their provider forms and environment variables are
+unchanged. The required database migration moves existing `dynamic:plaid_secret`
+and `dynamic:plaid_eu_secret` rows to the declared setting names and encrypts their
+values with the existing settings key derived from `SECRET_KEY_BASE`.
+
+Stop old web and worker processes before upgrading, keep `SECRET_KEY_BASE`
+unchanged, and take a protected database backup. Run normal database migrations
+before starting the new web and worker processes. The default Docker web
+entrypoint runs `db:prepare`; custom deployments must include that step too.
+This conversion is mandatory, not an optional backfill task.
+
+A conflict between legacy and declared rows, an unexpected legacy format, or an
+encryption failure stops the migration and preserves the original rows. Resolve
+the reported issue before retrying; do not skip the migration. Missing/empty
+credentials remain empty and ENV-only credentials are not copied to the database.
+After conversion, the existing `security:rotate_setting_secrets` task covers both
+Plaid secrets. The migration is irreversible: it does not recreate plaintext
+credentials for a downgrade.
Re-enter any key the task lists under `not_decryptable`. Then start the
app (web and worker) and check a login and a provider sync.
diff --git a/test/controllers/settings/providers_controller_test.rb b/test/controllers/settings/providers_controller_test.rb
index 5134467346..1e619b8b0e 100644
--- a/test/controllers/settings/providers_controller_test.rb
+++ b/test/controllers/settings/providers_controller_test.rb
@@ -327,17 +327,13 @@ class Settings::ProvidersControllerTest < ActionDispatch::IntegrationTest
end
test "correctly identifies declared vs dynamic fields" do
- # All current provider fields are dynamic, but the logic should correctly
- # distinguish between declared and dynamic fields
with_self_hosting do
# plaid_client_id is a dynamic field (not defined in Setting)
refute Setting.singleton_class.method_defined?(:plaid_client_id=),
"plaid_client_id= should NOT be defined on Setting's singleton class"
- # openai_model IS a declared field (defined in Setting)
- # but it's not a provider field, so it won't go through this controller
- assert Setting.singleton_class.method_defined?(:openai_model=),
- "openai_model= should be defined on Setting's singleton class"
+ assert Setting.singleton_class.method_defined?(:plaid_secret=)
+ assert Setting.singleton_class.method_defined?(:plaid_eu_secret=)
end
end
@@ -356,7 +352,7 @@ class Settings::ProvidersControllerTest < ActionDispatch::IntegrationTest
end
end
- test "batches multiple dynamic fields from same provider atomically" do
+ test "batches declared and dynamic fields from same provider atomically" do
# Test that multiple fields from Plaid are updated as individual entries
with_self_hosting do
# Clear existing fields
@@ -381,7 +377,7 @@ class Settings::ProvidersControllerTest < ActionDispatch::IntegrationTest
end
end
- test "batches dynamic fields from multiple providers atomically" do
+ test "batches provider fields from multiple providers atomically" do
# Test that fields from different providers are stored as individual entries
with_self_hosting do
# Clear existing fields
@@ -460,6 +456,36 @@ class Settings::ProvidersControllerTest < ActionDispatch::IntegrationTest
end
end
+ test "existing provider forms save and mask declared Plaid secrets" do
+ %w[plaid plaid_eu].each do |provider|
+ key = "#{provider}_secret"
+ secret = "synthetic-#{provider}-secret"
+ patch settings_providers_url, params: { setting: {
+ "#{provider}_client_id" => "synthetic-client", key => secret
+ } }
+
+ assert_redirected_to settings_providers_url
+ ciphertext = Setting.find_by!(var: key).value
+ refute_includes ciphertext, secret
+ assert_equal secret, Setting[key]
+ assert_not Setting.exists?(var: "dynamic:#{key}")
+
+ get connect_form_settings_providers_path(provider_key: provider)
+ assert_response :success
+ assert_select "input[name=?][type=password][value=?]", "setting[#{key}]", "********"
+ refute_includes response.body, secret
+ refute_includes response.body, ciphertext
+
+ patch settings_providers_url, params: { setting: { key => "********" } }
+ assert_redirected_to settings_providers_url
+ assert_equal ciphertext, Setting.find_by!(var: key).value
+
+ patch settings_providers_url, params: { setting: { key => "" } }
+ assert_redirected_to settings_providers_url
+ assert_nil Setting[key]
+ end
+ end
+
test "converts blank values to nil and removes from dynamic_fields" do
with_self_hosting do
# Set initial values
diff --git a/test/lib/tasks/security_setting_secrets_test.rb b/test/lib/tasks/security_setting_secrets_test.rb
index 8a59051a0a..e3c8a0a962 100644
--- a/test/lib/tasks/security_setting_secrets_test.rb
+++ b/test/lib/tasks/security_setting_secrets_test.rb
@@ -43,6 +43,38 @@ class SecuritySettingSecretsTaskTest < ActiveSupport::TestCase
assert_not_equal "sk-old-key", Setting.openai_access_token
end
+ test "existing rotation task previews and rotates both Plaid secrets" do
+ keys = %w[plaid_secret plaid_eu_secret]
+ keys.each { |key| store_with_old_key(key, "synthetic-#{key}") }
+ before = keys.index_with { |key| Setting.find_by!(var: key).value }
+
+ with_env_overrides("OLD_SECRET_KEY_BASE" => OLD_SECRET_KEY_BASE) do
+ output = capture_io { @task.invoke }.first
+ result = JSON.parse(output.lines.last)
+ assert result["ok"]
+ assert result["dry_run"]
+ keys.each do |key|
+ assert_equal "would_reencrypt", result["results"][key]
+ assert_equal before[key], Setting.find_by!(var: key).value
+ end
+
+ @task.reenable
+ output = capture_io { @task.invoke("0") }.first
+ result = JSON.parse(output.lines.last)
+ assert result["ok"]
+ keys.each do |key|
+ assert_equal "reencrypted", result["results"][key]
+ assert_equal "synthetic-#{key}", Setting[key]
+ refute_equal before[key], Setting.find_by!(var: key).value
+ end
+
+ @task.reenable
+ output = capture_io { @task.invoke("0") }.first
+ result = JSON.parse(output.lines.last)
+ keys.each { |key| assert_equal "current", result["results"][key] }
+ end
+ end
+
test "refuses to run without OLD_SECRET_KEY_BASE" do
output = with_env_overrides("OLD_SECRET_KEY_BASE" => nil) do
capture_io { assert_raises(SystemExit) { @task.invoke("0") } }.first
diff --git a/test/migrations/promote_plaid_secrets_to_declared_settings_migration_test.rb b/test/migrations/promote_plaid_secrets_to_declared_settings_migration_test.rb
new file mode 100644
index 0000000000..06e162910a
--- /dev/null
+++ b/test/migrations/promote_plaid_secrets_to_declared_settings_migration_test.rb
@@ -0,0 +1,166 @@
+# frozen_string_literal: true
+
+require "test_helper"
+require Rails.root.join("db/migrate/20261113130000_promote_plaid_secrets_to_declared_settings")
+
+class PromotePlaidSecretsToDeclaredSettingsMigrationTest < ActiveSupport::TestCase
+ setup do
+ Setting.where(var: %w[plaid_secret plaid_eu_secret dynamic:plaid_secret dynamic:plaid_eu_secret]).delete_all
+ Setting.clear_cache
+ end
+
+ test "moves both legacy secrets into encrypted declared settings without changing the UI read path" do
+ %w[plaid_secret plaid_eu_secret].each { |key| store_legacy(key, "synthetic-#{key}") }
+ ids = Setting.where("var LIKE ?", "dynamic:plaid%secret").pluck(:id).sort
+ Setting.plaid_secret # Populate the declared-setting cache before conversion.
+
+ run_migration
+
+ %w[plaid_secret plaid_eu_secret].each do |key|
+ assert_equal "synthetic-#{key}", Setting[key]
+ refute_includes Setting.find_by!(var: key).value, "synthetic-#{key}"
+ assert_not Setting.exists?(var: "dynamic:#{key}")
+ end
+ assert_equal ids, Setting.where(var: %w[plaid_secret plaid_eu_secret]).pluck(:id).sort
+ assert_equal "synthetic-plaid_secret", Provider::PlaidAdapter.config_value(:secret)
+ assert_equal "synthetic-plaid_eu_secret", Provider::PlaidEuAdapter.config_value(:secret)
+ end
+
+ test "does nothing on fresh and ENV-only installations" do
+ Rails.application.expects(:secret_key_base).never
+ with_env_overrides("PLAID_SECRET" => "synthetic-env-secret", "PLAID_EU_SECRET" => "synthetic-eu-env-secret") do
+ run_migration
+
+ assert_equal "synthetic-env-secret", Provider::PlaidAdapter.config_value(:secret)
+ assert_equal "synthetic-eu-env-secret", Provider::PlaidEuAdapter.config_value(:secret)
+ assert_empty Setting.where(var: %w[plaid_secret plaid_eu_secret])
+ end
+ end
+
+ test "reruns do not rewrite already converted secrets" do
+ store_legacy("plaid_secret", "synthetic-secret")
+ run_migration
+ ciphertext = Setting.find_by!(var: "plaid_secret").value
+
+ run_migration
+
+ assert_equal ciphertext, Setting.find_by!(var: "plaid_secret").value
+ assert_equal "synthetic-secret", Setting.plaid_secret
+ end
+
+ test "preserves empty legacy values and unrelated dynamic settings" do
+ store_legacy("plaid_secret", "")
+ store_legacy("plaid_eu_secret", nil)
+ Setting[:plaid_client_id] = "synthetic-client"
+ Setting[:custom_value] = "ordinary-value"
+
+ run_migration
+
+ assert_equal "", Setting.find_by!(var: "plaid_secret").value
+ assert_nil Setting.find_by!(var: "plaid_eu_secret").value
+ assert_equal "synthetic-client", Setting[:plaid_client_id]
+ assert_equal "ordinary-value", Setting[:custom_value]
+ assert_empty Setting.where(var: %w[dynamic:plaid_secret dynamic:plaid_eu_secret])
+ end
+
+ test "missing key blocks conversion rather than moving credentials as plaintext" do
+ store_legacy("plaid_secret", "synthetic-secret")
+ Rails.application.stubs(:secret_key_base).returns(nil)
+
+ error = assert_raises(PromotePlaidSecretsToDeclaredSettings::ConversionError) { run_migration }
+
+ assert_includes error.message, "SECRET_KEY_BASE is required"
+ assert_equal "synthetic-secret", Setting.find_by!(var: "dynamic:plaid_secret").value
+ assert_not Setting.exists?(var: "plaid_secret")
+ end
+
+ test "conflicts stop conversion and roll back the other region" do
+ store_legacy("plaid_secret", "synthetic-us-secret")
+ store_legacy("plaid_eu_secret", "synthetic-eu-secret")
+ Setting.plaid_eu_secret = "synthetic-existing-secret"
+ existing = Setting.find_by!(var: "plaid_eu_secret").value
+
+ assert_raises(PromotePlaidSecretsToDeclaredSettings::ConversionError) { run_migration }
+
+ assert_equal "synthetic-us-secret", Setting.find_by!(var: "dynamic:plaid_secret").value
+ assert_equal "synthetic-eu-secret", Setting.find_by!(var: "dynamic:plaid_eu_secret").value
+ assert_not Setting.exists?(var: "plaid_secret")
+ assert_equal existing, Setting.find_by!(var: "plaid_eu_secret").value
+ end
+
+ test "unexpected legacy formats stop conversion instead of encrypting an envelope or hash" do
+ store_legacy("plaid_secret", "synthetic-us-secret")
+ store_legacy("plaid_eu_secret", { "sure_provider_secret" => 1, "ciphertext" => "synthetic-envelope" })
+
+ error = assert_raises(PromotePlaidSecretsToDeclaredSettings::ConversionError) { run_migration }
+
+ assert_includes error.message, "not a plaintext string"
+ refute_includes error.message, "synthetic-envelope"
+ assert_not Setting.exists?(var: "plaid_secret")
+ assert Setting.exists?(var: "dynamic:plaid_secret")
+ assert Setting.exists?(var: "dynamic:plaid_eu_secret")
+ end
+
+ test "encryption failures preserve both sources and hide sensitive error messages" do
+ store_legacy("plaid_secret", "synthetic-us-secret")
+ store_legacy("plaid_eu_secret", "synthetic-eu-secret")
+ migration = PromotePlaidSecretsToDeclaredSettings.new
+ encryptor = mock("encryptor")
+ encryptor.expects(:encrypt_and_sign).with("synthetic-us-secret").returns("synthetic-ciphertext")
+ encryptor.expects(:encrypt_and_sign).with("synthetic-eu-secret").raises(StandardError, "synthetic-sensitive-details")
+ migration.stubs(:encryptor).returns(encryptor)
+
+ error = assert_raises(PromotePlaidSecretsToDeclaredSettings::ConversionError) { migration.up }
+
+ refute_includes error.message, "synthetic-sensitive-details"
+ assert_nil error.cause
+ assert_equal "synthetic-us-secret", Setting.find_by!(var: "dynamic:plaid_secret").value
+ assert_equal "synthetic-eu-secret", Setting.find_by!(var: "dynamic:plaid_eu_secret").value
+ assert_empty Setting.where(var: %w[plaid_secret plaid_eu_secret])
+ end
+
+ test "conversion does not log credential values or ciphertext" do
+ store_legacy("plaid_secret", "synthetic-sensitive-secret")
+ output = StringIO.new
+ original_logger = ActiveRecord::Base.logger
+ ActiveRecord::Base.logger = ActiveSupport::Logger.new(output)
+
+ run_migration
+
+ refute_includes output.string, "synthetic-sensitive-secret"
+ refute_includes output.string, Setting.find_by!(var: "plaid_secret").value
+ ensure
+ ActiveRecord::Base.logger = original_logger
+ end
+
+ test "conversion works without an Active Record logger" do
+ store_legacy("plaid_secret", "synthetic-secret")
+ original_logger = ActiveRecord::Base.logger
+ ActiveRecord::Base.logger = nil
+
+ run_migration
+
+ assert_equal "synthetic-secret", Setting.plaid_secret
+ assert_not Setting.exists?(var: "dynamic:plaid_secret")
+ ensure
+ ActiveRecord::Base.logger = original_logger
+ end
+
+ test "rollback cannot restore plaintext credentials" do
+ assert_raises(ActiveRecord::IrreversibleMigration) do
+ PromotePlaidSecretsToDeclaredSettings.new.down
+ end
+ end
+
+ private
+
+ def store_legacy(key, value)
+ Setting.create!(var: "dynamic:#{key}", value: value)
+ end
+
+ def run_migration
+ ActiveRecord::Migration.suppress_messages do
+ PromotePlaidSecretsToDeclaredSettings.new.migrate(:up)
+ end
+ end
+end
diff --git a/test/models/setting_test.rb b/test/models/setting_test.rb
index 96c720eb45..964860d0cc 100644
--- a/test/models/setting_test.rb
+++ b/test/models/setting_test.rb
@@ -249,6 +249,55 @@ class SettingTest < ActiveSupport::TestCase
Setting.securities_provider = original_provider.presence || "twelve_data"
end
+ test "Plaid secrets use declared encrypted settings through bracket and named accessors" do
+ %w[plaid_secret plaid_eu_secret].each do |key|
+ secret = "synthetic-#{key}"
+ Setting[key] = secret
+
+ stored = Setting.find_by!(var: key).value
+ refute_includes stored, secret
+ assert_equal secret, Setting[key]
+ assert_equal secret, Setting.public_send(key)
+ assert_not Setting.exists?(var: "dynamic:#{key}")
+
+ Setting.public_send("#{key}=", "replacement-secret")
+ assert_equal "replacement-secret", Setting[key]
+ Setting[key] = nil
+ assert_nil Setting[key]
+ end
+ end
+
+ test "Plaid provider configuration retains ENV fallback and stored-secret precedence" do
+ { Provider::PlaidAdapter => "PLAID_SECRET", Provider::PlaidEuAdapter => "PLAID_EU_SECRET" }.each do |adapter, env_key|
+ key = adapter.configuration.fields.find { |field| field.name == :secret }.setting_key
+ Setting[key] = nil
+
+ with_env_overrides(env_key => "synthetic-env-secret") do
+ assert_no_changes -> { Setting.find_by(var: key.to_s)&.value } do
+ assert_equal "synthetic-env-secret", adapter.config_value(:secret)
+ end
+
+ Setting[key] = "synthetic-stored-secret"
+ assert_equal "synthetic-stored-secret", adapter.config_value(:secret)
+
+ Setting[key] = nil
+ assert_equal "synthetic-env-secret", adapter.config_value(:secret)
+ end
+ end
+ end
+
+ test "Plaid declared settings retain the existing plaintext-read compatibility" do
+ %w[plaid_secret plaid_eu_secret].each do |key|
+ store_raw_setting(key, "synthetic-legacy-secret")
+
+ assert_equal "synthetic-legacy-secret", Setting[key]
+ assert_equal "synthetic-legacy-secret", Setting.find_by!(var: key).value
+
+ Setting[key] = Setting[key]
+ refute_includes Setting.find_by!(var: key).value, "synthetic-legacy-secret"
+ end
+ end
+
test "reencrypt_secrets_from moves values from the old key to the current key" do
old_secret_key_base = "old-secret-key-base-" + "a" * 64
store_raw_setting("openai_access_token", old_setting_encryptor(old_secret_key_base).encrypt_and_sign("sk-old-key"))