From 1f4a26add6fc09c5488371610719e36e86637bee Mon Sep 17 00:00:00 2001 From: Sophia Chu <112967780+sophia-bq@users.noreply.github.com> Date: Wed, 14 Oct 2026 08:23:37 -0700 Subject: [PATCH 1/2] feat: adfs --- CHANGELOG.md | 5 + .../errors.rb | 1 + .../plugins/blue_green/status_provider.rb | 18 +- .../federated_auth/base_saml_auth_plugin.rb | 219 +++++++++ .../federated_auth/federated_auth_plugin.rb | 122 +++++ .../property_definition.rb | 21 + .../services/plugin_manager.rb | 5 +- .../utils/saml_utils.rb | 129 +++++ .../base_saml_auth_plugin_spec.rb | 454 ++++++++++++++++++ .../federated_auth_plugin_spec.rb | 233 +++++++++ 10 files changed, 1203 insertions(+), 4 deletions(-) create mode 100644 lib/aws_advanced_ruby_driver_wrapper/plugins/federated_auth/base_saml_auth_plugin.rb create mode 100644 lib/aws_advanced_ruby_driver_wrapper/plugins/federated_auth/federated_auth_plugin.rb create mode 100644 lib/aws_advanced_ruby_driver_wrapper/utils/saml_utils.rb create mode 100644 spec/unit/plugins/federated_auth/base_saml_auth_plugin_spec.rb create mode 100644 spec/unit/plugins/federated_auth/federated_auth_plugin_spec.rb diff --git a/CHANGELOG.md b/CHANGELOG.md index 609816be..6b899eb5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,11 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/#semantic-versioning-200). +## [Unreleased] + +### :magic_wand: Added +- [Federated Authentication Plugin](https://aws.github.io/aws-advanced-wrapper-docs/ruby/using-plugins/federated-auth), which authenticates with Active Directory Federation Services (AD FS), exchanges the resulting SAML assertion for temporary AWS credentials via STS, and connects to the database with an RDS IAM authentication token. Enabled with the `federated_auth` plugin code. + ## [1.0.1] - 2026-10-07 ### :bug: Fixed diff --git a/lib/aws_advanced_ruby_driver_wrapper/errors.rb b/lib/aws_advanced_ruby_driver_wrapper/errors.rb index 6d8a9584..5fd2d523 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/errors.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/errors.rb @@ -51,6 +51,7 @@ def initialize end class IamAuthError < AwsError; end + class SamlAuthError < AwsError; end class SecretsManagerAuthError < AwsError; end class PluginConflictError < AwsError; end class BlueGreenTimeoutError < AwsError; end diff --git a/lib/aws_advanced_ruby_driver_wrapper/plugins/blue_green/status_provider.rb b/lib/aws_advanced_ruby_driver_wrapper/plugins/blue_green/status_provider.rb index e8eaaa5d..7b16c8c0 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/plugins/blue_green/status_provider.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/plugins/blue_green/status_provider.rb @@ -31,6 +31,7 @@ require_relative 'switchover_state' require_relative 'switchover_timer' require_relative '../../plugins/iam_auth_plugin' +require_relative '../../plugins/federated_auth/federated_auth_plugin' module AwsAdvancedRubyDriverWrapper module Plugins @@ -191,7 +192,9 @@ def reset_context_when_completed @monitors = { Role::SOURCE => nil, Role::TARGET => nil } old_monitors.each_value { |m| m&.stop } - Plugins::IamAuthPlugin.clear_cache(@storage_service) if iam_enabled? + # IamAuthPlugin and FederatedAuthPlugin all cache tokens under the same + # shared IAM_TOKEN_CACHE_NAME, so clearing through any one of them clears all of them. + Plugins::IamAuthPlugin.clear_cache(@storage_service) if iam_token_cache_in_use? @rollback = false @green_topology_recognized_logged = false @@ -356,8 +359,17 @@ def switchover_finalized? completed && @event_log.any? { |_, v| v.phase&.active_switchover_or_completed? } end - def iam_enabled? - @service_container.plugin_manager&.plugin_in_use?(Plugins::IamAuthPlugin) || false + # True when any auth plugin backed by the shared IAM token cache (IAM, AD FS federated + # auth) is in use, so a switchover knows to purge that cache regardless of which + # one of them is actually active. + def iam_token_cache_in_use? + plugin_manager = @service_container.plugin_manager + return false unless plugin_manager + + [ + Plugins::IamAuthPlugin, + Plugins::FederatedAuth::FederatedAuthPlugin + ].any? { |plugin_class| plugin_manager.plugin_in_use?(plugin_class) } end def context_hash diff --git a/lib/aws_advanced_ruby_driver_wrapper/plugins/federated_auth/base_saml_auth_plugin.rb b/lib/aws_advanced_ruby_driver_wrapper/plugins/federated_auth/base_saml_auth_plugin.rb new file mode 100644 index 00000000..28228667 --- /dev/null +++ b/lib/aws_advanced_ruby_driver_wrapper/plugins/federated_auth/base_saml_auth_plugin.rb @@ -0,0 +1,219 @@ +# frozen_string_literal: true + +# 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. + +require 'concurrent' +require_relative '../../errors' +require_relative '../../property_definition' +require_relative '../../utils/iam_auth_utils' +require_relative '../../utils/rds_utils' +require_relative '../../utils/rds_url_type' +require_relative '../../utils/saml_utils' + +module AwsAdvancedRubyDriverWrapper + module Plugins + module FederatedAuth + # Shared connect flow for the SAML-based authentication plugins (AD FS and + # Okta). + class BaseSamlAuthPlugin + SUBSCRIBED_METHODS = Set['connect', 'internal_connect'].freeze + # Shared with the IAM and Okta/AD FS plugins so a token minted by one is + # visible to the others. + IAM_TOKEN_CACHE_NAME = :iam_token + + attr_reader :subscribed_methods + + def initialize(service_container, props = ::Concurrent::Map.new) + ensure_aws_sdk! + @service_container = service_container + @wrapper_props = props + expiration = PropertyDefinition::IAM_EXPIRATION_SEC.get_float(props) + PropertyDefinition::IAM_EXPIRATION_SEC.validate!(expiration) + service_container.storage_service.register(IAM_TOKEN_CACHE_NAME, ttl: expiration) + @subscribed_methods = SUBSCRIBED_METHODS + end + + def connect(host_info, driver_props, _is_initial_connection, pipeline_callable) + saml_connect(host_info, driver_props, pipeline_callable) + end + + def internal_connect(host_info, driver_props, wrapper_props_override, _is_initial_connection, pipeline_callable) + saml_connect(host_info, driver_props, pipeline_callable, wrapper_props_override || @wrapper_props) + end + + def self.clear_cache(storage_service) + storage_service.clear(IAM_TOKEN_CACHE_NAME) + end + + # Exchanges a SAML assertion for temporary AWS credentials via STS + # AssumeRoleWithSAML. + # + # @return [Aws::Credentials] + def self.credentials_from_saml(saml_assertion, role_arn:, idp_arn:, region:) + require 'aws-sdk-core' + client_opts = {} + client_opts[:region] = region if region && !region.to_s.empty? + resp = Aws::STS::Client.new(**client_opts).assume_role_with_saml( + role_arn:, principal_arn: idp_arn, saml_assertion: + ) + creds = resp.credentials + Aws::Credentials.new(creds.access_key_id, creds.secret_access_key, creds.session_token) + end + + private + + def saml_connect(host_info, driver_props, pipeline_callable, wrapper_props_override = nil) + wrapper_props_override ||= @wrapper_props + saml_props = wrapper_props_override + + validate_required!(saml_props) + + db_user = PropertyDefinition::DB_USER.get(saml_props) + # The IdP login defaults to the connection's user/password when idp_username + # / idp_password are not given. + idp_username = PropertyDefinition::IDP_USERNAME.get(saml_props) || + driver_props[:user] || driver_props[:username] + idp_password = PropertyDefinition::IDP_PASSWORD.get(saml_props) || driver_props[:password] + + host = Utils::IamAuthUtils.resolve_host( + PropertyDefinition::IAM_HOST.get(wrapper_props_override), host_info + ) + port = Utils::IamAuthUtils.resolve_port( + PropertyDefinition::IAM_PORT.get(wrapper_props_override), + host_info, + @service_container.dialect_service.db_dialect.default_port + ) + rds_type = Utils::RdsUtils.identify_rds_type(host) + + # A global writer cluster needs AWS credentials to resolve its region, so + # the SAML exchange has to happen before the region lookup (and therefore + # before the token-cache check) for those endpoints only. + preassumed_credentials = nil + if rds_type == Utils::RdsUrlType::RDS_GLOBAL_WRITER_CLUSTER + preassumed_credentials = obtain_credentials(saml_props, nil, idp_username, idp_password) + end + + region = Utils::IamAuthUtils.region_for( + host:, props: wrapper_props_override, rds_type:, + credentials_provider: preassumed_credentials, + rds_client_func: preassumed_credentials ? -> { Aws::RDS::Client.new(credentials: preassumed_credentials) } : nil + ) + unless region + raise Errors::SamlAuthError, + "#{self.class.name}: unable to determine connection region. " \ + "If you are using a non-standard RDS URL, please set the 'iam_region' property." + end + + fingerprint = Utils::SamlUtils.principal_fingerprint( + PropertyDefinition::IAM_ROLE_ARN.get(saml_props), + PropertyDefinition::IAM_IDP_ARN.get(saml_props) + ) + cache_key = Utils::IamAuthUtils.cache_key(region, host, port, db_user, fingerprint) + entry = @service_container.storage_service.get(IAM_TOKEN_CACHE_NAME, cache_key) + expiration = PropertyDefinition::IAM_EXPIRATION_SEC.get_float(wrapper_props_override) + PropertyDefinition::IAM_EXPIRATION_SEC.validate!(expiration) + + if Utils::IamAuthUtils.valid_entry?(entry) + token = entry.token + is_cached_token = true + else + token = fetch_and_cache_token(saml_props, region, host, port, db_user, cache_key, expiration, + idp_username, idp_password, preassumed_credentials) + is_cached_token = false + end + + user_key = @service_container.dialect_service.driver_dialect.user_property_key + driver_props[user_key] = db_user + driver_props[:password] = token + + begin + pipeline_callable.call + rescue StandardError => e + raise unless is_cached_token && @service_container.dialect_service.login_error?(e) + + driver_props[:password] = fetch_and_cache_token(saml_props, region, host, port, db_user, cache_key, + expiration, idp_username, idp_password, nil) + pipeline_callable.call + end + end + + # Mints a fresh RDS token signed with SAML-derived credentials and caches it. + def fetch_and_cache_token(saml_props, region, host, port, db_user, cache_key, expiration, + idp_username, idp_password, credentials) + credentials ||= obtain_credentials(saml_props, region, idp_username, idp_password) + token = Utils::IamAuthUtils.generate_token( + region:, hostname: host, port:, user: db_user, credentials_provider: credentials + ) + @service_container.storage_service.set( + IAM_TOKEN_CACHE_NAME, cache_key, Utils::IamAuthUtils.build_token_entry(token, expiration) + ) + token + end + + # Fetches a SAML assertion from the IdP and exchanges it for AWS credentials. + def obtain_credentials(saml_props, region, idp_username, idp_password) + assertion = self.class.fetch_saml_assertion( + **saml_fetch_options(saml_props, idp_username, idp_password) + ) + self.class.credentials_from_saml( + assertion, + role_arn: PropertyDefinition::IAM_ROLE_ARN.get(saml_props), + idp_arn: PropertyDefinition::IAM_IDP_ARN.get(saml_props), + region: + ) + end + + def validate_required!(saml_props) + missing = required_identity(saml_props).select { |_name, value| value.nil? || value.to_s.empty? } + return if missing.empty? + + names = missing.map(&:first) + raise Errors::SamlAuthError, + "#{self.class.name}: #{names.join(', ')} #{names.length > 1 ? 'are' : 'is'} required" + end + + # The properties that must be present for this IdP. Subclasses override to + # append their own (e.g. Okta's app_id). + def required_identity(saml_props) + [ + ['db_user', PropertyDefinition::DB_USER.get(saml_props)], + ['idp_endpoint', PropertyDefinition::IDP_ENDPOINT.get(saml_props)], + ['iam_role_arn', PropertyDefinition::IAM_ROLE_ARN.get(saml_props)], + ['iam_idp_arn', PropertyDefinition::IAM_IDP_ARN.get(saml_props)] + ] + end + + # The keyword arguments passed to .fetch_saml_assertion. Subclasses override. + def saml_fetch_options(saml_props, idp_username, idp_password) + { + idp_endpoint: PropertyDefinition::IDP_ENDPOINT.get(saml_props), + idp_username:, + idp_password:, + ssl_insecure: PropertyDefinition::SSL_INSECURE.get_bool(saml_props), + socket_timeout_ms: PropertyDefinition::HTTP_CLIENT_SOCKET_TIMEOUT.get_int(saml_props), + connect_timeout_ms: PropertyDefinition::HTTP_CLIENT_CONNECT_TIMEOUT.get_int(saml_props) + } + end + + def ensure_aws_sdk! + require 'aws-sdk-rds' + rescue LoadError + raise LoadError, + "The SAML auth plugins require 'aws-sdk-rds'. Add it to your Gemfile: gem 'aws-sdk-rds'" + end + end + end + end +end diff --git a/lib/aws_advanced_ruby_driver_wrapper/plugins/federated_auth/federated_auth_plugin.rb b/lib/aws_advanced_ruby_driver_wrapper/plugins/federated_auth/federated_auth_plugin.rb new file mode 100644 index 00000000..4d7d30ca --- /dev/null +++ b/lib/aws_advanced_ruby_driver_wrapper/plugins/federated_auth/federated_auth_plugin.rb @@ -0,0 +1,122 @@ +# frozen_string_literal: true + +# 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. + +require 'uri' +require_relative 'base_saml_auth_plugin' + +module AwsAdvancedRubyDriverWrapper + module Plugins + module FederatedAuth + # Federated authentication against Active Directory Federation Services + # (AD FS). Scrapes the IdP-initiated sign-on page for its form, posts the + # federated credentials, and extracts the SAML assertion from the response. + # Everything else (STS exchange, token minting, caching, retry) is handled by + # BaseSamlAuthPlugin. + class FederatedAuthPlugin < BaseSamlAuthPlugin + INPUT_TAG_PATTERN = /]*)>/ + FORM_ACTION_PATTERN = /