Removing sensitive informations from the logs using regex

143 Views Asked by At

In my Ruby app I have the following regex that helps me with removing sensitive informations from logs:

/(\\"|")secure[^:]+:\s*\1.*?\1/

It works when in logs are the following information:

{"secure_data": "Test"}

but when instead of string I have object in logs it does not work:

{"secure_data": {"name": "Test"}}

How can I update regex to work with both scenarios?

https://rubular.com/r/h9EBZot1e7NUkS

2

There are 2 best solutions below

0
anubhava On BEST ANSWER

You may use this regex with negated character classes and an alternation:

"secure[^:]+:\s*(?:"[^"]*"|{[^}]*})

Inside non-capturing group (?:"[^"]*"|{[^}]*}) we are matching a quoted string or an object that starts with { and ends with }.

Update RegEx Demo

0
Harm van der Wal On

The following should work for what you're trying to do. I'd suggest using a json parser though.

{"secure[^:]*?:\s({?(?:(?:,[^"]*?)?"[^"]*?"(?::\s"[^"]*?")?)*?)*?}?}

With this regex the object in secure_data may also contain multiple key-value(string)-pairs. It will still match. Other objects will not.