Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
12.0 KB
Raw Blame
# 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.
  #
  # During a key rotation (docs/hosting/encryption.md) the write pass also
  # re-encrypts existing ciphertext under the current key, deterministic
  # attributes included (see current_key_ciphertexts).
  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"
    raw_dry = args[:dry_run].presence || ENV["DRY_RUN"].presence

    batch_size = raw_batch.to_i
    batch_size = 100 if batch_size <= 0

    dry_run = case raw_dry.to_s.strip.downcase
    when "0", "false", "no", "n" then false
    when "1", "true", "yes", "y" then true
    else
      true # Default to dry run for safety
    end

    # Check encryption configuration (use User model which includes Encryptable)
    unless User.encryption_ready?
      puts({
        ok: false,
        error: "encryption_not_configured",
        message: "ActiveRecord encryption is not configured. Set credentials or environment variables."
      }.to_json)
      exit 1
    end

    # Invalidate any previous completion flag before this run starts (not just
    # on failure at the end): if a prior run already completed successfully
    # and this run then fails or aborts partway through, leaving the old flag
    # in place would let ActiveRecordEncryptionConfig.backfill_completed?
    # report "complete" while this run's still-plaintext rows are unencrypted.
    Setting.encryption_backfill_completed_version = nil unless dry_run

    results = {}
    puts "Starting security backfill (dry_run: #{dry_run}, batch_size: #{batch_size})..."

    # Field lists live in ActiveRecordEncryptionConfig::BACKFILL_MANIFEST
    # (lib/active_record_encryption_config.rb), kept in sync with each model's
    # `encrypts` declarations by test/lib/tasks/security_backfill_test.rb.
    ActiveRecordEncryptionConfig::BACKFILL_MANIFEST.each do |key, (model_class_name, fields)|
      results[key] = backfill_model(model_class_name.constantize, fields, batch_size, dry_run)
    end

    results[:sessions] = backfill_model(Session, Session.encrypted_attributes.to_a, batch_size, dry_run)
    results[:session_ip_digests] = backfill_session_ip_digests(batch_size, dry_run)

    all_succeeded = results.values.all? { |r| r[:failed_count].zero? }

    # Only mark the backfill complete on a clean, non-dry-run pass: a partial
    # failure leaves some rows still plaintext, and flipping the flag would
    # disable the legacy-plaintext fallback (config/initializers/
    # active_record_encryption.rb) for models that still need it, turning a
    # readable row into a boot-time ActiveRecord::Encryption::Errors::Decryption.
    if !dry_run && all_succeeded
      Setting.encryption_backfill_completed_version = ActiveRecordEncryptionConfig::CURRENT_BACKFILL_VERSION
    end

    # A row that fails here stays unreadable once the app runs with the keys,
    # so any failure makes the whole run fail.
    failed_count = results.values.sum { |result| result[:failed_count] }
    puts({
      ok: failed_count.zero?,
      dry_run: dry_run,
      batch_size: batch_size,
      failed_count: failed_count,
      results: results
    }.to_json)
    exit 1 unless failed_count.zero?
  end

  def backfill_model(model_class, fields, batch_size, dry_run, &filter_block)
    processed = 0
    updated = 0
    failed = []

    model_class.order(:id).in_batches(of: batch_size) do |batch|
      batch.each do |record|
        processed += 1

        # 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).
        # 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? }

        if dry_run
          # Report the rows the real run would refuse, so the preview shows them.
          refused = fields.find { |f| undecryptable_ciphertext?(safe_read_field(record, f)) }
          failed << { id: record.id, error: ActiveRecord::Encryption::Errors::Decryption.name, message: "#{refused} holds ciphertext that no configured key decrypts" } if refused
          next
        end

        begin
          # Read and write under a row lock: an app write between the read
          # and update_columns (a new last_psu_ip, or DataCleanerJob clearing
          # it) would otherwise be overwritten with the stale value.
          written = record.with_lock do
            # Read plaintext values safely
            plaintext_values = {}
            fields.each do |field|
              value = safe_read_field(record, field)
              # Ciphertext that no configured key decrypts comes back as its
              # raw envelope (a Hash on json/jsonb columns); encrypting it
              # again would lose the original value for good.
              if undecryptable_ciphertext?(value)
                raise ActiveRecord::Encryption::Errors::Decryption, "#{field} holds ciphertext that no configured key decrypts"
              end
              plaintext_values[field] = value unless value.nil?
            end

            next false if plaintext_values.empty?

            # Use a temporary instance to encrypt values (avoids triggering
            # validations/callbacks that might read other encrypted fields)
            encryptor = model_class.new
            plaintext_values.each do |field, value|
              encryptor.send("#{field}=", value)
            end

            # During a key rotation Rails would write deterministic fields
            # under the oldest key, so those get current-key ciphertext.
            rotated = current_key_ciphertexts(encryptor, plaintext_values.keys)

            # Extract the encrypted values from the temporary instance
            encrypted_attrs = {}
            (plaintext_values.keys - rotated.keys).each do |field|
              encrypted_attrs[field] = encryptor.read_attribute_before_type_cast(field)
            end

            # Write directly to database, bypassing callbacks/validations
            record.update_columns(encrypted_attrs) if encrypted_attrs.any?
            write_raw_columns(record, rotated) if rotated.any?
            true
          end
          updated += 1 if written
        rescue ActiveRecord::RecordNotFound
          # Deleted since the batch was loaded; nothing left to encrypt.
          next
        rescue => e
          failed << { id: record.id, error: e.class.name, message: e.message }
        end
      end
    end

    {
      processed: processed,
      updated: updated,
      failed_count: failed.size,
      failed_samples: failed.take(3)
    }
  end

  # While `previous` schemes are configured (a key rotation), Rails encrypts
  # deterministic attributes with the OLDEST scheme so equality lookups keep
  # matching. Re-encrypting that way would leave the data under the key
  # being rotated out, so build ciphertext with the current scheme instead,
  # the same way EncryptedAttributeType does when no previous scheme exists.
  def current_key_ciphertexts(instance, fields)
    fields.each_with_object({}) do |field, ciphertexts|
      type = backfill_encrypted_type(instance.class, field)
      next unless type.fixed? && type.previous_schemes.any?

      value = type.cast_type.serialize(instance.read_attribute(field))
      next if value.nil?

      value = value.downcase if type.downcase?
      ciphertexts[field] = type.with_context do
        ActiveRecord::Encryption.encryptor.encrypt(
          value.to_s, **{ key_provider: type.key_provider, cipher_options: { deterministic: true } }.compact
        )
      end
    end
  end

  # `normalizes` wraps the encrypted type, so unwrap to reach it.
  def backfill_encrypted_type(model_class, field)
    type = model_class.type_for_attribute(field)
    type = type.cast_type while !type.is_a?(ActiveRecord::Encryption::EncryptedAttributeType) && type.respond_to?(:cast_type)
    return type if type.is_a?(ActiveRecord::Encryption::EncryptedAttributeType)

    raise ArgumentError, "#{model_class.name}##{field} is not an encrypted attribute"
  end

  # Raw SQL so the attribute type does not encrypt the ciphertext again.
  def write_raw_columns(record, values)
    connection = record.class.connection
    assignments = values.keys.map { |field| "#{connection.quote_column_name(field)} = ?" }.join(", ")
    record.class.where(id: record.id).update_all([ assignments, *values.values ])
  end

  # Rails' encryption envelope: {"p": payload, "h": {"iv": ..., "at": ..., ...}}.
  # Matches the whole shape, since Encryptor#encrypted? accepts any object
  # with a "p" key and would flag plaintext payloads such as {"p": null}.
  def undecryptable_ciphertext?(value)
    envelope = value
    if value.is_a?(String)
      return false unless value.start_with?("{")

      envelope = begin
        JSON.parse(value)
      rescue JSON::ParserError
        return false
      end
    end

    envelope.is_a?(Hash) && envelope.keys.sort == %w[h p] && envelope["p"].is_a?(String) &&
      envelope["h"].is_a?(Hash) && envelope["h"].key?("iv") && envelope["h"].key?("at")
  end

  # 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. 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::Base, NoMethodError, TypeError
    # Rails reads any json/jsonb object with a "p" key as an encryption
    # envelope, so plaintext like {"p": 1, "h": "x"} can fail with
    # NoMethodError or TypeError instead of a Decryption error.
    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

  # Hashes legacy session IP addresses into ip_address_digest. The encrypted
  # Session columns go through backfill_model like every other model.
  def backfill_session_ip_digests(batch_size, dry_run)
    processed = 0
    updated = 0
    failed = []

    Session.where.not(ip_address: [ nil, "" ]).where(ip_address_digest: [ nil, "" ])
      .select(:id, :ip_address, :ip_address_digest).order(:id).in_batches(of: batch_size) do |batch|
      batch.each do |session|
        processed += 1
        next if dry_run

        begin
          session.update_columns(ip_address_digest: Digest::SHA256.hexdigest(session.ip_address.to_s))
          updated += 1
        rescue => e
          failed << { id: session.id, error: e.class.name, message: e.message }
        end
      end
    end

    {
      processed: processed,
      updated: updated,
      failed_count: failed.size,
      failed_samples: failed.take(3)
    }
  end
end