RSpec model test testing encrypted attribute randomly failing with "key_derivation_salt is not configured"

Viewed 195

I have a Rails 7.0.3 app with a model that has an encrypted attribute. I have an RSpec test which tests the model's behaviour. I have a GitHub Actions workflow setup running RSpec. However: every first run for a specific commit fails, every next run succeeds. As

The error:

ActiveRecord::Encryption::Errors::Configuration:
       key_derivation_salt is not configured. Please configure it via credential active_record_encryption.key_derivation_salt or by setting config.active_record.encryption.key_derivation_salt

The GitHub actions config (non-essential details left out for brevity):

name: CI
on: [push]
jobs:
  rspec:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v1
    - name: Set up Ruby
      uses: ruby/setup-ruby@v1
      with:
        ruby-version: ".ruby-version"
    - name: Bundle Install
      run: |
        gem install bundler -v $(grep 'BUNDLED WITH' -A1 Gemfile.lock | tail -n 1 )
        bundle config set --local path 'vendor/bundle'
        bundle install --jobs 4 --retry 3
    - env:
        RAILS_MASTER_KEY: "${{ secrets.RAILS_MASTER_KEY }}"
      run: RAILS_ENV=test bundle exec rspec

I have the secret setup in the repo configuration:

enter image description here

The necessary encryption configuration is stored in test.enc.yml:

active_record_encryption:
  primary_key: u▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉
  deterministic_key: 4▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉
  key_derivation_salt: R▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉

I really dislike the idea of using some flavour of RSpec retry/rerun gem to fix it. I'd really like to solve the underlying issue. Anybody any idea?

1 Answers

it looks more like a issue with loading your credentials in test environment. I've stumbled upon similar error today, but I don't want to pass RAILS_MASTER_KEY for test environment. What I did were adding this code to config/environments/test.rb file:

config.active_record.encryption.primary_key = 'test'
config.active_record.encryption.deterministic_key = 'test'
config.active_record.encryption.key_derivation_salt = 'test'

Unless you don't need an exteremly secure DB in a test environment this should do the job for you.

Related