house9
house9

Reputation: 20624

Replace sensitive data in VCR gem cassettes request body

I am able to remove sensitive headers using filter_sensitive_data but it does not seem to be working for replacing sensitive data in the request body.

VCR configuration

VCR.configure do |config|
  config.cassette_library_dir = 'spec/vcr'
  config.hook_into :webmock
  config.configure_rspec_metadata!
  # this does not work for request body
  config.filter_sensitive_data('<PASSWORD-REDACTED>') do
    ENV['PASSWORD']
  end
  # this works for headers
  config.filter_sensitive_data('<Authorization-REDACTED>') do |interaction|
    interaction.request.headers['Authorization'].try(:first)
  end
end

Run spec

PASSWORD=secret bin/rspec spec/my_spec.rb

Cassette

Recording contains password=secret in the request body

but should be password=PASSWORD-REDACTED

---
http_interactions:
- request:
    method: post
    uri: https://xxxx
    body:
      encoding: US-ASCII
      string: username=somebody%40example.com&password=secret
    headers:
      Accept:
      - application/json
      Content-Type:
      - application/x-www-form-urlencoded
      User-Agent:
      - Faraday v2.2.0
      Accept-Encoding:
      - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
  response:
    status:
      code: 200
      message: OK
    headers:
    ...

Upvotes: 2

Views: 1183

Answers (2)

cilantro
cilantro

Reputation: 550

An unconventional out of the box solution is to simply let VCR record your request and later on editing it manually. I tried this and works as expected. The reason why I did this is because the string I'm trying to replace changes with every request.

Upvotes: 0

channa ly
channa ly

Reputation: 9937

It works well for me. You might need to check the values returned by the filter_sensitive_data block as indicated here https://relishapp.com/vcr/vcr/v/1-10-1/docs/configuration/filter-sensitive-data

A substitution string. This is the string that will be written to the cassette file as a placeholder. It should be unique and you may want to wrap it in special characters like { } or < >.

Make sure the string returned by the block are unique.

In your case, I would inspect the value of ENV['PASSWORD'] and
interaction.request.headers['Authorization'].try(:first) if they are correctly returned.

Upvotes: 1

Related Questions