-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
influxdb.go
266 lines (224 loc) · 7.69 KB
/
influxdb.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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package influxdb
import (
"context"
"fmt"
"strings"
multierror "github.com/hashicorp/go-multierror"
"github.com/hashicorp/go-secure-stdlib/strutil"
dbplugin "github.com/hashicorp/vault/sdk/database/dbplugin/v5"
"github.com/hashicorp/vault/sdk/database/helper/dbutil"
"github.com/hashicorp/vault/sdk/helper/template"
influx "github.com/influxdata/influxdb1-client/v2"
)
const (
defaultUserCreationIFQL = `CREATE USER "{{username}}" WITH PASSWORD '{{password}}';`
defaultUserDeletionIFQL = `DROP USER "{{username}}";`
defaultRootCredentialRotationIFQL = `SET PASSWORD FOR "{{username}}" = '{{password}}';`
influxdbTypeName = "influxdb"
defaultUserNameTemplate = `{{ printf "v_%s_%s_%s_%s" (.DisplayName | truncate 15) (.RoleName | truncate 15) (random 20) (unix_time) | truncate 100 | replace "-" "_" | lowercase }}`
)
var _ dbplugin.Database = &Influxdb{}
// Influxdb is an implementation of Database interface
type Influxdb struct {
*influxdbConnectionProducer
usernameProducer template.StringTemplate
}
// New returns a new Cassandra instance
func New() (interface{}, error) {
db := new()
dbType := dbplugin.NewDatabaseErrorSanitizerMiddleware(db, db.secretValues)
return dbType, nil
}
func new() *Influxdb {
connProducer := &influxdbConnectionProducer{}
connProducer.Type = influxdbTypeName
return &Influxdb{
influxdbConnectionProducer: connProducer,
}
}
// Type returns the TypeName for this backend
func (i *Influxdb) Type() (string, error) {
return influxdbTypeName, nil
}
func (i *Influxdb) getConnection(ctx context.Context) (influx.Client, error) {
cli, err := i.Connection(ctx)
if err != nil {
return nil, err
}
return cli.(influx.Client), nil
}
func (i *Influxdb) Initialize(ctx context.Context, req dbplugin.InitializeRequest) (resp dbplugin.InitializeResponse, err error) {
usernameTemplate, err := strutil.GetString(req.Config, "username_template")
if err != nil {
return dbplugin.InitializeResponse{}, fmt.Errorf("failed to retrieve username_template: %w", err)
}
if usernameTemplate == "" {
usernameTemplate = defaultUserNameTemplate
}
up, err := template.NewTemplate(template.Template(usernameTemplate))
if err != nil {
return dbplugin.InitializeResponse{}, fmt.Errorf("unable to initialize username template: %w", err)
}
i.usernameProducer = up
_, err = i.usernameProducer.Generate(dbplugin.UsernameMetadata{})
if err != nil {
return dbplugin.InitializeResponse{}, fmt.Errorf("invalid username template: %w", err)
}
return i.influxdbConnectionProducer.Initialize(ctx, req)
}
// NewUser generates the username/password on the underlying Influxdb secret backend as instructed by
// the statements provided.
func (i *Influxdb) NewUser(ctx context.Context, req dbplugin.NewUserRequest) (resp dbplugin.NewUserResponse, err error) {
i.Lock()
defer i.Unlock()
cli, err := i.getConnection(ctx)
if err != nil {
return dbplugin.NewUserResponse{}, fmt.Errorf("unable to get connection: %w", err)
}
creationIFQL := req.Statements.Commands
if len(creationIFQL) == 0 {
creationIFQL = []string{defaultUserCreationIFQL}
}
rollbackIFQL := req.RollbackStatements.Commands
if len(rollbackIFQL) == 0 {
rollbackIFQL = []string{defaultUserDeletionIFQL}
}
username, err := i.usernameProducer.Generate(req.UsernameConfig)
if err != nil {
return dbplugin.NewUserResponse{}, err
}
for _, stmt := range creationIFQL {
for _, query := range strutil.ParseArbitraryStringSlice(stmt, ";") {
query = strings.TrimSpace(query)
if len(query) == 0 {
continue
}
m := map[string]string{
"username": username,
"password": req.Password,
}
qry := influx.NewQuery(dbutil.QueryHelper(query, m), "", "")
response, err := cli.Query(qry)
// err can be nil with response.Error() being not nil, so both need to be handled
merr := multierror.Append(err, response.Error())
if merr.ErrorOrNil() != nil {
// Attempt rollback only when the response has an error
if response != nil && response.Error() != nil {
attemptRollback(cli, username, rollbackIFQL)
}
return dbplugin.NewUserResponse{}, fmt.Errorf("failed to run query in InfluxDB: %w", merr)
}
}
}
resp = dbplugin.NewUserResponse{
Username: username,
}
return resp, nil
}
// attemptRollback will attempt to roll back user creation if an error occurs in
// CreateUser
func attemptRollback(cli influx.Client, username string, rollbackStatements []string) error {
for _, stmt := range rollbackStatements {
for _, query := range strutil.ParseArbitraryStringSlice(stmt, ";") {
query = strings.TrimSpace(query)
if len(query) == 0 {
continue
}
q := influx.NewQuery(dbutil.QueryHelper(query, map[string]string{
"username": username,
}), "", "")
response, err := cli.Query(q)
// err can be nil with response.Error() being not nil, so both need to be handled
merr := multierror.Append(err, response.Error())
if merr.ErrorOrNil() != nil {
return merr
}
}
}
return nil
}
func (i *Influxdb) DeleteUser(ctx context.Context, req dbplugin.DeleteUserRequest) (dbplugin.DeleteUserResponse, error) {
i.Lock()
defer i.Unlock()
cli, err := i.getConnection(ctx)
if err != nil {
return dbplugin.DeleteUserResponse{}, fmt.Errorf("unable to get connection: %w", err)
}
revocationIFQL := req.Statements.Commands
if len(revocationIFQL) == 0 {
revocationIFQL = []string{defaultUserDeletionIFQL}
}
var result *multierror.Error
for _, stmt := range revocationIFQL {
for _, query := range strutil.ParseArbitraryStringSlice(stmt, ";") {
query = strings.TrimSpace(query)
if len(query) == 0 {
continue
}
m := map[string]string{
"username": req.Username,
}
q := influx.NewQuery(dbutil.QueryHelper(query, m), "", "")
response, err := cli.Query(q)
result = multierror.Append(result, err)
if response != nil {
result = multierror.Append(result, response.Error())
}
}
}
if result.ErrorOrNil() != nil {
return dbplugin.DeleteUserResponse{}, fmt.Errorf("failed to delete user cleanly: %w", result.ErrorOrNil())
}
return dbplugin.DeleteUserResponse{}, nil
}
func (i *Influxdb) UpdateUser(ctx context.Context, req dbplugin.UpdateUserRequest) (dbplugin.UpdateUserResponse, error) {
if req.Password == nil && req.Expiration == nil {
return dbplugin.UpdateUserResponse{}, fmt.Errorf("no changes requested")
}
i.Lock()
defer i.Unlock()
if req.Password != nil {
err := i.changeUserPassword(ctx, req.Username, req.Password)
if err != nil {
return dbplugin.UpdateUserResponse{}, fmt.Errorf("failed to change %q password: %w", req.Username, err)
}
}
// Expiration is a no-op
return dbplugin.UpdateUserResponse{}, nil
}
func (i *Influxdb) changeUserPassword(ctx context.Context, username string, changePassword *dbplugin.ChangePassword) error {
cli, err := i.getConnection(ctx)
if err != nil {
return fmt.Errorf("unable to get connection: %w", err)
}
rotateIFQL := changePassword.Statements.Commands
if len(rotateIFQL) == 0 {
rotateIFQL = []string{defaultRootCredentialRotationIFQL}
}
var result *multierror.Error
for _, stmt := range rotateIFQL {
for _, query := range strutil.ParseArbitraryStringSlice(stmt, ";") {
query = strings.TrimSpace(query)
if len(query) == 0 {
continue
}
m := map[string]string{
"username": username,
"password": changePassword.NewPassword,
}
q := influx.NewQuery(dbutil.QueryHelper(query, m), "", "")
response, err := cli.Query(q)
result = multierror.Append(result, err)
if response != nil {
result = multierror.Append(result, response.Error())
}
}
}
err = result.ErrorOrNil()
if err != nil {
return fmt.Errorf("failed to execute rotation queries: %w", err)
}
return nil
}