-
Notifications
You must be signed in to change notification settings - Fork 27
feat: redact secrets in debug logging #209
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
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
3c0a584
chore: add a missing type hint
pyrooka 3eca256
chore: make the local test server more general
pyrooka 5c110a3
chore: remove debug print (oops)
pyrooka a348672
feat: redact secrets in debug logging
pyrooka 08f00eb
chore: improve message filtering (#210)
padamstx 01391ff
chore: fix copyright year in a new file
pyrooka 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 |
|---|---|---|
| @@ -1,19 +1,16 @@ | ||
| # pylint: disable=missing-docstring | ||
| import logging | ||
| import os | ||
| import threading | ||
| import warnings | ||
| from http.server import HTTPServer, SimpleHTTPRequestHandler | ||
| from ssl import SSLContext, PROTOCOL_TLSv1_1, PROTOCOL_TLSv1_2 | ||
| from typing import Callable | ||
| from ssl import PROTOCOL_TLSv1_1, PROTOCOL_TLSv1_2 | ||
|
|
||
| import pytest | ||
| import urllib3 | ||
| from requests import exceptions | ||
|
|
||
| from ibm_cloud_sdk_core.base_service import BaseService | ||
| from ibm_cloud_sdk_core.authenticators import NoAuthAuthenticator | ||
| from .utils.logger_utils import setup_test_logger | ||
| from .utils.http_utils import local_server | ||
|
|
||
|
|
||
| setup_test_logger(logging.ERROR) | ||
|
|
||
|
|
@@ -33,40 +30,7 @@ | |
| key = os.path.join(os.path.dirname(__file__), '../resources/test_ssl.key') | ||
|
|
||
|
|
||
| def _local_server(tls_version: int, port: int) -> Callable: | ||
|
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I moved this to a separate file, so that it's easier to use it in other tests too. |
||
| def decorator(test_function: Callable) -> Callable: | ||
| def inner(): | ||
| # Disable warnings caused by the self-signed certificate. | ||
| urllib3.disable_warnings() | ||
|
|
||
| # Build the SSL context for the server. | ||
| ssl_context = SSLContext(tls_version) | ||
| ssl_context.load_cert_chain(certfile=cert, keyfile=key) | ||
|
|
||
| # Create and start the server on a separate thread. | ||
| server = HTTPServer(('localhost', port), SimpleHTTPRequestHandler) | ||
| server.socket = ssl_context.wrap_socket(server.socket, server_side=True) | ||
| t = threading.Thread(target=server.serve_forever) | ||
| t.start() | ||
|
|
||
| # We run everything in a big try-except-finally block to make sure we always | ||
| # shutdown the HTTP server gracefully. | ||
| try: | ||
| test_function() | ||
| except Exception: # pylint: disable=try-except-raise | ||
| raise | ||
| finally: | ||
| server.shutdown() | ||
| t.join() | ||
| # Re-enable warnings. | ||
| warnings.resetwarnings() | ||
|
|
||
| return inner | ||
|
|
||
| return decorator | ||
|
|
||
|
|
||
| @_local_server(PROTOCOL_TLSv1_1, 3333) | ||
| @local_server(3333, PROTOCOL_TLSv1_1, cert, key) | ||
| def test_tls_v1_1(): | ||
| service = BaseService(service_url='https://localhost:3333', authenticator=NoAuthAuthenticator()) | ||
| prepped = service.prepare_request('GET', url='/') | ||
|
|
@@ -78,7 +42,7 @@ def test_tls_v1_1(): | |
| assert exception.type is exceptions.SSLError or exception.type is exceptions.ConnectionError | ||
|
|
||
|
|
||
| @_local_server(PROTOCOL_TLSv1_2, 3334) | ||
| @local_server(3334, PROTOCOL_TLSv1_2, cert, key) | ||
| def test_tls_v1_2(): | ||
| service = BaseService(service_url='https://localhost:3334', authenticator=NoAuthAuthenticator()) | ||
|
|
||
|
|
||
This file contains hidden or 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,94 @@ | ||
| # coding: utf-8 | ||
|
|
||
| # Copyright 2024 IBM All Rights Reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| # pylint: disable=missing-docstring | ||
|
|
||
| import logging | ||
|
|
||
| from ibm_cloud_sdk_core import base_service | ||
| from ibm_cloud_sdk_core.authenticators import NoAuthAuthenticator | ||
| from ibm_cloud_sdk_core.logger import LoggingFilter | ||
| from .utils.http_utils import local_server | ||
|
|
||
|
|
||
| def test_redact_secrets(): | ||
| redact_secrets = LoggingFilter.redact_secrets | ||
|
|
||
| assert "secret" not in redact_secrets("Authorization: Bearer secret") | ||
| assert "secret" not in redact_secrets("Authorization: Basic secret") | ||
| assert "secret" not in redact_secrets("X-Authorization: secret") | ||
| assert "secret" not in redact_secrets("ApIKey=secret") | ||
| assert "secret" not in redact_secrets("ApI_Key=secret") | ||
| assert "secret" not in redact_secrets("passCode=secret") | ||
| assert "secret" not in redact_secrets("PASSword=secret") | ||
| assert "secret" not in redact_secrets("toKen=secret") | ||
| assert "secret" not in redact_secrets("client_id=secret") | ||
| assert "secret" not in redact_secrets("client_x509_cert_url=secret") | ||
| assert "secret" not in redact_secrets("client_id=secret") | ||
| assert "secret" not in redact_secrets("key=secret") | ||
| assert "secret" not in redact_secrets("project_id=secret") | ||
| assert "DaSecret" not in redact_secrets("secret=DaSecret") | ||
| assert "secret" not in redact_secrets("subscriptionId=secret") | ||
| assert "secret" not in redact_secrets("tenantId=secret") | ||
| assert "secret" not in redact_secrets("thumbprint=secret") | ||
| assert "secret" not in redact_secrets("token_uri=secret") | ||
| assert "secret" not in redact_secrets('xxx "apIKEy": "secret",xxx') | ||
| assert "secret" not in redact_secrets('xxx "apI_KEy": "secret",xxx') | ||
| assert "secret" not in redact_secrets('xxx "pAsSCoDe": "secret",xxx') | ||
| assert "secret" not in redact_secrets('xxx "passWORD": "secret",xxx') | ||
| assert "secret" not in redact_secrets('xxx {"token": "secret"},xxx') | ||
| assert "secret" not in redact_secrets('xxx "aadClientId": "secret",xxx') | ||
| assert "secret" not in redact_secrets('xxx "aadClientSecret": "secret",xxx') | ||
| assert "secret" not in redact_secrets('xxx "auth": "secret",xxx') | ||
| assert "secret" not in redact_secrets('xxx "auth_provider_x509_cert_url": "secret",xxx') | ||
| assert "secret" not in redact_secrets('xxx "auth_uri": "secret",xxx') | ||
| assert "secret" not in redact_secrets('xxx "client_email": "secret",xxx') | ||
| # Now use a real-world example, to validate the correct behavior. | ||
| assert ( | ||
| redact_secrets( | ||
| 'GET / HTTP/1.1\r\nHost: localhost:3335\r\n' | ||
| + 'User-Agent: ibm-python-sdk-core-3.20.6 os.name=Darwin os.version=23.6.0 python.version=3.11.10\r\n' | ||
| + 'Accept-Encoding: gzip, deflate\r\nAccept: */*\r\nAuthorization: token-foo-bar-123\r\n' | ||
| + 'Connection: keep-alive\r\n\r\n' | ||
| ) | ||
| == 'GET / HTTP/1.1\r\nHost: localhost:3335\r\n' | ||
| + 'User-Agent: ibm-python-sdk-core-3.20.6 os.name=Darwin os.version=23.6.0 python.version=3.11.10\r\n' | ||
| + 'Accept-Encoding: gzip, deflate\r\nAccept: */*\r\nAuthorization: [redacted]\r\nConnection: keep-alive\r\n\r\n' | ||
| ) | ||
|
|
||
|
|
||
| # Simulate a real-world scenario. | ||
| @local_server(3335) | ||
| def test_redact_secrets_log(caplog): | ||
| # Since we use a real BaseService here, we need to set the logging level | ||
| # to DEBUG in its module, to simulate the real behavior. | ||
| original_logging_level = base_service.logger.level | ||
| base_service.logger.setLevel(logging.DEBUG) | ||
|
|
||
| try: | ||
| service = base_service.BaseService(service_url="http://localhost:3335", authenticator=NoAuthAuthenticator()) | ||
| prepped = service.prepare_request('GET', url='/', headers={'Authorization': 'token-foo-bar-123'}) | ||
| res = service.send(prepped) | ||
| except Exception as ex: | ||
| raise ex | ||
| finally: | ||
| # And now we restore the logger's level to the original value. | ||
| base_service.logger.setLevel(original_logging_level) | ||
|
|
||
| assert res is not None | ||
| # Make sure the request has been logged and the token is redacted. | ||
| assert "Authorization" in caplog.text | ||
| assert "token" not in caplog.text |
This file contains hidden or 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,66 @@ | ||
| # coding: utf-8 | ||
|
|
||
| # Copyright 2024 IBM All Rights Reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| import functools | ||
| import threading | ||
| import warnings | ||
| from typing import Callable, Optional | ||
| from http.server import HTTPServer, SimpleHTTPRequestHandler | ||
| from ssl import SSLContext | ||
|
|
||
| import urllib3 | ||
|
|
||
|
|
||
| def local_server( | ||
| port: int, tls_version: Optional[int] = None, cert: Optional[str] = None, key: Optional[str] = None | ||
| ) -> Callable: | ||
| """local_server helps setting up and running an HTTP(S) server for testing purposes.""" | ||
|
|
||
| def decorator(test_function: Callable) -> Callable: | ||
| @functools.wraps(test_function) | ||
| def inner(*args, **kwargs): | ||
| is_https = tls_version and cert and key | ||
| # Disable warnings caused by the self-signed certificate. | ||
| urllib3.disable_warnings() | ||
|
|
||
| if is_https: | ||
| # Build the SSL context for the server. | ||
| ssl_context = SSLContext(tls_version) | ||
| ssl_context.load_cert_chain(certfile=cert, keyfile=key) | ||
|
|
||
| # Create and start the server on a separate thread. | ||
| server = HTTPServer(('localhost', port), SimpleHTTPRequestHandler) | ||
| if is_https: | ||
| server.socket = ssl_context.wrap_socket(server.socket, server_side=True) | ||
|
|
||
| t = threading.Thread(target=server.serve_forever) | ||
| t.start() | ||
|
|
||
| # We run everything in a big try-except-finally block to make sure we always | ||
| # shutdown the HTTP server gracefully. | ||
| try: | ||
| test_function(*args, **kwargs) | ||
| except Exception: # pylint: disable=try-except-raise | ||
| raise | ||
| finally: | ||
| server.shutdown() | ||
| t.join() | ||
| # Re-enable warnings. | ||
| warnings.resetwarnings() | ||
|
|
||
| return inner | ||
|
|
||
| return decorator |
This file contains hidden or 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
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.
Uh oh!
There was an error while loading. Please reload this page.