parroty / exvcr

HTTP request/response recording library for elixir, inspired by VCR.
MIT License
724 stars 132 forks source link

Can't match json response bodies for removing sensitive data? #172

Closed addstar34 closed 3 years ago

addstar34 commented 3 years ago

I'm struggling to match a json response body. I want to match the key and replace its value. Example response body:

"{\"apiKey\":\"ROj7Jpxb1iERp5l3pxZYLiVOPCOIv_hQM4cGOTl4m-N2t\"}"

So ExVCR looks to do the following: String.replace(body, ~r/#{pattern}/, placeholder) and when calling filter_sensitive_data you have to pass the regex as a string. I think this is the problem because when I convert my regex to a string I have to escape the additional quotes which then doesn't match. See the following iex commands:

# Show the regex is correct and works
iex(51)> body = "{\"apiKey\":\"ROj7Jpxb1iERp5l3pxZYLiVOPCOIv_hQM4cGOTl4m-N2t\"}"
"{\"apiKey\":\"ROj7Jpxb1iERp5l3pxZYLiVOPCOIv_hQM4cGOTl4m-N2t\"}"
iex(52)> String.replace(body, ~r/apiKey":"[\w-]*/, "X")
"{\"X\"}"

# move regex into a variable by wrapping it in quotes fails due to inner quotes
iex(49)> pattern = "apiKey":"[\w-]*"
** (SyntaxError) iex:49:19: syntax error before: '[w-]*'

# escape the quotes
iex(49)> pattern = "apiKey\":\"[\w-]*"
"apiKey\":\"[w-]*"

# Replace using the pattern variable no longer works it should be the same as above and return "{\"X\"}"
iex(54)> String.replace(body, ~r/#{pattern}/, "X")
"{\"XROj7Jpxb1iERp5l3pxZYLiVOPCOIv_hQM4cGOTl4m-N2t\"}"
addstar34 commented 3 years ago

I had a mistake in my regex 🤦 although I do wonder if instead of passing a string passing the regex sigil might be a better api... all good though closing issue.