Debian Codegraph @

ibm_cloud_sdk_core/logger.py

raw
1 # coding: utf-8
2
3 # Copyright 2024 IBM All Rights Reserved.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 import logging
18 import re
19
20
21 # This is the name of the primary logger used by the library.
22 LOGGER_NAME = 'ibm-cloud-sdk-core'
23 # Keywords that are redacted.
24 REDACTED_KEYWORDS = [
25 "apikey",
26 "api_key",
27 "passcode",
28 "password",
29 "token",
30 "aadClientId",
31 "aadClientSecret",
32 "auth",
33 "auth_provider_x509_cert_url",
34 "auth_uri",
35 "client_email",
36 "client_id",
37 "client_x509_cert_url",
38 "key",
39 "project_id",
40 "secret",
41 "subscriptionId",
42 "tenantId",
43 "thumbprint",
44 "token_uri",
45 ]
46
47
48 class LoggingFilter:
49 """Functions used to filter messages before they are logged."""
50
51 redacted_tokens = "|".join(REDACTED_KEYWORDS)
52 auth_header_pattern = re.compile(r"(?m)(Authorization|X-Auth\S*): ((.*?)(\r\n.*)|(.*))")
53 property_settings_pattern = re.compile(r"(?i)(" + redacted_tokens + r")=[^&]*(&|$)")
54 json_field_pattern = re.compile(r'(?i)"([^"]*(' + redacted_tokens + r')[^"_]*)":\s*"[^\,]*"')
55
56 @classmethod
57 def redact_secrets(cls, text: str) -> str:
58 """Replaces values of potential secret keywords with a placeholder value.
59 Args:
60 text (str): the string to check and process
61
62 Returns:
63 str: the safe, redacted string with all secrets masked out
64 """
65
66 placeholder = "[redacted]"
67 redacted = cls.auth_header_pattern.sub(r"\1: " + placeholder + r"\4", text)
68 redacted = cls.property_settings_pattern.sub(r"\1=" + placeholder + r"\2", redacted)
69 redacted = cls.json_field_pattern.sub(r'"\1":"' + placeholder + r'"', redacted)
70 return redacted
71
72 @classmethod
73 def filter_message(cls, s: str) -> str:
74 """Filters 's' prior to logging it as a debug message"""
75 # Redact secrets
76 s = LoggingFilter.redact_secrets(s)
77
78 # Replace CRLF characters with an actual newline to make the message more readable.
79 s = s.replace('\\r\\n', '\n')
80 return s
81
82
83 def get_logger() -> logging.Logger:
84 """Returns the primary logger object instance used by the library."""
85 return logging.getLogger(LOGGER_NAME)