forked from hashicorp/vault
-
Notifications
You must be signed in to change notification settings - Fork 0
/
identity_store_groups.go
550 lines (473 loc) · 15.2 KB
/
identity_store_groups.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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
package vault
import (
"context"
"fmt"
"strings"
"github.com/golang/protobuf/ptypes"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/vault/helper/identity"
"github.com/hashicorp/vault/helper/namespace"
"github.com/hashicorp/vault/helper/strutil"
"github.com/hashicorp/vault/logical"
"github.com/hashicorp/vault/logical/framework"
)
const (
groupTypeInternal = "internal"
groupTypeExternal = "external"
)
func groupPathFields() map[string]*framework.FieldSchema {
return map[string]*framework.FieldSchema{
"id": {
Type: framework.TypeString,
Description: "ID of the group. If set, updates the corresponding existing group.",
},
"type": {
Type: framework.TypeString,
Description: "Type of the group, 'internal' or 'external'. Defaults to 'internal'",
},
"name": {
Type: framework.TypeString,
Description: "Name of the group.",
},
"metadata": {
Type: framework.TypeKVPairs,
Description: `Metadata to be associated with the group.
In CLI, this parameter can be repeated multiple times, and it all gets merged together.
For example:
vault <command> <path> metadata=key1=value1 metadata=key2=value2
`,
},
"policies": {
Type: framework.TypeCommaStringSlice,
Description: "Policies to be tied to the group.",
},
"member_group_ids": {
Type: framework.TypeCommaStringSlice,
Description: "Group IDs to be assigned as group members.",
},
"member_entity_ids": {
Type: framework.TypeCommaStringSlice,
Description: "Entity IDs to be assigned as group members.",
},
}
}
func groupPaths(i *IdentityStore) []*framework.Path {
return []*framework.Path{
{
Pattern: "group$",
Fields: groupPathFields(),
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: i.pathGroupRegister(),
},
HelpSynopsis: strings.TrimSpace(groupHelp["register"][0]),
HelpDescription: strings.TrimSpace(groupHelp["register"][1]),
},
{
Pattern: "group/id/" + framework.GenericNameRegex("id"),
Fields: groupPathFields(),
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: i.pathGroupIDUpdate(),
logical.ReadOperation: i.pathGroupIDRead(),
logical.DeleteOperation: i.pathGroupIDDelete(),
},
HelpSynopsis: strings.TrimSpace(groupHelp["group-by-id"][0]),
HelpDescription: strings.TrimSpace(groupHelp["group-by-id"][1]),
},
{
Pattern: "group/id/?$",
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ListOperation: i.pathGroupIDList(),
},
HelpSynopsis: strings.TrimSpace(groupHelp["group-id-list"][0]),
HelpDescription: strings.TrimSpace(groupHelp["group-id-list"][1]),
},
{
Pattern: "group/name/" + framework.GenericNameRegex("name"),
Fields: groupPathFields(),
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: i.pathGroupNameUpdate(),
logical.ReadOperation: i.pathGroupNameRead(),
logical.DeleteOperation: i.pathGroupNameDelete(),
},
HelpSynopsis: strings.TrimSpace(groupHelp["group-by-name"][0]),
HelpDescription: strings.TrimSpace(groupHelp["group-by-name"][1]),
},
{
Pattern: "group/name/?$",
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ListOperation: i.pathGroupNameList(),
},
HelpSynopsis: strings.TrimSpace(groupHelp["group-name-list"][0]),
HelpDescription: strings.TrimSpace(groupHelp["group-name-list"][1]),
},
}
}
func (i *IdentityStore) pathGroupRegister() framework.OperationFunc {
return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
_, ok := d.GetOk("id")
if ok {
return i.pathGroupIDUpdate()(ctx, req, d)
}
i.groupLock.Lock()
defer i.groupLock.Unlock()
return i.handleGroupUpdateCommon(ctx, req, d, nil)
}
}
func (i *IdentityStore) pathGroupIDUpdate() framework.OperationFunc {
return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
groupID := d.Get("id").(string)
if groupID == "" {
return logical.ErrorResponse("empty group ID"), nil
}
i.groupLock.Lock()
defer i.groupLock.Unlock()
group, err := i.MemDBGroupByID(groupID, true)
if err != nil {
return nil, err
}
if group == nil {
return logical.ErrorResponse("invalid group ID"), nil
}
return i.handleGroupUpdateCommon(ctx, req, d, group)
}
}
func (i *IdentityStore) pathGroupNameUpdate() framework.OperationFunc {
return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
groupName := d.Get("name").(string)
if groupName == "" {
return logical.ErrorResponse("empty group name"), nil
}
i.groupLock.Lock()
defer i.groupLock.Unlock()
group, err := i.MemDBGroupByName(ctx, groupName, true)
if err != nil {
return nil, err
}
return i.handleGroupUpdateCommon(ctx, req, d, group)
}
}
func (i *IdentityStore) handleGroupUpdateCommon(ctx context.Context, req *logical.Request, d *framework.FieldData, group *identity.Group) (*logical.Response, error) {
var newGroup bool
if group == nil {
group = new(identity.Group)
newGroup = true
}
// Update the policies if supplied
policiesRaw, ok := d.GetOk("policies")
if ok {
group.Policies = policiesRaw.([]string)
}
if strutil.StrListContains(group.Policies, "root") {
return logical.ErrorResponse("policies cannot contain root"), nil
}
groupTypeRaw, ok := d.GetOk("type")
if ok {
groupType := groupTypeRaw.(string)
if group.Type != "" && groupType != group.Type {
return logical.ErrorResponse(fmt.Sprintf("group type cannot be changed")), nil
}
group.Type = groupType
}
// If group type is not set, default to internal type
if group.Type == "" {
group.Type = groupTypeInternal
}
if group.Type != groupTypeInternal && group.Type != groupTypeExternal {
return logical.ErrorResponse(fmt.Sprintf("invalid group type %q", group.Type)), nil
}
// Get the name
groupName := d.Get("name").(string)
if groupName != "" {
// Check if there is a group already existing for the given name
groupByName, err := i.MemDBGroupByName(ctx, groupName, false)
if err != nil {
return nil, err
}
// If this is a new group and if there already exists a group by this
// name, error out. If the name of an existing group is about to be
// modified into something which is already tied to a different group,
// error out.
switch {
case groupByName == nil:
// Allowed
case group.ID == "":
group = groupByName
case group.ID != "" && groupByName.ID != group.ID:
return logical.ErrorResponse("group name is already in use"), nil
}
group.Name = groupName
}
metadata, ok, err := d.GetOkErr("metadata")
if err != nil {
return logical.ErrorResponse(fmt.Sprintf("failed to parse metadata: %v", err)), nil
}
if ok {
group.Metadata = metadata.(map[string]string)
}
memberEntityIDsRaw, ok := d.GetOk("member_entity_ids")
if ok {
if group.Type == groupTypeExternal {
return logical.ErrorResponse("member entities can't be set manually for external groups"), nil
}
group.MemberEntityIDs = memberEntityIDsRaw.([]string)
if len(group.MemberEntityIDs) > 512 {
return logical.ErrorResponse("member entity IDs exceeding the limit of 512"), nil
}
}
memberGroupIDsRaw, ok := d.GetOk("member_group_ids")
var memberGroupIDs []string
if ok {
if group.Type == groupTypeExternal {
return logical.ErrorResponse("member groups can't be set for external groups"), nil
}
memberGroupIDs = memberGroupIDsRaw.([]string)
}
err = i.sanitizeAndUpsertGroup(ctx, group, memberGroupIDs)
if err != nil {
return nil, err
}
if !newGroup {
return nil, nil
}
respData := map[string]interface{}{
"id": group.ID,
"name": group.Name,
}
return &logical.Response{
Data: respData,
}, nil
}
func (i *IdentityStore) pathGroupIDRead() framework.OperationFunc {
return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
groupID := d.Get("id").(string)
if groupID == "" {
return logical.ErrorResponse("empty group id"), nil
}
group, err := i.MemDBGroupByID(groupID, false)
if err != nil {
return nil, err
}
if group == nil {
return nil, nil
}
return i.handleGroupReadCommon(ctx, group)
}
}
func (i *IdentityStore) pathGroupNameRead() framework.OperationFunc {
return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
groupName := d.Get("name").(string)
if groupName == "" {
return logical.ErrorResponse("empty group name"), nil
}
group, err := i.MemDBGroupByName(ctx, groupName, false)
if err != nil {
return nil, err
}
if group == nil {
return nil, nil
}
return i.handleGroupReadCommon(ctx, group)
}
}
func (i *IdentityStore) handleGroupReadCommon(ctx context.Context, group *identity.Group) (*logical.Response, error) {
if group == nil {
return nil, nil
}
ns, err := namespace.FromContext(ctx)
if err != nil {
return nil, err
}
if ns.ID != group.NamespaceID {
return nil, nil
}
respData := map[string]interface{}{}
respData["id"] = group.ID
respData["name"] = group.Name
respData["policies"] = group.Policies
respData["member_entity_ids"] = group.MemberEntityIDs
respData["parent_group_ids"] = group.ParentGroupIDs
respData["metadata"] = group.Metadata
respData["creation_time"] = ptypes.TimestampString(group.CreationTime)
respData["last_update_time"] = ptypes.TimestampString(group.LastUpdateTime)
respData["modify_index"] = group.ModifyIndex
respData["type"] = group.Type
aliasMap := map[string]interface{}{}
if group.Alias != nil {
aliasMap["id"] = group.Alias.ID
aliasMap["canonical_id"] = group.Alias.CanonicalID
aliasMap["mount_accessor"] = group.Alias.MountAccessor
aliasMap["metadata"] = group.Alias.Metadata
aliasMap["name"] = group.Alias.Name
aliasMap["merged_from_canonical_ids"] = group.Alias.MergedFromCanonicalIDs
aliasMap["creation_time"] = ptypes.TimestampString(group.Alias.CreationTime)
aliasMap["last_update_time"] = ptypes.TimestampString(group.Alias.LastUpdateTime)
if mountValidationResp := i.core.router.validateMountByAccessor(group.Alias.MountAccessor); mountValidationResp != nil {
aliasMap["mount_path"] = mountValidationResp.MountPath
aliasMap["mount_type"] = mountValidationResp.MountType
}
}
respData["alias"] = aliasMap
var memberGroupIDs []string
memberGroups, err := i.MemDBGroupsByParentGroupID(group.ID, false)
if err != nil {
return nil, err
}
for _, memberGroup := range memberGroups {
memberGroupIDs = append(memberGroupIDs, memberGroup.ID)
}
respData["member_group_ids"] = memberGroupIDs
return &logical.Response{
Data: respData,
}, nil
}
func (i *IdentityStore) pathGroupIDDelete() framework.OperationFunc {
return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
groupID := d.Get("id").(string)
if groupID == "" {
return logical.ErrorResponse("empty group ID"), nil
}
return i.handleGroupDeleteCommon(ctx, groupID, true)
}
}
func (i *IdentityStore) pathGroupNameDelete() framework.OperationFunc {
return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
groupName := d.Get("name").(string)
if groupName == "" {
return logical.ErrorResponse("empty group name"), nil
}
return i.handleGroupDeleteCommon(ctx, groupName, false)
}
}
func (i *IdentityStore) handleGroupDeleteCommon(ctx context.Context, key string, byID bool) (*logical.Response, error) {
// Acquire the lock to modify the group storage entry
i.groupLock.Lock()
defer i.groupLock.Unlock()
// Create a MemDB transaction to delete group
txn := i.db.Txn(true)
defer txn.Abort()
var group *identity.Group
var err error
switch byID {
case true:
group, err = i.MemDBGroupByIDInTxn(txn, key, false)
if err != nil {
return nil, err
}
default:
group, err = i.MemDBGroupByNameInTxn(ctx, txn, key, false)
if err != nil {
return nil, err
}
}
if group == nil {
return nil, nil
}
ns, err := namespace.FromContext(ctx)
if err != nil {
return nil, err
}
if group.NamespaceID != ns.ID {
return nil, nil
}
// Delete group alias from memdb
if group.Type == groupTypeExternal && group.Alias != nil {
err = i.MemDBDeleteAliasByIDInTxn(txn, group.Alias.ID, true)
if err != nil {
return nil, err
}
}
// Delete the group using the same transaction
err = i.MemDBDeleteGroupByIDInTxn(txn, group.ID)
if err != nil {
return nil, err
}
// Delete the group from storage
err = i.groupPacker.DeleteItem(group.ID)
if err != nil {
return nil, err
}
// Committing the transaction *after* successfully deleting group
txn.Commit()
return nil, nil
}
// pathGroupIDList lists the IDs of all the groups in the identity store
func (i *IdentityStore) pathGroupIDList() framework.OperationFunc {
return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
return i.handleGroupListCommon(ctx, true)
}
}
// pathGroupNameList lists the names of all the groups in the identity store
func (i *IdentityStore) pathGroupNameList() framework.OperationFunc {
return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
return i.handleGroupListCommon(ctx, false)
}
}
func (i *IdentityStore) handleGroupListCommon(ctx context.Context, byID bool) (*logical.Response, error) {
ns, err := namespace.FromContext(ctx)
if err != nil {
return nil, err
}
txn := i.db.Txn(false)
iter, err := txn.Get(groupsTable, "namespace_id", ns.ID)
if err != nil {
return nil, errwrap.Wrapf("failed to lookup groups using namespace ID: {{err}}", err)
}
var keys []string
groupInfo := map[string]interface{}{}
type mountInfo struct {
MountType string
MountPath string
}
mountAccessorMap := map[string]mountInfo{}
for entry := iter.Next(); entry != nil; entry = iter.Next() {
group := entry.(*identity.Group)
if byID {
keys = append(keys, group.ID)
} else {
keys = append(keys, group.Name)
}
groupInfoEntry := map[string]interface{}{
"name": group.Name,
"num_member_entities": len(group.MemberEntityIDs),
"num_parent_groups": len(group.ParentGroupIDs),
}
if group.Alias != nil {
entry := map[string]interface{}{
"id": group.Alias.ID,
"name": group.Alias.Name,
"mount_accessor": group.Alias.MountAccessor,
}
mi, ok := mountAccessorMap[group.Alias.MountAccessor]
if ok {
entry["mount_type"] = mi.MountType
entry["mount_path"] = mi.MountPath
} else {
mi = mountInfo{}
if mountValidationResp := i.core.router.validateMountByAccessor(group.Alias.MountAccessor); mountValidationResp != nil {
mi.MountType = mountValidationResp.MountType
mi.MountPath = mountValidationResp.MountPath
entry["mount_type"] = mi.MountType
entry["mount_path"] = mi.MountPath
}
mountAccessorMap[group.Alias.MountAccessor] = mi
}
groupInfoEntry["alias"] = entry
}
groupInfo[group.ID] = groupInfoEntry
}
return logical.ListResponseWithInfo(keys, groupInfo), nil
}
var groupHelp = map[string][2]string{
"register": {
"Create a new group.",
"",
},
"group-by-id": {
"Update or delete an existing group using its ID.",
"",
},
"group-id-list": {
"List all the group IDs.",
"",
},
}