-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
identity_store.go
636 lines (540 loc) · 18.3 KB
/
identity_store.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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
package vault
import (
"context"
"fmt"
"strings"
"time"
metrics "github.com/armon/go-metrics"
"github.com/golang/protobuf/ptypes"
log "github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-memdb"
"github.com/hashicorp/go-secure-stdlib/strutil"
"github.com/hashicorp/vault/helper/identity"
"github.com/hashicorp/vault/helper/metricsutil"
"github.com/hashicorp/vault/helper/namespace"
"github.com/hashicorp/vault/helper/storagepacker"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/helper/consts"
"github.com/hashicorp/vault/sdk/logical"
"github.com/patrickmn/go-cache"
)
const (
groupBucketsPrefix = "packer/group/buckets/"
)
var (
caseSensitivityKey = "casesensitivity"
parseExtraEntityFromBucket = func(context.Context, *IdentityStore, *identity.Entity) (bool, error) { return false, nil }
addExtraEntityDataToResponse = func(*identity.Entity, map[string]interface{}) {}
)
func (c *Core) IdentityStore() *IdentityStore {
return c.identityStore
}
func (i *IdentityStore) resetDB(ctx context.Context) error {
var err error
i.db, err = memdb.NewMemDB(identityStoreSchema(!i.disableLowerCasedNames))
if err != nil {
return err
}
return nil
}
func NewIdentityStore(ctx context.Context, core *Core, config *logical.BackendConfig, logger log.Logger) (*IdentityStore, error) {
iStore := &IdentityStore{
view: config.StorageView,
logger: logger,
router: core.router,
redirectAddr: core.redirectAddr,
localNode: core,
namespacer: core,
metrics: core.MetricSink(),
totpPersister: core,
groupUpdater: core,
tokenStorer: core,
}
// Create a memdb instance, which by default, operates on lower cased
// identity names
err := iStore.resetDB(ctx)
if err != nil {
return nil, err
}
entitiesPackerLogger := iStore.logger.Named("storagepacker").Named("entities")
core.AddLogger(entitiesPackerLogger)
groupsPackerLogger := iStore.logger.Named("storagepacker").Named("groups")
core.AddLogger(groupsPackerLogger)
iStore.entityPacker, err = storagepacker.NewStoragePacker(iStore.view, entitiesPackerLogger, "")
if err != nil {
return nil, fmt.Errorf("failed to create entity packer: %w", err)
}
iStore.groupPacker, err = storagepacker.NewStoragePacker(iStore.view, groupsPackerLogger, groupBucketsPrefix)
if err != nil {
return nil, fmt.Errorf("failed to create group packer: %w", err)
}
iStore.Backend = &framework.Backend{
BackendType: logical.TypeLogical,
Paths: iStore.paths(),
Invalidate: iStore.Invalidate,
InitializeFunc: iStore.initialize,
PathsSpecial: &logical.Paths{
Unauthenticated: []string{
"oidc/.well-known/*",
"oidc/provider/+/.well-known/*",
"oidc/provider/+/token",
},
},
PeriodicFunc: func(ctx context.Context, req *logical.Request) error {
iStore.oidcPeriodicFunc(ctx)
return nil
},
}
iStore.oidcCache = newOIDCCache(cache.NoExpiration, cache.NoExpiration)
iStore.oidcAuthCodeCache = newOIDCCache(5*time.Minute, 5*time.Minute)
err = iStore.Setup(ctx, config)
if err != nil {
return nil, err
}
return iStore, nil
}
func (i *IdentityStore) paths() []*framework.Path {
return framework.PathAppend(
entityPaths(i),
aliasPaths(i),
groupAliasPaths(i),
groupPaths(i),
lookupPaths(i),
upgradePaths(i),
oidcPaths(i),
oidcProviderPaths(i),
)
}
func (i *IdentityStore) initialize(ctx context.Context, req *logical.InitializationRequest) error {
// Only primary should write the status
if i.System().ReplicationState().HasState(consts.ReplicationPerformanceSecondary | consts.ReplicationPerformanceStandby | consts.ReplicationDRSecondary) {
return nil
}
entry, err := logical.StorageEntryJSON(caseSensitivityKey, &casesensitivity{
DisableLowerCasedNames: i.disableLowerCasedNames,
})
if err != nil {
return err
}
return i.view.Put(ctx, entry)
}
// Invalidate is a callback wherein the backend is informed that the value at
// the given key is updated. In identity store's case, it would be the entity
// storage entries that get updated. The value needs to be read and MemDB needs
// to be updated accordingly.
func (i *IdentityStore) Invalidate(ctx context.Context, key string) {
i.logger.Debug("invalidate notification received", "key", key)
i.lock.Lock()
defer i.lock.Unlock()
switch {
case key == caseSensitivityKey:
entry, err := i.view.Get(ctx, caseSensitivityKey)
if err != nil {
i.logger.Error("failed to read case sensitivity setting during invalidation", "error", err)
return
}
if entry == nil {
return
}
var setting casesensitivity
if err := entry.DecodeJSON(&setting); err != nil {
i.logger.Error("failed to decode case sensitivity setting during invalidation", "error", err)
return
}
// Fast return if the setting is the same
if i.disableLowerCasedNames == setting.DisableLowerCasedNames {
return
}
// If the setting is different, reset memdb and reload all the artifacts
i.disableLowerCasedNames = setting.DisableLowerCasedNames
if err := i.resetDB(ctx); err != nil {
i.logger.Error("failed to reset memdb during invalidation", "error", err)
return
}
if err := i.loadEntities(ctx); err != nil {
i.logger.Error("failed to load entities during invalidation", "error", err)
return
}
if err := i.loadGroups(ctx); err != nil {
i.logger.Error("failed to load groups during invalidation", "error", err)
return
}
if err := i.loadOIDCClients(ctx); err != nil {
i.logger.Error("failed to load OIDC clients during invalidation", "error", err)
return
}
// Check if the key is a storage entry key for an entity bucket
case strings.HasPrefix(key, storagepacker.StoragePackerBucketsPrefix):
// Create a MemDB transaction
txn := i.db.Txn(true)
defer txn.Abort()
// Each entity object in MemDB holds the MD5 hash of the storage
// entry key of the entity bucket. Fetch all the entities that
// belong to this bucket using the hash value. Remove these entities
// from MemDB along with all the aliases of each entity.
entitiesFetched, err := i.MemDBEntitiesByBucketKeyInTxn(txn, key)
if err != nil {
i.logger.Error("failed to fetch entities using the bucket key", "key", key)
return
}
for _, entity := range entitiesFetched {
// Delete all the aliases in the entity. This function will also remove
// the corresponding alias indexes too.
err = i.deleteAliasesInEntityInTxn(txn, entity, entity.Aliases)
if err != nil {
i.logger.Error("failed to delete aliases in entity", "entity_id", entity.ID, "error", err)
return
}
// Delete the entity using the same transaction
err = i.MemDBDeleteEntityByIDInTxn(txn, entity.ID)
if err != nil {
i.logger.Error("failed to delete entity from MemDB", "entity_id", entity.ID, "error", err)
return
}
}
// Get the storage bucket entry
bucket, err := i.entityPacker.GetBucket(ctx, key)
if err != nil {
i.logger.Error("failed to refresh entities", "key", key, "error", err)
return
}
// If the underlying entry is nil, it means that this invalidation
// notification is for the deletion of the underlying storage entry. At
// this point, since all the entities belonging to this bucket are
// already removed, there is nothing else to be done. But, if the
// storage entry is non-nil, its an indication of an update. In this
// case, entities in the updated bucket needs to be reinserted into
// MemDB.
if bucket != nil {
for _, item := range bucket.Items {
entity, err := i.parseEntityFromBucketItem(ctx, item)
if err != nil {
i.logger.Error("failed to parse entity from bucket entry item", "error", err)
return
}
// Only update MemDB and don't touch the storage
err = i.upsertEntityInTxn(ctx, txn, entity, nil, false)
if err != nil {
i.logger.Error("failed to update entity in MemDB", "error", err)
return
}
}
}
txn.Commit()
return
// Check if the key is a storage entry key for an group bucket
case strings.HasPrefix(key, groupBucketsPrefix):
// Create a MemDB transaction
txn := i.db.Txn(true)
defer txn.Abort()
groupsFetched, err := i.MemDBGroupsByBucketKeyInTxn(txn, key)
if err != nil {
i.logger.Error("failed to fetch groups using the bucket key", "key", key)
return
}
for _, group := range groupsFetched {
// Delete the group using the same transaction
err = i.MemDBDeleteGroupByIDInTxn(txn, group.ID)
if err != nil {
i.logger.Error("failed to delete group from MemDB", "group_id", group.ID, "error", err)
return
}
if group.Alias != nil {
err := i.MemDBDeleteAliasByIDInTxn(txn, group.Alias.ID, true)
if err != nil {
i.logger.Error("failed to delete group alias from MemDB", "error", err)
return
}
}
}
// Get the storage bucket entry
bucket, err := i.groupPacker.GetBucket(ctx, key)
if err != nil {
i.logger.Error("failed to refresh group", "key", key, "error", err)
return
}
if bucket != nil {
for _, item := range bucket.Items {
group, err := i.parseGroupFromBucketItem(item)
if err != nil {
i.logger.Error("failed to parse group from bucket entry item", "error", err)
return
}
// Before updating the group, check if the group exists. If it
// does, then delete the group alias from memdb, for the
// invalidation would have sent an update.
groupFetched, err := i.MemDBGroupByIDInTxn(txn, group.ID, true)
if err != nil {
i.logger.Error("failed to fetch group from MemDB", "error", err)
return
}
// If the group has an alias remove it from memdb
if groupFetched != nil && groupFetched.Alias != nil {
err := i.MemDBDeleteAliasByIDInTxn(txn, groupFetched.Alias.ID, true)
if err != nil {
i.logger.Error("failed to delete old group alias from MemDB", "error", err)
return
}
}
// Only update MemDB and don't touch the storage
err = i.UpsertGroupInTxn(ctx, txn, group, false)
if err != nil {
i.logger.Error("failed to update group in MemDB", "error", err)
return
}
}
}
txn.Commit()
return
case strings.HasPrefix(key, oidcTokensPrefix):
ns, err := namespace.FromContext(ctx)
if err != nil {
i.logger.Error("error retrieving namespace", "error", err)
return
}
// Wipe the cache for the requested namespace. This will also clear
// the shared namespace as well.
if err := i.oidcCache.Flush(ns); err != nil {
i.logger.Error("error flushing oidc cache", "error", err)
}
case strings.HasPrefix(key, clientPath):
name := strings.TrimPrefix(key, clientPath)
// Invalidate the cached client in memdb
if err := i.memDBDeleteClientByName(ctx, name); err != nil {
i.logger.Error("error invalidating client", "error", err, "key", key)
return
}
}
}
func (i *IdentityStore) parseEntityFromBucketItem(ctx context.Context, item *storagepacker.Item) (*identity.Entity, error) {
if item == nil {
return nil, fmt.Errorf("nil item")
}
persistNeeded := false
var entity identity.Entity
err := ptypes.UnmarshalAny(item.Message, &entity)
if err != nil {
// If we encounter an error, it would mean that the format of the
// entity is an older one. Try decoding using the older format and if
// successful, upgrage the storage with the newer format.
var oldEntity identity.EntityStorageEntry
oldEntityErr := ptypes.UnmarshalAny(item.Message, &oldEntity)
if oldEntityErr != nil {
return nil, fmt.Errorf("failed to decode entity from storage bucket item: %w", err)
}
i.logger.Debug("upgrading the entity using patch introduced with vault 0.8.2.1", "entity_id", oldEntity.ID)
// Successfully decoded entity using older format. Entity is stored
// with older format. Upgrade it.
entity.ID = oldEntity.ID
entity.Name = oldEntity.Name
entity.Metadata = oldEntity.Metadata
entity.CreationTime = oldEntity.CreationTime
entity.LastUpdateTime = oldEntity.LastUpdateTime
entity.MergedEntityIDs = oldEntity.MergedEntityIDs
entity.Policies = oldEntity.Policies
entity.BucketKey = oldEntity.BucketKeyHash
entity.MFASecrets = oldEntity.MFASecrets
// Copy each alias individually since the format of aliases were
// also different
for _, oldAlias := range oldEntity.Personas {
var newAlias identity.Alias
newAlias.ID = oldAlias.ID
newAlias.Name = oldAlias.Name
newAlias.CanonicalID = oldAlias.EntityID
newAlias.MountType = oldAlias.MountType
newAlias.MountAccessor = oldAlias.MountAccessor
newAlias.MountPath = oldAlias.MountPath
newAlias.Metadata = oldAlias.Metadata
newAlias.CreationTime = oldAlias.CreationTime
newAlias.LastUpdateTime = oldAlias.LastUpdateTime
newAlias.MergedFromCanonicalIDs = oldAlias.MergedFromEntityIDs
entity.Aliases = append(entity.Aliases, &newAlias)
}
persistNeeded = true
}
pN, err := parseExtraEntityFromBucket(ctx, i, &entity)
if err != nil {
return nil, err
}
if pN {
persistNeeded = true
}
if persistNeeded && !i.localNode.ReplicationState().HasState(consts.ReplicationPerformanceSecondary) {
entityAsAny, err := ptypes.MarshalAny(&entity)
if err != nil {
return nil, err
}
item := &storagepacker.Item{
ID: entity.ID,
Message: entityAsAny,
}
// Store the entity with new format
err = i.entityPacker.PutItem(ctx, item)
if err != nil {
return nil, err
}
}
if entity.NamespaceID == "" {
entity.NamespaceID = namespace.RootNamespaceID
}
return &entity, nil
}
func (i *IdentityStore) parseGroupFromBucketItem(item *storagepacker.Item) (*identity.Group, error) {
if item == nil {
return nil, fmt.Errorf("nil item")
}
var group identity.Group
err := ptypes.UnmarshalAny(item.Message, &group)
if err != nil {
return nil, fmt.Errorf("failed to decode group from storage bucket item: %w", err)
}
if group.NamespaceID == "" {
group.NamespaceID = namespace.RootNamespaceID
}
return &group, nil
}
// entityByAliasFactors fetches the entity based on factors of alias, i.e mount
// accessor and the alias name.
func (i *IdentityStore) entityByAliasFactors(mountAccessor, aliasName string, clone bool) (*identity.Entity, error) {
if mountAccessor == "" {
return nil, fmt.Errorf("missing mount accessor")
}
if aliasName == "" {
return nil, fmt.Errorf("missing alias name")
}
txn := i.db.Txn(false)
return i.entityByAliasFactorsInTxn(txn, mountAccessor, aliasName, clone)
}
// entityByAliasFactorsInTxn fetches the entity based on factors of alias, i.e
// mount accessor and the alias name.
func (i *IdentityStore) entityByAliasFactorsInTxn(txn *memdb.Txn, mountAccessor, aliasName string, clone bool) (*identity.Entity, error) {
if txn == nil {
return nil, fmt.Errorf("nil txn")
}
if mountAccessor == "" {
return nil, fmt.Errorf("missing mount accessor")
}
if aliasName == "" {
return nil, fmt.Errorf("missing alias name")
}
alias, err := i.MemDBAliasByFactorsInTxn(txn, mountAccessor, aliasName, false, false)
if err != nil {
return nil, err
}
if alias == nil {
return nil, nil
}
return i.MemDBEntityByAliasIDInTxn(txn, alias.ID, clone)
}
// CreateOrFetchEntity creates a new entity. This is used by core to
// associate each login attempt by an alias to a unified entity in Vault.
func (i *IdentityStore) CreateOrFetchEntity(ctx context.Context, alias *logical.Alias) (*identity.Entity, error) {
defer metrics.MeasureSince([]string{"identity", "create_or_fetch_entity"}, time.Now())
var entity *identity.Entity
var err error
var update bool
if alias == nil {
return nil, fmt.Errorf("alias is nil")
}
if alias.Name == "" {
return nil, fmt.Errorf("empty alias name")
}
mountValidationResp := i.router.ValidateMountByAccessor(alias.MountAccessor)
if mountValidationResp == nil {
return nil, fmt.Errorf("invalid mount accessor %q", alias.MountAccessor)
}
if mountValidationResp.MountLocal {
return nil, fmt.Errorf("mount_accessor %q is of a local mount", alias.MountAccessor)
}
if mountValidationResp.MountType != alias.MountType {
return nil, fmt.Errorf("mount accessor %q is not a mount of type %q", alias.MountAccessor, alias.MountType)
}
// Check if an entity already exists for the given alias
entity, err = i.entityByAliasFactors(alias.MountAccessor, alias.Name, false)
if err != nil {
return nil, err
}
if entity != nil && changedAliasIndex(entity, alias) == -1 {
return entity, nil
}
i.lock.Lock()
defer i.lock.Unlock()
// Create a MemDB transaction to update both alias and entity
txn := i.db.Txn(true)
defer txn.Abort()
// Check if an entity was created before acquiring the lock
entity, err = i.entityByAliasFactorsInTxn(txn, alias.MountAccessor, alias.Name, true)
if err != nil {
return nil, err
}
if entity != nil {
idx := changedAliasIndex(entity, alias)
if idx == -1 {
return entity, nil
}
a := entity.Aliases[idx]
a.Metadata = alias.Metadata
a.LastUpdateTime = ptypes.TimestampNow()
update = true
}
if !update {
entity = new(identity.Entity)
err = i.sanitizeEntity(ctx, entity)
if err != nil {
return nil, err
}
// Create a new alias
newAlias := &identity.Alias{
CanonicalID: entity.ID,
Name: alias.Name,
MountAccessor: alias.MountAccessor,
Metadata: alias.Metadata,
MountPath: mountValidationResp.MountPath,
MountType: mountValidationResp.MountType,
}
err = i.sanitizeAlias(ctx, newAlias)
if err != nil {
return nil, err
}
i.logger.Debug("creating a new entity", "alias", newAlias)
// Append the new alias to the new entity
entity.Aliases = []*identity.Alias{
newAlias,
}
// Emit a metric for the new entity
ns, err := i.namespacer.NamespaceByID(ctx, entity.NamespaceID)
var nsLabel metrics.Label
if err != nil {
nsLabel = metrics.Label{"namespace", "unknown"}
} else {
nsLabel = metricsutil.NamespaceLabel(ns)
}
i.metrics.IncrCounterWithLabels(
[]string{"identity", "entity", "creation"},
1,
[]metrics.Label{
nsLabel,
{"auth_method", newAlias.MountType},
{"mount_point", newAlias.MountPath},
})
}
// Update MemDB and persist entity object
err = i.upsertEntityInTxn(ctx, txn, entity, nil, true)
if err != nil {
return nil, err
}
txn.Commit()
return entity, nil
}
// changedAliasIndex searches an entity for changed alias metadata.
//
// If a match is found, the changed alias's index is returned. If no alias
// names match or no metadata is different, -1 is returned.
func changedAliasIndex(entity *identity.Entity, alias *logical.Alias) int {
for i, a := range entity.Aliases {
if a.Name == alias.Name && !strutil.EqualStringMaps(a.Metadata, alias.Metadata) {
return i
}
}
return -1
}