-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcouchbase.go
More file actions
247 lines (200 loc) · 6.4 KB
/
couchbase.go
File metadata and controls
247 lines (200 loc) · 6.4 KB
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
// Copyright IBM Corp. 2020, 2025
// SPDX-License-Identifier: MPL-2.0
package couchbase
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/couchbase/gocb/v2"
"github.com/hashicorp/errwrap"
"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 (
couchbaseTypeName = "couchbase"
defaultCouchbaseUserRole = `{"Roles": [{"role":"ro_admin"}]}`
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 = &CouchbaseDB{}
// Type that combines the custom plugins Couchbase database connection configuration options and the Vault CredentialsProducer
// used for generating user information for the Couchbase database.
type CouchbaseDB struct {
*couchbaseDBConnectionProducer
credsutil.CredentialsProducer
usernameProducer template.StringTemplate
}
// Type that combines the Couchbase Roles and Groups representing specific account permissions. Used to pass roles and or
// groups between the Vault server and the custom plugin in the dbplugin.Statements
type RolesAndGroups struct {
Roles []gocb.Role `json:"roles"`
Groups []string `json:"groups"`
}
// 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() *CouchbaseDB {
connProducer := &couchbaseDBConnectionProducer{}
connProducer.Type = couchbaseTypeName
db := &CouchbaseDB{
couchbaseDBConnectionProducer: connProducer,
}
return db
}
func (c *CouchbaseDB) 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.couchbaseDBConnectionProducer.Initialize(ctx, req.Config, req.VerifyConnection)
if err != nil {
return dbplugin.InitializeResponse{}, err
}
resp := dbplugin.InitializeResponse{
Config: req.Config,
}
return resp, nil
}
func (c *CouchbaseDB) 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)
}
db, err := c.getConnection(ctx)
if err != nil {
return dbplugin.NewUserResponse{}, fmt.Errorf("failed to get connection: %w", err)
}
err = newUser(ctx, db, username, req)
if err != nil {
return dbplugin.NewUserResponse{}, err
}
resp := dbplugin.NewUserResponse{
Username: username,
}
return resp, nil
}
func (c *CouchbaseDB) UpdateUser(ctx context.Context, req dbplugin.UpdateUserRequest) (dbplugin.UpdateUserResponse, error) {
if req.Password != nil {
err := c.changeUserPassword(ctx, req.Username, req.Password.NewPassword)
return dbplugin.UpdateUserResponse{}, err
}
return dbplugin.UpdateUserResponse{}, nil
}
func (c *CouchbaseDB) 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()
db, err := c.getConnection(ctx)
if err != nil {
return dbplugin.DeleteUserResponse{}, fmt.Errorf("failed to make connection: %w", err)
}
// Get the UserManager
mgr := db.Users()
err = mgr.DropUser(req.Username, nil)
if err != nil {
return dbplugin.DeleteUserResponse{}, err
}
return dbplugin.DeleteUserResponse{}, nil
}
func newUser(ctx context.Context, db *gocb.Cluster, username string, req dbplugin.NewUserRequest) error {
statements := removeEmpty(req.Statements.Commands)
if len(statements) == 0 {
statements = append(statements, defaultCouchbaseUserRole)
}
jsonRoleAndGroupData := []byte(statements[0])
var rag RolesAndGroups
err := json.Unmarshal(jsonRoleAndGroupData, &rag)
if err != nil {
return errwrap.Wrapf("error unmarshalling roles and groups creation statement JSON: {{err}}", err)
}
// Get the UserManager
mgr := db.Users()
user := gocb.User{
Username: username,
DisplayName: req.UsernameConfig.DisplayName,
Password: req.Password,
Roles: rag.Roles,
Groups: rag.Groups,
}
err = mgr.UpsertUser(user,
&gocb.UpsertUserOptions{
Timeout: computeTimeout(ctx),
DomainName: "local",
})
if err != nil {
return err
}
return nil
}
func (c *CouchbaseDB) changeUserPassword(ctx context.Context, username, password string) error {
// Don't let anyone write the config while we're using it
c.RLock()
defer c.RUnlock()
db, err := c.getConnection(ctx)
if err != nil {
return err
}
// Get the UserManager
mgr := db.Users()
user, err := mgr.GetUser(username, nil)
if err != nil {
return fmt.Errorf("unable to retrieve user %s: %w", username, err)
}
user.User.Password = password
err = mgr.UpsertUser(user.User,
&gocb.UpsertUserOptions{
Timeout: computeTimeout(ctx),
DomainName: "local",
})
if err != nil {
return err
}
return 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 *CouchbaseDB) 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 *CouchbaseDB) Type() (string, error) {
return couchbaseTypeName, nil
}