diff --git a/CHANGELOG.md b/CHANGELOG.md index 609816be..221a373d 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 ([PR #207](https://github.com/aws/aws-advanced-ruby-driver-wrapper/pull/207)). + ## [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/routing/substitute_connect_routing.rb b/lib/aws_advanced_ruby_driver_wrapper/plugins/blue_green/routing/substitute_connect_routing.rb index 7150e1d2..ba6fb080 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/plugins/blue_green/routing/substitute_connect_routing.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/plugins/blue_green/routing/substitute_connect_routing.rb @@ -63,13 +63,13 @@ def apply(_host_info, # Fall back to connecting via hostname (DNS will resolve to the correct IP post-switchover), # matching the effective behaviour of the Java/Go MySQL drivers which use the original # hostname for TLS regardless of the socket address. - if driver_props[:sslca] && !plugin_manager.plugin_in_use?(Plugins::IamAuthPlugin) + if driver_props[:sslca] && !plugin_manager.iam_token_plugin_in_use? hostname_host = @substitute_host.deep_dup(host: @host) return open_connection(plugin_manager, hostname_host, driver_props, wrapper_props, is_initial_connection, is_internal, bg_plugin) end - if plugin_manager.plugin_in_use?(Plugins::IamAuthPlugin) + if plugin_manager.iam_token_plugin_in_use? if @iam_hosts.nil? || @iam_hosts.empty? raise StandardError, 'Connecting with IP address when IAM authentication is enabled requires an \'iam_host\' parameter.' diff --git a/lib/aws_advanced_ruby_driver_wrapper/plugins/blue_green/status_monitor.rb b/lib/aws_advanced_ruby_driver_wrapper/plugins/blue_green/status_monitor.rb index 35d2cf07..19cb76a4 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/plugins/blue_green/status_monitor.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/plugins/blue_green/status_monitor.rb @@ -394,7 +394,7 @@ def map_merge(base, overrides) end def iam_enabled? - @service_container.plugin_manager.plugin_in_use?(Plugins::IamAuthPlugin) + @service_container.plugin_manager.iam_token_plugin_in_use? end def driver_dialect 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..4c717910 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,11 @@ 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 or AD FS + # federated auth) is in use, so a switchover knows to purge that cache regardless + # of which one is active. + def iam_token_cache_in_use? + @service_container.plugin_manager&.iam_token_plugin_in_use? || false 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..f4ddde0c --- /dev/null +++ b/lib/aws_advanced_ruby_driver_wrapper/plugins/federated_auth/base_saml_auth_plugin.rb @@ -0,0 +1,251 @@ +# 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 '../iam_auth_plugin' +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 + # Reuse the IAM plugin's cache name. + IAM_TOKEN_CACHE_NAME = AwsAdvancedRubyDriverWrapper::Plugins::IamAuthPlugin::IAM_TOKEN_CACHE_NAME + + 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' + # AssumeRoleWithSAML is unsigned, so no AWS credentials are needed. Passing + # credentials: nil keeps the SDK from running the default credential chain (which + # on a credential-less, non-EC2 host wastes ~1s probing IMDS and logs a misleading + # "Error retrieving instance profile credentials"). + client_opts = { credentials: nil } + 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) + + # The connection's driver_props :user/:password double as the fallback IdP login when + # idp_username / idp_password are not set. We overwrite driver_props with db_user and the + # RDS token further down, and that hash is reused across reconnects (failover, retry, + # Blue/Green rerouting), so capture the fallback into the wrapper props once, up front. + # A later reconnect then still logs in to the IdP with the original credentials rather + # than db_user and a stale token. + persist_idp_credentials_fallback(saml_props, driver_props) + db_user = PropertyDefinition::DB_USER.get(saml_props) + idp_username = PropertyDefinition::IDP_USERNAME.get(saml_props) + idp_password = PropertyDefinition::IDP_PASSWORD.get(saml_props) + + 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) + + # Only a global writer cluster with no explicit iam_region needs AWS credentials to look + # its region up. In that one case the SAML exchange has to happen before the region lookup + # (and so before the token-cache check); every other case - including a global cluster + # whose iam_region is set - defers the IdP round-trip to the token-cache miss path, so a + # pool or failover storm does not trigger one IdP login per connection. + explicit_region = PropertyDefinition::IAM_REGION.get(wrapper_props_override) + preassumed_credentials = nil + if rds_type == Utils::RdsUrlType::RDS_GLOBAL_WRITER_CLUSTER && (explicit_region.nil? || explicit_region.to_s.empty?) + 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 + + # Captures the connection's user/password as the IdP login when idp_username / + # idp_password are unset, persisting them into the wrapper props so the value survives + # the driver_props overwrite later in the flow and any subsequent reconnect. Never stores + # a nil (Concurrent::Map rejects nil values), so a connection with no fallback simply + # keeps idp_username / idp_password unset. + def persist_idp_credentials_fallback(saml_props, driver_props) + if PropertyDefinition::IDP_USERNAME.get(saml_props).nil? + fallback_user = driver_props[:user] || driver_props[:username] + PropertyDefinition::IDP_USERNAME.set(saml_props, fallback_user) unless fallback_user.nil? + end + return unless PropertyDefinition::IDP_PASSWORD.get(saml_props).nil? + + fallback_password = driver_props[:password] + PropertyDefinition::IDP_PASSWORD.set(saml_props, fallback_password) unless fallback_password.nil? + 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: + ) + rescue Errors::SamlAuthError + raise + rescue StandardError => e + # Surface IdP/STS failures (DNS, TLS, STS errors) as a SamlAuthError. + raise Errors::SamlAuthError, "#{self.class.name}: failed to obtain credentials via SAML: #{e.message}" + 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_sec: PropertyDefinition::HTTP_CLIENT_SOCKET_TIMEOUT_SEC.get_float(saml_props), + connect_timeout_sec: PropertyDefinition::HTTP_CLIENT_CONNECT_TIMEOUT_SEC.get_float(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..4cbb7c2a --- /dev/null +++ b/lib/aws_advanced_ruby_driver_wrapper/plugins/federated_auth/federated_auth_plugin.rb @@ -0,0 +1,132 @@ +# 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 'cgi' +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 = /]*?\baction="([^"]+)"/ + + # Fetches a SAML assertion from AD FS. + # + # @return [String] the base64 SAML assertion + def self.fetch_saml_assertion(idp_endpoint:, idp_port:, idp_username:, idp_password:, + rp_identifier:, ssl_insecure:, socket_timeout_sec:, connect_timeout_sec:, **_rest) + # One cookie jar shared by the sign-on GET and the credential POST, so cookies AD FS + # (or a load balancer in front of it) sets on the sign-on page are returned with the POST. + cookies = {} + http = lambda do |method, url, body: nil, headers: {}| + Utils::SamlUtils.http_request( + method:, url:, body:, headers:, ssl_insecure:, cookies:, + open_timeout_sec: connect_timeout_sec, read_timeout_sec: socket_timeout_sec + ) + end + + sign_in_url = "https://#{idp_endpoint}:#{idp_port}/adfs/ls/IdpInitiatedSignOn.aspx?loginToRp=#{rp_identifier}" + sign_in_body = require_body!(http.call(:get, sign_in_url), 'sign-on page') + + action = form_action(sign_in_body) + post_url = action&.start_with?('/') ? "https://#{idp_endpoint}:#{idp_port}#{action}" : sign_in_url + + params = form_parameters(sign_in_body, idp_username, idp_password) + response = http.call(:post, post_url, + body: URI.encode_www_form(params), + headers: { 'Content-Type' => 'application/x-www-form-urlencoded' }) + content = require_body!(response, 'sign-on POST') + + match = Utils::SamlUtils::SAML_RESPONSE_PATTERN.match(content) + unless match + # AD FS answers a rejected login with the sign-on page again (no SAMLResponse); the + # body is not included as it may contain sensitive markup. + raise Errors::SamlAuthError, + 'FederatedAuthPlugin: no SAML assertion in the AD FS response - check idp_username, ' \ + 'idp_password, and idp_endpoint' + end + + match[1] + end + + def self.require_body!(response, what) + return response.body if response.is_a?(Net::HTTPSuccess) + + raise Errors::SamlAuthError, + "FederatedAuthPlugin: AD FS #{what} request failed (#{response.code} #{response.message})" + end + + def self.form_action(body) + match = FORM_ACTION_PATTERN.match(body) + match && unescape_html(match[1]) + end + + # Builds the POST parameters from the sign-on form's input tags, filling in + # the federated username/password and preserving every other hidden field. + def self.form_parameters(body, idp_username, idp_password) + params = [] + seen = {} + body.scan(INPUT_TAG_PATTERN).flatten.each do |tag| + name = value_by_key(tag, 'name') + next if name.empty? + + lower = name.downcase + next if seen[lower] + + seen[lower] = true + value = value_by_key(tag, 'value') + + if lower.include?('username') + params << [name, idp_username] + elsif lower.include?('authmethod') + params << [name, value] unless value.empty? + elsif lower.include?('password') + params << [name, idp_password] + else + params << [name, value] + end + end + params + end + + def self.value_by_key(input, key) + match = /#{Regexp.quote(key)}\s*=\s*"(.*?)"/.match(input) + match ? unescape_html(match[1]) : '' + end + + def self.unescape_html(html) + CGI.unescapeHTML(html) + end + + private + + def saml_fetch_options(saml_props, idp_username, idp_password) + super.merge( + idp_port: PropertyDefinition::IDP_PORT.get(saml_props), + rp_identifier: PropertyDefinition::RP_IDENTIFIER.get(saml_props) + ) + end + end + end + end +end diff --git a/lib/aws_advanced_ruby_driver_wrapper/property_definition.rb b/lib/aws_advanced_ruby_driver_wrapper/property_definition.rb index 5e519e5e..3b022370 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/property_definition.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/property_definition.rb @@ -171,6 +171,27 @@ module PropertyDefinition IAM_ACCESS_TOKEN_PROPERTY_NAME = WrapperProperty.new(:iam_access_token_property_name, 'Property name used to pass the IAM token', default_value: :password, type: Symbol) + # -- Federated / Okta Authentication (SAML) -- + IDP_ENDPOINT = WrapperProperty.new(:idp_endpoint, 'The hosting URL of the Identity Provider', default_value: nil, type: String) + IDP_PORT = WrapperProperty.new(:idp_port, 'The hosting port of the Identity Provider', default_value: 443, type: Integer) + IDP_NAME = WrapperProperty.new(:idp_name, 'The name of the Identity Provider implementation used', default_value: 'adfs', + type: String) + IDP_USERNAME = WrapperProperty.new(:idp_username, 'The federated user name', default_value: nil, type: String) + IDP_PASSWORD = WrapperProperty.new(:idp_password, 'The federated user password', default_value: nil, type: String) + IAM_ROLE_ARN = WrapperProperty.new(:iam_role_arn, 'The ARN of the IAM Role that is to be assumed', default_value: nil, type: String) + IAM_IDP_ARN = WrapperProperty.new(:iam_idp_arn, 'The ARN of the Identity Provider', default_value: nil, type: String) + RP_IDENTIFIER = WrapperProperty.new(:rp_identifier, 'The relying party identifier', default_value: 'urn:amazon:webservices', + type: String) + DB_USER = WrapperProperty.new(:db_user, 'The database user used to access the database', default_value: nil, type: String) + SSL_INSECURE = WrapperProperty.new(:ssl_insecure, "Whether the IdP server's TLS certificate chain should not be verified", + default_value: false, type: :boolean) + HTTP_CLIENT_SOCKET_TIMEOUT_SEC = WrapperProperty.new(:http_client_socket_timeout_sec, + 'Socket timeout in seconds for IdP HTTP requests', + default_value: 60.0, type: Float, validator: POSITIVE_FLOAT) + HTTP_CLIENT_CONNECT_TIMEOUT_SEC = WrapperProperty.new(:http_client_connect_timeout_sec, + 'Connect timeout in seconds for IdP HTTP requests', + default_value: 60.0, type: Float, validator: POSITIVE_FLOAT) + # -- Initial Connection Strategy -- INITIAL_CONNECTION_SUBSTITUTE_HOST = WrapperProperty.new( :initial_connection_substitute_host, diff --git a/lib/aws_advanced_ruby_driver_wrapper/services/plugin_manager.rb b/lib/aws_advanced_ruby_driver_wrapper/services/plugin_manager.rb index a4747f43..15b3b6e6 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/services/plugin_manager.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/services/plugin_manager.rb @@ -23,6 +23,7 @@ require_relative '../plugins/failover_plugin' require_relative '../plugins/gdb/gdb_failover_plugin' require_relative '../plugins/iam_auth_plugin' +require_relative '../plugins/federated_auth/federated_auth_plugin' require_relative '../plugins/initial_connection_strategy_plugin' require_relative '../plugins/kms_encryption/kms_encryption_plugin' require_relative '../plugins/secrets_manager_plugin' @@ -44,6 +45,7 @@ class PluginManager 'failover' => Plugins::FailoverPlugin, 'gdb_failover' => Plugins::Gdb::GdbFailoverPlugin, 'iam' => Plugins::IamAuthPlugin, + 'federated_auth' => Plugins::FederatedAuth::FederatedAuthPlugin, 'initial_connection' => Plugins::InitialConnectionStrategyPlugin, 'kms_encryption' => Plugins::KmsEncryptionPlugin, 'secrets_manager' => Plugins::SecretsManagerPlugin @@ -60,9 +62,16 @@ class PluginManager Plugins::Gdb::GdbFailoverPlugin => 500, Plugins::IamAuthPlugin => 1800, Plugins::SecretsManagerPlugin => 1900, + Plugins::FederatedAuth::FederatedAuthPlugin => 2000, Plugins::KmsEncryptionPlugin => 2050 } + # Plugins that authenticate by minting an RDS IAM token into the shared IAM token cache. + IAM_TOKEN_PLUGIN_CLASSES = [ + Plugins::IamAuthPlugin, + Plugins::FederatedAuth::FederatedAuthPlugin + ].freeze + class << self def register_plugin(plugin_code, plugin_class, weight: WEIGHT_RELATIVE_TO_PRIOR_PLUGIN) @plugin_classes[plugin_code] = plugin_class @@ -164,6 +173,12 @@ def plugin_in_use?(plugin_class) @plugins.any?(plugin_class) end + # Whether any plugin that mints RDS IAM tokens into the shared cache is active. + # @see IAM_TOKEN_PLUGIN_CLASSES + def iam_token_plugin_in_use? + IAM_TOKEN_PLUGIN_CLASSES.any? { |plugin_class| plugin_in_use?(plugin_class) } + end + private def load_plugins(service_container) @@ -185,7 +200,7 @@ def load_plugins(service_container) end def ensure_single_auth_plugin(plugin_code_list) - auth_plugins_used = plugin_code_list & %w[iam secrets_manager].freeze + auth_plugins_used = plugin_code_list & %w[iam secrets_manager federated_auth].freeze return unless auth_plugins_used.length > 1 diff --git a/lib/aws_advanced_ruby_driver_wrapper/utils/saml_utils.rb b/lib/aws_advanced_ruby_driver_wrapper/utils/saml_utils.rb new file mode 100644 index 00000000..0c0f237e --- /dev/null +++ b/lib/aws_advanced_ruby_driver_wrapper/utils/saml_utils.rb @@ -0,0 +1,133 @@ +# 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 'digest' +require 'net/http' +require 'openssl' +require 'uri' +require_relative '../errors' + +module AwsAdvancedRubyDriverWrapper + module Utils + # Shared helpers for the SAML-based authentication plugins (AD FS, Okta): + # URL validation, the cache-key principal fingerprint, and a small Net::HTTP + # client used to talk to the identity provider's HTTP endpoints (there is no + # AWS SDK for these calls). + module SamlUtils + module_function + + HTTPS_URL_PATTERN = %r{\Ahttps://[-a-zA-Z0-9+&@#/%?=~_!:,.']*[-a-zA-Z0-9+&@#/%=~_']} + + # The regex the IdP sign-in response is scraped with for the SAML assertion, + # shared by the AD FS and Okta flows. + SAML_RESPONSE_PATTERN = /SAMLResponse\W+value="([^"]+)"/ + + # Rejects anything that is not a well-formed https:// URL, guarding the IdP + # requests against being redirected to a non-TLS or malformed endpoint. + # + # @raise [Errors::SamlAuthError] when the URL is not a valid https URL + def validate_url!(url) + uri = URI.parse(url) + return if uri.is_a?(URI::HTTPS) && url.match?(HTTPS_URL_PATTERN) + + raise Errors::SamlAuthError, "Invalid HTTPS URL: #{url}" + rescue URI::InvalidURIError + raise Errors::SamlAuthError, "Invalid HTTPS URL: #{url}" + end + + # A short, stable fingerprint of the AWS principal a SAML connection assumes, + # for the token cache key. The principal is fully determined by the STS + # inputs iam_role_arn + iam_idp_arn, so two connections that assume different + # roles (or trust different identity providers) never share a cached token. + # No secret is included, and the federated username is intentionally excluded: + # once the role is assumed the database authority is the role. + # + # @param parts [Array] role_arn, idp_arn + # @return [String] 16 hex characters + def principal_fingerprint(*parts) + Digest::SHA256.hexdigest(parts.join("\0"))[0, 16] + end + + # Performs an HTTP request against an IdP endpoint, following redirects and + # carrying cookies across them (AD FS and Okta both rely on this). Only + # https URLs are allowed; each hop is validated. + # + # @param method [Symbol] :get or :post + # @param url [String] the https URL to request + # @param body [String, nil] request body for :post + # @param headers [Hash] request headers + # @param ssl_insecure [Boolean] skip TLS verification when true + # @param open_timeout_sec [Float] connect timeout in seconds + # @param read_timeout_sec [Float] socket timeout in seconds + # @param cookies [Hash] a cookie jar, keyed by host then cookie name, shared across the + # calls of one sign-on flow and mutated in place. Cookies are only sent back to the host + # that set them, so following a redirect to another host cannot leak them. + # @return [Net::HTTPResponse] + def http_request(method:, url:, body: nil, headers: {}, ssl_insecure: false, + open_timeout_sec: 60.0, read_timeout_sec: 60.0, max_redirects: 3, cookies: {}) + redirects = 0 + loop do + validate_url!(url) + uri = URI.parse(url) + http = Net::HTTP.new(uri.host, uri.port) + http.use_ssl = true + http.verify_mode = ssl_insecure ? OpenSSL::SSL::VERIFY_NONE : OpenSSL::SSL::VERIFY_PEER + http.open_timeout = open_timeout_sec + http.read_timeout = read_timeout_sec + + request = build_request(method, uri, body, headers, cookies) + response = http.request(request) + merge_cookies!(cookies, uri.host, response) + + if response.is_a?(Net::HTTPRedirection) && response['location'] && redirects < max_redirects + url = absolute_redirect(uri, response['location']) + method = :get + body = nil + redirects += 1 + next + end + + return response + end + end + + def build_request(method, uri, body, headers, cookies) + request = + case method + when :post then Net::HTTP::Post.new(uri) + else Net::HTTP::Get.new(uri) + end + headers.each { |k, v| request[k] = v } + request.body = body if body + host_jar = cookies[uri.host] + request['Cookie'] = host_jar.map { |k, v| "#{k}=#{v}" }.join('; ') if host_jar && !host_jar.empty? + request + end + + def merge_cookies!(cookies, host, response) + jar = (cookies[host] ||= {}) + Array(response.get_fields('set-cookie')).each do |raw| + pair = raw.split(';', 2).first.to_s.split('=', 2) + jar[pair[0].strip] = pair[1] if pair.length == 2 + end + end + + def absolute_redirect(uri, location) + URI.join(uri, location).to_s + end + end + end +end diff --git a/spec/unit/plugin_manager_spec.rb b/spec/unit/plugin_manager_spec.rb index c2960dde..e1a8fc64 100644 --- a/spec/unit/plugin_manager_spec.rb +++ b/spec/unit/plugin_manager_spec.rb @@ -573,6 +573,19 @@ def service_container_with_wrapper_props(wrapper_props = {}) .to raise_error(AwsAdvancedRubyDriverWrapper::Errors::PluginConflictError, /iam.*secrets_manager|secrets_manager.*iam/) end + it 'raises when iam and federated_auth are specified' do + container = service_container_with_wrapper_props(wrapper_plugins: 'iam,federated_auth') + expect { described_class.new(container) } + .to raise_error(AwsAdvancedRubyDriverWrapper::Errors::PluginConflictError, /iam.*federated_auth|federated_auth.*iam/) + end + + it 'raises when secrets_manager and federated_auth are specified' do + container = service_container_with_wrapper_props(wrapper_plugins: 'secrets_manager,federated_auth') + expect { described_class.new(container) } + .to raise_error(AwsAdvancedRubyDriverWrapper::Errors::PluginConflictError, + /secrets_manager.*federated_auth|federated_auth.*secrets_manager/) + end + it 'does not raise when neither auth plugin is specified' do container = service_container_with_wrapper_props(wrapper_plugins: 'failover') expect { described_class.new(container) }.not_to raise_error diff --git a/spec/unit/plugins/blue_green/blue_green_routing_spec.rb b/spec/unit/plugins/blue_green/blue_green_routing_spec.rb index efd6db87..24de2f73 100644 --- a/spec/unit/plugins/blue_green/blue_green_routing_spec.rb +++ b/spec/unit/plugins/blue_green/blue_green_routing_spec.rb @@ -172,6 +172,7 @@ def make_routing(host: nil, port: nil, role: nil) before do allow(plugin_manager).to receive(:plugin_in_use?).and_return(false) + allow(plugin_manager).to receive(:iam_token_plugin_in_use?).and_return(false) allow(plugin_manager).to receive(:connect).and_return(connection) end @@ -192,6 +193,7 @@ def make_routing(host: nil, port: nil, role: nil) before do allow(plugin_manager).to receive(:plugin_in_use?).and_return(true) + allow(plugin_manager).to receive(:iam_token_plugin_in_use?).and_return(true) allow(service_container).to receive(:connection_service).and_return(connection_service) end @@ -238,6 +240,7 @@ def make_routing(host: nil, port: nil, role: nil) before do allow(plugin_manager).to receive(:plugin_in_use?).and_return(false) + allow(plugin_manager).to receive(:iam_token_plugin_in_use?).and_return(false) end subject { routing::SubstituteConnectRouting.new(host_val, nil, role::SOURCE, sub_host, [], nil) } diff --git a/spec/unit/plugins/blue_green/blue_green_status_provider_spec.rb b/spec/unit/plugins/blue_green/blue_green_status_provider_spec.rb index 4457ef8c..16aced0d 100644 --- a/spec/unit/plugins/blue_green/blue_green_status_provider_spec.rb +++ b/spec/unit/plugins/blue_green/blue_green_status_provider_spec.rb @@ -59,7 +59,7 @@ dup: double('config_dup', initial_host_info: nil, 'initial_host_info=': nil, wrapper_props: {}, 'wrapper_props=': nil))) end - let(:plugin_manager) { double('plugin_manager', plugin_in_use?: false) } + let(:plugin_manager) { double('plugin_manager', plugin_in_use?: false, iam_token_plugin_in_use?: false) } let(:service_container) do AwsAdvancedRubyDriverWrapper::Services::ServiceContainer.new( connection_service, dialect_service, event_publisher, diff --git a/spec/unit/plugins/federated_auth/base_saml_auth_plugin_spec.rb b/spec/unit/plugins/federated_auth/base_saml_auth_plugin_spec.rb new file mode 100644 index 00000000..226a2324 --- /dev/null +++ b/spec/unit/plugins/federated_auth/base_saml_auth_plugin_spec.rb @@ -0,0 +1,531 @@ +# 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_relative '../../../spec_helper' +require 'aws-sdk-rds' +require 'aws_advanced_ruby_driver_wrapper/plugins/federated_auth/base_saml_auth_plugin' +require 'aws_advanced_ruby_driver_wrapper/host/host_info' +require 'aws_advanced_ruby_driver_wrapper/utils/rds_url_type' +require 'aws_advanced_ruby_driver_wrapper/utils/rds_utils' +require 'aws_advanced_ruby_driver_wrapper/utils/iam_auth_utils' +require 'aws_advanced_ruby_driver_wrapper/utils/saml_utils' +require 'aws_advanced_ruby_driver_wrapper/errors' + +# A minimal concrete SAML plugin. It only declares the IdP seam (and a required +# property) so the base flow can be driven and the seam stubbed; it performs no +# HTTP of its own. +class TestSamlPlugin < AwsAdvancedRubyDriverWrapper::Plugins::FederatedAuth::BaseSamlAuthPlugin + def self.fetch_saml_assertion(**_opts) + raise 'fetch_saml_assertion must be stubbed in specs' + end +end + +RSpec.describe AwsAdvancedRubyDriverWrapper::Plugins::FederatedAuth::BaseSamlAuthPlugin do + subject(:described_class) { TestSamlPlugin } + + SAML_GENERATED_TOKEN = 'someTestToken' + SAML_CACHED_TOKEN = 'cachedToken' + SAML_DEFAULT_PG_PORT = 5432 + + SAML_PG_HOST = 'pg.testdb.us-east-2.rds.amazonaws.com' + SAML_IAM_HOST_OVER = 'pg-123.testdb.us-east-2.rds.amazonaws.com' + SAML_GLOBAL_HOST = 'gdb.global-abc123.global.rds.amazonaws.com' + SAML_DB_USER = 'iamUser' + + SAML_FAKE_SAML_ASSERTION = 'fake-base64-saml-assertion' + + SAML_PRINCIPAL_FINGERPRINT = + AwsAdvancedRubyDriverWrapper::Utils::SamlUtils.principal_fingerprint( + 'arn:aws:iam::123456789012:role/example_iam_role', + 'arn:aws:iam::123456789012:saml-provider/example' + ) + + SAML_PG_CACHE_KEY = "us-east-2:#{SAML_PG_HOST}:#{SAML_DEFAULT_PG_PORT}:#{SAML_DB_USER}:#{SAML_PRINCIPAL_FINGERPRINT}".freeze + + SAML_TOKEN_CACHE_NAME = + AwsAdvancedRubyDriverWrapper::Plugins::FederatedAuth::BaseSamlAuthPlugin::IAM_TOKEN_CACHE_NAME + + SAML_IAM_AUTH_UTILS = AwsAdvancedRubyDriverWrapper::Utils::IamAuthUtils + + def pg_host_info(port: nil) + AwsAdvancedRubyDriverWrapper::Host::HostInfo.new( + host: SAML_PG_HOST, + port: port ? port.to_s : AwsAdvancedRubyDriverWrapper::Host::HostInfo::NO_PORT + ) + end + + def arbitrary_host_info(host) + AwsAdvancedRubyDriverWrapper::Host::HostInfo.new(host:) + end + + # The SAML identity a real connection string supplies. idp_username / + # idp_password are deliberately omitted so the fallback-to-user/password + # behaviour can be exercised. Every key is a registered WrapperProperty, so + # this is wrapper-props shaped (see `build_plugin`). + def base_wrapper_props + { + db_user: SAML_DB_USER, + idp_endpoint: 'ec2amaz-ab3cdef.example.com', + iam_role_arn: 'arn:aws:iam::123456789012:role/example_iam_role', + iam_idp_arn: 'arn:aws:iam::123456789012:saml-provider/example', + iam_region: 'us-east-2' + } + end + + def valid_token_entry(token = SAML_CACHED_TOKEN) + SAML_IAM_AUTH_UTILS::TokenEntry.new( + token:, + expires_at: Process.clock_gettime(Process::CLOCK_MONOTONIC) + 900 + ) + end + + let(:mock_storage_service) { instance_double(AwsAdvancedRubyDriverWrapper::Utils::Storage::StorageService) } + let(:mock_db_dialect) { double('DbDialect') } + let(:mock_driver_dialect) { double('DriverDialect', user_property_key: :user) } + let(:mock_dialect_service) do + double('DialectService', + db_dialect: mock_db_dialect, + login_error?: false, + driver_dialect: mock_driver_dialect) + end + let(:mock_service_container) do + double('ServiceContainer', + storage_service: mock_storage_service, + dialect_service: mock_dialect_service) + end + + let(:mock_credentials) { Aws::Credentials.new('AKID', 'SECRET') } + let(:mock_token_generator) { instance_double(Aws::RDS::AuthTokenGenerator) } + + before do + # The IdP seam that returns a SAML assertion and the STS exchange that turns + # it into AWS credentials are both replaced so no HTTP ever happens. + allow(described_class).to receive(:fetch_saml_assertion).and_return(SAML_FAKE_SAML_ASSERTION) + allow(described_class).to receive(:credentials_from_saml).and_return(mock_credentials) + + allow(Aws::RDS::AuthTokenGenerator).to receive(:new).and_return(mock_token_generator) + allow(mock_token_generator).to receive(:auth_token).and_return(SAML_GENERATED_TOKEN) + + allow(mock_storage_service).to receive(:register) + allow(mock_storage_service).to receive(:get).with(SAML_TOKEN_CACHE_NAME, anything).and_return(nil) + allow(mock_storage_service).to receive(:set) + allow(mock_db_dialect).to receive(:default_port).and_return(SAML_DEFAULT_PG_PORT) + end + + def wrapper_props_map(hash) + map = Concurrent::Map.new + hash.each { |k, v| map[k] = v } + map + end + + def build_plugin(wrapper_overrides = {}) + described_class.new(mock_service_container, wrapper_props_map(base_wrapper_props.merge(wrapper_overrides))) + end + + # Connects, always raising inside the pipeline callable, and returns the + # user/password the plugin injected into driver_props. + def connect_and_capture(plugin:, host_info:, driver_props: {}) + plugin.connect(host_info, driver_props, true, -> { raise StandardError, 'simulated driver error' }) + rescue StandardError + [driver_props[:user], driver_props[:password]] + end + + describe '#initialize' do + it 'registers the shared IAM token cache with the configured expiration ttl' do + build_plugin(iam_expiration_sec: '600') + expect(mock_storage_service).to have_received(:register).with(SAML_TOKEN_CACHE_NAME, ttl: 600.0) + end + + it 'raises when the configured expiration exceeds the cache validity bound' do + expect { build_plugin(iam_expiration_sec: '-5') }.to raise_error(ArgumentError) + end + end + + describe '#connect with a valid cached token' do + it 'injects db_user and the cached token without touching the IdP or minting a token' do + allow(mock_storage_service).to receive(:get).with(SAML_TOKEN_CACHE_NAME, SAML_PG_CACHE_KEY) + .and_return(valid_token_entry) + + user, password = connect_and_capture(plugin: build_plugin, host_info: pg_host_info) + + expect(user).to eq(SAML_DB_USER) + expect(password).to eq(SAML_CACHED_TOKEN) + expect(described_class).not_to have_received(:fetch_saml_assertion) + expect(mock_token_generator).not_to have_received(:auth_token) + end + end + + describe '#connect with no cached token' do + it 'fetches a SAML assertion, mints a fresh token, and injects it' do + user, password = connect_and_capture(plugin: build_plugin, host_info: pg_host_info) + + expect(described_class).to have_received(:fetch_saml_assertion).once + expect(mock_token_generator).to have_received(:auth_token).once.with( + region: 'us-east-2', + endpoint: "#{SAML_PG_HOST}:#{SAML_DEFAULT_PG_PORT}", + user_name: SAML_DB_USER + ) + expect(user).to eq(SAML_DB_USER) + expect(password).to eq(SAML_GENERATED_TOKEN) + end + + it 'stores the freshly minted token under the cache key' do + connect_and_capture(plugin: build_plugin, host_info: pg_host_info) + + expect(mock_storage_service).to have_received(:set).with( + SAML_TOKEN_CACHE_NAME, SAML_PG_CACHE_KEY, having_attributes(token: SAML_GENERATED_TOKEN) + ) + end + + it 'signs the token with the STS credentials exchanged from the SAML assertion' do + captured_signing_credentials = nil + allow(Aws::RDS::AuthTokenGenerator).to receive(:new) do |credentials:| + captured_signing_credentials = credentials + mock_token_generator + end + + connect_and_capture(plugin: build_plugin, host_info: pg_host_info) + + expect(described_class).to have_received(:credentials_from_saml).with( + SAML_FAKE_SAML_ASSERTION, + role_arn: 'arn:aws:iam::123456789012:role/example_iam_role', + idp_arn: 'arn:aws:iam::123456789012:saml-provider/example', + region: 'us-east-2' + ) + expect(captured_signing_credentials.access_key_id).to eq('AKID') + end + end + + describe '#connect with iam_host / iam_port / iam_region overrides' do + it 'uses the overridden host, port, and region to mint the token' do + plugin = build_plugin(iam_host: 'pg.testdb.us-west-2.rds.amazonaws.com', + iam_port: '9876', iam_region: 'us-west-2') + + connect_and_capture(plugin:, host_info: pg_host_info) + + expect(mock_token_generator).to have_received(:auth_token).with( + region: 'us-west-2', + endpoint: 'pg.testdb.us-west-2.rds.amazonaws.com:9876', + user_name: SAML_DB_USER + ) + end + + it 'mints the token against iam_host rather than the connection host' do + connect_and_capture( + plugin: build_plugin(iam_host: SAML_IAM_HOST_OVER), + host_info: arbitrary_host_info('8.8.8.8') + ) + + expect(mock_token_generator).to have_received(:auth_token).with( + hash_including(endpoint: "#{SAML_IAM_HOST_OVER}:#{SAML_DEFAULT_PG_PORT}", user_name: SAML_DB_USER) + ) + end + end + + describe '#connect IdP credential fallback' do + before do + allow(described_class).to receive(:fetch_saml_assertion) do |idp_username:, idp_password:, **_rest| + @captured_idp = { username: idp_username, password: idp_password } + SAML_FAKE_SAML_ASSERTION + end + end + + it 'uses idp_username / idp_password when provided' do + plugin = build_plugin(idp_username: 'jimbob@example.com', idp_password: 'idpSecret') + connect_and_capture(plugin:, host_info: pg_host_info, + driver_props: { user: 'ignoredUser', password: 'ignoredPassword' }) + + expect(@captured_idp).to eq(username: 'jimbob@example.com', password: 'idpSecret') + end + + it 'falls back to the connection user / password when idp_username / idp_password are absent' do + connect_and_capture(plugin: build_plugin, host_info: pg_host_info, + driver_props: { user: 'fallbackUser', password: 'fallbackPassword' }) + + expect(@captured_idp).to eq(username: 'fallbackUser', password: 'fallbackPassword') + end + + # Regression: the connect flow overwrites driver_props[:user]/[:password] with db_user and the + # RDS token, and that hash is reused across reconnects (failover, retry, Blue/Green rerouting). + # The fallback IdP login must still be the ORIGINAL user/password on the second connect, not the + # overwritten db_user and stale token. + it 'keeps using the original user/password for the IdP login across a reconnect that reuses driver_props' do + captured = [] + allow(described_class).to receive(:fetch_saml_assertion) do |idp_username:, idp_password:, **_rest| + captured << [idp_username, idp_password] + SAML_FAKE_SAML_ASSERTION + end + + plugin = build_plugin + driver_props = { user: 'realUser', password: 'realPw' } + 2.times do + plugin.connect(pg_host_info, driver_props, true, -> { raise StandardError, 'simulated' }) + rescue StandardError + nil + end + + expect(captured).to eq([%w[realUser realPw], %w[realUser realPw]]) + expect(driver_props[:user]).to eq(SAML_DB_USER) + expect(driver_props[:password]).to eq(SAML_GENERATED_TOKEN) + end + end + + describe '#connect retry on login error with a cached token' do + it 'mints a fresh SAML-derived token and retries the pipeline once' do + allow(mock_storage_service).to receive(:get).with(SAML_TOKEN_CACHE_NAME, SAML_PG_CACHE_KEY) + .and_return(valid_token_entry) + allow(mock_dialect_service).to receive(:login_error?).and_return(true) + + calls = 0 + retrying = lambda do + calls += 1 + raise StandardError, 'login failure' if calls == 1 + + :ok + end + + result = build_plugin.connect(pg_host_info, {}, true, retrying) + + expect(result).to eq(:ok) + expect(calls).to eq(2) + expect(mock_token_generator).to have_received(:auth_token).once + end + + it 'injects the freshly minted token, not the stale cached one, on the retry' do + allow(mock_storage_service).to receive(:get).with(SAML_TOKEN_CACHE_NAME, SAML_PG_CACHE_KEY) + .and_return(valid_token_entry) + allow(mock_dialect_service).to receive(:login_error?).and_return(true) + allow(mock_token_generator).to receive(:auth_token).and_return('fresh-token') + + driver_props = {} + passwords = [] + calls = 0 + retrying = lambda do + calls += 1 + passwords << driver_props[:password] + raise StandardError, 'login failure' if calls == 1 + + :ok + end + + build_plugin.connect(pg_host_info, driver_props, true, retrying) + + # First attempt uses the cached token; the retry uses the freshly minted one. + expect(passwords).to eq([SAML_CACHED_TOKEN, 'fresh-token']) + end + + it 'does not retry when the token was freshly minted (not from cache)' do + allow(mock_dialect_service).to receive(:login_error?).and_return(true) + + calls = 0 + always_failing = lambda do + calls += 1 + raise StandardError, 'login failure' + end + + expect do + build_plugin.connect(pg_host_info, {}, true, always_failing) + end.to raise_error(StandardError, 'login failure') + + expect(calls).to eq(1) + end + + it 're-raises a non-login error without retrying even with a cached token' do + allow(mock_storage_service).to receive(:get).with(SAML_TOKEN_CACHE_NAME, SAML_PG_CACHE_KEY) + .and_return(valid_token_entry) + allow(mock_dialect_service).to receive(:login_error?).and_return(false) + + calls = 0 + failing = lambda do + calls += 1 + raise StandardError, 'not a login error' + end + + expect do + build_plugin.connect(pg_host_info, {}, true, failing) + end.to raise_error(StandardError, 'not a login error') + expect(calls).to eq(1) + end + end + + describe '#connect validation' do + { + 'db_user' => :db_user, + 'idp_endpoint' => :idp_endpoint, + 'iam_role_arn' => :iam_role_arn, + 'iam_idp_arn' => :iam_idp_arn + }.each do |name, key| + it "raises SamlAuthError when #{name} is missing" do + expect do + build_plugin(key => nil).connect(pg_host_info, {}, true, -> {}) + end.to raise_error(AwsAdvancedRubyDriverWrapper::Errors::SamlAuthError, /#{name}/) + end + end + + it 'lists every missing property in one error' do + expect do + build_plugin(db_user: nil, iam_role_arn: nil).connect(pg_host_info, {}, true, -> {}) + end.to raise_error(AwsAdvancedRubyDriverWrapper::Errors::SamlAuthError, /db_user.*iam_role_arn|iam_role_arn.*db_user/) + end + end + + describe '#connect region resolution' do + it 'raises SamlAuthError when the region cannot be determined' do + plugin = build_plugin(iam_region: nil) + expect do + plugin.connect(arbitrary_host_info('not-an-rds-host.example.com'), {}, true, -> {}) + end.to raise_error(AwsAdvancedRubyDriverWrapper::Errors::SamlAuthError, /region/) + end + end + + describe '#connect against a global writer cluster' do + it 'with an explicit iam_region, defers the SAML exchange to the token-cache miss path' do + # iam_region makes the region resolvable without credentials, so there is no up-front + # SAML exchange - the IdP round-trip happens only when minting on a cache miss. + connect_and_capture( + plugin: build_plugin(iam_region: 'us-east-2'), + host_info: arbitrary_host_info(SAML_GLOBAL_HOST) + ) + + expect(described_class).to have_received(:fetch_saml_assertion).once + expect(described_class).to have_received(:credentials_from_saml).once + expect(mock_token_generator).to have_received(:auth_token).once + end + + it 'with an explicit iam_region and a cached token, does not call the IdP at all' do + # A global endpoint with iam_region no longer logs in to the IdP before the + # cache check, so a pool/failover storm of cache hits triggers zero IdP logins. + allow(mock_storage_service).to receive(:get).with(SAML_TOKEN_CACHE_NAME, SAML_PG_CACHE_KEY) + .and_return(valid_token_entry) + allow(mock_storage_service).to receive(:get) + .with(SAML_TOKEN_CACHE_NAME, "us-east-2:#{SAML_GLOBAL_HOST}:#{SAML_DEFAULT_PG_PORT}:#{SAML_DB_USER}:#{SAML_PRINCIPAL_FINGERPRINT}") + .and_return(valid_token_entry) + + connect_and_capture( + plugin: build_plugin(iam_region: 'us-east-2'), + host_info: arbitrary_host_info(SAML_GLOBAL_HOST) + ) + + expect(described_class).not_to have_received(:fetch_saml_assertion) + expect(mock_token_generator).not_to have_received(:auth_token) + end + + it 'with no iam_region, assumes credentials up front and resolves the region with them' do + allow(SAML_IAM_AUTH_UTILS).to receive(:region_for).and_return('us-east-2') + + connect_and_capture( + plugin: build_plugin(iam_region: nil), + host_info: arbitrary_host_info(SAML_GLOBAL_HOST) + ) + + expect(described_class).to have_received(:fetch_saml_assertion).at_least(:once) + expect(SAML_IAM_AUTH_UTILS).to have_received(:region_for) + .with(hash_including(credentials_provider: mock_credentials)) + end + end + + describe 'cache key' do + it 'is region:host:port:db_user:principal-fingerprint' do + captured_key = nil + allow(mock_storage_service).to receive(:set) { |_name, key, _value| captured_key = key } + + connect_and_capture(plugin: build_plugin, host_info: pg_host_info) + + expect(captured_key).to eq(SAML_PG_CACHE_KEY) + end + + it 'never contains the raw STS access key id' do + allow(described_class).to receive(:credentials_from_saml) + .and_return(Aws::Credentials.new('AKIDVISIBLE', 'SECRET')) + captured_key = nil + allow(mock_storage_service).to receive(:set) { |_name, key, _value| captured_key = key } + + connect_and_capture(plugin: build_plugin, host_info: pg_host_info) + + expect(captured_key).not_to include('AKIDVISIBLE') + end + end + + describe '#internal_connect' do + it 'defaults to @wrapper_props when the override is nil' do + allow(mock_storage_service).to receive(:get).with(SAML_TOKEN_CACHE_NAME, SAML_PG_CACHE_KEY) + .and_return(valid_token_entry) + + driver_props = {} + begin + build_plugin.internal_connect(pg_host_info, driver_props, nil, true, -> { raise StandardError, 'simulated' }) + rescue StandardError + nil + end + + expect(driver_props[:user]).to eq(SAML_DB_USER) + expect(driver_props[:password]).to eq(SAML_CACHED_TOKEN) + end + + it 'honours an iam_host supplied via the wrapper_props override' do + override_host = 'override.testdb.us-east-2.rds.amazonaws.com' + begin + build_plugin.internal_connect(pg_host_info, {}, + wrapper_props_map(base_wrapper_props.merge(iam_host: override_host)), + false, -> { raise StandardError, 'simulated' }) + rescue StandardError + nil + end + + expect(mock_token_generator).to have_received(:auth_token).with( + hash_including(endpoint: "#{override_host}:#{SAML_DEFAULT_PG_PORT}") + ) + end + end + + describe '#subscribed_methods' do + it 'subscribes to connect and internal_connect only' do + expect(build_plugin.subscribed_methods).to include('connect', 'internal_connect') + expect(build_plugin.subscribed_methods).not_to include('execute') + end + end + + describe '.clear_cache' do + it 'delegates to the storage service with the shared IAM token cache name' do + allow(mock_storage_service).to receive(:clear) + described_class.clear_cache(mock_storage_service) + expect(mock_storage_service).to have_received(:clear).with(SAML_TOKEN_CACHE_NAME) + end + end + + describe '.credentials_from_saml' do + it 'exchanges the assertion via STS AssumeRoleWithSAML and returns the credentials' do + allow(described_class).to receive(:credentials_from_saml).and_call_original + sts_client = instance_double(Aws::STS::Client) + sts_creds = double('StsCreds', access_key_id: 'AKIASTS', secret_access_key: 'secret', session_token: 'session') + allow(Aws::STS::Client).to receive(:new).and_return(sts_client) + allow(sts_client).to receive(:assume_role_with_saml) + .and_return(double('Resp', credentials: sts_creds)) + + creds = described_class.credentials_from_saml( + SAML_FAKE_SAML_ASSERTION, + role_arn: 'role', idp_arn: 'idp', region: 'us-east-2' + ) + + expect(Aws::STS::Client).to have_received(:new).with(region: 'us-east-2', credentials: nil) + expect(sts_client).to have_received(:assume_role_with_saml).with( + role_arn: 'role', principal_arn: 'idp', saml_assertion: SAML_FAKE_SAML_ASSERTION + ) + expect(creds.access_key_id).to eq('AKIASTS') + expect(creds.session_token).to eq('session') + end + end +end diff --git a/spec/unit/plugins/federated_auth/federated_auth_plugin_spec.rb b/spec/unit/plugins/federated_auth/federated_auth_plugin_spec.rb new file mode 100644 index 00000000..d093e536 --- /dev/null +++ b/spec/unit/plugins/federated_auth/federated_auth_plugin_spec.rb @@ -0,0 +1,243 @@ +# 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_relative '../../../spec_helper' +require 'net/http' +require 'aws-sdk-rds' +require 'aws_advanced_ruby_driver_wrapper/plugins/federated_auth/federated_auth_plugin' +require 'aws_advanced_ruby_driver_wrapper/utils/saml_utils' +require 'aws_advanced_ruby_driver_wrapper/errors' + +RSpec.describe AwsAdvancedRubyDriverWrapper::Plugins::FederatedAuth::FederatedAuthPlugin do + SamlUtils = AwsAdvancedRubyDriverWrapper::Utils::SamlUtils + SamlAuthError = AwsAdvancedRubyDriverWrapper::Errors::SamlAuthError + + # A stand-in Net::HTTPResponse: real enough for the `is_a?(Net::HTTPSuccess)` + # check the plugin performs, without an actual HTTP round-trip. + class FakeHttpResponse + attr_reader :body, :code, :message + + def initialize(body: '', code: '200', message: 'OK', success: true) + @body = body + @code = code + @message = message + @success = success + end + + def is_a?(klass) + return @success if klass == Net::HTTPSuccess + + super + end + end + + ADFS_ENDPOINT = 'ec2amaz-ab3cdef.example.com' + ADFS_PORT = 443 + RP_IDENTIFIER = 'urn:amazon:webservices' + + SIGN_ON_URL = + "https://#{ADFS_ENDPOINT}:#{ADFS_PORT}/adfs/ls/IdpInitiatedSignOn.aspx?loginToRp=#{RP_IDENTIFIER}".freeze + + # A sign-on page with the fields AD FS actually posts back: a form action, the + # username and password inputs, an AuthMethod hidden field, and an opaque + # hidden field that must be carried through untouched. + SIGN_ON_PAGE = <<~HTML + +
+ + + + +
+ + HTML + + SAML_RESPONSE_PAGE = <<~HTML + +
+ +
+ + HTML + + def fetch_options(overrides = {}) + { + idp_endpoint: ADFS_ENDPOINT, + idp_port: ADFS_PORT, + idp_username: 'jimbob@example.com', + idp_password: 'idpSecret', + rp_identifier: RP_IDENTIFIER, + ssl_insecure: false, + socket_timeout_sec: 60.0, + connect_timeout_sec: 60.0 + }.merge(overrides) + end + + describe '.fetch_saml_assertion' do + it 'GETs the sign-on page, POSTs the form, and returns the extracted assertion' do + allow(SamlUtils).to receive(:http_request) do |method:, url:, **_rest| + if method == :get + expect(url).to eq(SIGN_ON_URL) + FakeHttpResponse.new(body: SIGN_ON_PAGE) + else + FakeHttpResponse.new(body: SAML_RESPONSE_PAGE) + end + end + + assertion = described_class.fetch_saml_assertion(**fetch_options) + + expect(assertion).to eq('BASE64ASSERTION==') + end + + it 'POSTs to the absolute URL built from the form action and the federated credentials' do + posted = {} + allow(SamlUtils).to receive(:http_request) do |method:, url:, body: nil, **_rest| + if method == :get + FakeHttpResponse.new(body: SIGN_ON_PAGE) + else + posted[:url] = url + posted[:body] = body + FakeHttpResponse.new(body: SAML_RESPONSE_PAGE) + end + end + + described_class.fetch_saml_assertion(**fetch_options) + + expect(posted[:url]).to eq("https://#{ADFS_ENDPOINT}:#{ADFS_PORT}/adfs/ls/?client-request-id=abc&foo=bar") + params = URI.decode_www_form(posted[:body]).to_h + expect(params['UserName']).to eq('jimbob@example.com') + expect(params['Password']).to eq('idpSecret') + expect(params['AuthMethod']).to eq('FormsAuthentication') + expect(params['Kmsi']).to eq('true') + end + + it 'raises SamlAuthError when the sign-on page request fails' do + allow(SamlUtils).to receive(:http_request) + .and_return(FakeHttpResponse.new(code: '500', message: 'Server Error', success: false)) + + expect { described_class.fetch_saml_assertion(**fetch_options) } + .to raise_error(SamlAuthError, /sign-on page.*500/) + end + + it 'raises SamlAuthError with a diagnostic hint when the POST response carries no SAML assertion' do + allow(SamlUtils).to receive(:http_request) do |method:, **_rest| + FakeHttpResponse.new(body: method == :get ? SIGN_ON_PAGE : 'no assertion here') + end + + expect { described_class.fetch_saml_assertion(**fetch_options) } + .to raise_error(SamlAuthError, /no SAML assertion.*check idp_username, idp_password, and idp_endpoint/) + end + + it 'does not include the response body in the no-assertion error' do + secret_markup = 'SENSITIVE-ERROR-DETail-xyz' + allow(SamlUtils).to receive(:http_request) do |method:, **_rest| + FakeHttpResponse.new(body: method == :get ? SIGN_ON_PAGE : secret_markup) + end + + expect { described_class.fetch_saml_assertion(**fetch_options) } + .to raise_error(SamlAuthError) { |e| expect(e.message).not_to include('SENSITIVE-ERROR-DETail') } + end + end + + describe '.form_parameters' do + let(:body) { SIGN_ON_PAGE } + + it 'substitutes the username and password inputs with the federated credentials' do + params = described_class.form_parameters(body, 'user@corp', 'secretpw').to_h + expect(params['UserName']).to eq('user@corp') + expect(params['Password']).to eq('secretpw') + end + + it 'preserves the AuthMethod and other hidden fields' do + params = described_class.form_parameters(body, 'u', 'p').to_h + expect(params['AuthMethod']).to eq('FormsAuthentication') + expect(params['Kmsi']).to eq('true') + end + + it 'drops an AuthMethod field with an empty value' do + html = '' + names = described_class.form_parameters(html, 'u', 'p').map(&:first) + expect(names).not_to include('AuthMethod') + end + + it 'skips inputs with no name attribute' do + html = '' + expect(described_class.form_parameters(html, 'u', 'p')).to be_empty + end + + it 'de-duplicates inputs case-insensitively by name, keeping the first' do + html = '' + params = described_class.form_parameters(html, 'u', 'p') + expect(params).to eq([%w[Token first]]) + end + end + + describe '.form_action' do + it 'extracts and HTML-unescapes the form action' do + expect(described_class.form_action(SIGN_ON_PAGE)).to eq('/adfs/ls/?client-request-id=abc&foo=bar') + end + + it 'returns nil when there is no form' do + expect(described_class.form_action('no form')).to be_nil + end + end + + describe '.unescape_html' do + it 'unescapes the standard XML entities' do + expect(described_class.unescape_html('a&b<c>d"e'f')).to eq(%(a&bd"e'f)) + end + end + + describe '.require_body!' do + it 'returns the body for a successful response' do + expect(described_class.require_body!(FakeHttpResponse.new(body: 'ok'), 'thing')).to eq('ok') + end + + it 'raises SamlAuthError describing the failing request' do + resp = FakeHttpResponse.new(code: '403', message: 'Forbidden', success: false) + expect { described_class.require_body!(resp, 'sign-on POST') } + .to raise_error(SamlAuthError, /sign-on POST.*403 Forbidden/) + end + end + + describe 'PluginManager registration' do + before { require 'aws_advanced_ruby_driver_wrapper/services/plugin_manager' } + + it "is registered under the code 'federated_auth'" do + plugin_classes = AwsAdvancedRubyDriverWrapper::Services::PluginManager.plugin_classes + expect(plugin_classes['federated_auth']).to eq(described_class) + end + + it 'cannot be combined with another authentication plugin' do + wrapper_props = Concurrent::Map.new + wrapper_props[:wrapper_plugins] = 'federated_auth,iam' + connection_service = double('ConnectionService', wrapper_props:) + container = double('ServiceContainer', connection_service:) + + expect do + AwsAdvancedRubyDriverWrapper::Services::PluginManager.new(container) + end.to raise_error(AwsAdvancedRubyDriverWrapper::Errors::PluginConflictError) + end + end + + describe 'default idp_name' do + it 'defaults the identity provider name to adfs' do + expect( + AwsAdvancedRubyDriverWrapper::PropertyDefinition::IDP_NAME.get(Concurrent::Map.new) + ).to eq('adfs') + end + end +end