github.com/hashicorp/vault/sdk@v0.13.0/database/helper/connutil/cloudsql.go (about) 1 // Copyright (c) HashiCorp, Inc. 2 // SPDX-License-Identifier: MPL-2.0 3 4 package connutil 5 6 import ( 7 "fmt" 8 9 "cloud.google.com/go/cloudsqlconn" 10 "cloud.google.com/go/cloudsqlconn/postgres/pgxv4" 11 ) 12 13 var configurableAuthTypes = []string{ 14 AuthTypeGCPIAM, 15 } 16 17 func (c *SQLConnectionProducer) getCloudSQLDriverType() (string, error) { 18 var driverType string 19 // using switch case for future extensibility 20 switch c.Type { 21 case dbTypePostgres: 22 driverType = cloudSQLPostgres 23 default: 24 return "", fmt.Errorf("unsupported DB type for cloud IAM: %s", c.Type) 25 } 26 27 return driverType, nil 28 } 29 30 func (c *SQLConnectionProducer) registerDrivers(driverName string, credentials string) (func() error, error) { 31 typ, err := c.getCloudSQLDriverType() 32 if err != nil { 33 return nil, err 34 } 35 36 opts, err := GetCloudSQLAuthOptions(credentials) 37 if err != nil { 38 return nil, err 39 } 40 41 // using switch case for future extensibility 42 switch typ { 43 case cloudSQLPostgres: 44 return pgxv4.RegisterDriver(driverName, opts...) 45 } 46 47 return nil, fmt.Errorf("unrecognized cloudsql type encountered: %s", typ) 48 } 49 50 // GetCloudSQLAuthOptions takes a credentials JSON and returns 51 // a set of GCP CloudSQL options - always WithIAMAUthN, and then the appropriate file/JSON option. 52 func GetCloudSQLAuthOptions(credentials string) ([]cloudsqlconn.Option, error) { 53 opts := []cloudsqlconn.Option{cloudsqlconn.WithIAMAuthN()} 54 55 if credentials != "" { 56 opts = append(opts, cloudsqlconn.WithCredentialsJSON([]byte(credentials))) 57 } 58 59 return opts, nil 60 } 61 62 func ValidateAuthType(authType string) bool { 63 var valid bool 64 for _, typ := range configurableAuthTypes { 65 if authType == typ { 66 valid = true 67 break 68 } 69 } 70 71 return valid 72 }