-
Notifications
You must be signed in to change notification settings - Fork 0
/
couchbasecapella.go
201 lines (167 loc) · 5.74 KB
/
couchbasecapella.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
package couchbasecapella
import (
"context"
"fmt"
"strings"
"time"
"github.com/couchbase/gocb/v2"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-secure-stdlib/strutil"
dbplugin "github.com/hashicorp/vault/sdk/database/dbplugin/v5"
"github.com/hashicorp/vault/sdk/database/helper/credsutil"
"github.com/hashicorp/vault/sdk/helper/template"
)
const (
couchbaseCapellaTypeName = "couchbasecapella"
defaultCouchbaseCapellaUserRole = `{"access": [{
"privileges": [
"data_reader"
],
"resources": {
"buckets": [
{ "name" :"*" }
]
}
}]}`
defaultTimeout = 20000 * time.Millisecond
defaultUserNameTemplate = `{{printf "V_%s_%s_%s_%s" (printf "%s" .DisplayName | uppercase | truncate 64) (printf "%s" .RoleName | uppercase | truncate 64) (random 20 | uppercase) (unix_time) | truncate 128}}`
)
var _ dbplugin.Database = &CouchbaseCapellaDB{}
var logger hclog.Logger
// Type that combines the custom plugins Couchbase Capella database connection configuration options and the Vault CredentialsProducer
// used for generating user information for the Couchbase Capella database.
type CouchbaseCapellaDB struct {
*couchbaseCapellaDBConnectionProducer
credsutil.CredentialsProducer
usernameProducer template.StringTemplate
logger hclog.Logger
}
// New implements builtinplugins.BuiltinFactory
func New() (interface{}, error) {
db := new()
// Wrap the plugin with middleware to sanitize errors
dbType := dbplugin.NewDatabaseErrorSanitizerMiddleware(db, db.secretValues)
return dbType, nil
}
func new() *CouchbaseCapellaDB {
connProducer := &couchbaseCapellaDBConnectionProducer{}
connProducer.Type = couchbaseCapellaTypeName
db := &CouchbaseCapellaDB{
couchbaseCapellaDBConnectionProducer: connProducer,
logger: hclog.New(&hclog.LoggerOptions{}),
}
logger = hclog.New(&hclog.LoggerOptions{})
return db
}
func (c *CouchbaseCapellaDB) Initialize(ctx context.Context, req dbplugin.InitializeRequest) (dbplugin.InitializeResponse, 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)
}
c.usernameProducer = up
err = c.couchbaseCapellaDBConnectionProducer.Initialize(ctx, req.Config, req.VerifyConnection)
if err != nil {
return dbplugin.InitializeResponse{}, err
}
resp := dbplugin.InitializeResponse{
Config: req.Config,
}
return resp, nil
}
func (c *CouchbaseCapellaDB) NewUser(ctx context.Context, req dbplugin.NewUserRequest) (dbplugin.NewUserResponse, error) {
// Don't let anyone write the config while we're using it
c.RLock()
defer c.RUnlock()
username, err := c.usernameProducer.Generate(req.UsernameConfig)
if err != nil {
return dbplugin.NewUserResponse{}, fmt.Errorf("failed to generate username: %w", err)
}
username = strings.ToUpper(username)
err = newUser(ctx, c.couchbaseCapellaDBConnectionProducer, username, req)
if err != nil {
return dbplugin.NewUserResponse{}, err
}
resp := dbplugin.NewUserResponse{
Username: username,
}
return resp, nil
}
func (c *CouchbaseCapellaDB) UpdateUser(ctx context.Context, req dbplugin.UpdateUserRequest) (dbplugin.UpdateUserResponse, error) {
if req.Password != nil {
newpassword := req.Password.NewPassword
_, err := c.changeUserPassword(ctx, req.Username, newpassword)
return dbplugin.UpdateUserResponse{}, err
}
return dbplugin.UpdateUserResponse{}, nil
}
func (c *CouchbaseCapellaDB) DeleteUser(ctx context.Context, req dbplugin.DeleteUserRequest) (dbplugin.DeleteUserResponse, error) {
// Don't let anyone write the config while we're using it
c.RLock()
defer c.RUnlock()
err := DeleteCapellaDbCredUser(c.CloudAPIBaseURL, c.couchbaseCapellaDBConnectionProducer.CloudAPIClustersPath,
c.couchbaseCapellaDBConnectionProducer.Username,
c.couchbaseCapellaDBConnectionProducer.Password,
req.Username)
if err != nil {
return dbplugin.DeleteUserResponse{}, err
}
return dbplugin.DeleteUserResponse{}, nil
}
func newUser(ctx context.Context, c *couchbaseCapellaDBConnectionProducer, username string, req dbplugin.NewUserRequest) error {
statements := removeEmpty(req.Statements.Commands)
if len(statements) == 0 {
statements = append(statements, defaultCouchbaseCapellaUserRole)
}
err := CreateCapellaDbCredUser(c.CloudAPIBaseURL, c.CloudAPIClustersPath, c.Username, c.Password,
username, req.Password, statements[0])
if err != nil {
return err
}
return nil
}
func (c *CouchbaseCapellaDB) changeUserPassword(ctx context.Context, username, password string) (string, error) {
// Don't let anyone write the config while we're using it
c.RLock()
defer c.RUnlock()
pwd, err := UpdateCapellaDbCredUser(c.CloudAPIBaseURL, c.CloudAPIClustersPath, c.Username, c.Password,
username, password)
if err != nil {
return pwd, err
}
return pwd, nil
}
func removeEmpty(strs []string) []string {
var newStrs []string
for _, str := range strs {
str = strings.TrimSpace(str)
if str == "" {
continue
}
newStrs = append(newStrs, str)
}
return newStrs
}
func computeTimeout(ctx context.Context) (timeout time.Duration) {
deadline, ok := ctx.Deadline()
if ok {
return time.Until(deadline)
}
return defaultTimeout
}
func (c *CouchbaseCapellaDB) getConnection(ctx context.Context) (*gocb.Cluster, error) {
db, err := c.Connection(ctx)
if err != nil {
return nil, err
}
return db.(*gocb.Cluster), nil
}
func (c *CouchbaseCapellaDB) Type() (string, error) {
return couchbaseCapellaTypeName, nil
}