Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions aws_advanced_python_wrapper/aio/auth_plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {}
Expand Down
2 changes: 1 addition & 1 deletion aws_advanced_python_wrapper/aio/federated_auth_plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
24 changes: 20 additions & 4 deletions aws_advanced_python_wrapper/aws_secrets_manager_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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:
Expand Down Expand Up @@ -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))

Expand Down
2 changes: 1 addition & 1 deletion aws_advanced_python_wrapper/federated_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion aws_advanced_python_wrapper/iam_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion aws_advanced_python_wrapper/okta_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion aws_advanced_python_wrapper/plugin_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion aws_advanced_python_wrapper/read_write_splitting_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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: '{}'
Expand Down Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion aws_advanced_python_wrapper/utils/iam_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
3 changes: 3 additions & 0 deletions aws_advanced_python_wrapper/utils/properties.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
28 changes: 28 additions & 0 deletions tests/unit/test_aio_auth_plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
from __future__ import annotations

import asyncio
import json
import logging
from unittest.mock import MagicMock, patch

import pytest
Expand Down Expand Up @@ -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 ------------------------------------------------


Expand Down
39 changes: 39 additions & 0 deletions tests/unit/test_aio_federated_okta.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from __future__ import annotations

import asyncio
import logging
from unittest.mock import AsyncMock, MagicMock, patch

import pytest
Expand All @@ -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)

Expand Down Expand Up @@ -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
28 changes: 28 additions & 0 deletions tests/unit/test_federated_auth_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

from __future__ import annotations

import logging
from datetime import datetime, timedelta

import pytest
Expand All @@ -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)
Expand Down Expand Up @@ -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)]
24 changes: 24 additions & 0 deletions tests/unit/test_iam_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

from __future__ import annotations

import logging
from datetime import datetime, timedelta

import pytest
Expand All @@ -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)

Expand Down Expand Up @@ -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)]
Loading
Loading