forked from hashicorp/vault
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logical_system.go
3602 lines (3093 loc) · 106 KB
/
logical_system.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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package vault
import (
"context"
"crypto/sha256"
"crypto/sha512"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"hash"
"net/http"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/hashicorp/errwrap"
log "github.com/hashicorp/go-hclog"
memdb "github.com/hashicorp/go-memdb"
uuid "github.com/hashicorp/go-uuid"
"github.com/hashicorp/vault/helper/compressutil"
"github.com/hashicorp/vault/helper/consts"
"github.com/hashicorp/vault/helper/identity"
"github.com/hashicorp/vault/helper/jsonutil"
"github.com/hashicorp/vault/helper/namespace"
"github.com/hashicorp/vault/helper/parseutil"
"github.com/hashicorp/vault/helper/strutil"
"github.com/hashicorp/vault/helper/wrapping"
"github.com/hashicorp/vault/logical"
"github.com/hashicorp/vault/logical/framework"
"github.com/mitchellh/mapstructure"
)
var (
// protectedPaths cannot be accessed via the raw APIs.
// This is both for security and to prevent disrupting Vault.
protectedPaths = []string{
keyringPath,
// Changing the cluster info path can change the cluster ID which can be disruptive
coreLocalClusterInfoPath,
}
)
func systemBackendMemDBSchema() *memdb.DBSchema {
systemSchema := &memdb.DBSchema{
Tables: make(map[string]*memdb.TableSchema),
}
schemas := getSystemSchemas()
for _, schemaFunc := range schemas {
schema := schemaFunc()
if _, ok := systemSchema.Tables[schema.Name]; ok {
panic(fmt.Sprintf("duplicate table name: %s", schema.Name))
}
systemSchema.Tables[schema.Name] = schema
}
return systemSchema
}
func NewSystemBackend(core *Core, logger log.Logger) *SystemBackend {
db, _ := memdb.NewMemDB(systemBackendMemDBSchema())
b := &SystemBackend{
Core: core,
db: db,
logger: logger,
mfaLogger: core.baseLogger.Named("mfa"),
mfaLock: &sync.RWMutex{},
}
core.AddLogger(b.mfaLogger)
b.Backend = &framework.Backend{
Help: strings.TrimSpace(sysHelpRoot),
PathsSpecial: &logical.Paths{
Root: []string{
"auth/*",
"remount",
"audit",
"audit/*",
"raw",
"raw/*",
"replication/primary/secondary-token",
"replication/performance/primary/secondary-token",
"replication/dr/primary/secondary-token",
"replication/reindex",
"replication/dr/reindex",
"replication/performance/reindex",
"rotate",
"config/cors",
"config/auditing/*",
"config/ui/headers/*",
"plugins/catalog/*",
"revoke-prefix/*",
"revoke-force/*",
"leases/revoke-prefix/*",
"leases/revoke-force/*",
"leases/lookup/*",
},
Unauthenticated: []string{
"wrapping/lookup",
"wrapping/pubkey",
"replication/status",
"internal/ui/mounts",
"internal/ui/mounts/*",
"internal/ui/namespaces",
"replication/performance/status",
"replication/dr/status",
"replication/dr/secondary/promote",
"replication/dr/secondary/update-primary",
"replication/dr/secondary/operation-token/delete",
"replication/dr/secondary/license",
"replication/dr/secondary/reindex",
},
LocalStorage: []string{
expirationSubPath,
},
},
}
b.Backend.Paths = append(b.Backend.Paths, entPaths(b)...)
b.Backend.Paths = append(b.Backend.Paths, b.configPaths()...)
b.Backend.Paths = append(b.Backend.Paths, b.rekeyPaths()...)
b.Backend.Paths = append(b.Backend.Paths, b.sealPaths()...)
b.Backend.Paths = append(b.Backend.Paths, b.pluginsCatalogPath())
b.Backend.Paths = append(b.Backend.Paths, b.pluginsCatalogListPath())
b.Backend.Paths = append(b.Backend.Paths, b.pluginsReloadPath())
b.Backend.Paths = append(b.Backend.Paths, b.auditPaths()...)
b.Backend.Paths = append(b.Backend.Paths, b.mountPaths()...)
b.Backend.Paths = append(b.Backend.Paths, b.authPaths()...)
b.Backend.Paths = append(b.Backend.Paths, b.leasePaths()...)
b.Backend.Paths = append(b.Backend.Paths, b.policyPaths()...)
b.Backend.Paths = append(b.Backend.Paths, b.wrappingPaths()...)
b.Backend.Paths = append(b.Backend.Paths, b.toolsPaths()...)
b.Backend.Paths = append(b.Backend.Paths, b.capabilitiesPaths()...)
b.Backend.Paths = append(b.Backend.Paths, b.internalUIPaths()...)
b.Backend.Paths = append(b.Backend.Paths, b.remountPath())
if core.rawEnabled {
b.Backend.Paths = append(b.Backend.Paths, &framework.Path{
Pattern: "(raw/?$|raw/(?P<path>.+))",
Fields: map[string]*framework.FieldSchema{
"path": &framework.FieldSchema{
Type: framework.TypeString,
},
"value": &framework.FieldSchema{
Type: framework.TypeString,
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ReadOperation: b.handleRawRead,
logical.UpdateOperation: b.handleRawWrite,
logical.DeleteOperation: b.handleRawDelete,
logical.ListOperation: b.handleRawList,
},
HelpSynopsis: strings.TrimSpace(sysHelp["raw"][0]),
HelpDescription: strings.TrimSpace(sysHelp["raw"][1]),
})
}
b.Backend.Invalidate = sysInvalidate(b)
return b
}
// SystemBackend implements logical.Backend and is used to interact with
// the core of the system. This backend is hardcoded to exist at the "sys"
// prefix. Conceptually it is similar to procfs on Linux.
type SystemBackend struct {
*framework.Backend
Core *Core
db *memdb.MemDB
mfaLock *sync.RWMutex
mfaLogger log.Logger
logger log.Logger
}
// handleCORSRead returns the current CORS configuration
func (b *SystemBackend) handleCORSRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
corsConf := b.Core.corsConfig
enabled := corsConf.IsEnabled()
resp := &logical.Response{
Data: map[string]interface{}{
"enabled": enabled,
},
}
if enabled {
corsConf.RLock()
resp.Data["allowed_origins"] = corsConf.AllowedOrigins
resp.Data["allowed_headers"] = corsConf.AllowedHeaders
corsConf.RUnlock()
}
return resp, nil
}
// handleCORSUpdate sets the list of origins that are allowed to make
// cross-origin requests and sets the CORS enabled flag to true
func (b *SystemBackend) handleCORSUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
origins := d.Get("allowed_origins").([]string)
headers := d.Get("allowed_headers").([]string)
return nil, b.Core.corsConfig.Enable(ctx, origins, headers)
}
// handleCORSDelete sets the CORS enabled flag to false and clears the list of
// allowed origins & headers.
func (b *SystemBackend) handleCORSDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
return nil, b.Core.corsConfig.Disable(ctx)
}
func (b *SystemBackend) handleTidyLeases(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
ns, err := namespace.FromContext(ctx)
if err != nil {
return nil, err
}
go func() {
tidyCtx := namespace.ContextWithNamespace(b.Core.activeContext, ns)
err := b.Core.expiration.Tidy(tidyCtx)
if err != nil {
b.Backend.Logger().Error("failed to tidy leases", "error", err)
return
}
}()
resp := &logical.Response{}
resp.AddWarning("Tidy operation successfully started. Any information from the operation will be printed to Vault's server logs.")
return logical.RespondWithStatusCode(resp, req, http.StatusAccepted)
}
func (b *SystemBackend) handlePluginCatalogList(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
plugins, err := b.Core.pluginCatalog.List(ctx)
if err != nil {
return nil, err
}
return logical.ListResponse(plugins), nil
}
func (b *SystemBackend) handlePluginCatalogUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
pluginName := d.Get("name").(string)
if pluginName == "" {
return logical.ErrorResponse("missing plugin name"), nil
}
sha256 := d.Get("sha256").(string)
if sha256 == "" {
sha256 = d.Get("sha_256").(string)
if sha256 == "" {
return logical.ErrorResponse("missing SHA-256 value"), nil
}
}
command := d.Get("command").(string)
if command == "" {
return logical.ErrorResponse("missing command value"), nil
}
// For backwards compatibility, also accept args as part of command. Don't
// accepts args in both command and args.
args := d.Get("args").([]string)
parts := strings.Split(command, " ")
if len(parts) <= 0 {
return logical.ErrorResponse("missing command value"), nil
} else if len(parts) > 1 && len(args) > 0 {
return logical.ErrorResponse("must not specify args in command and args field"), nil
} else if len(parts) > 1 {
args = parts[1:]
}
env := d.Get("env").([]string)
sha256Bytes, err := hex.DecodeString(sha256)
if err != nil {
return logical.ErrorResponse("Could not decode SHA-256 value from Hex"), err
}
err = b.Core.pluginCatalog.Set(ctx, pluginName, parts[0], args, env, sha256Bytes)
if err != nil {
return nil, err
}
return nil, nil
}
func (b *SystemBackend) handlePluginCatalogRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
pluginName := d.Get("name").(string)
if pluginName == "" {
return logical.ErrorResponse("missing plugin name"), nil
}
plugin, err := b.Core.pluginCatalog.Get(ctx, pluginName)
if err != nil {
return nil, err
}
if plugin == nil {
return nil, nil
}
command := ""
if !plugin.Builtin {
command, err = filepath.Rel(b.Core.pluginCatalog.directory, plugin.Command)
if err != nil {
return nil, err
}
}
data := map[string]interface{}{
"name": plugin.Name,
"args": plugin.Args,
"command": command,
"sha256": hex.EncodeToString(plugin.Sha256),
"builtin": plugin.Builtin,
}
return &logical.Response{
Data: data,
}, nil
}
func (b *SystemBackend) handlePluginCatalogDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
pluginName := d.Get("name").(string)
if pluginName == "" {
return logical.ErrorResponse("missing plugin name"), nil
}
err := b.Core.pluginCatalog.Delete(ctx, pluginName)
if err != nil {
return nil, err
}
return nil, nil
}
func (b *SystemBackend) handlePluginReloadUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
pluginName := d.Get("plugin").(string)
pluginMounts := d.Get("mounts").([]string)
if pluginName != "" && len(pluginMounts) > 0 {
return logical.ErrorResponse("plugin and mounts cannot be set at the same time"), nil
}
if pluginName == "" && len(pluginMounts) == 0 {
return logical.ErrorResponse("plugin or mounts must be provided"), nil
}
if pluginName != "" {
err := b.Core.reloadMatchingPlugin(ctx, pluginName)
if err != nil {
return nil, err
}
} else if len(pluginMounts) > 0 {
err := b.Core.reloadMatchingPluginMounts(ctx, pluginMounts)
if err != nil {
return nil, err
}
}
return nil, nil
}
// handleAuditedHeaderUpdate creates or overwrites a header entry
func (b *SystemBackend) handleAuditedHeaderUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
header := d.Get("header").(string)
hmac := d.Get("hmac").(bool)
if header == "" {
return logical.ErrorResponse("missing header name"), nil
}
headerConfig := b.Core.AuditedHeadersConfig()
err := headerConfig.add(ctx, header, hmac)
if err != nil {
return nil, err
}
return nil, nil
}
// handleAuditedHeaderDelete deletes the header with the given name
func (b *SystemBackend) handleAuditedHeaderDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
header := d.Get("header").(string)
if header == "" {
return logical.ErrorResponse("missing header name"), nil
}
headerConfig := b.Core.AuditedHeadersConfig()
err := headerConfig.remove(ctx, header)
if err != nil {
return nil, err
}
return nil, nil
}
// handleAuditedHeaderRead returns the header configuration for the given header name
func (b *SystemBackend) handleAuditedHeaderRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
header := d.Get("header").(string)
if header == "" {
return logical.ErrorResponse("missing header name"), nil
}
headerConfig := b.Core.AuditedHeadersConfig()
settings, ok := headerConfig.Headers[strings.ToLower(header)]
if !ok {
return logical.ErrorResponse("Could not find header in config"), nil
}
return &logical.Response{
Data: map[string]interface{}{
header: settings,
},
}, nil
}
// handleAuditedHeadersRead returns the whole audited headers config
func (b *SystemBackend) handleAuditedHeadersRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
headerConfig := b.Core.AuditedHeadersConfig()
return &logical.Response{
Data: map[string]interface{}{
"headers": headerConfig.Headers,
},
}, nil
}
// handleCapabilitiesAccessor returns the ACL capabilities of the
// token associated with the given accessor for a given path.
func (b *SystemBackend) handleCapabilitiesAccessor(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
accessor := d.Get("accessor").(string)
if accessor == "" {
return logical.ErrorResponse("missing accessor"), nil
}
aEntry, err := b.Core.tokenStore.lookupByAccessor(ctx, accessor, false, false)
if err != nil {
return nil, err
}
d.Raw["token"] = aEntry.TokenID
return b.handleCapabilities(ctx, req, d)
}
// handleCapabilities returns the ACL capabilities of the token for a given path
func (b *SystemBackend) handleCapabilities(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
var token string
if strings.HasSuffix(req.Path, "capabilities-self") {
token = req.ClientToken
} else {
tokenRaw, ok := d.Raw["token"]
if ok {
token, _ = tokenRaw.(string)
}
}
if token == "" {
return nil, fmt.Errorf("no token found")
}
ret := &logical.Response{
Data: map[string]interface{}{},
}
paths := d.Get("paths").([]string)
if len(paths) == 0 {
// Read from the deprecated field
paths = d.Get("path").([]string)
}
if len(paths) == 0 {
return logical.ErrorResponse("paths must be supplied"), nil
}
for _, path := range paths {
pathCap, err := b.Core.Capabilities(ctx, token, path)
if err != nil {
if !strings.HasSuffix(req.Path, "capabilities-self") && errwrap.Contains(err, logical.ErrPermissionDenied.Error()) {
return nil, &logical.StatusBadRequest{Err: "invalid token"}
}
return nil, err
}
ret.Data[path] = pathCap
}
// This is only here for backwards compatibility
if len(paths) == 1 {
ret.Data["capabilities"] = ret.Data[paths[0]]
}
return ret, nil
}
// handleRekeyRetrieve returns backed-up, PGP-encrypted unseal keys from a
// rekey operation
func (b *SystemBackend) handleRekeyRetrieve(
ctx context.Context,
req *logical.Request,
data *framework.FieldData,
recovery bool) (*logical.Response, error) {
backup, err := b.Core.RekeyRetrieveBackup(ctx, recovery)
if err != nil {
return nil, errwrap.Wrapf("unable to look up backed-up keys: {{err}}", err)
}
if backup == nil {
return logical.ErrorResponse("no backed-up keys found"), nil
}
keysB64 := map[string][]string{}
for k, v := range backup.Keys {
for _, j := range v {
currB64Keys := keysB64[k]
if currB64Keys == nil {
currB64Keys = []string{}
}
key, err := hex.DecodeString(j)
if err != nil {
return nil, errwrap.Wrapf("error decoding hex-encoded backup key: {{err}}", err)
}
currB64Keys = append(currB64Keys, base64.StdEncoding.EncodeToString(key))
keysB64[k] = currB64Keys
}
}
// Format the status
resp := &logical.Response{
Data: map[string]interface{}{
"nonce": backup.Nonce,
"keys": backup.Keys,
"keys_base64": keysB64,
},
}
return resp, nil
}
func (b *SystemBackend) handleRekeyRetrieveBarrier(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
return b.handleRekeyRetrieve(ctx, req, data, false)
}
func (b *SystemBackend) handleRekeyRetrieveRecovery(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
return b.handleRekeyRetrieve(ctx, req, data, true)
}
// handleRekeyDelete deletes backed-up, PGP-encrypted unseal keys from a rekey
// operation
func (b *SystemBackend) handleRekeyDelete(
ctx context.Context,
req *logical.Request,
data *framework.FieldData,
recovery bool) (*logical.Response, error) {
err := b.Core.RekeyDeleteBackup(ctx, recovery)
if err != nil {
return nil, errwrap.Wrapf("error during deletion of backed-up keys: {{err}}", err)
}
return nil, nil
}
func (b *SystemBackend) handleRekeyDeleteBarrier(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
return b.handleRekeyDelete(ctx, req, data, false)
}
func (b *SystemBackend) handleRekeyDeleteRecovery(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
return b.handleRekeyDelete(ctx, req, data, true)
}
func mountInfo(entry *MountEntry) map[string]interface{} {
info := map[string]interface{}{
"type": entry.Type,
"description": entry.Description,
"accessor": entry.Accessor,
"local": entry.Local,
"seal_wrap": entry.SealWrap,
"options": entry.Options,
}
entryConfig := map[string]interface{}{
"default_lease_ttl": int64(entry.Config.DefaultLeaseTTL.Seconds()),
"max_lease_ttl": int64(entry.Config.MaxLeaseTTL.Seconds()),
"force_no_cache": entry.Config.ForceNoCache,
"plugin_name": entry.Config.PluginName,
}
if rawVal, ok := entry.synthesizedConfigCache.Load("audit_non_hmac_request_keys"); ok {
entryConfig["audit_non_hmac_request_keys"] = rawVal.([]string)
}
if rawVal, ok := entry.synthesizedConfigCache.Load("audit_non_hmac_response_keys"); ok {
entryConfig["audit_non_hmac_response_keys"] = rawVal.([]string)
}
// Even though empty value is valid for ListingVisibility, we can ignore
// this case during mount since there's nothing to unset/hide.
if len(entry.Config.ListingVisibility) > 0 {
entryConfig["listing_visibility"] = entry.Config.ListingVisibility
}
if rawVal, ok := entry.synthesizedConfigCache.Load("passthrough_request_headers"); ok {
entryConfig["passthrough_request_headers"] = rawVal.([]string)
}
info["config"] = entryConfig
return info
}
// handleMountTable handles the "mounts" endpoint to provide the mount table
func (b *SystemBackend) handleMountTable(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
ns, err := namespace.FromContext(ctx)
if err != nil {
return nil, err
}
b.Core.mountsLock.RLock()
defer b.Core.mountsLock.RUnlock()
resp := &logical.Response{
Data: make(map[string]interface{}),
}
for _, entry := range b.Core.mounts.Entries {
// Only show entries for current namespace
if entry.Namespace().Path != ns.Path {
continue
}
cont, err := b.Core.checkReplicatedFiltering(ctx, entry, "")
if err != nil {
return nil, err
}
if cont {
continue
}
// Populate mount info
info := mountInfo(entry)
resp.Data[entry.Path] = info
}
return resp, nil
}
// handleMount is used to mount a new path
func (b *SystemBackend) handleMount(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
repState := b.Core.ReplicationState()
local := data.Get("local").(bool)
if !local && repState.HasState(consts.ReplicationPerformanceSecondary) {
return logical.ErrorResponse("cannot add a non-local mount to a replication secondary"), nil
}
// Get all the options
path := data.Get("path").(string)
path = sanitizeMountPath(path)
logicalType := data.Get("type").(string)
description := data.Get("description").(string)
pluginName := data.Get("plugin_name").(string)
sealWrap := data.Get("seal_wrap").(bool)
options := data.Get("options").(map[string]string)
var config MountConfig
var apiConfig APIMountConfig
configMap := data.Get("config").(map[string]interface{})
if configMap != nil && len(configMap) != 0 {
err := mapstructure.Decode(configMap, &apiConfig)
if err != nil {
return logical.ErrorResponse(
"unable to convert given mount config information"),
logical.ErrInvalidRequest
}
}
switch apiConfig.DefaultLeaseTTL {
case "":
case "system":
default:
tmpDef, err := parseutil.ParseDurationSecond(apiConfig.DefaultLeaseTTL)
if err != nil {
return logical.ErrorResponse(fmt.Sprintf(
"unable to parse default TTL of %s: %s", apiConfig.DefaultLeaseTTL, err)),
logical.ErrInvalidRequest
}
config.DefaultLeaseTTL = tmpDef
}
switch apiConfig.MaxLeaseTTL {
case "":
case "system":
default:
tmpMax, err := parseutil.ParseDurationSecond(apiConfig.MaxLeaseTTL)
if err != nil {
return logical.ErrorResponse(fmt.Sprintf(
"unable to parse max TTL of %s: %s", apiConfig.MaxLeaseTTL, err)),
logical.ErrInvalidRequest
}
config.MaxLeaseTTL = tmpMax
}
if config.MaxLeaseTTL != 0 && config.DefaultLeaseTTL > config.MaxLeaseTTL {
return logical.ErrorResponse(
"given default lease TTL greater than given max lease TTL"),
logical.ErrInvalidRequest
}
if config.DefaultLeaseTTL > b.Core.maxLeaseTTL && config.MaxLeaseTTL == 0 {
return logical.ErrorResponse(fmt.Sprintf(
"given default lease TTL greater than system max lease TTL of %d", int(b.Core.maxLeaseTTL.Seconds()))),
logical.ErrInvalidRequest
}
switch logicalType {
case "":
return logical.ErrorResponse(
"backend type must be specified as a string"),
logical.ErrInvalidRequest
case "plugin":
// Only set plugin-name if mount is of type plugin, with apiConfig.PluginName
// option taking precedence.
switch {
case apiConfig.PluginName != "":
config.PluginName = apiConfig.PluginName
case pluginName != "":
config.PluginName = pluginName
default:
return logical.ErrorResponse(
"plugin_name must be provided for plugin backend"),
logical.ErrInvalidRequest
}
}
switch logicalType {
case "kv":
case "kv-v1":
// Alias KV v1
logicalType = "kv"
if options == nil {
options = map[string]string{}
}
options["version"] = "1"
case "kv-v2":
// Alias KV v2
logicalType = "kv"
if options == nil {
options = map[string]string{}
}
options["version"] = "2"
default:
if options != nil && options["version"] != "" {
return logical.ErrorResponse(fmt.Sprintf(
"secrets engine %q does not allow setting a version", logicalType)),
logical.ErrInvalidRequest
}
}
// Copy over the force no cache if set
if apiConfig.ForceNoCache {
config.ForceNoCache = true
}
if err := checkListingVisibility(apiConfig.ListingVisibility); err != nil {
return logical.ErrorResponse(fmt.Sprintf("invalid listing_visibility %s", apiConfig.ListingVisibility)), nil
}
config.ListingVisibility = apiConfig.ListingVisibility
if len(apiConfig.AuditNonHMACRequestKeys) > 0 {
config.AuditNonHMACRequestKeys = apiConfig.AuditNonHMACRequestKeys
}
if len(apiConfig.AuditNonHMACResponseKeys) > 0 {
config.AuditNonHMACResponseKeys = apiConfig.AuditNonHMACResponseKeys
}
if len(apiConfig.PassthroughRequestHeaders) > 0 {
config.PassthroughRequestHeaders = apiConfig.PassthroughRequestHeaders
}
// Create the mount entry
me := &MountEntry{
Table: mountTableType,
Path: path,
Type: logicalType,
Description: description,
Config: config,
Local: local,
SealWrap: sealWrap,
Options: options,
}
// Attempt mount
if err := b.Core.mount(ctx, me); err != nil {
b.Backend.Logger().Error("mount failed", "path", me.Path, "error", err)
return handleError(err)
}
return nil, nil
}
// used to intercept an HTTPCodedError so it goes back to callee
func handleError(
err error) (*logical.Response, error) {
if strings.Contains(err.Error(), logical.ErrReadOnly.Error()) {
return logical.ErrorResponse(err.Error()), err
}
switch err.(type) {
case logical.HTTPCodedError:
return logical.ErrorResponse(err.Error()), err
default:
return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
}
}
// Performs a similar function to handleError, but upon seeing a ReadOnlyError
// will actually strip it out to prevent forwarding
func handleErrorNoReadOnlyForward(
err error) (*logical.Response, error) {
if strings.Contains(err.Error(), logical.ErrReadOnly.Error()) {
return nil, fmt.Errorf("operation could not be completed as storage is read-only")
}
switch err.(type) {
case logical.HTTPCodedError:
return logical.ErrorResponse(err.Error()), err
default:
return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
}
}
// handleUnmount is used to unmount a path
func (b *SystemBackend) handleUnmount(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
path := data.Get("path").(string)
path = sanitizeMountPath(path)
ns, err := namespace.FromContext(ctx)
if err != nil {
return nil, err
}
repState := b.Core.ReplicationState()
entry := b.Core.router.MatchingMountEntry(ctx, path)
if entry != nil && !entry.Local && repState.HasState(consts.ReplicationPerformanceSecondary) {
return logical.ErrorResponse("cannot unmount a non-local mount on a replication secondary"), nil
}
// We return success when the mount does not exists to not expose if the
// mount existed or not
match := b.Core.router.MatchingMount(ctx, path)
if match == "" || ns.Path+path != match {
return nil, nil
}
prefix, found := b.Core.router.MatchingStoragePrefixByAPIPath(ctx, path)
if !found {
b.Backend.Logger().Error("unable to find storage for path", "path", path)
return handleError(fmt.Errorf("unable to find storage for path: %q", path))
}
// Attempt unmount
if err := b.Core.unmount(ctx, path); err != nil {
b.Backend.Logger().Error("unmount failed", "path", path, "error", err)
return handleError(err)
}
// Remove from filtered mounts
if err := b.Core.removePrefixFromFilteredPaths(ctx, prefix); err != nil {
b.Backend.Logger().Error("filtered path removal failed", path, "error", err)
return handleError(err)
}
return nil, nil
}
// handleRemount is used to remount a path
func (b *SystemBackend) handleRemount(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
repState := b.Core.ReplicationState()
// Get the paths
fromPath := data.Get("from").(string)
toPath := data.Get("to").(string)
if fromPath == "" || toPath == "" {
return logical.ErrorResponse(
"both 'from' and 'to' path must be specified as a string"),
logical.ErrInvalidRequest
}
entry := b.Core.router.MatchingMountEntry(ctx, fromPath)
if entry != nil && !entry.Local && repState.HasState(consts.ReplicationPerformanceSecondary) {
return logical.ErrorResponse("cannot remount a non-local mount on a replication secondary"), nil
}
// Attempt remount
if err := b.Core.remount(ctx, fromPath, toPath); err != nil {
b.Backend.Logger().Error("remount failed", "from_path", fromPath, "to_path", toPath, "error", err)
return handleError(err)
}
return nil, nil
}
// handleAuthTuneRead is used to get config settings on a auth path
func (b *SystemBackend) handleAuthTuneRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
path := data.Get("path").(string)
if path == "" {
return logical.ErrorResponse(
"path must be specified as a string"),
logical.ErrInvalidRequest
}
return b.handleTuneReadCommon(ctx, "auth/"+path)
}
// handleMountTuneRead is used to get config settings on a backend
func (b *SystemBackend) handleMountTuneRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
path := data.Get("path").(string)
if path == "" {
return logical.ErrorResponse(
"path must be specified as a string"),
logical.ErrInvalidRequest
}
// This call will read both logical backend's configuration as well as auth methods'.
// Retaining this behavior for backward compatibility. If this behavior is not desired,
// an error can be returned if path has a prefix of "auth/".
return b.handleTuneReadCommon(ctx, path)
}
// handleTuneReadCommon returns the config settings of a path
func (b *SystemBackend) handleTuneReadCommon(ctx context.Context, path string) (*logical.Response, error) {
path = sanitizeMountPath(path)
sysView := b.Core.router.MatchingSystemView(ctx, path)
if sysView == nil {
b.Backend.Logger().Error("cannot fetch sysview", "path", path)
return handleError(fmt.Errorf("cannot fetch sysview for path %q", path))
}
mountEntry := b.Core.router.MatchingMountEntry(ctx, path)
if mountEntry == nil {
b.Backend.Logger().Error("cannot fetch mount entry", "path", path)
return handleError(fmt.Errorf("cannot fetch mount entry for path %q", path))
}
resp := &logical.Response{
Data: map[string]interface{}{
"default_lease_ttl": int(sysView.DefaultLeaseTTL().Seconds()),
"max_lease_ttl": int(sysView.MaxLeaseTTL().Seconds()),
"force_no_cache": mountEntry.Config.ForceNoCache,
},
}
if rawVal, ok := mountEntry.synthesizedConfigCache.Load("audit_non_hmac_request_keys"); ok {
resp.Data["audit_non_hmac_request_keys"] = rawVal.([]string)
}
if rawVal, ok := mountEntry.synthesizedConfigCache.Load("audit_non_hmac_response_keys"); ok {
resp.Data["audit_non_hmac_response_keys"] = rawVal.([]string)
}
if len(mountEntry.Config.ListingVisibility) > 0 {
resp.Data["listing_visibility"] = mountEntry.Config.ListingVisibility
}
if rawVal, ok := mountEntry.synthesizedConfigCache.Load("passthrough_request_headers"); ok {
resp.Data["passthrough_request_headers"] = rawVal.([]string)
}
if len(mountEntry.Options) > 0 {
resp.Data["options"] = mountEntry.Options
}
return resp, nil
}
// handleAuthTuneWrite is used to set config settings on an auth path
func (b *SystemBackend) handleAuthTuneWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
path := data.Get("path").(string)
if path == "" {
return logical.ErrorResponse("missing path"), nil
}
ns, err := namespace.FromContext(ctx)
if err != nil {
return nil, err
}
path = ns.Path + namespace.Canonicalize("auth/"+path)
return b.handleTuneWriteCommon(ctx, path, data)
}
// handleMountTuneWrite is used to set config settings on a backend
func (b *SystemBackend) handleMountTuneWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
path := data.Get("path").(string)
if path == "" {
return logical.ErrorResponse("missing path"), nil
}
// This call will write both logical backend's configuration as well as auth methods'.