From 174f619095a9860185b873e0e395a007db29978a Mon Sep 17 00:00:00 2001 From: Juan Lee Date: Mon, 2 Nov 2026 10:32:00 -0700 Subject: [PATCH] fix: keep auth tokens, secret values and statement text out of debug logs, errors and reprs --- .../aio/auth_plugins.py | 5 +- .../aio/federated_auth_plugins.py | 2 +- .../aws_secrets_manager_plugin.py | 24 ++++++++-- .../federated_plugin.py | 2 +- aws_advanced_python_wrapper/iam_plugin.py | 2 +- aws_advanced_python_wrapper/okta_plugin.py | 2 +- aws_advanced_python_wrapper/plugin_service.py | 2 +- .../read_write_splitting_plugin.py | 2 +- ...dvanced_python_wrapper_messages.properties | 8 ++-- .../utils/iam_utils.py | 2 +- .../utils/properties.py | 3 ++ tests/unit/test_aio_auth_plugins.py | 28 +++++++++++ tests/unit/test_aio_federated_okta.py | 39 +++++++++++++++ tests/unit/test_federated_auth_plugin.py | 28 +++++++++++ tests/unit/test_iam_plugin.py | 24 ++++++++++ tests/unit/test_okta_plugin.py | 28 +++++++++++ tests/unit/test_plugin_manager.py | 23 +++++++++ tests/unit/test_properties_utils.py | 28 +++++++++++ .../unit/test_read_write_splitting_plugin.py | 20 ++++++++ tests/unit/test_secrets_manager_plugin.py | 47 +++++++++++++++++++ 20 files changed, 302 insertions(+), 17 deletions(-) diff --git a/aws_advanced_python_wrapper/aio/auth_plugins.py b/aws_advanced_python_wrapper/aio/auth_plugins.py index 4f356c34e..301b3096d 100644 --- a/aws_advanced_python_wrapper/aio/auth_plugins.py +++ b/aws_advanced_python_wrapper/aio/auth_plugins.py @@ -39,7 +39,8 @@ from aws_advanced_python_wrapper.aio.plugin import AsyncPlugin from aws_advanced_python_wrapper.aws_credentials_manager import \ AwsCredentialsManager -from aws_advanced_python_wrapper.aws_secrets_manager_plugin import Secret +from aws_advanced_python_wrapper.aws_secrets_manager_plugin import ( + Secret, _get_secret_value) from aws_advanced_python_wrapper.errors import AwsConnectError, AwsWrapperError from aws_advanced_python_wrapper.pep249_methods import DbApiMethod from aws_advanced_python_wrapper.utils import services_container @@ -626,7 +627,7 @@ def _fetch_secret_blocking( session = AwsCredentialsManager.get_session(host_info, props, region) client = AwsCredentialsManager.get_client( "secretsmanager", session, host_info.host, region, endpoint) - resp = client.get_secret_value(SecretId=secret_id) + resp = _get_secret_value(client, secret_id) secret_str = resp.get("SecretString") if not secret_str: return {} diff --git a/aws_advanced_python_wrapper/aio/federated_auth_plugins.py b/aws_advanced_python_wrapper/aio/federated_auth_plugins.py index 8a0d4aac6..69c7e4519 100644 --- a/aws_advanced_python_wrapper/aio/federated_auth_plugins.py +++ b/aws_advanced_python_wrapper/aio/federated_auth_plugins.py @@ -264,7 +264,7 @@ async def _resolve_credentials( # 1. Token cache check before the expensive SAML round-trip. cached = await self._cached_rds_token(host, int(port), db_user, region) if cached is not None: - logger.debug("FederatedAuthPlugin.UseCachedToken", cached) + logger.debug("FederatedAuthPlugin.UseCachedToken") return db_user, cached, True # Cache miss -> generate a fresh RDS IAM token. Emit the counter here diff --git a/aws_advanced_python_wrapper/aws_secrets_manager_plugin.py b/aws_advanced_python_wrapper/aws_secrets_manager_plugin.py index 2ec929b6f..9ccd817e3 100644 --- a/aws_advanced_python_wrapper/aws_secrets_manager_plugin.py +++ b/aws_advanced_python_wrapper/aws_secrets_manager_plugin.py @@ -14,11 +14,13 @@ from __future__ import annotations +import logging +import threading from datetime import timedelta from json import JSONDecodeError, loads from re import search from types import SimpleNamespace -from typing import TYPE_CHECKING, Callable, Optional, Set, Tuple +from typing import TYPE_CHECKING, Any, Callable, Optional, Set, Tuple from botocore.exceptions import ClientError, EndpointConnectionError @@ -45,6 +47,22 @@ TelemetryTraceLevel logger = Logger(__name__) +_secret_fetch = threading.local() + + +def _outside_secret_fetch(record: logging.LogRecord) -> bool: + return not getattr(_secret_fetch, "active", False) + + +def _get_secret_value(client: Any, secret_id: str) -> Any: + # botocore.parsers logs every response body at DEBUG, and this one holds the secret. + # The filter stays on the logger: addFilter skips a repeat, and removing it could race another thread's fetch. + logging.getLogger("botocore.parsers").addFilter(_outside_secret_fetch) + _secret_fetch.active = True + try: + return client.get_secret_value(SecretId=secret_id) + finally: + _secret_fetch.active = False class Secret: @@ -200,9 +218,7 @@ def _fetch_latest_credentials(self, host_info: HostInfo, props: Properties): session = AwsCredentialsManager.get_session(host_info, props, self._secret_key[1]) client = AwsCredentialsManager.get_client("secretsmanager", session, host_info.host, self._secret_key[1], self._secret_key[2]) - secret = client.get_secret_value( - SecretId=self._secret_key[0], - ) + secret = _get_secret_value(client, self._secret_key[0]) return loads(secret.get("SecretString"), object_hook=lambda d: SimpleNamespace(**d)) diff --git a/aws_advanced_python_wrapper/federated_plugin.py b/aws_advanced_python_wrapper/federated_plugin.py index d6d052732..b0cd0782a 100644 --- a/aws_advanced_python_wrapper/federated_plugin.py +++ b/aws_advanced_python_wrapper/federated_plugin.py @@ -116,7 +116,7 @@ def _connect(self, host_info: HostInfo, props: Properties, connect_func: Callabl token_host_info = deepcopy(host_info) token_host_info.host = host if token_info is not None and not token_info.is_expired(): - logger.debug("FederatedAuthPlugin.UseCachedToken", token_info.token) + logger.debug("FederatedAuthPlugin.UseCachedToken") self._plugin_service.driver_dialect.set_password(props, token_info.token) else: self._update_authentication_token(token_host_info, props, user, region, cache_key, credentials) diff --git a/aws_advanced_python_wrapper/iam_plugin.py b/aws_advanced_python_wrapper/iam_plugin.py index 791a1a531..b04676d1d 100644 --- a/aws_advanced_python_wrapper/iam_plugin.py +++ b/aws_advanced_python_wrapper/iam_plugin.py @@ -109,7 +109,7 @@ def _connect(self, host_info: HostInfo, props: Properties, connect_func: Callabl token_info = self._storage_service.get(TokenInfo, cache_key) if token_info is not None and not token_info.is_expired(): - logger.debug("IamAuthPlugin.UseCachedIamToken", token_info.token) + logger.debug("IamAuthPlugin.UseCachedIamToken") self._plugin_service.driver_dialect.set_password(props, token_info.token) else: token_expiry = datetime.now() + timedelta(seconds=token_expiration_sec) diff --git a/aws_advanced_python_wrapper/okta_plugin.py b/aws_advanced_python_wrapper/okta_plugin.py index 375ed0eb1..268f739b8 100644 --- a/aws_advanced_python_wrapper/okta_plugin.py +++ b/aws_advanced_python_wrapper/okta_plugin.py @@ -112,7 +112,7 @@ def _connect(self, host_info: HostInfo, props: Properties, connect_func: Callabl token_host_info = deepcopy(host_info) token_host_info.host = host if token_info is not None and not token_info.is_expired(): - logger.debug("OktaAuthPlugin.UseCachedToken", token_info.token) + logger.debug("OktaAuthPlugin.UseCachedToken") self._plugin_service.driver_dialect.set_password(props, token_info.token) else: self._update_authentication_token(token_host_info, props, user, region, cache_key, credentials) diff --git a/aws_advanced_python_wrapper/plugin_service.py b/aws_advanced_python_wrapper/plugin_service.py index 74ac133b4..fbc52111c 100644 --- a/aws_advanced_python_wrapper/plugin_service.py +++ b/aws_advanced_python_wrapper/plugin_service.py @@ -1030,7 +1030,7 @@ def execute(self, target: object, method: DbApiMethod, target_driver_func: Calla current_conn: Optional[Connection] = driver_dialect.unwrap_connection(plugin_service.current_connection) if method not in [DbApiMethod.CONNECTION_CLOSE, DbApiMethod.CURSOR_CLOSE] and conn is not None and conn != current_conn: - raise AwsWrapperError(Messages.get_formatted("PluginManager.MethodInvokedAgainstOldConnection", target)) + raise AwsWrapperError(Messages.get_formatted("PluginManager.MethodInvokedAgainstOldConnection", type(target).__name__)) if conn is None and method in [DbApiMethod.CONNECTION_CLOSE, DbApiMethod.CURSOR_CLOSE]: return None diff --git a/aws_advanced_python_wrapper/read_write_splitting_plugin.py b/aws_advanced_python_wrapper/read_write_splitting_plugin.py index 23bd01742..f51db5e14 100644 --- a/aws_advanced_python_wrapper/read_write_splitting_plugin.py +++ b/aws_advanced_python_wrapper/read_write_splitting_plugin.py @@ -122,7 +122,7 @@ def execute( if conn is not None and conn != current_conn: msg = Messages.get_formatted( - "PluginManager.MethodInvokedAgainstOldConnection", target + "PluginManager.MethodInvokedAgainstOldConnection", type(target).__name__ ) raise AwsWrapperError(msg) diff --git a/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties b/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties index 295de3ca9..9e20837a4 100644 --- a/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties +++ b/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties @@ -211,11 +211,11 @@ FastestResponseStrategyPlugin.RandomHostSelected=[FastestResponseStrategyPlugin] FastestResponseStrategyPlugin.UnsupportedHostSelectorStrategy=[FastestResponseStrategyPlugin] Unsupported host selector strategy: '{}'. To use the fastest response strategy plugin, please ensure the property reader_host_selector_strategy is set to fastest_response. FederatedAuthPlugin.UnhandledException=[FederatedAuthPlugin] Unhandled exception: '{}' -FederatedAuthPlugin.UseCachedToken=[FederatedAuthPlugin] Used cached authentication token = {} +FederatedAuthPlugin.UseCachedToken=[FederatedAuthPlugin] Used cached authentication token FederatedAuthPlugin.ConnectException=[FederatedAuthPlugin] Error occurred while opening a connection: {} OktaAuthPlugin.UnhandledException=[OktaAuthPlugin] Unhandled exception: '{}' -OktaAuthPlugin.UseCachedToken=[OktaAuthPlugin] Used cached authentication token = {} +OktaAuthPlugin.UseCachedToken=[OktaAuthPlugin] Used cached authentication token OktaAuthPlugin.ConnectException=[OktaAuthPlugin] Error occurred while opening a connection: {} OktaCredentialsProviderFactory.SamlAssertionUrl=[OktaCredentialsProviderFactory] Retrieving SAML assertion from URL: '{}' @@ -278,10 +278,10 @@ HostSelector.NoHostsMatchingRole=[HostSelector] No hosts were found matching the IamAuthPlugin.ConnectException=[IamAuthPlugin] Error occurred while opening a connection: {} IamAuthPlugin.UnhandledException=[IamAuthPlugin] Unhandled exception: {} -IamAuthPlugin.UseCachedIamToken=[IamAuthPlugin] Used cached IAM token = {} +IamAuthPlugin.UseCachedIamToken=[IamAuthPlugin] Used cached IAM token IamAuthPlugin.InvalidHost=[IamAuthPlugin] Invalid IAM host {}. The IAM host must be a valid RDS or Aurora endpoint. IamAuthPlugin.IsNoneOrEmpty=[IamAuthPlugin] Property "{}" is None or empty. -IamAuthUtils.GeneratedNewAuthToken=Generated new authentication token = {} +IamAuthUtils.GeneratedNewAuthToken=Generated new authentication token LimitlessPlugin.FailedToConnectToHost=[LimitlessPlugin] Failed to connect to host {}. LimitlessPlugin.UnsupportedDialectOrDatabase=[LimitlessPlugin] Unsupported dialect '{}' encountered. Please ensure the connection parameters are correct, and refer to the documentation to ensure that the connecting database is compatible with the Limitless Connection Plugin. diff --git a/aws_advanced_python_wrapper/utils/iam_utils.py b/aws_advanced_python_wrapper/utils/iam_utils.py index 528c1f2d8..97d78f77a 100644 --- a/aws_advanced_python_wrapper/utils/iam_utils.py +++ b/aws_advanced_python_wrapper/utils/iam_utils.py @@ -102,7 +102,7 @@ def generate_authentication_token( client.close() - logger.debug("IamAuthUtils.GeneratedNewAuthToken", token) + logger.debug("IamAuthUtils.GeneratedNewAuthToken") return token except Exception as ex: if context is not None: diff --git a/aws_advanced_python_wrapper/utils/properties.py b/aws_advanced_python_wrapper/utils/properties.py index 33b379c40..81aded0db 100644 --- a/aws_advanced_python_wrapper/utils/properties.py +++ b/aws_advanced_python_wrapper/utils/properties.py @@ -21,6 +21,9 @@ class Properties(Dict[str, Any]): + def __repr__(self) -> str: + return dict.__repr__(PropertiesUtils.mask_properties(self)) + def put_if_absent(self, key: str, value: Any): if self.get(key) is None: self[key] = value diff --git a/tests/unit/test_aio_auth_plugins.py b/tests/unit/test_aio_auth_plugins.py index 139a10ff6..f649a2f16 100644 --- a/tests/unit/test_aio_auth_plugins.py +++ b/tests/unit/test_aio_auth_plugins.py @@ -17,6 +17,8 @@ from __future__ import annotations import asyncio +import json +import logging from unittest.mock import MagicMock, patch import pytest @@ -816,6 +818,32 @@ def test_secrets_plugin_resolve_credentials_returns_was_cached_flag(): assert was2 is True +def test_secrets_plugin_drops_botocore_response_body_log(caplog): + props = Properties({ + "host": "h", "port": "5432", + "secrets_manager_secret_id": "my-secret", + "secrets_manager_region": "us-east-1", + }) + plugin = AsyncAwsSecretsManagerPlugin(_svc(props), props) + secret_json = '{"username": "u", "password": "async-secret-pw"}' + + def _get_secret_value(**kwargs): + # What botocore's ResponseParser.parse logs for every response. + body = json.dumps({"ARN": "arn:aws:secretsmanager:us-east-1:123456789012:secret:my-secret-AbCdEf", + "Name": "my-secret", "SecretString": secret_json}) + logging.getLogger("botocore.parsers").debug("Response body:\n%r", body.encode()) + return {"SecretString": secret_json} + + session_patch, client_patch = _patch_secrets_client(secret_json) + caplog.set_level(logging.DEBUG) + with session_patch, client_patch as get_client: + get_client.return_value.get_secret_value.side_effect = _get_secret_value + asyncio.run(plugin._resolve_credentials(HostInfo(host="h", port=5432), props)) + + get_client.return_value.get_secret_value.assert_called_once() + assert "async-secret-pw" not in caplog.text + + # ---- Telemetry counters ------------------------------------------------ diff --git a/tests/unit/test_aio_federated_okta.py b/tests/unit/test_aio_federated_okta.py index d633d5219..dc1542e75 100644 --- a/tests/unit/test_aio_federated_okta.py +++ b/tests/unit/test_aio_federated_okta.py @@ -17,6 +17,7 @@ from __future__ import annotations import asyncio +import logging from unittest.mock import AsyncMock, MagicMock, patch import pytest @@ -30,6 +31,7 @@ from aws_advanced_python_wrapper.pep249_methods import DbApiMethod from aws_advanced_python_wrapper.utils import services_container from aws_advanced_python_wrapper.utils.iam_utils import TokenInfo +from aws_advanced_python_wrapper.utils.log import Logger from aws_advanced_python_wrapper.utils.properties import (Properties, WrapperProperties) @@ -856,3 +858,40 @@ def test_okta_code_binds_okta_regardless_of_idp_name(): plugin = _OktaAuthFactory().get_instance( _FactoryMockService(), Properties()) assert isinstance(plugin, AsyncOktaAuthPlugin) + + +def test_federated_plugin_debug_log_omits_cached_token(caplog): + async def _body() -> None: + props = _federated_props() + plugin = AsyncFederatedAuthPlugin(_svc(props), props) + + async def _cf() -> object: + return MagicMock() + + with patch.object( + AsyncFederatedAuthPlugin, "_fetch_saml_assertion", + new=AsyncMock(return_value=_FAKE_SAML), + ), patch.object( + AsyncFederatedAuthPlugin, "_sts_assume_role_with_saml_blocking", + return_value=_FAKE_CREDS, + ), patch.object( + AsyncFederatedAuthPlugin, "_generate_rds_token_blocking", + return_value="fake-rds-token", + ), patch.object(Logger, "debug", autospec=True, side_effect=Logger.debug) as debug: + for _ in range(2): + await plugin.connect( + target_driver_func=lambda: None, + driver_dialect=MagicMock(), + host_info=HostInfo("instance-1.abc123.us-east-1.rds.amazonaws.com", 5432), + props=Properties(dict(props)), + is_initial_connection=True, + connect_func=_cf, + ) + assert not [c for c in debug.call_args_list if any("fake-rds-token" in str(a) for a in c.args)] + + caplog.set_level(logging.DEBUG) + asyncio.run(_body()) + + assert "Used cached authentication token" in caplog.text + assert "fake-rds-token" not in caplog.text + assert "token = {}" not in caplog.text diff --git a/tests/unit/test_federated_auth_plugin.py b/tests/unit/test_federated_auth_plugin.py index b84ed072b..5c8f92586 100644 --- a/tests/unit/test_federated_auth_plugin.py +++ b/tests/unit/test_federated_auth_plugin.py @@ -14,6 +14,7 @@ from __future__ import annotations +import logging from datetime import datetime, timedelta import pytest @@ -26,6 +27,7 @@ from aws_advanced_python_wrapper.hostinfo import HostInfo from aws_advanced_python_wrapper.iam_plugin import TokenInfo from aws_advanced_python_wrapper.utils import services_container +from aws_advanced_python_wrapper.utils.log import Logger from aws_advanced_python_wrapper.utils.messages import Messages from aws_advanced_python_wrapper.utils.properties import (Properties, WrapperProperties) @@ -243,3 +245,29 @@ def test_connect_with_specified_iam_host_port_region(mocker, assert WrapperProperties.USER.get(properties) == "specifiedUser" mock_dialect.set_password.assert_called_with(properties, _TEST_TOKEN) + + +@pytest.mark.parametrize("cached", [True, False], ids=["cached", "fresh"]) +def test_connect_debug_log_omits_token( + cached, caplog, mocker, mock_plugin_service, mock_func, mock_client, mock_dialect, mock_credentials_provider_factory): + mock_client.generate_db_auth_token.return_value = _GENERATED_TOKEN + if cached: + services_container.get_storage_service().put( + TokenInfo, _PG_CACHE_KEY, TokenInfo(_TEST_TOKEN, datetime.now() + timedelta(minutes=5))) + props: Properties = Properties({"plugins": "federated_auth", "idp_username": "user", "idp_password": "password"}) + WrapperProperties.DB_USER.set(props, _DB_USER) + caplog.set_level(logging.DEBUG) + debug = mocker.spy(Logger, "debug") + + FederatedAuthPlugin(mock_plugin_service, mock_credentials_provider_factory).connect( + target_driver_func=mocker.MagicMock(), + driver_dialect=mock_dialect, + host_info=_PG_HOST_INFO, + props=props, + is_initial_connection=False, + connect_func=mock_func) + + assert ("Used cached authentication token" if cached else "Generated new authentication token") in caplog.text + assert (_TEST_TOKEN if cached else _GENERATED_TOKEN) not in caplog.text + assert "token = {}" not in caplog.text + assert not [c for c in debug.call_args_list if any((_TEST_TOKEN if cached else _GENERATED_TOKEN) in str(a) for a in c.args)] diff --git a/tests/unit/test_iam_plugin.py b/tests/unit/test_iam_plugin.py index 758b3ea8e..65b42e735 100644 --- a/tests/unit/test_iam_plugin.py +++ b/tests/unit/test_iam_plugin.py @@ -14,6 +14,7 @@ from __future__ import annotations +import logging from datetime import datetime, timedelta import pytest @@ -26,6 +27,7 @@ from aws_advanced_python_wrapper.iam_plugin import IamAuthPlugin from aws_advanced_python_wrapper.utils import services_container from aws_advanced_python_wrapper.utils.iam_utils import TokenInfo +from aws_advanced_python_wrapper.utils.log import Logger from aws_advanced_python_wrapper.utils.properties import (Properties, WrapperProperties) @@ -405,3 +407,25 @@ def test_invalid_iam_host(host, mocker, mock_plugin_service, mock_session, mock_ props=test_props, is_initial_connection=False, connect_func=mock_func) + + +@pytest.mark.parametrize("cached", [True, False], ids=["cached", "fresh"]) +def test_connect_debug_log_omits_token(cached, caplog, mocker, mock_plugin_service, mock_func, mock_dialect): + if cached: + services_container.get_storage_service().put( + TokenInfo, _PG_CACHE_KEY, TokenInfo(_TEST_TOKEN, datetime.now() + timedelta(minutes=5))) + caplog.set_level(logging.DEBUG) + debug = mocker.spy(Logger, "debug") + + IamAuthPlugin(mock_plugin_service).connect( + target_driver_func=mocker.MagicMock(), + driver_dialect=mock_dialect, + host_info=_PG_HOST_INFO, + props=Properties({"user": "postgresqlUser"}), + is_initial_connection=False, + connect_func=mock_func) + + assert ("Used cached IAM token" if cached else "Generated new authentication token") in caplog.text + assert (_TEST_TOKEN if cached else _GENERATED_TOKEN) not in caplog.text + assert "token = {}" not in caplog.text + assert not [c for c in debug.call_args_list if any((_TEST_TOKEN if cached else _GENERATED_TOKEN) in str(a) for a in c.args)] diff --git a/tests/unit/test_okta_plugin.py b/tests/unit/test_okta_plugin.py index 0ebafb95f..61bbdb8e5 100644 --- a/tests/unit/test_okta_plugin.py +++ b/tests/unit/test_okta_plugin.py @@ -14,6 +14,7 @@ from __future__ import annotations +import logging from datetime import datetime, timedelta import pytest @@ -26,6 +27,7 @@ from aws_advanced_python_wrapper.okta_plugin import OktaAuthPlugin from aws_advanced_python_wrapper.utils import services_container from aws_advanced_python_wrapper.utils.iam_utils import TokenInfo +from aws_advanced_python_wrapper.utils.log import Logger from aws_advanced_python_wrapper.utils.messages import Messages from aws_advanced_python_wrapper.utils.properties import (Properties, WrapperProperties) @@ -241,3 +243,29 @@ def test_connect_with_specified_iam_host_port_region(mocker, assert WrapperProperties.USER.get(properties) == "specifiedUser" mock_dialect.set_password.assert_called_with(properties, _TEST_TOKEN) + + +@pytest.mark.parametrize("cached", [True, False], ids=["cached", "fresh"]) +def test_connect_debug_log_omits_token( + cached, caplog, mocker, mock_plugin_service, mock_func, mock_client, mock_dialect, mock_credentials_provider_factory): + mock_client.generate_db_auth_token.return_value = _GENERATED_TOKEN + if cached: + services_container.get_storage_service().put( + TokenInfo, _PG_CACHE_KEY, TokenInfo(_TEST_TOKEN, datetime.now() + timedelta(minutes=5))) + props: Properties = Properties({"plugins": "okta", "idp_username": "user", "idp_password": "password"}) + WrapperProperties.DB_USER.set(props, _DB_USER) + caplog.set_level(logging.DEBUG) + debug = mocker.spy(Logger, "debug") + + OktaAuthPlugin(mock_plugin_service, mock_credentials_provider_factory).connect( + target_driver_func=mocker.MagicMock(), + driver_dialect=mock_dialect, + host_info=_PG_HOST_INFO, + props=props, + is_initial_connection=False, + connect_func=mock_func) + + assert ("Used cached authentication token" if cached else "Generated new authentication token") in caplog.text + assert (_TEST_TOKEN if cached else _GENERATED_TOKEN) not in caplog.text + assert "token = {}" not in caplog.text + assert not [c for c in debug.call_args_list if any((_TEST_TOKEN if cached else _GENERATED_TOKEN) in str(a) for a in c.args)] diff --git a/tests/unit/test_plugin_manager.py b/tests/unit/test_plugin_manager.py index 97c6e88bf..6408825a2 100644 --- a/tests/unit/test_plugin_manager.py +++ b/tests/unit/test_plugin_manager.py @@ -712,3 +712,26 @@ def test_must_use_pipeline(mocker, container, mock_telemetry_factory): manager._function_cache[DbApiMethod.CURSOR_LASTROWID.id] = \ manager._make_pipeline(DbApiMethod.CURSOR_LASTROWID.method_name) assert manager.must_use_pipeline(DbApiMethod.CURSOR_LASTROWID) + + +class CMySQLCursor: + """Stands in for a mysql-connector cursor, whose str() quotes the start of its last statement with the values.""" + + def __str__(self) -> str: + return "CMySQLCursor: SELECT 'secret-literal'" + + +def test_execute_against_old_connection_omits_statement_text(mocker, container, mock_plugin_service, mock_driver_dialect): + mocker.patch.object(PluginManager, "__init__", lambda w, x, y, z: None) + manager = PluginManager(mocker.MagicMock(), mocker.MagicMock(), mocker.MagicMock()) + container.plugin_service = mock_plugin_service + mock_plugin_service.driver_dialect = mock_driver_dialect + mock_driver_dialect.get_connection_from_obj.return_value = mocker.MagicMock() + mock_driver_dialect.unwrap_connection.return_value = mocker.MagicMock() + manager._container = container + + with pytest.raises(AwsWrapperError) as e: + manager.execute(CMySQLCursor(), DbApiMethod.CURSOR_EXECUTE, mocker.MagicMock()) + + assert "secret-literal" not in str(e.value) + assert "'CMySQLCursor'" in str(e.value) diff --git a/tests/unit/test_properties_utils.py b/tests/unit/test_properties_utils.py index 5d56a95d7..45350c028 100644 --- a/tests/unit/test_properties_utils.py +++ b/tests/unit/test_properties_utils.py @@ -12,6 +12,8 @@ # See the License for the specific language governing permissions and # limitations under the License. +import traceback + import pytest from aws_advanced_python_wrapper.errors import AwsWrapperError @@ -196,3 +198,29 @@ def test_get_bool(expected, props): wrapper_prop = WrapperProperty("test_prop", "Test property") result = wrapper_prop.get_bool(props) assert result == expected + + +def test_properties_repr_masks_secrets(): + props = Properties({"user": "test-user", "password": "props-secret-pw", "ssl_key_passwd": "props-secret-passwd"}) + + for text in (repr(props), str(props), f"{props}"): + assert "props-secret-pw" not in text + assert "props-secret-passwd" not in text + assert "'user': 'test-user'" in text + assert "'password': '***'" in text + assert props["password"] == "props-secret-pw" + assert dict(props)["ssl_key_passwd"] == "props-secret-passwd" + + +def test_traceback_locals_mask_properties_password(): + def _connect(props: Properties) -> None: + raise ValueError("connect failed") + + # Built outside the raising line, so the traceback's source lines don't quote the password. + props = Properties({"user": "test-user", "password": "props-secret-pw"}) + with pytest.raises(ValueError) as e: + _connect(props) + text = "".join(traceback.TracebackException.from_exception(e.value, capture_locals=True).format()) + + assert "props = {'user': 'test-user', 'password': '***'}" in text + assert "props-secret-pw" not in text diff --git a/tests/unit/test_read_write_splitting_plugin.py b/tests/unit/test_read_write_splitting_plugin.py index ab24cde52..200032861 100644 --- a/tests/unit/test_read_write_splitting_plugin.py +++ b/tests/unit/test_read_write_splitting_plugin.py @@ -795,3 +795,23 @@ def test_get_verified_connection_sql_exception_retry_srw(srw_plugin, plugin_serv assert plugin_service_mock.connect.call_count == 2 assert srw_plugin._reader_connection == reader_conn_mock + + +class CMySQLCursor: + """Stands in for a mysql-connector cursor, whose str() quotes the start of its last statement with the values.""" + + def __str__(self) -> str: + return "CMySQLCursor: SELECT 'secret-literal'" + + +@pytest.mark.parametrize("plugin_fixture", ["read_write_splitting_plugin", "srw_plugin"]) +def test_execute_against_old_connection_omits_statement_text( + request, plugin_service_mock, driver_dialect_mock, new_writer_conn_mock, plugin_fixture): + plugin = request.getfixturevalue(plugin_fixture) + driver_dialect_mock.unwrap_connection.return_value = new_writer_conn_mock + + with pytest.raises(AwsWrapperError) as e: + plugin.execute(CMySQLCursor(), "Cursor.execute", lambda: None) + + assert "secret-literal" not in str(e.value) + assert "'CMySQLCursor'" in str(e.value) diff --git a/tests/unit/test_secrets_manager_plugin.py b/tests/unit/test_secrets_manager_plugin.py index 526de38a5..8b9fbf1ee 100644 --- a/tests/unit/test_secrets_manager_plugin.py +++ b/tests/unit/test_secrets_manager_plugin.py @@ -14,6 +14,9 @@ from __future__ import annotations +import json +import logging +import threading from types import SimpleNamespace import pytest @@ -308,3 +311,47 @@ def test_connect_with_different_secret_keys( mock_func.assert_called_once() assert _TEST_USERNAME == test_properties.get("user") assert _TEST_PASSWORD == test_properties.get("password") + + +def test_connect_drops_botocore_response_body_log( + caplog, mocker, mock_plugin_service, mock_session, mock_func, mock_client, test_properties): + def _get_secret_value(**kwargs): + # What botocore's ResponseParser.parse logs for every response. + body = json.dumps({"ARN": "arn:aws:secretsmanager:us-east-2:123456789012:secret:secretId-AbCdEf", + "Name": _TEST_SECRET_ID, "SecretString": _VALID_SECRET_STRING["SecretString"]}) + logging.getLogger("botocore.parsers").debug("Response body:\n%r", body.encode()) + return _VALID_SECRET_STRING + + mock_client.get_secret_value.side_effect = _get_secret_value + caplog.set_level(logging.DEBUG) + + AwsSecretsManagerPlugin(mock_plugin_service, test_properties, mock_session).connect( + mocker.MagicMock(), mocker.MagicMock(), _TEST_HOST_INFO, test_properties, True, mock_func) + + assert _TEST_PASSWORD == test_properties.get("password") + assert _TEST_PASSWORD not in caplog.text + + +def test_connect_keeps_other_botocore_parsers_logs( + caplog, mocker, mock_plugin_service, mock_session, mock_func, mock_client, test_properties): + parsers_logger = logging.getLogger("botocore.parsers") + + def _other_thread_log(): + parsers_logger.debug("Response body:\n%r", b'{"Name":"app","SecretString":"{\\"password\\":\\"other-thread-pw\\"}"}') + + def _get_secret_value(**kwargs): + other = threading.Thread(target=_other_thread_log) + other.start() + other.join() + return _VALID_SECRET_STRING + + mock_client.get_secret_value.side_effect = _get_secret_value + caplog.set_level(logging.DEBUG) + + AwsSecretsManagerPlugin(mock_plugin_service, test_properties, mock_session).connect( + mocker.MagicMock(), mocker.MagicMock(), _TEST_HOST_INFO, test_properties, True, mock_func) + parsers_logger.debug("Response body:\n%r", b'{"Name":"app","SecretString":"{\\"password\\":\\"after-fetch-pw\\"}"}') + + assert _TEST_PASSWORD == test_properties.get("password") + assert "other-thread-pw" in caplog.text + assert "after-fetch-pw" in caplog.text