-
-
Notifications
You must be signed in to change notification settings - Fork 424
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Adds logger filter for TOKENS when logging in DEBUG MODE #539
Draft
jtroussard
wants to merge
9
commits into
master
Choose a base branch
from
536-access-tokens-leaked-in-logs-when-using-debug-level
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+119
−4
Draft
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
e0e20cd
532: adds a logger filter for tokens in debug mode
f350642
532: updates authorship file
103d28c
532: fixes logic so filter checks the logger record level, updates tests
a77b392
532: moves the logger warning to the requests initializer, updates tests
577a085
536: updatea regex for log filter
54676d1
Merge branch 'master' into 536-access-tokens-leaked-in-logs-when-usin…
33d5bb5
updates env var name, improve SUPRESSED scope implementation, black f…
6b8f87c
updates unit tests, pending one last test to assert warning message i…
jtroussard 5a6e94a
updates README with correct env var and makes headers render properly
jtroussard File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -25,3 +25,5 @@ Maintainers & Contributors | |
- Sylvain Marie <[email protected]> | ||
- Craig Anderson <[email protected]> | ||
- Hugo van Kemenade <https://github.com/hugovk> | ||
- Jacques Troussard <https://github.com/jtroussard> | ||
- Erland Vollset <https://github.com/erlendvollset> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
import os | ||
import re | ||
import logging | ||
|
||
|
||
class DebugModeTokenFilter(logging.Filter): | ||
""" | ||
A logging filter that while in DEBUG mode can filter TOKENS dependent on configuration. | ||
|
||
This filter uses an environment variable to determine its mode, | ||
which can either mask sensitive tokens in log messages, suppress logging, | ||
or default to standard logging behavior with a warning. | ||
|
||
Attributes: | ||
mode (str): The mode of operation based on the environment variable | ||
'DEBUG_MODE_TOKEN_FILTER'. Can be 'MASK', 'SUPPRESS', or 'DEFAULT'. | ||
""" | ||
|
||
def __init__(self): | ||
""" | ||
Initializes the DebugModeTokenFilter with the 'DEBUG_MODE_TOKEN_FILTER' | ||
environment variable. | ||
""" | ||
super().__init__() | ||
self.mode = os.getenv( | ||
'REQUESTS_OAUTHLIB_DEBUG_MODE_TOKEN_FILTER', 'DEFAULT').upper() | ||
|
||
def filter(self, record): | ||
""" | ||
Filters logs of TOKENS dependent on the configured mode. | ||
|
||
Args: | ||
record (logging.LogRecord): The log record to filter. | ||
|
||
Returns: | ||
bool: True if the record should be logged, False otherwise. | ||
""" | ||
if record.levelno == logging.DEBUG: | ||
if self.mode == "MASK": | ||
record.msg = re.sub( | ||
r'Bearer\s+([A-Za-z0-9\-._~+\/]+)', '[MASKED]', record.getMessage()) | ||
elif self.mode == "SUPPRESS": | ||
record.msg = " " | ||
else: | ||
return False | ||
return True # if mode is not MASKED then DEFAULT is implied |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
import unittest | ||
from unittest.mock import patch | ||
import logging | ||
from requests_oauthlib.log_filters import DebugModeTokenFilter | ||
|
||
class TestDebugModeTokenFilter(unittest.TestCase): | ||
|
||
def setUp(self): | ||
self.record = logging.LogRecord(name="test", level=logging.DEBUG, pathname=None, lineno=None, msg="Bearer i-am-a-little-token-here-is-my-scope-and-here-is-my-hash", args=None, exc_info=None) | ||
|
||
@patch.dict('os.environ', {'REQUESTS_OAUTHLIB_DEBUG_MODE_TOKEN_FILTER': 'MASK'}) | ||
def test_mask_mode(self): | ||
filter = DebugModeTokenFilter() | ||
filter.filter(self.record) | ||
self.assertIn('[MASKED]', self.record.msg) | ||
|
||
@patch.dict('os.environ', {'REQUESTS_OAUTHLIB_DEBUG_MODE_TOKEN_FILTER': 'SUPPRESS'}) | ||
def test_suppress_mode(self): | ||
filter = DebugModeTokenFilter() | ||
filter.filter(self.record) | ||
self.assertEqual(" ", self.record.msg) # No logging | ||
|
||
# @patch.dict('os.environ', {'REQUESTS_OAUTHLIB_DEBUG_MODE_TOKEN_FILTER': 'DEFAULT'}) | ||
# def test_default_mode_raises_warning(self): | ||
# with self.assertLogs('requests_oauthlib', level='WARN') as cm: | ||
# DebugModeTokenFilter() | ||
# logging.getLogger("requests_oauthlib").addFilter(DebugModeTokenFilter()) | ||
# # Trigger the log event to check for the warning message | ||
# logging.getLogger("requests_oauthlib").debug(self.record.getMessage()) | ||
|
||
# self.assertIn("Your logger, when in DEBUG mode, will log TOKENS", cm.output[0]) | ||
|
||
|
||
if __name__ == '__main__': | ||
unittest.main() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe only suppress log messages which match the above regex? Otherwise this equivalent to disabling the logger entirely.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I am hoping a single space would suffice as a replacement? Or maybe just pass None to the msg?