Class: PG::AzureWorkloadIdentity::AuthTokenInjector

Inherits:
Object
  • Object
show all
Defined in:
lib/pg/azure_workload_identity/auth_token_injector.rb

Overview

AuthTokenInjector is responsible for injecting auth tokens into connection strings and PSQL environment variables when required.

Instance Method Summary collapse

Constructor Details

#initialize(auth_token_generator: nil) ⇒ AuthTokenInjector

Initializes a new AuthTokenInjector.

The generator is resolved lazily — only on the code paths that actually need a token — so that constructing an injector is cheap and side-effect-free for connections that don't opt into workload identity.

Parameters:

  • auth_token_generator (#call, nil) (defaults to: nil)

    A callable that generates an auth token. Defaults to the module-level generator at the time a token is first needed.



21
22
23
# File 'lib/pg/azure_workload_identity/auth_token_injector.rb', line 21

def initialize(auth_token_generator: nil)
  @auth_token_generator = auth_token_generator
end

Instance Method Details

#inject_into_connection_string(connection_string) ⇒ String

Injects an auth token into the given connection string as password if required.

Parameters:

  • connection_string (String)

    The original connection string.

Returns:

  • (String)

    The modified connection string with the auth token injected if required.



29
30
31
32
33
34
35
# File 'lib/pg/azure_workload_identity/auth_token_injector.rb', line 29

def inject_into_connection_string(connection_string)
  connection_info = ConnectionInfo.from_connection_string(connection_string)
  return connection_string unless generate_auth_token?(connection_info)

  connection_info.password = auth_token_generator.call
  connection_info.to_s
end

#inject_into_psql_env!(configuration_hash, psql_env) ⇒ Object

Injects an auth token into the given PSQL environment hash if required. This is used for the db:console rake task.

Parameters:

  • configuration_hash (Hash)

    The ActiveRecord connection configuration hash from database.yml

  • psql_env (Hash)

    The environment hash to be passed to the PSQL process.



42
43
44
45
46
47
# File 'lib/pg/azure_workload_identity/auth_token_injector.rb', line 42

def inject_into_psql_env!(configuration_hash, psql_env)
  connection_info = ConnectionInfo.from_active_record_configuration_hash(configuration_hash)
  return unless generate_auth_token?(connection_info)

  psql_env["PGPASSWORD"] = auth_token_generator.call
end