Search code examples
pythonpython-3.xsentry

Sentry - scrubbing local variables sensitive data


I would like to scrub sensitive data from Python before I send it to Sentry

However, in method before_send and truncate_breadcrumb_message I am not sure where I can get the list of local variables and scrub them.

sentry_sdk.init(
    dsn=settings.get('SENTRY_DSN', ""),
    before_breadcrumb=truncate_breadcrumb_message,
    integrations=[FlaskIntegration()],
    before_send=sanitize_sentry_event,
)

def sanitize_sentry_event(event, hint):
    pass

def truncate_breadcrumb_message(crumb, hint):
    pass

def raise_execption(password):
    auth = 5
    raise Exception()

In the above method, I wouldn't want password and auth to be send to Sentry at all.

How can I do it?


Solution

  • event is a JSON payload that contains the same exact JSON you see in the "JSON" download in Sentry's UI. So you have a event like this:

    {
      "exception": {
        "values": [
          {
            "stacktrace": {
              "frames": [
                {"vars": ...}
              ]
            }
          }
        ]
      }
    }
    

    And you want to remove vars, you need to do this:

    def sanitize_sentry_event(event, hint):
        for exception in event.get("exception", {}).get("values", []):
            for frame in exception.get("stacktrace", {}).get("frames", []):
                frame.pop("vars", None)
    
        for exception in event.get("threads", {}).get("values", []):
            for frame in exception.get("stacktrace", {}).get("frames", []):
                frame.pop("vars", None)
    
    
        return event
    

    You probably want to wrap the entire function body with a try-except. If the function raises an exception the event is dropped. Make sure to test this using init(debug=True) to see all exceptions your before_send hook might throw