/
connections.go
140 lines (116 loc) · 3.72 KB
/
connections.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package postgreSQL
import (
"cloud.google.com/go/cloudsqlconn"
secretmanager "cloud.google.com/go/secretmanager/apiv1"
"cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"github.com/jackc/pgx/v4"
"github.com/jackc/pgx/v4/stdlib"
_ "github.com/jackc/pgx/v4/stdlib"
"hash/crc32"
"log"
"net"
"os"
"strings"
)
type Connection struct {
Database string `json:"database"`
UseID string `json:"userID"`
Password string `json:"password"`
ConnectionName string `json:"connectionName"`
DBIAMUser string `json:"dbIAMUser"`
}
func NewConnection(ctx context.Context) (*sql.DB, error) {
var db *sql.DB
projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")
postgresSecretsName := os.Getenv("CLOUD_SQL_POSTGRES_SECRETS_NAME")
sqlSecretsReq := fmt.Sprintf("projects/%v/secrets/%v/versions/latest", projectID, postgresSecretsName)
//log.Printf("sqlSecretsReq: %v\n", sqlSecretsReq)
payload, err := accessSecretVersion(sqlSecretsReq)
if err != nil {
return nil, err
}
conn := Connection{}
if err := json.Unmarshal(payload, &conn); err != nil {
return nil, fmt.Errorf("error parsing secrets payload, %v", err)
}
db, err = connectWithConnector(conn)
if err != nil {
return nil, fmt.Errorf("connectIAM: unable to connect: %s", err)
}
return db, nil
}
func connectWithConnector(connDetails Connection) (*sql.DB, error) {
usePrivate, err := getEnv("PRIVATE_IP", false, false)
if err != nil {
return nil, fmt.Errorf("%v", err)
}
dsn := fmt.Sprintf("user=%s password=%s database=%s", connDetails.UseID, connDetails.Password, connDetails.Database)
config, err := pgx.ParseConfig(dsn)
if err != nil {
return nil, err
}
var opts []cloudsqlconn.Option
if usePrivate != "" {
opts = append(opts, cloudsqlconn.WithDefaultDialOptions(cloudsqlconn.WithPrivateIP()))
}
d, err := cloudsqlconn.NewDialer(context.Background(), opts...)
if err != nil {
return nil, err
}
// Use the Cloud SQL connector to handle connecting to the instance.
// This approach does *NOT* require the Cloud SQL proxy.
config.DialFunc = func(ctx context.Context, network, instance string) (net.Conn, error) {
return d.Dial(ctx, connDetails.ConnectionName)
}
dbURI := stdlib.RegisterConnConfig(config)
dbPool, err := sql.Open("pgx", dbURI)
if err != nil {
return nil, fmt.Errorf("sql.Open: %w", err)
}
return dbPool, nil
}
func accessSecretVersion(name string) ([]byte, error) {
// name := "projects/my-project/secrets/my-secret/versions/latest"
// Create the client.
ctx := context.Background()
client, err := secretmanager.NewClient(ctx)
if err != nil {
return nil, fmt.Errorf("failed to create secretmanager client: %w", err)
}
defer client.Close()
// Build the request.
req := &secretmanagerpb.AccessSecretVersionRequest{
Name: name,
}
// Call the API.
result, err := client.AccessSecretVersion(ctx, req)
if err != nil {
return nil, fmt.Errorf("failed to access secret version: %w", err)
}
// Verify the data checksum.
crc32c := crc32.MakeTable(crc32.Castagnoli)
checksum := int64(crc32.Checksum(result.Payload.Data, crc32c))
if checksum != *result.Payload.DataCrc32C {
return nil, errors.New("data corruption detected")
}
// WARNING: Do not print the secret in a production environment - this snippet
// is showing how to access the secret material.
//log.Printf("Plaintext: %s\n", string(result.Payload.Data))
return result.Payload.Data, nil
}
func getEnv(env string, required bool, mask bool) (string, error) {
value := os.Getenv(env)
if len(value) == 0 && required {
return value, fmt.Errorf("%s environment variable not set", env)
}
if mask {
value = strings.Repeat("*", len(value))
}
log.Printf("%v : %v\n", env, value)
return value, nil
}