Class: CloudSQLRubyConnector::PostgreSQL::Connector

Inherits:
Object
  • Object
show all
Defined in:
lib/cloud_sql_ruby_connector/postgresql/connector.rb

Overview

PostgreSQL connector for Cloud SQL connections

Provides secure, authenticated connections to Cloud SQL PostgreSQL instances using ephemeral certificates and optional IAM authentication.

Examples:

Basic usage

connector = CloudSQLRubyConnector::PostgreSQL::Connector.new("my-project:us-central1:my-instance")
conn = connector.connect(user: "myuser", password: "mypass", dbname: "mydb")
result = conn.exec("SELECT NOW()")
conn.close
connector.close

Using IAM authentication

connector = CloudSQLRubyConnector::PostgreSQL::Connector.new(
  "my-project:us-central1:my-instance",
  auth_type: :iam
)
conn = connector.connect(user: "[email protected]", dbname: "mydb")

Constant Summary collapse

CLOUD_SQL_PORT =
3307
CERT_REFRESH_BUFFER =

Refresh certificate 5 minutes before expiration

300

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(instance_connection_name, credentials: nil, ip_type: IpAddressTypes::PUBLIC, auth_type: AuthTypes::PASSWORD, api_endpoint: nil) ⇒ Connector

Initialize a new connector

Parameters:

  • instance_connection_name (String)

    Cloud SQL instance connection name (PROJECT:REGION:INSTANCE)

  • credentials (Credentials::Base) (defaults to: nil)

    Optional credentials object

  • ip_type (String, Symbol) (defaults to: IpAddressTypes::PUBLIC)

    IP address type: :public, :private, or :psc (default: :public)

  • auth_type (String, Symbol) (defaults to: AuthTypes::PASSWORD)

    Authentication type: :password or :iam (default: :password)

  • api_endpoint (String) (defaults to: nil)

    Optional custom API endpoint



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/cloud_sql_ruby_connector/postgresql/connector.rb', line 54

def initialize(instance_connection_name, credentials: nil, ip_type: IpAddressTypes::PUBLIC,
               auth_type: AuthTypes::PASSWORD, api_endpoint: nil)
  @project, @region, @instance_name = parse_connection_name(instance_connection_name)
  @ip_type = IpAddressTypes.normalize(ip_type)
  @auth_type = AuthTypes.normalize(auth_type)
  @credentials = credentials || default_credentials
  @api_endpoint = api_endpoint

  # Generate RSA key pair once per connector instance
  @private_key, @public_key = generate_keys

  # Certificate cache with expiration tracking
  @cached_info = nil
  @cert_expiration = Time.at(0)
  @lock = Mutex.new

  # SQL Admin API fetcher
  @fetcher = SQLAdminFetcher.new(credentials: @credentials, api_endpoint: @api_endpoint)

  # Track active proxies for cleanup
  @proxies = []
end

Instance Attribute Details

#auth_typeObject (readonly)

Returns the value of attribute auth_type.



45
46
47
# File 'lib/cloud_sql_ruby_connector/postgresql/connector.rb', line 45

def auth_type
  @auth_type
end

#instance_nameObject (readonly)

Returns the value of attribute instance_name.



45
46
47
# File 'lib/cloud_sql_ruby_connector/postgresql/connector.rb', line 45

def instance_name
  @instance_name
end

#ip_typeObject (readonly)

Returns the value of attribute ip_type.



45
46
47
# File 'lib/cloud_sql_ruby_connector/postgresql/connector.rb', line 45

def ip_type
  @ip_type
end

#projectObject (readonly)

Returns the value of attribute project.



45
46
47
# File 'lib/cloud_sql_ruby_connector/postgresql/connector.rb', line 45

def project
  @project
end

#regionObject (readonly)

Returns the value of attribute region.



45
46
47
# File 'lib/cloud_sql_ruby_connector/postgresql/connector.rb', line 45

def region
  @region
end

Instance Method Details

#closeObject

Close the connector and clean up resources



138
139
140
141
142
143
144
# File 'lib/cloud_sql_ruby_connector/postgresql/connector.rb', line 138

def close
  @lock.synchronize do
    @proxies.each(&:stop)
    @proxies.clear
    @cached_info = nil
  end
end

#connect(user:, dbname:, password: nil, **extra_options) ⇒ PG::Connection

Create a connected PG::Connection

Parameters:

  • user (String)

    Database username

  • password (String) (defaults to: nil)

    Database password (optional for IAM auth)

  • dbname (String)

    Database name

  • extra_options (Hash)

    Additional options to pass to PG.connect

Returns:

  • (PG::Connection)

    Connected PostgreSQL connection



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/cloud_sql_ruby_connector/postgresql/connector.rb', line 84

def connect(user:, dbname:, password: nil, **extra_options)
  require "pg"

  validate_connection_params!(user: user)
  conn_info = ensure_valid_connection_info!

  effective_user = @auth_type == AuthTypes::IAM ? format_iam_user(user) : user
  effective_password = @auth_type == AuthTypes::IAM ? @credentials.access_token(scope: :login) : password

  ssl_socket = create_ssl_connection(conn_info)
  proxy = SslProxy.new(ssl_socket)
  proxy.start
  @lock.synchronize { @proxies << proxy }

  begin
    PG.connect(
      host: "127.0.0.1",
      port: proxy.port,
      user: effective_user,
      password: effective_password,
      dbname: dbname,
      sslmode: "disable",
      **extra_options
    )
  rescue StandardError => e
    proxy.stop
    raise e
  end
end

#get_optionsHash

Get connection options that can be used with PG.connect This is an alternative to using #connect directly

Returns:

  • (Hash)

    Connection options including :stream proc



118
119
120
121
122
123
124
125
126
127
128
# File 'lib/cloud_sql_ruby_connector/postgresql/connector.rb', line 118

def get_options
  conn_info = ensure_valid_connection_info!

  {
    stream: -> { create_ssl_connection(conn_info) },
    ip_address: conn_info[:ip_address],
    server_ca_cert: conn_info[:server_ca_cert],
    client_cert: conn_info[:client_cert],
    private_key: conn_info[:private_key]
  }
end

#ip_addressString

Get the IP address for the instance

Returns:

  • (String)

    IP address



133
134
135
# File 'lib/cloud_sql_ruby_connector/postgresql/connector.rb', line 133

def ip_address
  ensure_valid_connection_info![:ip_address]
end