This repository has been archived by the owner on Jul 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 59
/
sql_account_manager.go
214 lines (177 loc) · 6.48 KB
/
sql_account_manager.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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
// Copyright 2018 the Service Broker Project Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cloudsql
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
"code.cloudfoundry.org/lager"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
googlecloudsql "google.golang.org/api/sqladmin/v1beta4"
sqladmin "google.golang.org/api/sqladmin/v1beta4"
)
// inserts a new user into the database and creates new ssl certs
func (broker *CloudSQLBroker) createSqlCredentials(ctx context.Context, vars *varcontext.VarContext) (map[string]interface{}, error) {
userAccount, err := broker.createSqlUserAccount(ctx, vars)
if err != nil {
return nil, err
}
sslCert, err := broker.createSqlSslCert(ctx, vars)
if err != nil {
return nil, err
}
return varcontext.Builder().MergeStruct(userAccount).MergeStruct(sslCert).BuildMap()
}
type sqlUserAccount struct {
Username string `json:"Username"`
Password string `json:"Password"`
}
type sqlSslCert struct {
CaCert string `json:"CaCert"`
ClientCert string `json:"ClientCert"`
ClientKey string `json:"ClientKey"`
Sha1Fingerprint string `json:"Sha1Fingerprint"`
}
func (broker *CloudSQLBroker) createSqlUserAccount(ctx context.Context, vars *varcontext.VarContext) (*sqlUserAccount, error) {
request := &googlecloudsql.User{
Name: vars.GetString("username"),
Password: vars.GetString("password"),
}
instanceName := vars.GetString("db_name")
if err := vars.Error(); err != nil {
return nil, err
}
// create username, pw with grants
client, err := broker.createClient(ctx)
if err != nil {
return nil, err
}
op, err := client.Users.Insert(broker.ProjectId, instanceName, request).Do()
if err != nil {
return nil, fmt.Errorf("Error creating new database user: %s", err)
}
// poll for the user creation operation to be completed
if err := broker.pollOperationUntilDone(ctx, op, broker.ProjectId); err != nil {
return nil, fmt.Errorf("Error encountered waiting for operation %q to finish: %s", op.Name, err)
}
return &sqlUserAccount{
Username: request.Name,
Password: request.Password,
}, nil
}
func (broker *CloudSQLBroker) deleteSqlUserAccount(ctx context.Context, binding models.ServiceBindingCredentials, instance models.ServiceInstanceDetails) error {
var creds sqlUserAccount
if err := json.Unmarshal([]byte(binding.OtherDetails), &creds); err != nil {
return fmt.Errorf("Error unmarshalling credentials: %s", err)
}
client, err := broker.createClient(ctx)
if err != nil {
return err
}
userList, err := client.Users.List(broker.ProjectId, instance.Name).Do()
if err != nil {
return fmt.Errorf("Error fetching users to delete: %s", err)
}
// XXX: CloudSQL used to allow deleting users without specifying the host,
// however that no longer works. They also no longer accept a blank string
// which _is_ a valid host, so we expand to a single space string if the
// user we're trying to delete doesn't have some other host specified.
hostToDelete := ""
foundUser := false
for _, user := range userList.Items {
if user.Name == creds.Username {
hostToDelete = user.Host
foundUser = true
break
}
}
// XXX: If the user was already deleted, don't fail here because it could
// block deprovisioning.
if !foundUser {
return nil
}
if hostToDelete == "" {
hostToDelete = " "
}
return broker.retryWhileConflict(ctx, "user", creds.Username, func() (*sqladmin.Operation, error) {
return client.Users.Delete(broker.ProjectId, instance.Name, hostToDelete, creds.Username).Do()
})
}
func (broker *CloudSQLBroker) createSqlSslCert(ctx context.Context, vars *varcontext.VarContext) (*sqlSslCert, error) {
request := &googlecloudsql.SslCertsInsertRequest{
CommonName: vars.GetString("certname"),
}
instanceName := vars.GetString("db_name")
if err := vars.Error(); err != nil {
return nil, err
}
// create username, pw with grants
client, err := broker.createClient(ctx)
if err != nil {
return nil, err
}
newCert, err := client.SslCerts.Insert(broker.ProjectId, instanceName, request).Do()
if err != nil {
return nil, fmt.Errorf("Error creating SSL certs: %s", err)
}
// poll for the user creation operation to be completed
return &sqlSslCert{
Sha1Fingerprint: newCert.ClientCert.CertInfo.Sha1Fingerprint,
CaCert: newCert.ServerCaCert.Cert,
ClientCert: newCert.ClientCert.CertInfo.Cert,
ClientKey: newCert.ClientCert.CertPrivateKey,
}, nil
}
func (broker *CloudSQLBroker) deleteSqlSslCert(ctx context.Context, binding models.ServiceBindingCredentials, instance models.ServiceInstanceDetails) error {
var creds sqlSslCert
if err := json.Unmarshal([]byte(binding.OtherDetails), &creds); err != nil {
return fmt.Errorf("Error unmarshalling credentials: %s", err)
}
// If we didn't generate SSL certs for this binding, then we cannot delete them
if creds.CaCert == "" {
return nil
}
client, err := broker.createClient(ctx)
if err != nil {
return err
}
return broker.retryWhileConflict(ctx, "SSL Cert", creds.Sha1Fingerprint, func() (*sqladmin.Operation, error) {
return client.SslCerts.Delete(broker.ProjectId, instance.Name, creds.Sha1Fingerprint).Do()
})
}
func (broker *CloudSQLBroker) retryWhileConflict(ctx context.Context, typeName, instanceName string, callback func() (*sqladmin.Operation, error)) error {
for {
select {
case <-ctx.Done():
return fmt.Errorf("couldn't delete %s %q, timed out", typeName, instanceName)
default:
op, err := callback()
if err != nil {
if isErrStatus(err, http.StatusConflict) {
time.Sleep(5 * time.Second)
continue
}
return fmt.Errorf("couldn't delete %s: %s", typeName, err)
}
broker.Logger.Info("started deletion operation", lager.Data{"type": typeName, "name": instanceName, "op": op})
if err := broker.pollOperationUntilDone(ctx, op, broker.ProjectId); err != nil {
return fmt.Errorf("Error encountered waiting for operation %q to finish: %s", op.Name, err)
}
return nil
}
}
}