Skip to content

Commit

Permalink
feat: Sanitize proxy credentials
Browse files Browse the repository at this point in the history
Closes: SDK-2823
  • Loading branch information
lukaszsocha2 committed Dec 21, 2022
1 parent 8d218c3 commit 44c82cf
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
18 changes: 17 additions & 1 deletion boxsdk/util/log.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import logging
import re
import sys

from collections.abc import Mapping
Expand All @@ -25,6 +26,11 @@ class Logging:
'password',
)

PROXY_KEYS_TO_SANITIZE = (
'http',
'https',
)

def setup_logging(self, stream_or_file=_no_logger, debug=False, name=None):
if not self._has_setup:
self._has_setup = True
Expand All @@ -43,13 +49,23 @@ def _setup_logging(stream_or_file=_no_logger, debug=False, name=None):
def sanitize_value(value):
return f'---{value[-4:]}'

def sanitize_dictionary(self, dictionary):
@staticmethod
def sanitize_proxy_value(value: str) -> str:
return re.sub(
'^(.*://)(.*):(.*)(@.*)$',
lambda repl: f'{repl.group(1)}{Logging.sanitize_value(repl.group(2))}:{Logging.sanitize_value(repl.group(3))}{repl.group(4)}',
value
)

def sanitize_dictionary(self, dictionary: Mapping) -> Mapping:
if not isinstance(dictionary, Mapping):
return dictionary
sanitized_dictionary = {}
for key, value in dictionary.items():
if key in self.KEYS_TO_SANITIZE and isinstance(value, str):
sanitized_dictionary[key] = self.sanitize_value(value)
elif key in self.PROXY_KEYS_TO_SANITIZE and isinstance(value, str):
sanitized_dictionary[key] = self.sanitize_proxy_value(value)
elif isinstance(value, Mapping):
sanitized_dictionary[key] = self.sanitize_dictionary(value)
else:
Expand Down
10 changes: 10 additions & 0 deletions test/unit/util/test_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,16 @@ def test_setup_logging_is_reentrant(mock_logger):
{'download_url': None},
{'download_url': None},
),
# Test for proxy http
(
{'http': 'http://username:password@localhost:8080'},
{'http': 'http://---name:---word@localhost:8080'},
),
# Test for proxy https
(
{'https': 'http://username:password@localhost:8080'},
{'https': 'http://---name:---word@localhost:8080'},
),
]
)
def test_sanitize_dictionary_correctly_sanitizes_params(mock_logger, unsanitized_dict, expected_result):
Expand Down

0 comments on commit 44c82cf

Please sign in to comment.