Class: PG::AWS_RDS_IAM::AuthTokenGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/pg/aws_rds_iam/auth_token_generator.rb

Overview

Generates short-lived authentication tokens for connecting to Amazon RDS instances.

Instance Method Summary collapse

Constructor Details

#initialize(credentials:, region:) ⇒ AuthTokenGenerator

Creates a new authentication token generator.

Parameters:

  • credentials (Aws::CredentialProvider)

    the IAM credentials with which to sign the token

  • region (String)

    the AWS region in which the RDS instances are running



13
14
15
16
17
18
# File 'lib/pg/aws_rds_iam/auth_token_generator.rb', line 13

def initialize(credentials:, region:)
  @generator = Aws::RDS::AuthTokenGenerator.new(credentials:)
  @region = region
  @mutex = Mutex.new
  @cache = {}
end

Instance Method Details

#call(host:, port:, user:) ⇒ String

Generates an authentication token for connecting to an Amazon RDS instance. Generated tokens are cached and reused until 1 minute before they are due to expire.

Parameters:

  • host (String)

    the host name of the RDS instance that you want to access

  • port (String)

    the port number used for connecting to your RDS instance

  • user (String)

    the database account that you want to access

Returns:

  • (String)

    the generated authentication token



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/pg/aws_rds_iam/auth_token_generator.rb', line 27

def call(host:, port:, user:)
  endpoint = "#{host}:#{port}"
  key = "#{user}@#{endpoint}"

  token = cached_token(key)
  return token if token

  @mutex.synchronize do
    token = cached_token(key)
    break token if token

    @generator.auth_token(region: @region, endpoint:, user_name: user).tap do |new_token|
      @cache[key] = AuthToken.new(new_token)
    end
  end
end