Language: Python
Label: safe
CWE: CWE-532 \u2014 Insertion of Sensitive Information into Log File
Information written to log files can be of a sensitive nature and give valuable guidance to an attacker or expose sensitive user information.

Code:
def redact_sensitive_keys(metadata, redact_value=REDACT_SENSITIVE_VALUE):
    """Redact any sensitive keys from to provided metadata dictionary.

    Replace any keys values listed in 'sensitive_keys' with redact_value.
    """
    # While 'sensitive_keys' should already sanitized to only include what
    # is in metadata, it is possible keys will overlap. For example, if
    # "merged_cfg" and "merged_cfg/ds/userdata" both match, it's possible that
    # "merged_cfg" will get replaced first, meaning "merged_cfg/ds/userdata"
    # no longer represents a valid key.
    # Thus, we still need to do membership checks in this function.
    if not metadata.get("sensitive_keys", []):
        return metadata
    md_copy = copy.deepcopy(metadata)
    for key_path in metadata.get("sensitive_keys"):
        path_parts = key_path.split("/")
        obj = md_copy
        for path in path_parts:
            if (
                path in obj
                and isinstance(obj[path], dict)
                and path != path_parts[-1]
            ):
                obj = obj[path]
        if path in obj:
            obj[path] = redact_value
    return md_copy