pg.ddx.io aws/aws-advanced-jdbc-wrapper GitHub issues and pull requests
help / color / mirror / Atom feedFrom: sergiyvamz (@sergiyvamz) <noreply+sergiyvamz@github.com>
To: aws/aws-advanced-jdbc-wrapper <noreply+aws-aws-advanced-jdbc-wrapper@github.com>
Subject: [aws/aws-advanced-jdbc-wrapper] PR #2265: fix: scope cached IAM auth tokens to the signing identity
Date: Fri, 20 Nov 2026 01:15:00 +0000
Message-ID: <gh-aws-aws-advanced-jdbc-wrapper-2265@github.com> (raw)
### Summary
Scope cached IAM authentication tokens to the identity that signed them.
### Description
The `iam`, `federatedAuth` and `okta` plugins cached tokens by region, host, port and database user only. Two connections in the same process that target the same database user but sign with different AWS identities could reuse each other's token.
The cache key now also includes the plugin and the signing identity:
- `iam`: a SHA-256 hash of the access key ID resolved from the credentials provider on each connect. This follows changes to the credentials behind a profile, rotated or temporary credentials, and custom `AwsCredentialsManager` handlers.
- `federatedAuth`: `idpEndpoint`, `idpPort`, `rpIdentifier`, `idpUsername`, `iamRoleArn`, `iamIdpArn`
- `okta`: `idpEndpoint`, `appId`, `idpUsername`, `iamRoleArn`, `iamIdpArn`
The `iam` plugin now resolves credentials on every connect instead of only on a cache miss. Key components are escaped so values containing `:` cannot collide.
### Additional Reviewers
### By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.
inline patch 1: wrapper/src/main/java/software/amazon/jdbc/plugin/federatedauth/BaseSamlAuthPlugin.java, wrapper/src/main/java/software/amazon/jdbc/plugin/federatedauth/FederatedAuthPlugin.java, wrapper/src/main/java/software/amazon/jdbc/plugin/federatedauth/OktaAuthPlugin.java and 7 more (+446/-33 lines) download inline-1.patch
diff --git a/wrapper/src/main/java/software/amazon/jdbc/plugin/federatedauth/BaseSamlAuthPlugin.java b/wrapper/src/main/java/software/amazon/jdbc/plugin/federatedauth/BaseSamlAuthPlugin.java
index 933b299fac..64b073dca3 100644
--- a/wrapper/src/main/java/software/amazon/jdbc/plugin/federatedauth/BaseSamlAuthPlugin.java
+++ b/wrapper/src/main/java/software/amazon/jdbc/plugin/federatedauth/BaseSamlAuthPlugin.java
@@ -144,7 +144,11 @@ protected Connection connectInternal(final HostSpec hostSpec, final Properties p
Messages.get("OktaAuthPlugin.unableToDetermineRegion", new Object[] {BaseSamlAuthPlugin.IAM_REGION_NAME}));
}
+ // The token is signed with the role assumed for the federated user, so the IdP, the user and the
+ // role are part of the key: connections using different identities must not share a token.
final String cacheKey = IamAuthUtils.getCacheKey(
+ this.getCacheKeyScope(),
+ this.getCredentialsIdentity(props),
this.getDbUserProperty(props),
host.getHost(),
port,
@@ -248,4 +252,10 @@ public static void clearCache() {
abstract int getIamTokenExpiration(Properties props);
abstract void checkIdpCredentialsWithFallback(Properties props);
+
+ /** Returns a value that keeps this plugin's cached tokens apart from other plugins' tokens. */
+ abstract String getCacheKeyScope();
+
+ /** Returns the configured values that determine the AWS identity used to sign the token. */
+ abstract @Nullable String[] getCredentialsIdentity(Properties props);
}
diff --git a/wrapper/src/main/java/software/amazon/jdbc/plugin/federatedauth/FederatedAuthPlugin.java b/wrapper/src/main/java/software/amazon/jdbc/plugin/federatedauth/FederatedAuthPlugin.java
index a5709fc736..7ef617db30 100644
--- a/wrapper/src/main/java/software/amazon/jdbc/plugin/federatedauth/FederatedAuthPlugin.java
+++ b/wrapper/src/main/java/software/amazon/jdbc/plugin/federatedauth/FederatedAuthPlugin.java
@@ -156,4 +156,20 @@ int getIamTokenExpiration(Properties props) {
void checkIdpCredentialsWithFallback(Properties props) {
this.samlUtils.checkIdpCredentialsWithFallback(IDP_USERNAME, IDP_PASSWORD, props);
}
+
+ @Override
+ String getCacheKeyScope() {
+ return "federatedAuth";
+ }
+
+ @Override
+ @Nullable String[] getCredentialsIdentity(Properties props) {
+ return new @Nullable String[] {
+ IDP_ENDPOINT.getString(props),
+ IDP_PORT.getString(props),
+ RELAYING_PARTY_ID.getString(props),
+ IDP_USERNAME.getString(props),
+ IAM_ROLE_ARN.getString(props),
+ IAM_IDP_ARN.getString(props)};
+ }
}
diff --git a/wrapper/src/main/java/software/amazon/jdbc/plugin/federatedauth/OktaAuthPlugin.java b/wrapper/src/main/java/software/amazon/jdbc/plugin/federatedauth/OktaAuthPlugin.java
index fb96fa2c2f..fdb56dd6c1 100644
--- a/wrapper/src/main/java/software/amazon/jdbc/plugin/federatedauth/OktaAuthPlugin.java
+++ b/wrapper/src/main/java/software/amazon/jdbc/plugin/federatedauth/OktaAuthPlugin.java
@@ -130,4 +130,19 @@ int getIamTokenExpiration(Properties props) {
void checkIdpCredentialsWithFallback(Properties props) {
this.samlUtils.checkIdpCredentialsWithFallback(IDP_USERNAME, IDP_PASSWORD, props);
}
+
+ @Override
+ String getCacheKeyScope() {
+ return "okta";
+ }
+
+ @Override
+ @Nullable String[] getCredentialsIdentity(Properties props) {
+ return new @Nullable String[] {
+ IDP_ENDPOINT.getString(props),
+ APP_ID.getString(props),
+ IDP_USERNAME.getString(props),
+ IAM_ROLE_ARN.getString(props),
+ IAM_IDP_ARN.getString(props)};
+ }
}
diff --git a/wrapper/src/main/java/software/amazon/jdbc/plugin/iam/IamAuthConnectionPlugin.java b/wrapper/src/main/java/software/amazon/jdbc/plugin/iam/IamAuthConnectionPlugin.java
index 43aa5917e6..a0c1886f22 100644
--- a/wrapper/src/main/java/software/amazon/jdbc/plugin/iam/IamAuthConnectionPlugin.java
+++ b/wrapper/src/main/java/software/amazon/jdbc/plugin/iam/IamAuthConnectionPlugin.java
@@ -29,6 +29,7 @@
import java.util.logging.Logger;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
+import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.jdbc.AwsWrapperProperty;
import software.amazon.jdbc.HostSpec;
@@ -66,6 +67,7 @@ public class IamAuthConnectionPlugin extends AbstractConnectionPlugin implements
});
private static final int DEFAULT_TOKEN_EXPIRATION_SEC = 15 * 60 - 30;
private static final long DISPOSAL_TIME_NANO = TimeUnit.MINUTES.toNanos(15);
+ private static final String CACHE_KEY_SCOPE = "iam";
public static final AwsWrapperProperty IAM_HOST = new AwsWrapperProperty(
"iamHost", null,
@@ -170,11 +172,10 @@ private Connection connectInternal(String driverProtocol, HostSpec hostSpec, Pro
final int tokenExpirationSec = IAM_EXPIRATION.getInteger(props);
- final String cacheKey = IamAuthUtils.getCacheKey(
- user,
- host.getHost(),
- port,
- region);
+ // A token is only valid for the credentials that signed it, so the resolved credentials are part of
+ // the key: connections that sign with different credentials must not share a token.
+ final AwsCredentialsProvider credentialsProvider = AwsCredentialsManager.getProvider(hostSpec, props, region);
+ final String cacheKey = this.getCacheKey(credentialsProvider, user, host.getHost(), port, region);
final TokenInfo tokenInfo = this.servicesContainer.getStorageService().get(TokenInfo.class, cacheKey);
final boolean isCachedToken = tokenInfo != null && !tokenInfo.isExpired();
@@ -199,7 +200,7 @@ private Connection connectInternal(String driverProtocol, HostSpec hostSpec, Pro
host.getHost(),
port,
region,
- AwsCredentialsManager.getProvider(hostSpec, props, region));
+ credentialsProvider);
LOGGER.finest(
() -> Messages.get(
"AuthenticationToken.generatedNewToken",
@@ -232,6 +233,10 @@ private Connection connectInternal(String driverProtocol, HostSpec hostSpec, Pro
if (this.fetchTokenCounter != null) {
this.fetchTokenCounter.inc();
}
+ // Use a fresh provider, which may resolve newer credentials, and key the new token by them.
+ final AwsCredentialsProvider retryCredentialsProvider =
+ AwsCredentialsManager.getProvider(hostSpec, props, region);
+ final String retryCacheKey = this.getCacheKey(retryCredentialsProvider, user, host.getHost(), port, region);
final String token = IamAuthUtils.generateAuthenticationToken(
iamTokenUtility,
pluginService,
@@ -239,14 +244,14 @@ private Connection connectInternal(String driverProtocol, HostSpec hostSpec, Pro
host.getHost(),
port,
region,
- AwsCredentialsManager.getProvider(hostSpec, props, region));
+ retryCredentialsProvider);
LOGGER.finest(
() -> Messages.get(
"AuthenticationToken.generatedNewToken",
new Object[] {token}));
props.setProperty(iamTokenPropertyName, token);
this.servicesContainer.getStorageService().set(
- cacheKey,
+ retryCacheKey,
new TokenInfo(token, tokenExpiry));
return connectFunc.call();
@@ -260,6 +265,21 @@ private Connection connectInternal(String driverProtocol, HostSpec hostSpec, Pro
}
}
+ private String getCacheKey(
+ final AwsCredentialsProvider credentialsProvider,
+ final String user,
+ final String host,
+ final int port,
+ final Region region) {
+ return IamAuthUtils.getCacheKey(
+ CACHE_KEY_SCOPE,
+ new @Nullable String[] {IamAuthUtils.getCredentialsIdentity(credentialsProvider)},
+ user,
+ host,
+ port,
+ region);
+ }
+
@Override
public Connection forceConnect(
final @NonNull String driverProtocol,
diff --git a/wrapper/src/main/java/software/amazon/jdbc/util/IamAuthUtils.java b/wrapper/src/main/java/software/amazon/jdbc/util/IamAuthUtils.java
index 33bc1186e1..587b06d42e 100644
--- a/wrapper/src/main/java/software/amazon/jdbc/util/IamAuthUtils.java
+++ b/wrapper/src/main/java/software/amazon/jdbc/util/IamAuthUtils.java
@@ -16,8 +16,13 @@
package software.amazon.jdbc.util;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.Base64;
import java.util.logging.Logger;
import org.checkerframework.checker.nullness.qual.Nullable;
+import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.jdbc.HostSpec;
@@ -61,6 +66,72 @@ public static String getCacheKey(
return String.format("%s:%s:%d:%s", region, hostname, port, user);
}
+ /**
+ * Builds an authentication token cache key that is scoped to the identity used to sign the token.
+ *
+ * <p>A token is only valid for the AWS identity that signed it. Two connections that target the same
+ * region, host, port and database user but sign with different identities (for example, different
+ * AWS credentials, or different federated users or roles) must not share a cached token.
+ *
+ * @param scope the plugin that owns the token, so different plugins never share an entry.
+ * @param identity the components that identify the signing identity, as configured for the connection.
+ * @param user the database user.
+ * @param hostname the host the token is generated for.
+ * @param port the port the token is generated for.
+ * @param region the region the token is generated for.
+ * @return the cache key.
+ */
+ public static String getCacheKey(
+ final String scope,
+ final @Nullable String[] identity,
+ final @Nullable String user,
+ final String hostname,
+ final int port,
+ final Region region) {
+ final StringBuilder sb = new StringBuilder()
+ .append(escapeCacheKeyComponent(scope))
+ .append(':').append(region)
+ .append(':').append(escapeCacheKeyComponent(hostname))
+ .append(':').append(port)
+ .append(':').append(escapeCacheKeyComponent(user));
+ for (final @Nullable String component : identity) {
+ sb.append(':').append(escapeCacheKeyComponent(component));
+ }
+ return sb.toString();
+ }
+
+ /**
+ * Returns a value that identifies the AWS credentials the provider currently resolves to, for use as a
+ * cache key component. It is derived from the access key ID, so it changes whenever the provider starts
+ * returning different credentials (for example, after the profile in the credentials file is edited, or
+ * when temporary credentials are refreshed). The access key ID is hashed so the raw ID is not kept in
+ * the cache key.
+ *
+ * @param credentialsProvider the provider that will sign the token.
+ * @return a SHA-256 hash of the resolved access key ID, Base64-encoded.
+ */
+ public static String getCredentialsIdentity(final AwsCredentialsProvider credentialsProvider) {
+ final AwsCredentials credentials = credentialsProvider.resolveCredentials();
+ try {
+ final MessageDigest digest = MessageDigest.getInstance("SHA-256");
+ final byte[] hash = digest.digest(credentials.accessKeyId().getBytes(StandardCharsets.UTF_8));
+ return Base64.getEncoder().encodeToString(hash);
+ } catch (final NoSuchAlgorithmException e) {
+ throw new IllegalStateException(Messages.get("IamAuthUtils.sha256NotAvailable"), e);
+ }
+ }
+
+ /**
+ * Escapes a cache key component so that values containing the separator cannot make two different
+ * identities produce the same key. A null component is encoded differently from an empty one.
+ */
+ private static String escapeCacheKeyComponent(final @Nullable String component) {
+ if (component == null) {
+ return "\\0";
+ }
+ return component.replace("\\", "\\\\").replace(":", "\\:");
+ }
+
public static IamTokenUtility getTokenUtility() {
try {
// RegularRdsUtility requires AWS Java SDK RDS v2.x to be presented in classpath.
diff --git a/wrapper/src/main/resources/aws_advanced_jdbc_wrapper_messages.properties b/wrapper/src/main/resources/aws_advanced_jdbc_wrapper_messages.properties
index b1e4ac35c6..8e0be2150c 100644
--- a/wrapper/src/main/resources/aws_advanced_jdbc_wrapper_messages.properties
+++ b/wrapper/src/main/resources/aws_advanced_jdbc_wrapper_messages.properties
@@ -358,6 +358,8 @@ IamAuthConnectionPlugin.unhandledException=Unhandled exception: ''{0}''
IamAuthConnectionPlugin.connectException=Error occurred while opening a connection: ''{0}''
IamAuthConnectionPlugin.unableToDetermineRegion=Unable to determine connection region. If you are using a non-standard RDS URL, please set the ''{0}'' property.
+IamAuthUtils.sha256NotAvailable=SHA-256 algorithm is required to build the authentication token cache key but is not available.
+
PartialPluginService.unexpectedMethodCall=Calling ''{0}()'' is not supported with this PluginService.
LimitlessConnectionPlugin.failedToConnectToHost=Failed to connect to host {0}.
diff --git a/wrapper/src/test/java/software/amazon/jdbc/plugin/federatedauth/FederatedAuthPluginTest.java b/wrapper/src/test/java/software/amazon/jdbc/plugin/federatedauth/FederatedAuthPluginTest.java
index 77344c1af0..fc5aed5c58 100644
--- a/wrapper/src/test/java/software/amazon/jdbc/plugin/federatedauth/FederatedAuthPluginTest.java
+++ b/wrapper/src/test/java/software/amazon/jdbc/plugin/federatedauth/FederatedAuthPluginTest.java
@@ -31,6 +31,7 @@
import java.util.Properties;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
+import org.checkerframework.checker.nullness.qual.Nullable;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -124,7 +125,7 @@ void testCachedToken() throws SQLException {
FederatedAuthPlugin plugin =
new FederatedAuthPlugin(mockServicesContainer, mockCredentialsProviderFactory);
- String key = "us-east-2:pg.testdb.us-east-2.rds.amazonaws.com:" + DEFAULT_PORT + ":iamUser";
+ String key = cacheKey("us-east-2:pg.testdb.us-east-2.rds.amazonaws.com:" + DEFAULT_PORT + ":iamUser", null);
when(mockStorageService.get(eq(TokenInfo.class), eq(key))).thenReturn(TEST_TOKEN_INFO);
plugin.connect(DRIVER_PROTOCOL, HOST_SPEC, props, true, mockLambda);
@@ -139,7 +140,7 @@ void testExpiredCachedToken() throws SQLException {
new FederatedAuthPlugin(
mockServicesContainer, mockCredentialsProviderFactory, mockRdsUtils, mockIamTokenUtils));
- String key = "us-east-2:pg.testdb.us-east-2.rds.amazonaws.com:" + DEFAULT_PORT + ":iamUser";
+ String key = cacheKey("us-east-2:pg.testdb.us-east-2.rds.amazonaws.com:" + DEFAULT_PORT + ":iamUser", null);
String someExpiredToken = "someExpiredToken";
TokenInfo expiredTokenInfo = new TokenInfo(
someExpiredToken, Instant.now().minusMillis(300000));
@@ -182,7 +183,7 @@ void testSpecifiedIamHostPortRegion() throws SQLException {
props.setProperty(FederatedAuthPlugin.IAM_DEFAULT_PORT.name, String.valueOf(expectedPort));
props.setProperty(FederatedAuthPlugin.IAM_REGION.name, expectedRegion.toString());
- final String key = "us-west-2:pg.testdb.us-west-2.rds.amazonaws.com:" + expectedPort + ":iamUser";
+ final String key = cacheKey("us-west-2:pg.testdb.us-west-2.rds.amazonaws.com:" + expectedPort + ":iamUser", null);
when(mockStorageService.get(eq(TokenInfo.class), eq(key))).thenReturn(TEST_TOKEN_INFO);
FederatedAuthPlugin plugin =
@@ -205,7 +206,8 @@ void testIdpCredentialsFallback() throws SQLException {
new FederatedAuthPlugin(
mockServicesContainer, mockCredentialsProviderFactory, mockRdsUtils, mockIamTokenUtils);
- String key = "us-east-2:pg.testdb.us-east-2.rds.amazonaws.com:" + DEFAULT_PORT + ":iamUser";
+ String key = cacheKey(
+ "us-east-2:pg.testdb.us-east-2.rds.amazonaws.com:" + DEFAULT_PORT + ":iamUser", "expectedUser");
when(mockStorageService.get(eq(TokenInfo.class), eq(key))).thenReturn(TEST_TOKEN_INFO);
plugin.connect(DRIVER_PROTOCOL, HOST_SPEC, props, true, mockLambda);
@@ -234,4 +236,59 @@ public void testUsingIamHost() throws SQLException {
DEFAULT_PORT,
DB_USER);
}
-}
+
+ @Test
+ void testCachedTokenNotReusedForDifferentRole() throws SQLException {
+ // A token cached for one role must not be handed to a connection that assumes another role.
+ final String roleA = "arn:aws:iam::123456789012:role/roleA";
+ final String roleB = "arn:aws:iam::123456789012:role/roleB";
+ final String keyPrefix = "us-east-2:pg.testdb.us-east-2.rds.amazonaws.com:" + DEFAULT_PORT + ":iamUser";
+ FederatedAuthPlugin.IDP_USERNAME.set(props, "idpUser");
+ FederatedAuthPlugin.IAM_ROLE_ARN.set(props, roleB);
+ when(mockStorageService.get(eq(TokenInfo.class), eq(cacheKey(keyPrefix, "idpUser", roleA))))
+ .thenReturn(TEST_TOKEN_INFO);
+
+ final FederatedAuthPlugin plugin =
+ new FederatedAuthPlugin(mockServicesContainer, mockCredentialsProviderFactory, mockRdsUtils, mockIamTokenUtils);
+ plugin.connect(DRIVER_PROTOCOL, HOST_SPEC, props, true, mockLambda);
+
+ verify(mockIamTokenUtils, times(1)).generateAuthenticationToken(
+ mockAwsCredentialsProvider,
+ Region.US_EAST_2,
+ HOST_SPEC.getHost(),
+ DEFAULT_PORT,
+ DB_USER);
+ verify(mockStorageService, times(1)).set(eq(cacheKey(keyPrefix, "idpUser", roleB)), any(TokenInfo.class));
+ }
+
+ @Test
+ void testCachedTokenNotReusedForDifferentIdpUser() throws SQLException {
+ final String keyPrefix = "us-east-2:pg.testdb.us-east-2.rds.amazonaws.com:" + DEFAULT_PORT + ":iamUser";
+ FederatedAuthPlugin.IDP_USERNAME.set(props, "idpUserB");
+ when(mockStorageService.get(eq(TokenInfo.class), eq(cacheKey(keyPrefix, "idpUserA"))))
+ .thenReturn(TEST_TOKEN_INFO);
+
+ final FederatedAuthPlugin plugin =
+ new FederatedAuthPlugin(mockServicesContainer, mockCredentialsProviderFactory, mockRdsUtils, mockIamTokenUtils);
+ plugin.connect(DRIVER_PROTOCOL, HOST_SPEC, props, true, mockLambda);
+
+ verify(mockIamTokenUtils, times(1)).generateAuthenticationToken(
+ mockAwsCredentialsProvider,
+ Region.US_EAST_2,
+ HOST_SPEC.getHost(),
+ DEFAULT_PORT,
+ DB_USER);
+ verify(mockStorageService, times(1)).set(eq(cacheKey(keyPrefix, "idpUserB")), any(TokenInfo.class));
+ }
+
+ private static String cacheKey(final String regionHostPortUser, final @Nullable String idpUser) {
+ return cacheKey(regionHostPortUser, idpUser, null);
+ }
+
+ private static String cacheKey(
+ final String regionHostPortUser, final @Nullable String idpUser, final @Nullable String roleArn) {
+ return "federatedAuth:" + regionHostPortUser + ":\\0:443:urn\\:amazon\\:webservices:"
+ + (idpUser == null ? "\\0" : idpUser) + ":"
+ + (roleArn == null ? "\\0" : roleArn.replace(":", "\\:")) + ":\\0";
+ }
+}
\ No newline at end of file
diff --git a/wrapper/src/test/java/software/amazon/jdbc/plugin/federatedauth/OktaAuthPluginTest.java b/wrapper/src/test/java/software/amazon/jdbc/plugin/federatedauth/OktaAuthPluginTest.java
index c6329e2a26..36250b8eae 100644
--- a/wrapper/src/test/java/software/amazon/jdbc/plugin/federatedauth/OktaAuthPluginTest.java
+++ b/wrapper/src/test/java/software/amazon/jdbc/plugin/federatedauth/OktaAuthPluginTest.java
@@ -29,6 +29,7 @@
import java.sql.SQLException;
import java.time.Instant;
import java.util.Properties;
+import org.checkerframework.checker.nullness.qual.Nullable;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -118,7 +119,7 @@ void testCachedToken() throws SQLException {
final OktaAuthPlugin plugin =
new OktaAuthPlugin(mockServicesContainer, mockCredentialsProviderFactory, mockRdsUtils, mockIamTokenUtils);
- String key = "us-east-2:pg.testdb.us-east-2.rds.amazonaws.com:" + DEFAULT_PORT + ":iamUser";
+ String key = cacheKey("us-east-2:pg.testdb.us-east-2.rds.amazonaws.com:" + DEFAULT_PORT + ":iamUser", null);
when(mockStorageService.get(eq(TokenInfo.class), eq(key))).thenReturn(TEST_TOKEN_INFO);
plugin.connect(DRIVER_PROTOCOL, HOST_SPEC, props, true, mockLambda);
@@ -132,7 +133,7 @@ void testExpiredCachedToken() throws SQLException {
final OktaAuthPlugin spyPlugin =
new OktaAuthPlugin(mockServicesContainer, mockCredentialsProviderFactory, mockRdsUtils, mockIamTokenUtils);
- final String key = "us-east-2:pg.testdb.us-east-2.rds.amazonaws.com:" + DEFAULT_PORT + ":iamUser";
+ final String key = cacheKey("us-east-2:pg.testdb.us-east-2.rds.amazonaws.com:" + DEFAULT_PORT + ":iamUser", null);
final String someExpiredToken = "someExpiredToken";
final TokenInfo expiredTokenInfo = new TokenInfo(
someExpiredToken, Instant.now().minusMillis(300000));
@@ -174,7 +175,7 @@ void testSpecifiedIamHostPortRegion() throws SQLException {
props.setProperty(OktaAuthPlugin.IAM_DEFAULT_PORT.name, String.valueOf(expectedPort));
props.setProperty(OktaAuthPlugin.IAM_REGION.name, expectedRegion.toString());
- final String key = "us-west-2:pg.testdb.us-west-2.rds.amazonaws.com:" + expectedPort + ":iamUser";
+ final String key = cacheKey("us-west-2:pg.testdb.us-west-2.rds.amazonaws.com:" + expectedPort + ":iamUser", null);
when(mockStorageService.get(eq(TokenInfo.class), eq(key))).thenReturn(TEST_TOKEN_INFO);
OktaAuthPlugin plugin =
@@ -196,7 +197,8 @@ void testIdpCredentialsFallback() throws SQLException {
final OktaAuthPlugin plugin =
new OktaAuthPlugin(mockServicesContainer, mockCredentialsProviderFactory, mockRdsUtils, mockIamTokenUtils);
- final String key = "us-east-2:pg.testdb.us-east-2.rds.amazonaws.com:" + DEFAULT_PORT + ":iamUser";
+ final String key = cacheKey(
+ "us-east-2:pg.testdb.us-east-2.rds.amazonaws.com:" + DEFAULT_PORT + ":iamUser", "expectedUser");
when(mockStorageService.get(eq(TokenInfo.class), eq(key))).thenReturn(TEST_TOKEN_INFO);
plugin.connect(DRIVER_PROTOCOL, HOST_SPEC, props, true, mockLambda);
@@ -224,4 +226,59 @@ public void testUsingIamHost() throws SQLException {
DEFAULT_PORT,
DB_USER);
}
-}
+
+ @Test
+ void testCachedTokenNotReusedForDifferentRole() throws SQLException {
+ // A token cached for one role must not be handed to a connection that assumes another role.
+ final String roleA = "arn:aws:iam::123456789012:role/roleA";
+ final String roleB = "arn:aws:iam::123456789012:role/roleB";
+ final String keyPrefix = "us-east-2:pg.testdb.us-east-2.rds.amazonaws.com:" + DEFAULT_PORT + ":iamUser";
+ OktaAuthPlugin.IDP_USERNAME.set(props, "idpUser");
+ OktaAuthPlugin.IAM_ROLE_ARN.set(props, roleB);
+ when(mockStorageService.get(eq(TokenInfo.class), eq(cacheKey(keyPrefix, "idpUser", roleA))))
+ .thenReturn(TEST_TOKEN_INFO);
+
+ final OktaAuthPlugin plugin =
+ new OktaAuthPlugin(mockServicesContainer, mockCredentialsProviderFactory, mockRdsUtils, mockIamTokenUtils);
+ plugin.connect(DRIVER_PROTOCOL, HOST_SPEC, props, true, mockLambda);
+
+ verify(mockIamTokenUtils, times(1)).generateAuthenticationToken(
+ mockAwsCredentialsProvider,
+ Region.US_EAST_2,
+ HOST_SPEC.getHost(),
+ DEFAULT_PORT,
+ DB_USER);
+ verify(mockStorageService, times(1)).set(eq(cacheKey(keyPrefix, "idpUser", roleB)), any(TokenInfo.class));
+ }
+
+ @Test
+ void testCachedTokenNotReusedForDifferentIdpUser() throws SQLException {
+ final String keyPrefix = "us-east-2:pg.testdb.us-east-2.rds.amazonaws.com:" + DEFAULT_PORT + ":iamUser";
+ OktaAuthPlugin.IDP_USERNAME.set(props, "idpUserB");
+ when(mockStorageService.get(eq(TokenInfo.class), eq(cacheKey(keyPrefix, "idpUserA"))))
+ .thenReturn(TEST_TOKEN_INFO);
+
+ final OktaAuthPlugin plugin =
+ new OktaAuthPlugin(mockServicesContainer, mockCredentialsProviderFactory, mockRdsUtils, mockIamTokenUtils);
+ plugin.connect(DRIVER_PROTOCOL, HOST_SPEC, props, true, mockLambda);
+
+ verify(mockIamTokenUtils, times(1)).generateAuthenticationToken(
+ mockAwsCredentialsProvider,
+ Region.US_EAST_2,
+ HOST_SPEC.getHost(),
+ DEFAULT_PORT,
+ DB_USER);
+ verify(mockStorageService, times(1)).set(eq(cacheKey(keyPrefix, "idpUserB")), any(TokenInfo.class));
+ }
+
+ private static String cacheKey(final String regionHostPortUser, final @Nullable String idpUser) {
+ return cacheKey(regionHostPortUser, idpUser, null);
+ }
+
+ private static String cacheKey(
+ final String regionHostPortUser, final @Nullable String idpUser, final @Nullable String roleArn) {
+ return "okta:" + regionHostPortUser + ":\\0:\\0:"
+ + (idpUser == null ? "\\0" : idpUser) + ":"
+ + (roleArn == null ? "\\0" : roleArn.replace(":", "\\:")) + ":\\0";
+ }
+}
\ No newline at end of file
diff --git a/wrapper/src/test/java/software/amazon/jdbc/plugin/iam/IamAuthConnectionPluginTest.java b/wrapper/src/test/java/software/amazon/jdbc/plugin/iam/IamAuthConnectionPluginTest.java
index 69a6e84237..c2d4c236be 100644
--- a/wrapper/src/test/java/software/amazon/jdbc/plugin/iam/IamAuthConnectionPluginTest.java
+++ b/wrapper/src/test/java/software/amazon/jdbc/plugin/iam/IamAuthConnectionPluginTest.java
@@ -39,8 +39,10 @@
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
+import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
+import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
-import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
+import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.jdbc.Driver;
import software.amazon.jdbc.HostSpec;
@@ -48,10 +50,12 @@
import software.amazon.jdbc.JdbcCallable;
import software.amazon.jdbc.PluginService;
import software.amazon.jdbc.PropertyDefinition;
+import software.amazon.jdbc.authentication.AwsCredentialsManager;
import software.amazon.jdbc.dialect.Dialect;
import software.amazon.jdbc.hostavailability.SimpleHostAvailabilityStrategy;
import software.amazon.jdbc.plugin.TokenInfo;
import software.amazon.jdbc.util.FullServicesContainer;
+import software.amazon.jdbc.util.IamAuthUtils;
import software.amazon.jdbc.util.RdsUtils;
import software.amazon.jdbc.util.storage.StorageService;
import software.amazon.jdbc.util.telemetry.TelemetryContext;
@@ -64,11 +68,15 @@ class IamAuthConnectionPluginTest {
private static final String GENERATED_TOKEN = "generatedToken";
private static final String TEST_TOKEN = "testToken";
private static final int DEFAULT_PG_PORT = 5432;
+ private static final AwsCredentials CREDENTIALS_A = AwsBasicCredentials.create("AKIAEXAMPLEA", "secretA");
+ private static final AwsCredentials CREDENTIALS_B = AwsBasicCredentials.create("AKIAEXAMPLEB", "secretB");
private static final int DEFAULT_MYSQL_PORT = 3306;
- private static final String PG_CACHE_KEY = "us-east-2:pg.testdb.us-east-2.rds.amazonaws.com:"
+ private static final String PG_CACHE_KEY = cacheKey("us-east-2:pg.testdb.us-east-2.rds.amazonaws.com:"
+ + DEFAULT_PG_PORT + ":postgresqlUser");
+ private static final String MYSQL_CACHE_KEY = cacheKey("us-east-2:mysql.testdb.us-east-2.rds.amazonaws.com:"
+ + DEFAULT_MYSQL_PORT + ":mysqlUser");
+ private static final String PG_KEY_PREFIX = "us-east-2:pg.testdb.us-east-2.rds.amazonaws.com:"
+ DEFAULT_PG_PORT + ":postgresqlUser";
- private static final String MYSQL_CACHE_KEY = "us-east-2:mysql.testdb.us-east-2.rds.amazonaws.com:"
- + DEFAULT_MYSQL_PORT + ":mysqlUser";
private static final String PG_DRIVER_PROTOCOL = "jdbc:postgresql:";
private static final String MYSQL_DRIVER_PROTOCOL = "jdbc:mysql:";
private static final HostSpec PG_HOST_SPEC = new HostSpecBuilder(new SimpleHostAvailabilityStrategy())
@@ -92,6 +100,7 @@ class IamAuthConnectionPluginTest {
@Mock private RdsUtils mockRdsUtils;
@Mock private IamTokenUtility mockIamTokenUtils;
private AutoCloseable closable;
+ private AwsCredentials currentCredentials;
@BeforeEach
public void init() {
@@ -101,6 +110,10 @@ public void init() {
props.setProperty(PropertyDefinition.PASSWORD.name, "postgresqlPassword");
props.setProperty(PropertyDefinition.PLUGINS.name, "iam");
IamAuthConnectionPlugin.clearCache();
+ // Sign with fixed credentials instead of the default chain, so the tests control the identity.
+ currentCredentials = CREDENTIALS_A;
+ AwsCredentialsManager.setCustomHandler(
+ (hostSpec, properties) -> StaticCredentialsProvider.create(currentCredentials));
when(mockRdsUtils.getRdsRegion(anyString())).thenReturn("us-east-2");
when(mockIamTokenUtils.generateAuthenticationToken(
@@ -121,6 +134,7 @@ public void init() {
@AfterEach
public void cleanUp() throws Exception {
+ AwsCredentialsManager.resetCustomHandler();
closable.close();
}
@@ -162,8 +176,8 @@ public void testPostgresConnectWithInvalidPortFallbacksToHostPort() throws SQLEx
final String invalidIamDefaultPort = "0";
props.setProperty(IamAuthConnectionPlugin.IAM_DEFAULT_PORT.name, invalidIamDefaultPort);
- final String cacheKeyWithNewPort = "us-east-2:pg.testdb.us-east-2.rds.amazonaws.com:"
- + PG_HOST_SPEC_WITH_PORT.getPort() + ":postgresqlUser";
+ final String cacheKeyWithNewPort = cacheKey("us-east-2:pg.testdb.us-east-2.rds.amazonaws.com:"
+ + PG_HOST_SPEC_WITH_PORT.getPort() + ":postgresqlUser");
when(mockStorageService.get(eq(TokenInfo.class), eq(cacheKeyWithNewPort)))
.thenReturn(new TokenInfo(TEST_TOKEN, Instant.now().plusMillis(300000)));
@@ -177,8 +191,8 @@ public void testPostgresConnectWithInvalidPortAndNoHostPortFallbacksToHostPort()
when(mockDialect.getDefaultPort()).thenReturn(DEFAULT_PG_PORT);
- final String cacheKeyWithNewPort = "us-east-2:pg.testdb.us-east-2.rds.amazonaws.com:"
- + DEFAULT_PG_PORT + ":postgresqlUser";
+ final String cacheKeyWithNewPort = cacheKey("us-east-2:pg.testdb.us-east-2.rds.amazonaws.com:"
+ + DEFAULT_PG_PORT + ":postgresqlUser");
when(mockStorageService.get(eq(TokenInfo.class), eq(cacheKeyWithNewPort)))
.thenReturn(new TokenInfo(TEST_TOKEN, Instant.now().plusMillis(300000)));
@@ -204,7 +218,7 @@ public void testConnectEmptyCache() throws SQLException {
@Test
public void testConnectWithSpecifiedPort() throws SQLException {
- final String cacheKeyWithNewPort = "us-east-2:pg.testdb.us-east-2.rds.amazonaws.com:1234:" + "postgresqlUser";
+ final String cacheKeyWithNewPort = cacheKey("us-east-2:pg.testdb.us-east-2.rds.amazonaws.com:1234:postgresqlUser");
when(mockStorageService.get(eq(TokenInfo.class), eq(cacheKeyWithNewPort)))
.thenReturn(new TokenInfo(TEST_TOKEN, Instant.now().plusMillis(300000)));
@@ -215,8 +229,8 @@ public void testConnectWithSpecifiedPort() throws SQLException {
public void testConnectWithSpecifiedIamDefaultPort() throws SQLException {
final String iamDefaultPort = "9999";
props.setProperty(IamAuthConnectionPlugin.IAM_DEFAULT_PORT.name, iamDefaultPort);
- final String cacheKeyWithNewPort = "us-east-2:pg.testdb.us-east-2.rds.amazonaws.com:"
- + iamDefaultPort + ":postgresqlUser";
+ final String cacheKeyWithNewPort = cacheKey("us-east-2:pg.testdb.us-east-2.rds.amazonaws.com:"
+ + iamDefaultPort + ":postgresqlUser");
when(mockStorageService.get(eq(TokenInfo.class), eq(cacheKeyWithNewPort)))
.thenReturn(new TokenInfo(TEST_TOKEN, Instant.now().plusMillis(300000)));
@@ -226,7 +240,7 @@ public void testConnectWithSpecifiedIamDefaultPort() throws SQLException {
@Test
public void testConnectWithSpecifiedRegion() throws SQLException {
final String cacheKeyWithNewRegion =
- "us-west-1:pg.testdb.us-west-1.rds.amazonaws.com:" + DEFAULT_PG_PORT + ":" + "postgresqlUser";
+ cacheKey("us-west-1:pg.testdb.us-west-1.rds.amazonaws.com:" + DEFAULT_PG_PORT + ":postgresqlUser");
props.setProperty(IamAuthConnectionPlugin.IAM_REGION.name, "us-west-1");
when(mockStorageService.get(eq(TokenInfo.class), eq(cacheKeyWithNewRegion)))
.thenReturn(new TokenInfo(TEST_TOKEN, Instant.now().plusMillis(300000)));
@@ -249,6 +263,31 @@ public void testConnectWithSpecifiedHost() throws SQLException {
"pg.testdb.us-east-2.rds.amazonaws.com");
}
+ @Test
+ public void testCachedTokenNotReusedForDifferentCredentials() throws SQLException {
+ // A token cached for one set of credentials must not be handed to a connection that signs with
+ // another, e.g. after the profile in the credentials file was changed, or when a custom
+ // credentials handler returns a different identity.
+ when(mockStorageService.get(eq(TokenInfo.class), eq(PG_CACHE_KEY)))
+ .thenReturn(new TokenInfo(TEST_TOKEN, Instant.now().plusMillis(300000)));
+ when(mockDialect.getDefaultPort()).thenReturn(DEFAULT_PG_PORT);
+ currentCredentials = CREDENTIALS_B;
+
+ testGenerateToken(PG_DRIVER_PROTOCOL, PG_HOST_SPEC, PG_HOST_SPEC.getHost(),
+ cacheKey(PG_KEY_PREFIX, CREDENTIALS_B));
+ }
+
+ @Test
+ public void testCachedTokenReusedForSameCredentialsRegardlessOfProfileName() throws SQLException {
+ // The key follows the resolved credentials, not the configured profile name.
+ when(mockStorageService.get(eq(TokenInfo.class), eq(PG_CACHE_KEY)))
+ .thenReturn(new TokenInfo(TEST_TOKEN, Instant.now().plusMillis(300000)));
+ when(mockDialect.getDefaultPort()).thenReturn(DEFAULT_PG_PORT);
+ props.setProperty(PropertyDefinition.AWS_PROFILE.name, "someProfile");
+
+ testTokenSetInProps(PG_DRIVER_PROTOCOL, PG_HOST_SPEC);
+ }
+
public void testTokenSetInProps(final String protocol, final HostSpec hostSpec) throws SQLException {
IamAuthConnectionPlugin targetPlugin = new IamAuthConnectionPlugin(mockServicesContainer, mockIamTokenUtils);
@@ -268,6 +307,14 @@ private void testGenerateToken(
final String protocol,
final HostSpec hostSpec,
final String expectedHost) throws SQLException {
+ testGenerateToken(protocol, hostSpec, expectedHost, PG_CACHE_KEY);
+ }
+
+ private void testGenerateToken(
+ final String protocol,
+ final HostSpec hostSpec,
+ final String expectedHost,
+ final String expectedCacheKey) throws SQLException {
final IamAuthConnectionPlugin targetPlugin = new IamAuthConnectionPlugin(mockServicesContainer, mockIamTokenUtils);
final IamAuthConnectionPlugin spyPlugin = Mockito.spy(targetPlugin);
@@ -277,7 +324,7 @@ private void testGenerateToken(
() -> spyPlugin.connect(protocol, hostSpec, props, true, mockLambda));
verify(mockIamTokenUtils).generateAuthenticationToken(
- any(DefaultCredentialsProvider.class),
+ any(AwsCredentialsProvider.class),
eq(Region.US_EAST_2),
eq(expectedHost),
eq(DEFAULT_PG_PORT),
@@ -291,7 +338,17 @@ private void testGenerateToken(
verify(mockStorageService, times(1)).set(keyArgumentCaptor.capture(), tokenArgumentCaptor.capture());
final Object actualKey = keyArgumentCaptor.getValue();
final TokenInfo actualToken = tokenArgumentCaptor.getValue();
- assertEquals(PG_CACHE_KEY, actualKey);
+ assertEquals(expectedCacheKey, actualKey);
assertEquals(GENERATED_TOKEN, actualToken.getToken());
}
-}
+
+ /** Builds the expected key for a connection that signs with {@link #CREDENTIALS_A}. */
+ private static String cacheKey(final String regionHostPortUser) {
+ return cacheKey(regionHostPortUser, CREDENTIALS_A);
+ }
+
+ private static String cacheKey(final String regionHostPortUser, final AwsCredentials credentials) {
+ return "iam:" + regionHostPortUser + ":"
+ + IamAuthUtils.getCredentialsIdentity(StaticCredentialsProvider.create(credentials));
+ }
+}
\ No newline at end of file
diff --git a/wrapper/src/test/java/software/amazon/jdbc/util/IamAuthUtilsTest.java b/wrapper/src/test/java/software/amazon/jdbc/util/IamAuthUtilsTest.java
new file mode 100644
index 0000000000..3dbfe89b60
--- /dev/null
+++ b/wrapper/src/test/java/software/amazon/jdbc/util/IamAuthUtilsTest.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. 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.
+ */
+
+package software.amazon.jdbc.util;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
+import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
+import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
+import software.amazon.awssdk.regions.Region;
+
+class IamAuthUtilsTest {
+
+ private static final String HOST = "db.cluster-xyz.us-east-2.rds.amazonaws.com";
+
+ @Test
+ void testCacheKeyIncludesScopeAndIdentity() {
+ assertEquals(
+ "iam:us-east-2:" + HOST + ":5432:dbUser:identityA",
+ key("iam", new @Nullable String[] {"identityA"}, "dbUser"));
+ }
+
+ @Test
+ void testCacheKeyDiffersByIdentity() {
+ assertNotEquals(
+ key("iam", new @Nullable String[] {"identityA"}, "dbUser"),
+ key("iam", new @Nullable String[] {"identityB"}, "dbUser"));
+ }
+
+ @Test
+ void testCacheKeyDiffersByScope() {
+ assertNotEquals(
+ key("iam", new @Nullable String[] {"x"}, "dbUser"),
+ key("okta", new @Nullable String[] {"x"}, "dbUser"));
+ }
+
+ @Test
+ void testCacheKeyDistinguishesNullFromEmptyIdentity() {
+ assertNotEquals(
+ key("iam", new @Nullable String[] {null}, "dbUser"),
+ key("iam", new @Nullable String[] {""}, "dbUser"));
+ }
+
+ @Test
+ void testCacheKeySeparatorInComponentsCannotCollide() {
+ // Without escaping, both of these would produce "...:a:b:c".
+ assertNotEquals(
+ key("iam", new @Nullable String[] {"a:b", "c"}, "dbUser"),
+ key("iam", new @Nullable String[] {"a", "b:c"}, "dbUser"));
+ assertNotEquals(
+ key("iam", new @Nullable String[] {"b"}, "dbUser:a"),
+ key("iam", new @Nullable String[] {"a:b"}, "dbUser"));
+ }
+
+ @Test
+ void testCredentialsIdentityFollowsAccessKeyId() {
+ final String identityA = IamAuthUtils.getCredentialsIdentity(
+ StaticCredentialsProvider.create(AwsBasicCredentials.create("AKIAEXAMPLEA", "secret1")));
+ final String identityB = IamAuthUtils.getCredentialsIdentity(
+ StaticCredentialsProvider.create(AwsBasicCredentials.create("AKIAEXAMPLEB", "secret1")));
+ final String identityARotatedSecret = IamAuthUtils.getCredentialsIdentity(
+ StaticCredentialsProvider.create(AwsBasicCredentials.create("AKIAEXAMPLEA", "secret2")));
+
+ assertNotEquals(identityA, identityB);
+ assertEquals(identityA, identityARotatedSecret);
+ }
+
+ @Test
+ void testCredentialsIdentityDiffersForTemporaryCredentials() {
+ // Each set of temporary credentials has its own access key ID.
+ assertNotEquals(
+ IamAuthUtils.getCredentialsIdentity(StaticCredentialsProvider.create(
+ AwsSessionCredentials.create("ASIAEXAMPLE1", "secret", "token1"))),
+ IamAuthUtils.getCredentialsIdentity(StaticCredentialsProvider.create(
+ AwsSessionCredentials.create("ASIAEXAMPLE2", "secret", "token2"))));
+ }
+
+ @Test
+ void testCredentialsIdentityDoesNotExposeAccessKeyIdOrSecret() {
+ final String identity = IamAuthUtils.getCredentialsIdentity(
+ StaticCredentialsProvider.create(AwsBasicCredentials.create("AKIAEXAMPLEA", "secretValue")));
+
+ assertFalse(identity.contains("AKIAEXAMPLEA"));
+ assertFalse(identity.contains("secretValue"));
+ }
+
+ private static String key(final String scope, final @Nullable String[] identity, final String user) {
+ return IamAuthUtils.getCacheKey(scope, identity, user, HOST, 5432, Region.US_EAST_2);
+ }
+}
Message-ID: <gh-aws-aws-advanced-jdbc-wrapper-2265@github.com>
Permalink: ../gh-aws-aws-advanced-jdbc-wrapper-2265@github.com/
· ·
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox