vishalanandl177 / DRF-API-Logger

An API Logger for your Django Rest Framework project.
https://github.com/vishalanandl177/DRF-API-Logger
Apache License 2.0
303 stars 57 forks source link

Function mask_sensitive_data doesn't cover list of dicts #84

Closed dianaboiangiu closed 10 months ago

dianaboiangiu commented 10 months ago

In the case of the following response, sensitive values are not removed:

[
{
  "key1": "value",
  "key2": "value"
},
{
  "key1": "value",
  "key2": "value",
}
]

I checked the code and saw that mask_sensitive_data doesn't cover the case in which data is of type list. I added the modified code below, please consider including it in a future release :)

def mask_sensitive_data(data, mask_api_parameters=False):
    """
    Hides sensitive keys specified in sensitive_keys settings.
    Loops recursively over nested dictionaries.

    When the mask_api_parameters parameter is set, the function will 
    instead iterate over sensitive_keys and remove them from an api 
    URL string.
    """
    if type(data) != dict:
        if mask_api_parameters and type(data) == str:
            for sensitive_key in SENSITIVE_KEYS:
                data = re.sub('({}=)(.*?)($|&)'.format(sensitive_key), '\g<1>***FILTERED***\g<3>'.format(sensitive_key.upper()), data)
        # new code
        if type(data) == list:
            data = [mask_sensitive_data(item) for item in data]
        return data
    for key, value in data.items():
        if key in SENSITIVE_KEYS:
            data[key] = "***FILTERED***"

        if type(value) == dict:
            data[key] = mask_sensitive_data(data[key])

        if type(value) == list:
            data[key] = [mask_sensitive_data(item) for item in data[key]]

    return data
vishalanandl177 commented 10 months ago

Hi @dianaboiangiu Please raise as a pull request. I'll merge and release the new version.

vishalanandl177 commented 10 months ago

Fixes are available on version 1.1.15.