From 34760864b699498209692c8ce9979baee924aa23 Mon Sep 17 00:00:00 2001 From: aaron-congo Date: Wed, 2 Dec 2026 13:28:08 -0700 Subject: [PATCH] fix: key the Secrets Manager cache by the username and password JSON keys A cached secret entry holds the username and password picked with one configuration's secret_username_key and secret_password_key, but the cache key left them out. Two configurations reading different users from the same secret (for example an app user and a migration user) shared one entry, so the second connected as the first's database user. They also shared an in-flight fetch. The cache key now includes both JSON key names. It is also built as a frozen array of frozen strings instead of a colon-joined string, so values that contain a colon (ARNs, endpoint URLs, JSON key names) can no longer make two different keys equal. --- .../plugins/secrets_manager_plugin.rb | 25 +++- .../SKILL.md | 2 +- .../container/secrets_manager_spec.rb | 4 +- .../plugins/secrets_manager_plugin_spec.rb | 120 ++++++++++++++++-- 4 files changed, 134 insertions(+), 17 deletions(-) diff --git a/lib/aws_advanced_ruby_driver_wrapper/plugins/secrets_manager_plugin.rb b/lib/aws_advanced_ruby_driver_wrapper/plugins/secrets_manager_plugin.rb index bc042397..1fcda5f4 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/plugins/secrets_manager_plugin.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/plugins/secrets_manager_plugin.rb @@ -87,14 +87,26 @@ def release_pending_refreshes_after_fork @pending_refreshes.clear end - # The secret's value depends on which secret is read, from which region and endpoint, and - # with which AWS credentials, so all of them are part of the key. Connections that differ in - # any of them neither share a cached secret nor wait on each other's fetch. + # The cached entry depends on which secret is read, from which region and endpoint, with + # which AWS credentials, and which JSON fields are picked from it as the username and + # password, so all of them are part of the key. Connections that differ in any of them + # neither share a cached secret nor wait on each other's fetch. For example, an app user and + # a migration user stored in one secret under different JSON keys get separate entries. + # + # The key is an array rather than a delimited string, so values that contain the delimiter + # (an ARN, an endpoint URL, or a JSON key name) cannot make two different keys look equal. + # Each part is a frozen copy: a Hash freezes a copy of a String key but not of the strings + # inside an Array key, so without the copy, a caller mutating a configured value would + # change a stored key in place and its entry could no longer be found. # # @param endpoint [String, nil] the custom Secrets Manager endpoint, if any + # @param username_key [String] the secret's JSON key holding the database username + # @param password_key [String] the secret's JSON key holding the database password # @param credentials_identity [String] from {Utils::AwsCredentialsUtils.identity} - def cache_key(secret_id, region, endpoint, credentials_identity) - "#{secret_id}:#{region}:#{endpoint}:#{credentials_identity}" + def cache_key(secret_id, region, endpoint, username_key, password_key, credentials_identity) + [secret_id, region, endpoint, username_key, password_key, credentials_identity] + .map { |part| part && -part.to_s } + .freeze end end @@ -254,7 +266,8 @@ def load_secret_and_report_if_fresh?(force:) def secret_cache_key(credentials) return nil if credentials.nil? - self.class.cache_key(@secret_id, @region, @endpoint, Utils::AwsCredentialsUtils.identity(credentials)) + self.class.cache_key(@secret_id, @region, @endpoint, @username_key, @password_key, + Utils::AwsCredentialsUtils.identity(credentials)) end def fetch_synchronously(cache_key, credentials) diff --git a/skills/ruby-wrapper-configuration-assistant/SKILL.md b/skills/ruby-wrapper-configuration-assistant/SKILL.md index 7d8f2c16..917bda85 100644 --- a/skills/ruby-wrapper-configuration-assistant/SKILL.md +++ b/skills/ruby-wrapper-configuration-assistant/SKILL.md @@ -891,7 +891,7 @@ Fetches database credentials from a Secrets Manager secret (JSON) and connects w | `secret_rotation_retry_base_delay_sec` | Float | `0.5` | Initial delay for that loop; grows exponentially. Only used when the timeout is `> 0`. | | `aws_credentials_provider` | Object | SDK default chain | Custom credentials provider (ยง6.4). | -Secrets are cached process-wide, keyed by `secret_id`, region, `secret_endpoint`, and credential identity. A secret is served fresh for `secret_expiration_sec`. After that, the next connection still uses the cached value while a background refresh replaces it. If no refresh succeeds, the entry is dropped for good 20 minutes after it was fetched, regardless of `secret_expiration_sec`. A fetch that doesn't finish within 60 seconds fails with `SecretsManagerAuthError` (`Timed out fetching secret after 60s`). +Secrets are cached process-wide, keyed by `secret_id`, region, `secret_endpoint`, `secret_username_key`, `secret_password_key`, and credential identity, so configurations that read different users from one secret each get their own entry. A secret is served fresh for `secret_expiration_sec`. After that, the next connection still uses the cached value while a background refresh replaces it. If no refresh succeeds, the entry is dropped for good 20 minutes after it was fetched, regardless of `secret_expiration_sec`. A fetch that doesn't finish within 60 seconds fails with `SecretsManagerAuthError` (`Timed out fetching secret after 60s`). ### 5.7 `bg` - Blue/Green Deployment diff --git a/spec/integration/container/secrets_manager_spec.rb b/spec/integration/container/secrets_manager_spec.rb index fc38f165..169ba82a 100644 --- a/spec/integration/container/secrets_manager_spec.rb +++ b/spec/integration/container/secrets_manager_spec.rb @@ -300,10 +300,12 @@ def connected_host(conn) private # The plugin's cache key for the test secret, as read by a connection that uses the default AWS - # credentials and no custom Secrets Manager endpoint. + # credentials, no custom Secrets Manager endpoint, and the default username and password JSON keys. def cached_secret_key AwsAdvancedRubyDriverWrapper::Plugins::SecretsManagerPlugin.cache_key( @secret_id, region, nil, + AwsAdvancedRubyDriverWrapper::PropertyDefinition::SECRET_USERNAME_KEY.default_value, + AwsAdvancedRubyDriverWrapper::PropertyDefinition::SECRET_PASSWORD_KEY.default_value, AwsAdvancedRubyDriverWrapper::Utils::AwsCredentialsUtils.identity(Aws::CredentialProviderChain.new.resolve) ) end diff --git a/spec/unit/plugins/secrets_manager_plugin_spec.rb b/spec/unit/plugins/secrets_manager_plugin_spec.rb index 4e08c6c3..b5c95233 100644 --- a/spec/unit/plugins/secrets_manager_plugin_spec.rb +++ b/spec/unit/plugins/secrets_manager_plugin_spec.rb @@ -89,7 +89,7 @@ def expect_region_parsed_from_arn(arn, expected_region) plugin = build_plugin(props) plugin.connect(host_info, Concurrent::Map.new, true, -> {}) expect(mock_storage_service).to have_received(:get).with( - described_class::SECRETS_MANAGER_CACHE_NAME, a_string_starting_with("#{arn}:#{expected_region}:") + described_class::SECRETS_MANAGER_CACHE_NAME, a_collection_starting_with(arn, expected_region) ) end @@ -293,14 +293,17 @@ def expect_region_parsed_from_arn(arn, expected_region) end # The cached secret and the in-flight fetch are keyed by everything the fetched value depends on: - # the secret, its region and endpoint, and the AWS credentials it is read with. + # the secret, its region and endpoint, the AWS credentials it is read with, and the JSON keys the + # username and password are picked with. describe 'cache key' do - def plugin_with(credentials: mock_credentials, endpoint: nil) + def plugin_with(credentials: mock_credentials, endpoint: nil, username_key: nil, password_key: nil) props = Concurrent::Map.new props[:secret_id] = 'my-secret' props[:secret_region] = 'us-west-2' props[:aws_credentials_provider] = credentials props[:secret_endpoint] = endpoint if endpoint + props[:secret_username_key] = username_key if username_key + props[:secret_password_key] = password_key if password_key build_plugin(props) end @@ -314,10 +317,109 @@ def keys_read_by(plugin) keys end - it 'formats as secret_id:region:endpoint:credentials identity' do - expect(described_class.cache_key('my-secret', 'us-west-2', 'http://localhost:4566', 'abc123')) - .to eq('my-secret:us-west-2:http://localhost:4566:abc123') - expect(described_class.cache_key('my-secret', 'us-west-2', nil, 'abc123')).to eq('my-secret:us-west-2::abc123') + it 'holds the secret id, region, endpoint, JSON keys, and credentials identity' do + expect(described_class.cache_key('my-secret', 'us-west-2', 'http://localhost:4566', 'user', 'pass', 'abc123')) + .to eq(['my-secret', 'us-west-2', 'http://localhost:4566', 'user', 'pass', 'abc123']) + expect(described_class.cache_key('my-secret', 'us-west-2', nil, 'user', 'pass', 'abc123')) + .to eq(['my-secret', 'us-west-2', nil, 'user', 'pass', 'abc123']) + end + + it 'keeps keys apart when a value contains a colon' do + first = described_class.cache_key('my-secret', 'us-west-2', nil, 'a:b', 'c', 'abc123') + second = described_class.cache_key('my-secret', 'us-west-2', nil, 'a', 'b:c', 'abc123') + + expect(first).not_to eq(second) + end + + it 'is not changed by a later mutation of a value it was built from' do + username_key = +'app_username' + key = described_class.cache_key('my-secret', 'us-west-2', nil, username_key, 'app_password', 'abc123') + + username_key << '_changed' + + expect(key).to eq(['my-secret', 'us-west-2', nil, 'app_username', 'app_password', 'abc123']) + expect(key.compact).to all(be_frozen) + end + + context 'when the secret holds more than one user' do + let(:secret_json) do + '{"username":"dbuser","password":"dbpass","app_username":"app","app_password":"app_pass",' \ + '"migration_username":"migrator","migration_password":"m_pass"}' + end + + it 'gives connections with different username JSON keys different keys' do + first = keys_read_by(plugin_with(username_key: 'app_username')) + second = keys_read_by(plugin_with(username_key: 'migration_username')) + + expect(first.uniq).not_to eq(second.uniq) + end + + it 'gives connections with different password JSON keys different keys' do + first = keys_read_by(plugin_with(password_key: 'app_password')) + second = keys_read_by(plugin_with(password_key: 'migration_password')) + + expect(first.uniq).not_to eq(second.uniq) + end + + it 'gives connections with the same non-default JSON keys the same key' do + first = keys_read_by(plugin_with(username_key: +'app_username', password_key: +'app_password')) + second = keys_read_by(plugin_with(username_key: +'app_username', password_key: +'app_password')) + + expect(first.uniq).to eq(second.uniq) + end + + # A connection that joined another's in-flight fetch would be handed the user picked with the + # other connection's JSON keys, so each set of keys starts its own fetch. Each fetch waits until + # both have started, so the two are always in flight together: a connection that joined the + # other's fetch instead would leave only one call, which waits out the timeout. + it 'does not share an in-flight fetch between connections with different JSON keys' do + call_count = Concurrent::AtomicFixnum.new(0) + both_started = Concurrent::CountDownLatch.new(2) + allow(mock_sm_client).to receive(:get_secret_value) do + call_count.increment + both_started.count_down + both_started.wait(1) + secret_response + end + + plugins = [plugin_with(username_key: 'app_username', password_key: 'app_password'), + plugin_with(username_key: 'migration_username', password_key: 'migration_password')] + results = Array.new(plugins.size) + threads = plugins.each_with_index.map do |plugin, i| + Thread.new do + props = Concurrent::Map.new + plugin.connect(host_info, props, true, -> {}) + results[i] = props[:user] + end + end + threads.each(&:join) + + expect(call_count.value).to eq(2) + expect(results).to eq(%w[app migrator]) + end + end + + # One secret holding two database users under different JSON keys: each connection must log in + # as the user its own keys pick, even though both read the same secret through a shared cache. + it 'gives each set of JSON keys its own user from a shared secret' do + real_storage = AwsAdvancedRubyDriverWrapper::Utils::Storage::StorageService.new(event_publisher: nil) + allow(mock_service_container).to receive(:storage_service).and_return(real_storage) + allow(mock_sm_client).to receive(:get_secret_value).and_return( + double('GetSecretValueResponse', secret_string: '{"app_username":"app","app_password":"app_pass",' \ + '"migration_username":"migrator","migration_password":"m_pass"}') + ) + app = plugin_with(username_key: 'app_username', password_key: 'app_password') + migration = plugin_with(username_key: 'migration_username', password_key: 'migration_password') + + app_props = Concurrent::Map.new + migration_props = Concurrent::Map.new + app.connect(host_info, app_props, true, -> {}) + migration.connect(host_info, migration_props, true, -> {}) + + expect([app_props[:user], app_props[:password]]).to eq(%w[app app_pass]) + expect([migration_props[:user], migration_props[:password]]).to eq(%w[migrator m_pass]) + ensure + real_storage&.shutdown end it 'gives connections with different AWS credentials different keys' do @@ -364,7 +466,7 @@ def keys_read_by(plugin) it 'never puts the access key id itself in the key' do keys = keys_read_by(plugin_with(credentials: Aws::Credentials.new('AKIDVISIBLE', 'SECRET'))) - expect(keys).to all(satisfy { |key| !key.include?('AKIDVISIBLE') }) + expect(keys).to all(satisfy { |key| key.none? { |part| part.to_s.include?('AKIDVISIBLE') } }) end it 'stores the fetched secret under the key it was read with' do @@ -422,7 +524,7 @@ def keys_read_by(plugin) identity = AwsAdvancedRubyDriverWrapper::Utils::AwsCredentialsUtils.identity(Aws::Credentials.new('AKID1', 'x')) expect(client_key_ids).to eq(['AKID1']) - expect(stored_keys).to eq(["my-secret:us-west-2::#{identity}"]) + expect(stored_keys).to eq([['my-secret', 'us-west-2', nil, 'username', 'password', identity]]) end it 'does not share an in-flight fetch between connections with different AWS credentials' do