I have a rails project and I am using gem http_logger
and I need to mask sensitive information in the request headers and request body and response.
Rails.application.config.filter_parameters
do not work in this because because I make a request outside of rails request in a separate thread.
I need a way to replace "access_token" and "client_secret" within a string with [FILTERED]
Example strings:
Response body {"access_token":[FILTERED],"scope":"create:foo","expires_in":86400,"token_type":"Bearer"}
or
Request body {"client_id":"fn23uf32u9f34","client_secret":[FILTERED],"audience":"audience","grant_type":"client_credentials"}
I am fine having two separate regular expressions for both cases.
CodePudding user response:
You can use the regular expression:
rgx = /("(?:access_token|client_secret)":)"[^"] "/
in
str.sub(rgx, '\1[FILTERED]')
str = 'Response body {"access_token":"oigoi34oi34thj3489we89e2","scope":"create:foo","expires_in":86400,"token_type":"Bearer"}'
puts str.sub(rgx, '\1[FILTERED]')
displays
Response body {"access_token":[FILTERED],"scope":"create:foo","expires_in":86400,"token_type":"Bearer"}
str = 'Request body {"client_id":"fn23uf32u9f34","client_secret":"jibberish","audience":"audience","grant_type":"client_credentials"}'
puts str.sub(rgx, '\1[FILTERED]')
displays
Request body {"client_id":"fn23uf32u9f34","client_secret":[FILTERED],"audience":"audience","grant_type":"client_credentials"}
The regular expression can be broken down as follows.
( # begin capture group 1 \
" # match literal
(?: # begin non-capture group
access_token # match literal
| # or
client_secret # match literal
)
": # match literal
)
" # match literal
[^"] # match one or more characters other than
# double-quotes, as many as possible
" # match literal