Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
16.7 KB
Raw Blame
# frozen_string_literal: true

require "test_helper"

class EncryptionVerificationTest < ActiveSupport::TestCase
  # Skip all tests in this file if encryption is not configured.
  # This allows the test suite to pass in environments without encryption keys.
  setup do
    skip "Encryption not configured" unless User.encryption_ready?
  end

  # ============================================================================
  # USER MODEL TESTS
  # ============================================================================

  test "user email is encrypted and can be looked up" do
    user = User.create!(
      email: "[email protected]",
      password: "password123",
      family: families(:dylan_family)
    )

    # Verify we can find by email (deterministic encryption)
    found = User.find_by(email: "[email protected]")
    assert_equal user.id, found.id

    # Verify case-insensitive lookup works
    found_upper = User.find_by(email: "[email protected]")
    assert_equal user.id, found_upper.id

    # Clean up
    user.destroy
  end

  test "user email uniqueness validation works with encryption" do
    user1 = User.create!(
      email: "[email protected]",
      password: "password123",
      family: families(:dylan_family)
    )

    # Should fail uniqueness
    user2 = User.new(
      email: "[email protected]",
      password: "password123",
      family: families(:dylan_family)
    )
    assert_not user2.valid?
    assert user2.errors[:email].any?

    user1.destroy
  end

  test "user names are encrypted and retrievable" do
    user = users(:family_admin)
    original_first = user.first_name
    original_last = user.last_name

    # Update names
    user.update!(first_name: "EncryptedFirst", last_name: "EncryptedLast")
    user.reload

    assert_equal "EncryptedFirst", user.first_name
    assert_equal "EncryptedLast", user.last_name

    # Restore
    user.update!(first_name: original_first, last_name: original_last)
  end

  test "user MFA otp_secret is encrypted" do
    user = users(:family_admin)

    # Setup MFA
    user.setup_mfa!
    assert user.otp_secret.present?

    # Reload and verify we can still read it
    user.reload
    assert user.otp_secret.present?

    # Verify provisioning URI works
    assert user.provisioning_uri.present?

    # Clean up
    user.disable_mfa!
  end

  test "user unconfirmed_email is encrypted" do
    user = users(:family_admin)
    original_email = user.email

    # Set unconfirmed email
    user.update!(unconfirmed_email: "[email protected]")
    user.reload

    assert_equal "[email protected]", user.unconfirmed_email

    # Clean up
    user.update!(unconfirmed_email: nil)
  end

  # ============================================================================
  # INVITATION MODEL TESTS
  # ============================================================================

  test "invitation token is encrypted and lookups work" do
    invitation = Invitation.create!(
      email: "[email protected]",
      role: "member",
      inviter: users(:family_admin),
      family: families(:dylan_family)
    )

    # Token should be present
    assert invitation.token.present?
    token_value = invitation.token

    # Should be able to find by token
    found = Invitation.find_by(token: token_value)
    assert_equal invitation.id, found.id

    invitation.destroy
  end

  test "invitation email is encrypted and scoped uniqueness works" do
    invitation1 = Invitation.create!(
      email: "[email protected]",
      role: "member",
      inviter: users(:family_admin),
      family: families(:dylan_family)
    )

    # Same email, same family should fail
    invitation2 = Invitation.new(
      email: "[email protected]",
      role: "member",
      inviter: users(:family_admin),
      family: families(:dylan_family)
    )
    assert_not invitation2.valid?

    invitation1.destroy
  end

  # ============================================================================
  # INVITE CODE MODEL TESTS
  # ============================================================================

  test "invite code token is encrypted and claim works" do
    token = InviteCode.generate!
    assert token.present?

    # Should be able to claim
    result = InviteCode.claim!(token)
    assert result

    # Should not be able to claim again (destroyed)
    result2 = InviteCode.claim!(token)
    assert_nil result2
  end

  test "invite code case-insensitive lookup works" do
    invite_code = InviteCode.create!
    token = invite_code.token

    # Should find with lowercase
    found = InviteCode.find_by(token: token.downcase)
    assert_equal invite_code.id, found.id

    invite_code.destroy
  end

  # ============================================================================
  # SESSION MODEL TESTS
  # ============================================================================

  test "session user_agent is encrypted" do
    Current.user_agent = "Mozilla/5.0 Test Browser"
    Current.ip_address = "192.168.1.100"

    begin
      session = Session.create!(user: users(:family_admin))

      assert_equal "Mozilla/5.0 Test Browser", session.user_agent
      assert session.ip_address_digest.present?

      # Reload and verify
      session.reload
      assert_equal "Mozilla/5.0 Test Browser", session.user_agent

      # Verify IP hash is consistent
      expected_hash = Digest::SHA256.hexdigest("192.168.1.100")
      assert_equal expected_hash, session.ip_address_digest

      session.destroy
    ensure
      Current.user_agent = nil
      Current.ip_address = nil
    end
  end

  # ============================================================================
  # SECURITY AUDIT LOG MODEL TESTS
  # ============================================================================

  test "security audit log user_email, ip_address and user_agent are encrypted at rest" do
    request = ActionDispatch::TestRequest.create
    request.remote_addr = "203.0.113.5"
    request.user_agent = "EncryptionVerification/1.0"

    log = SecurityAuditLog.log_mfa_enabled!(user: users(:family_admin), request: request)

    assert_equal users(:family_admin).email, log.user_email
    assert_equal "203.0.113.5", log.ip_address
    assert_equal "EncryptionVerification/1.0", log.user_agent

    raw_email = log.read_attribute_before_type_cast(:user_email).to_s
    raw_ip = log.read_attribute_before_type_cast(:ip_address).to_s
    raw_agent = log.read_attribute_before_type_cast(:user_agent).to_s
    assert_not_includes raw_email, users(:family_admin).email
    assert_not_includes raw_ip, "203.0.113.5"
    assert_not_includes raw_agent, "EncryptionVerification/1.0"

    log.reload
    assert_equal users(:family_admin).email, log.user_email
    assert_equal "203.0.113.5", log.ip_address
    assert_equal "EncryptionVerification/1.0", log.user_agent
  end

  # ============================================================================
  # MOBILE DEVICE MODEL TESTS
  # ============================================================================

  test "mobile device device_id is encrypted and uniqueness works" do
    device = MobileDevice.create!(
      user: users(:family_admin),
      device_id: "test-device-12345",
      device_name: "Test iPhone",
      device_type: "ios"
    )

    # Should be able to find by device_id
    found = MobileDevice.find_by(device_id: "test-device-12345", user: users(:family_admin))
    assert_equal device.id, found.id

    # Same device_id for same user should fail
    device2 = MobileDevice.new(
      user: users(:family_admin),
      device_id: "test-device-12345",
      device_name: "Another iPhone",
      device_type: "ios"
    )
    assert_not device2.valid?

    # Same device_id for different user should work
    device3 = MobileDevice.new(
      user: users(:family_member),
      device_id: "test-device-12345",
      device_name: "Their iPhone",
      device_type: "ios"
    )
    assert device3.valid?

    device.destroy
  end

  # ============================================================================
  # PROVIDER ITEM TESTS (if fixtures exist)
  # ============================================================================

  test "lunchflow item credentials and payloads are encrypted" do
    skip "No lunchflow items in fixtures" unless LunchflowItem.any?

    item = LunchflowItem.first
    original_payload = item.raw_payload

    # Should be able to read
    assert item.api_key.present? || item.raw_payload.present?

    # Update payload
    item.update!(raw_payload: { test: "data" })
    item.reload

    assert_equal({ "test" => "data" }, item.raw_payload)

    # Restore
    item.update!(raw_payload: original_payload)
  end

  test "lunchflow account payloads are encrypted" do
    skip "No lunchflow accounts in fixtures" unless LunchflowAccount.any?

    account = LunchflowAccount.first
    original_payload = account.raw_payload

    # Should be able to read encrypted fields without error
    account.reload
    assert_nothing_raised { account.raw_payload }
    assert_nothing_raised { account.raw_transactions_payload }

    # Update and verify
    account.update!(raw_payload: { account_test: "value" })
    account.reload

    assert_equal({ "account_test" => "value" }, account.raw_payload)

    # Restore
    account.update!(raw_payload: original_payload)
  end

  test "redbark item credentials and payloads are encrypted" do
    skip "No redbark items in fixtures" unless RedbarkItem.any?

    item = RedbarkItem.first
    original_payload = item.raw_payload

    # Should be able to read
    assert item.api_key.present? || item.raw_payload.present?

    # Update payload
    item.update!(raw_payload: { test: "data" })
    item.reload

    assert_equal({ "test" => "data" }, item.raw_payload)

    # Restore
    item.update!(raw_payload: original_payload)
  end

  test "redbark account payloads are encrypted" do
    skip "No redbark accounts in fixtures" unless RedbarkAccount.any?

    account = RedbarkAccount.first
    original_payload = account.raw_payload

    # Should be able to read encrypted fields without error
    account.reload
    assert_nothing_raised { account.raw_payload }
    assert_nothing_raised { account.raw_transactions_payload }

    # Update and verify
    account.update!(raw_payload: { account_test: "value" })
    account.reload

    assert_equal({ "account_test" => "value" }, account.raw_payload)

    # Restore
    account.update!(raw_payload: original_payload)
  end

  test "monobank item credentials and payloads are encrypted" do
    skip "No monobank items in fixtures" unless MonobankItem.any?

    item = MonobankItem.first
    item.update!(access_token: "mono-token-plaintext-probe", raw_payload: { test: "data" })
    item.reload

    # The accessor round-trips...
    assert_equal "mono-token-plaintext-probe", item.access_token
    assert_equal({ "test" => "data" }, item.raw_payload)

    # ...but the column must not hold the value verbatim. Without this the assertions
    # above pass just as happily against plaintext columns.
    assert_column_not_plaintext(MonobankItem, item.id, :access_token, "mono-token-plaintext-probe")
    assert_column_not_plaintext(MonobankItem, item.id, :raw_payload, "test")
  end

  test "monobank account payloads are encrypted" do
    skip "No monobank accounts in fixtures" unless MonobankAccount.any?

    account = MonobankAccount.first
    account.update!(
      raw_payload: { account_test: "value" },
      raw_transactions_payload: [ { id: "tx_probe" } ]
    )
    account.reload

    assert_equal({ "account_test" => "value" }, account.raw_payload)

    assert_column_not_plaintext(MonobankAccount, account.id, :raw_payload, "account_test")
    assert_column_not_plaintext(MonobankAccount, account.id, :raw_transactions_payload, "tx_probe")
  end

  test "snaptrade account_number is encrypted" do
    skip "No snaptrade accounts in fixtures" unless SnaptradeAccount.any?

    account = SnaptradeAccount.first
    account.update!(account_number: "9988776655")
    account.reload

    assert_equal "9988776655", account.account_number

    # A brokerage account number is exactly the kind of field worth proving opaque.
    assert_column_not_plaintext(SnaptradeAccount, account.id, :account_number, "9988776655")
  end

  test "plaid account holdings stored before encryption was enabled can be read and backfilled" do
    account = PlaidAccount.create!(
      plaid_item: plaid_items(:one),
      plaid_id: "holdings_backfill_probe",
      name: "Brokerage",
      plaid_type: "investment",
      currency: "USD",
      current_balance: 1000
    )
    # Store plaintext, as an instance that enabled encryption after syncing would have.
    PlaidAccount.where(id: account.id).update_all(
      "raw_holdings_payload = '{\"holdings\": [{\"security_id\": \"sec_probe\"}]}'::jsonb"
    )

    with_unencrypted_data_supported do
      account = PlaidAccount.find(account.id)
      assert_equal "sec_probe", account.raw_holdings_payload["holdings"].first["security_id"]

      account.encrypt
    end

    assert_equal "sec_probe", account.reload.raw_holdings_payload["holdings"].first["security_id"]
    assert_column_not_plaintext(PlaidAccount, account.id, :raw_holdings_payload, "sec_probe")
  end

  test "provider account identifiers are encrypted at rest" do
    family = families(:dylan_family)

    eb_item = EnableBankingItem.create!(
      family: family, name: "EB probe", country_code: "FI", application_id: "app", client_certificate: "cert",
      last_psu_ip: "203.0.113.42"
    )
    akahu_account = AkahuAccount.create!(
      akahu_item: AkahuItem.create!(family: family, name: "Akahu probe", app_token: "app", user_token: "user"),
      name: "Everyday", account_id: "acc_probe", currency: "NZD", formatted_account: "12-3456-7654321-00"
    )
    lunchflow_account = lunchflow_items(:one).lunchflow_accounts.create!(
      name: "Brokerage", currency: "GBP", account_id: "holdings-probe",
      raw_holdings_payload: [ { "symbol" => "HOLDPROBE" } ]
    )

    assert_equal "203.0.113.42", eb_item.reload.last_psu_ip
    assert_equal "12-3456-7654321-00", akahu_account.reload.formatted_account
    assert_equal "HOLDPROBE", lunchflow_account.reload.raw_holdings_payload.first["symbol"]

    assert_column_not_plaintext(EnableBankingItem, eb_item.id, :last_psu_ip, "203.0.113.42")
    assert_column_not_plaintext(AkahuAccount, akahu_account.id, :formatted_account, "7654321")
    assert_column_not_plaintext(LunchflowAccount, lunchflow_account.id, :raw_holdings_payload, "HOLDPROBE")
  end

  test "provider identifiers stored before encryption stay readable" do
    eb_item = EnableBankingItem.create!(
      family: families(:dylan_family), name: "EB legacy", country_code: "FI", application_id: "app", client_certificate: "cert"
    )
    EnableBankingItem.where(id: eb_item.id).update_all("last_psu_ip = '203.0.113.50'")

    # The global setting can be on during the backfill window, so turn it off
    # here: the attribute's own option must cover the legacy value by itself.
    with_unencrypted_data_supported(false) do
      assert_equal "203.0.113.50", eb_item.reload.last_psu_ip
    end
  end

  # ============================================================================
  # DATABASE VERIFICATION TESTS
  # ============================================================================

  test "encrypted fields are not stored as plaintext in database" do
    user = User.create!(
      email: "[email protected]",
      password: "password123",
      first_name: "PlaintextFirst",
      last_name: "PlaintextLast",
      family: families(:dylan_family)
    )

    # Query raw database value
    raw_email = ActiveRecord::Base.connection.select_value(
      User.where(id: user.id).select(:email).to_sql
    )

    # Should NOT be plaintext (should be encrypted blob or different)
    assert_not_equal "[email protected]", raw_email,
      "Email should be encrypted in database, not stored as plaintext"

    user.destroy
  end

  private

    def with_unencrypted_data_supported(enabled = true)
      previous = ActiveRecord::Encryption.config.support_unencrypted_data
      ActiveRecord::Encryption.config.support_unencrypted_data = enabled
      yield
    ensure
      ActiveRecord::Encryption.config.support_unencrypted_data = previous
    end

    # Reads +column+ straight from the database, bypassing the model, and asserts the
    # stored bytes do not contain +value+. An accessor round-trip alone cannot tell
    # encryption from plaintext; this can.
    def assert_column_not_plaintext(model, id, column, value)
      raw = ActiveRecord::Base.connection.select_value(
        model.where(id: id).select(column).to_sql
      )

      assert raw.present?, "expected #{model}##{column} to be stored"
      assert_not_includes raw.to_s, value,
        "#{model}##{column} should be encrypted at rest, but the raw column contains #{value.inspect}"
    end
end