forked from openbao/openbao
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogical_system_namespaces.go
More file actions
481 lines (418 loc) · 14.6 KB
/
logical_system_namespaces.go
File metadata and controls
481 lines (418 loc) · 14.6 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
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
// Copyright (c) 2025 OpenBao a Series of LF Projects, LLC
// SPDX-License-Identifier: MPL-2.0
package vault
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"github.com/openbao/openbao/helper/namespace"
"github.com/openbao/openbao/sdk/v2/framework"
"github.com/openbao/openbao/sdk/v2/logical"
)
func (b *SystemBackend) namespacePaths() []*framework.Path {
namespaceListSchema := map[string]*framework.FieldSchema{
"keys": {
Type: framework.TypeStringSlice,
Description: "List of namespace paths.",
},
"key_info": {
Type: framework.TypeMap,
Description: "Map of namespace details by path.",
},
}
namespaceSchema := map[string]*framework.FieldSchema{
"uuid": {
Type: framework.TypeString,
Required: true,
Description: "Internal UUID of the namespace.",
},
"id": {
Type: framework.TypeString,
Required: true,
Description: "Accessor ID of the namespace.",
},
"path": {
Type: framework.TypeString,
Required: true,
Description: "Path of the namespace.",
},
"tainted": {
Type: framework.TypeBool,
Required: true,
Description: "Flag representing the taint status of the namespace.",
},
"locked": {
Type: framework.TypeBool,
Required: true,
Description: "Flag representing the lock status of the namespace.",
},
"custom_metadata": {
Type: framework.TypeMap,
Required: true,
Description: "User provided key-value pairs.",
},
}
return []*framework.Path{
{
Pattern: "namespaces/?$",
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: "namespaces",
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.ListOperation: &framework.PathOperation{
Callback: b.handleNamespacesList(),
Responses: map[int][]framework.Response{
http.StatusOK: {{Description: "OK", Fields: namespaceListSchema}},
},
Summary: "List namespaces.",
},
logical.ScanOperation: &framework.PathOperation{
Callback: b.handleNamespacesScan(),
Responses: map[int][]framework.Response{
http.StatusOK: {{Description: "OK", Fields: namespaceListSchema}},
},
Summary: "Scan (recursively list) namespaces.",
},
},
HelpSynopsis: strings.TrimSpace(sysHelp["list-namespaces"][0]),
HelpDescription: strings.TrimSpace(sysHelp["list-namespaces"][1]),
},
{
// should match
// .../lock
// .../lock/<path_to_namespace> capturing the "path_to_namespace"
// but should not match
// .../lockkk or any malformation of "lock" string
Pattern: "namespaces/api-lock/lock(?:$|/(?P<path>.+))",
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: "namespaces",
},
Fields: map[string]*framework.FieldSchema{
"path": {
Type: framework.TypeString,
Required: false,
Description: "Path of the namespace.",
},
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.UpdateOperation: &framework.PathOperation{
Callback: b.handleNamespacesLock(),
Responses: map[int][]framework.Response{
http.StatusOK: {{Description: "OK", Fields: map[string]*framework.FieldSchema{
"unlock_key": {
Type: framework.TypeString,
Required: true,
Description: "Unlock key required for unlocking the namespace.",
},
}}},
},
Summary: "Lock a namespace.",
},
},
HelpSynopsis: strings.TrimSpace(sysHelp["namespaces-lock"][0]),
HelpDescription: strings.TrimSpace(sysHelp["namespaces-lock"][1]),
},
{
// should match
// .../unlock
// .../unlock/<path_to_namespace> capturing the "path_to_namespace"
// but should not match
// .../unlockkk or any malformation of "unlock" string
Pattern: "namespaces/api-lock/unlock(?:$|/(?P<path>.+))",
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: "namespaces",
},
Fields: map[string]*framework.FieldSchema{
"path": {
Type: framework.TypeString,
Required: false,
Description: "Path of the namespace.",
},
"unlock_key": {
Type: framework.TypeString,
Required: true,
Description: "Unlock key required for unlocking the namespace",
},
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.UpdateOperation: &framework.PathOperation{
Callback: b.handleNamespacesUnlock(),
Responses: map[int][]framework.Response{
http.StatusNoContent: {{Description: "No Content"}},
},
Summary: "Unlock a namespace.",
},
},
HelpSynopsis: strings.TrimSpace(sysHelp["namespaces-unlock"][0]),
HelpDescription: strings.TrimSpace(sysHelp["namespaces-unlock"][1]),
},
{
Pattern: "namespaces/(?P<path>.+)",
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: "namespaces",
},
Fields: map[string]*framework.FieldSchema{
"path": {
Type: framework.TypeString,
Required: true,
Description: "Path of the namespace.",
},
"custom_metadata": {
Type: framework.TypeMap,
Description: "User provided key-value pairs.",
},
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.ReadOperation: &framework.PathOperation{
Callback: b.handleNamespacesRead(),
Responses: map[int][]framework.Response{
http.StatusOK: {{Description: "OK", Fields: namespaceSchema}},
},
Summary: "Retrieve a namespace.",
},
logical.UpdateOperation: &framework.PathOperation{
Callback: b.handleNamespacesSet(),
Responses: map[int][]framework.Response{
http.StatusOK: {{Description: "OK", Fields: namespaceSchema}},
},
Summary: "Create or update a namespace.",
},
logical.PatchOperation: &framework.PathOperation{
Callback: b.handleNamespacesPatch(),
Responses: map[int][]framework.Response{
http.StatusOK: {{Description: "OK", Fields: namespaceSchema}},
},
Summary: "Update a namespace's custom metadata.",
},
logical.DeleteOperation: &framework.PathOperation{
Callback: b.handleNamespacesDelete(),
Responses: map[int][]framework.Response{
http.StatusOK: {
{
Description: "OK",
Fields: map[string]*framework.FieldSchema{
"status": {
Type: framework.TypeString,
Description: "Status of the deletion operation.",
},
},
},
},
http.StatusNoContent: {{Description: "No Content"}},
},
Summary: "Delete a namespace.",
},
},
HelpSynopsis: strings.TrimSpace(sysHelp["namespaces"][0]),
HelpDescription: strings.TrimSpace(sysHelp["namespaces"][1]),
},
}
}
// createNamespaceDataResponse is the standard response object
// for any operations concerning a namespace
func createNamespaceDataResponse(ns *namespace.Namespace) map[string]any {
return map[string]any{
"uuid": ns.UUID,
"path": ns.Path,
"id": ns.ID,
"tainted": ns.Tainted,
"locked": ns.Locked,
"custom_metadata": ns.CustomMetadata,
}
}
// handleNamespacesList handles "/sys/namespaces" endpoint to list the enabled namespaces.
func (b *SystemBackend) handleNamespacesList() framework.OperationFunc {
return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
parent, err := namespace.FromContext(ctx)
if err != nil {
return nil, err
}
entries, err := b.Core.namespaceStore.ListNamespaces(ctx, false, false)
if err != nil {
return nil, err
}
var keys []string
keyInfo := make(map[string]interface{})
for _, entry := range entries {
p := parent.TrimmedPath(entry.Path)
keys = append(keys, p)
keyInfo[p] = createNamespaceDataResponse(entry)
}
return logical.ListResponseWithInfo(keys, keyInfo), nil
}
}
// handleNamespacesScan handles "/sys/namespaces" endpoint to scan the enabled namespaces.
func (b *SystemBackend) handleNamespacesScan() framework.OperationFunc {
return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
parent, err := namespace.FromContext(ctx)
if err != nil {
return nil, err
}
entries, err := b.Core.namespaceStore.ListNamespaces(ctx, false, true)
if err != nil {
return nil, err
}
var keys []string
keyInfo := make(map[string]interface{})
for _, entry := range entries {
p := parent.TrimmedPath(entry.Path)
keys = append(keys, p)
keyInfo[p] = createNamespaceDataResponse(entry)
}
return logical.ListResponseWithInfo(keys, keyInfo), nil
}
}
// handleNamespacesRead handles the "/sys/namespaces/<path>" endpoints to read a namespace.
func (b *SystemBackend) handleNamespacesRead() framework.OperationFunc {
return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
path := namespace.Canonicalize(data.Get("path").(string))
if len(path) > 0 && strings.Contains(path[:len(path)-1], "/") {
return nil, errors.New("path must not contain /")
}
ns, err := b.Core.namespaceStore.GetNamespaceByPath(ctx, path)
if err != nil {
return nil, err
}
if ns == nil {
return nil, nil
}
return &logical.Response{Data: createNamespaceDataResponse(ns)}, nil
}
}
// handleNamespaceSet handles the "/sys/namespaces/<path>" endpoint to set a namespace.
func (b *SystemBackend) handleNamespacesSet() framework.OperationFunc {
return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
path := namespace.Canonicalize(data.Get("path").(string))
if len(path) > 0 && strings.Contains(path[:len(path)-1], "/") {
return logical.ErrorResponse("path must not contain /"), logical.ErrInvalidRequest
}
imetadata, ok := data.GetOk("custom_metadata")
var metadata map[string]string
if ok {
metadata = make(map[string]string)
for k, v := range imetadata.(map[string]interface{}) {
if metadata[k], ok = v.(string); !ok {
return logical.ErrorResponse("custom_metadata values must be strings"), logical.ErrInvalidRequest
}
}
}
entry, err := b.Core.namespaceStore.ModifyNamespaceByPath(ctx, path, func(ctx context.Context, ns *namespace.Namespace) (*namespace.Namespace, error) {
ns.CustomMetadata = metadata
return ns, nil
})
if err != nil {
return handleError(err)
}
return &logical.Response{Data: createNamespaceDataResponse(entry)}, nil
}
}
// customMetadataPatchPreprocessor is passed to framework.HandlePatchOperation within the handleNamespacesPatch handler.
func customMetadataPatchPreprocessor(input map[string]interface{}) (map[string]interface{}, error) {
imetadata, ok := input["custom_metadata"]
var metadata map[string]interface{}
if ok {
metadata = imetadata.(map[string]interface{})
for _, v := range metadata {
// Allow nil values in addition to strings so keys can be removed.
if _, ok = v.(string); !ok && v != nil {
return nil, fmt.Errorf("custom_metadata values must be strings")
}
}
}
return metadata, nil
}
// handleNamespacesPatch handles the "/sys/namespace/<path>" endpoints to update a namespace's custom metadata.
func (b *SystemBackend) handleNamespacesPatch() framework.OperationFunc {
return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
path := namespace.Canonicalize(data.Get("path").(string))
if len(path) > 0 && strings.Contains(path[:len(path)-1], "/") {
return nil, errors.New("path must not contain /")
}
ns, err := b.Core.namespaceStore.ModifyNamespaceByPath(ctx, path, func(ctx context.Context, ns *namespace.Namespace) (*namespace.Namespace, error) {
if ns.UUID == "" {
return nil, fmt.Errorf("requested namespace does not exist")
}
current := make(map[string]interface{})
for k, v := range ns.CustomMetadata {
current[k] = v
}
patchedBytes, err := framework.HandlePatchOperation(data, current, customMetadataPatchPreprocessor)
if err != nil {
return nil, err
}
var patched map[string]string
if err = json.Unmarshal(patchedBytes, &patched); err != nil {
return nil, err
}
ns.CustomMetadata = patched
return ns, nil
})
if err != nil {
return nil, fmt.Errorf("failed to modify namespace: %w", err)
}
return &logical.Response{Data: createNamespaceDataResponse(ns)}, nil
}
}
// handleNamespacesLock handles the "/sys/namespaces/api-lock/lock/<path>" endpoint to lock a namespace.
func (b *SystemBackend) handleNamespacesLock() framework.OperationFunc {
return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
path := namespace.Canonicalize(data.Get("path").(string))
unlockKey, err := b.Core.namespaceStore.LockNamespace(ctx, path)
if err != nil {
return handleError(err)
}
if unlockKey != "" {
return &logical.Response{Data: map[string]interface{}{
"unlock_key": unlockKey,
}}, nil
}
return nil, nil
}
}
// handleNamespacesUnlock handles the "/sys/namespaces/api-lock/unlock/<path>" endpoint to unlock a namespace.
func (b *SystemBackend) handleNamespacesUnlock() framework.OperationFunc {
return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
path := namespace.Canonicalize(data.Get("path").(string))
unlockKey := data.Get("unlock_key").(string)
// sudo check
isSudo := b.System().(extendedSystemView).SudoPrivilege(ctx, req.MountPoint+req.Path, req.ClientToken)
if unlockKey == "" && !isSudo {
return nil, errors.New("provided empty key")
}
// unlockKey can only be empty if the request was made with token having sudo capability
err := b.Core.namespaceStore.UnlockNamespace(ctx, unlockKey, path)
if err != nil {
return handleError(err)
}
if unlockKey == "" {
return &logical.Response{Warnings: []string{"Namespace unlocked using sudo capabilities"}}, nil
}
return nil, nil
}
}
// handleNamespacesDelete handles the "/sys/namespace/<path>" endpoint to delete a namespace.
func (b *SystemBackend) handleNamespacesDelete() framework.OperationFunc {
return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
path := namespace.Canonicalize(data.Get("path").(string))
if len(path) > 0 && strings.Contains(path[:len(path)-1], "/") {
return nil, errors.New("path must not contain /")
}
status, err := b.Core.namespaceStore.DeleteNamespace(ctx, path)
if err != nil {
return handleError(err)
}
if status == "" {
resp := &logical.Response{}
resp.AddWarning("requested namespace does not exist")
return resp, nil
}
return &logical.Response{
Data: map[string]interface{}{
"status": status,
},
}, nil
}
}