-
Notifications
You must be signed in to change notification settings - Fork 61
/
path_role.go
416 lines (361 loc) · 14.3 KB
/
path_role.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package kubeauth
import (
"context"
"fmt"
"strings"
"time"
"github.com/hashicorp/go-secure-stdlib/strutil"
"github.com/hashicorp/go-sockaddr"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/helper/tokenutil"
"github.com/hashicorp/vault/sdk/logical"
)
// pathsRole returns the path configurations for the CRUD operations on roles
func pathsRole(b *kubeAuthBackend) []*framework.Path {
p := []*framework.Path{
{
Pattern: "role/?",
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ListOperation: b.pathRoleList,
},
HelpSynopsis: strings.TrimSpace(roleHelp["role-list"][0]),
HelpDescription: strings.TrimSpace(roleHelp["role-list"][1]),
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: operationPrefixKubernetes,
OperationSuffix: "auth-roles",
Navigation: true,
ItemType: "Role",
},
},
{
Pattern: "role/" + framework.GenericNameRegex("name"),
Fields: map[string]*framework.FieldSchema{
"name": {
Type: framework.TypeString,
Description: "Name of the role.",
},
"bound_service_account_names": {
Type: framework.TypeCommaStringSlice,
Description: `List of service account names able to access this role. If set to "*" all names
are allowed.`,
},
"bound_service_account_namespaces": {
Type: framework.TypeCommaStringSlice,
Description: `List of namespaces allowed to access this role. If set to "*" all namespaces
are allowed.`,
},
"bound_service_account_namespace_selector": {
Type: framework.TypeString,
Description: `A label selector for Kubernetes namespaces which are allowed to access this role.
Accepts either a JSON or YAML object. If set with bound_service_account_namespaces,
the conditions are ORed.`,
},
"audience": {
Type: framework.TypeString,
Description: "Optional Audience claim to verify in the jwt.",
},
"alias_name_source": {
Type: framework.TypeString,
Description: fmt.Sprintf(`Source to use when deriving the Alias name.
valid choices:
%q : <token.uid> e.g. 474b11b5-0f20-4f9d-8ca5-65715ab325e0 (most secure choice)
%q : <namespace>/<serviceaccount> e.g. vault/vault-agent
default: %q
`, aliasNameSourceSAUid, aliasNameSourceSAName, aliasNameSourceDefault),
Default: aliasNameSourceDefault,
},
"policies": {
Type: framework.TypeCommaStringSlice,
Description: tokenutil.DeprecationText("token_policies"),
Deprecated: true,
},
"num_uses": {
Type: framework.TypeInt,
Description: tokenutil.DeprecationText("token_num_uses"),
Deprecated: true,
},
"ttl": {
Type: framework.TypeDurationSecond,
Description: tokenutil.DeprecationText("token_ttl"),
Deprecated: true,
},
"max_ttl": {
Type: framework.TypeDurationSecond,
Description: tokenutil.DeprecationText("token_max_ttl"),
Deprecated: true,
},
"period": {
Type: framework.TypeDurationSecond,
Description: tokenutil.DeprecationText("token_period"),
Deprecated: true,
},
"bound_cidrs": {
Type: framework.TypeCommaStringSlice,
Description: tokenutil.DeprecationText("token_bound_cidrs"),
Deprecated: true,
},
},
ExistenceCheck: b.pathRoleExistenceCheck,
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.CreateOperation: b.pathRoleCreateUpdate,
logical.UpdateOperation: b.pathRoleCreateUpdate,
logical.ReadOperation: b.pathRoleRead,
logical.DeleteOperation: b.pathRoleDelete,
},
HelpSynopsis: strings.TrimSpace(roleHelp["role"][0]),
HelpDescription: strings.TrimSpace(roleHelp["role"][1]),
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: operationPrefixKubernetes,
OperationSuffix: "auth-role",
ItemType: "Role",
Action: "Create",
},
},
}
tokenutil.AddTokenFields(p[1].Fields)
return p
}
// pathRoleExistenceCheck returns whether the role with the given name exists or not.
func (b *kubeAuthBackend) pathRoleExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) {
b.l.RLock()
defer b.l.RUnlock()
role, err := b.role(ctx, req.Storage, data.Get("name").(string))
if err != nil {
return false, err
}
return role != nil, nil
}
// pathRoleList is used to list all the Roles registered with the backend.
func (b *kubeAuthBackend) pathRoleList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
b.l.RLock()
defer b.l.RUnlock()
roles, err := req.Storage.List(ctx, "role/")
if err != nil {
return nil, err
}
return logical.ListResponse(roles), nil
}
// pathRoleRead grabs a read lock and reads the options set on the role from the storage
func (b *kubeAuthBackend) pathRoleRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roleName := data.Get("name").(string)
if roleName == "" {
return logical.ErrorResponse("missing name"), nil
}
b.l.RLock()
defer b.l.RUnlock()
role, err := b.role(ctx, req.Storage, roleName)
if err != nil {
return nil, err
}
if role == nil {
return nil, nil
}
// Create a map of data to be returned
d := map[string]interface{}{
"bound_service_account_names": role.ServiceAccountNames,
"bound_service_account_namespaces": role.ServiceAccountNamespaces,
"bound_service_account_namespace_selector": role.ServiceAccountNamespaceSelector,
}
if role.Audience != "" {
d["audience"] = role.Audience
}
role.PopulateTokenData(d)
if len(role.Policies) > 0 {
d["policies"] = d["token_policies"]
}
if len(role.BoundCIDRs) > 0 {
d["bound_cidrs"] = d["token_bound_cidrs"]
}
if role.TTL > 0 {
d["ttl"] = int64(role.TTL.Seconds())
}
if role.MaxTTL > 0 {
d["max_ttl"] = int64(role.MaxTTL.Seconds())
}
if role.Period > 0 {
d["period"] = int64(role.Period.Seconds())
}
if role.NumUses > 0 {
d["num_uses"] = role.NumUses
}
d["alias_name_source"] = role.AliasNameSource
return &logical.Response{
Data: d,
}, nil
}
// pathRoleDelete removes the role from storage
func (b *kubeAuthBackend) pathRoleDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roleName := data.Get("name").(string)
if roleName == "" {
return logical.ErrorResponse("missing role name"), nil
}
// Acquire the lock before deleting the role.
b.l.Lock()
defer b.l.Unlock()
// Delete the role itself
if err := req.Storage.Delete(ctx, "role/"+strings.ToLower(roleName)); err != nil {
return nil, err
}
return nil, nil
}
// pathRoleCreateUpdate registers a new role with the backend or updates the options
// of an existing role
func (b *kubeAuthBackend) pathRoleCreateUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roleName := data.Get("name").(string)
if roleName == "" {
return logical.ErrorResponse("missing role name"), nil
}
b.l.Lock()
defer b.l.Unlock()
// Check if the role already exists
role, err := b.role(ctx, req.Storage, roleName)
if err != nil {
return nil, err
}
// Create a new entry object if this is a CreateOperation
if role == nil && req.Operation == logical.CreateOperation {
role = &roleStorageEntry{}
} else if role == nil {
return nil, fmt.Errorf("role entry not found during update operation")
}
if err := role.ParseTokenFields(req, data); err != nil {
return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
}
// Handle upgrade cases
{
if err := tokenutil.UpgradeValue(data, "policies", "token_policies", &role.Policies, &role.TokenPolicies); err != nil {
return logical.ErrorResponse(err.Error()), nil
}
if err := tokenutil.UpgradeValue(data, "bound_cidrs", "token_bound_cidrs", &role.BoundCIDRs, &role.TokenBoundCIDRs); err != nil {
return logical.ErrorResponse(err.Error()), nil
}
if err := tokenutil.UpgradeValue(data, "num_uses", "token_num_uses", &role.NumUses, &role.TokenNumUses); err != nil {
return logical.ErrorResponse(err.Error()), nil
}
if err := tokenutil.UpgradeValue(data, "ttl", "token_ttl", &role.TTL, &role.TokenTTL); err != nil {
return logical.ErrorResponse(err.Error()), nil
}
if err := tokenutil.UpgradeValue(data, "max_ttl", "token_max_ttl", &role.MaxTTL, &role.TokenMaxTTL); err != nil {
return logical.ErrorResponse(err.Error()), nil
}
if err := tokenutil.UpgradeValue(data, "period", "token_period", &role.Period, &role.TokenPeriod); err != nil {
return logical.ErrorResponse(err.Error()), nil
}
}
if role.TokenPeriod > b.System().MaxLeaseTTL() {
return logical.ErrorResponse(fmt.Sprintf("token period of '%q' is greater than the backend's maximum lease TTL of '%q'", role.TokenPeriod.String(), b.System().MaxLeaseTTL().String())), nil
}
// Check that the TTL value provided is less than the MaxTTL.
// Sanitizing the TTL and MaxTTL is not required now and can be performed
// at credential issue time.
if role.TokenMaxTTL > time.Duration(0) && role.TokenTTL > role.TokenMaxTTL {
return logical.ErrorResponse("token ttl should not be greater than token max ttl"), nil
}
var resp *logical.Response
if role.TokenMaxTTL > b.System().MaxLeaseTTL() {
resp = &logical.Response{}
resp.AddWarning("max_ttl is greater than the system or backend mount's maximum TTL value; issued tokens' max TTL value will be truncated")
}
if serviceAccountUUIDs, ok := data.GetOk("bound_service_account_names"); ok {
role.ServiceAccountNames = serviceAccountUUIDs.([]string)
} else if req.Operation == logical.CreateOperation {
role.ServiceAccountNames = data.Get("bound_service_account_names").([]string)
}
// Verify names was not empty
if len(role.ServiceAccountNames) == 0 {
return logical.ErrorResponse("%q can not be empty", "bound_service_account_names"), nil
}
// Verify * was not set with other data
if len(role.ServiceAccountNames) > 1 && strutil.StrListContains(role.ServiceAccountNames, "*") {
return logical.ErrorResponse("can not mix %q with values", "*"), nil
}
if namespaces, ok := data.GetOk("bound_service_account_namespaces"); ok {
role.ServiceAccountNamespaces = namespaces.([]string)
}
role.ServiceAccountNamespaceSelector = data.Get("bound_service_account_namespace_selector").(string)
// Verify namespaces is not empty unless selector is set
saNamespaceLen := len(role.ServiceAccountNamespaces)
if saNamespaceLen == 0 && role.ServiceAccountNamespaceSelector == "" {
return logical.ErrorResponse("%q can not be empty if %q is not set",
"bound_service_account_namespaces", "bound_service_account_namespace_selector"), nil
}
// Verify namespace selector is correct
if role.ServiceAccountNamespaceSelector != "" {
if _, err := makeNsLabelSelector(role.ServiceAccountNamespaceSelector); err != nil {
return logical.ErrorResponse("invalid %q configured", "bound_service_account_namespace_selector"), nil
}
}
// Verify * was not set with other data
if saNamespaceLen > 1 && strutil.StrListContains(role.ServiceAccountNamespaces, "*") {
return logical.ErrorResponse("can not mix %q with values", "*"), nil
}
// optional audience field
if audience, ok := data.GetOk("audience"); ok {
role.Audience = audience.(string)
}
if source, ok := data.GetOk("alias_name_source"); ok {
// migrate the role.AliasNameSource to be the default
// if both it and the field value are unset
if role.AliasNameSource == aliasNameSourceUnset && source.(string) == aliasNameSourceUnset {
role.AliasNameSource = data.GetDefaultOrZero("alias_name_source").(string)
} else {
role.AliasNameSource = source.(string)
}
} else if role.AliasNameSource == aliasNameSourceUnset {
role.AliasNameSource = data.Get("alias_name_source").(string)
}
if err := validateAliasNameSource(role.AliasNameSource); err != nil {
return logical.ErrorResponse(err.Error()), nil
}
// Store the entry.
entry, err := logical.StorageEntryJSON("role/"+strings.ToLower(roleName), role)
if err != nil {
return nil, err
}
if entry == nil {
return nil, fmt.Errorf("failed to create storage entry for role %s", roleName)
}
if err = req.Storage.Put(ctx, entry); err != nil {
return nil, err
}
return resp, nil
}
// roleStorageEntry stores all the options that are set on an role
type roleStorageEntry struct {
tokenutil.TokenParams
// ServiceAccountNames is the array of service accounts able to
// access this role.
ServiceAccountNames []string `json:"bound_service_account_names" mapstructure:"bound_service_account_names" structs:"bound_service_account_names"`
// ServiceAccountNamespaces is the array of namespaces able to access this
// role.
ServiceAccountNamespaces []string `json:"bound_service_account_namespaces" mapstructure:"bound_service_account_namespaces" structs:"bound_service_account_namespaces"`
// ServiceAccountNamespaceSelector is the label selector string of the
// namespaces able to access this role.
ServiceAccountNamespaceSelector string `json:"bound_service_account_namespace_selector" mapstructure:"bound_service_account_namespace_selector" structs:"bound_service_account_namespace_selector"`
// Audience is an optional jwt claim to verify
Audience string `json:"audience" mapstructure:"audience" structs:"audience"`
// AliasNameSource used when deriving the Alias' name.
AliasNameSource string `json:"alias_name_source" mapstructure:"alias_name_source" structs:"alias_name_source"`
// Deprecated by TokenParams
Policies []string `json:"policies" structs:"policies" mapstructure:"policies"`
NumUses int `json:"num_uses" mapstructure:"num_uses" structs:"num_uses"`
TTL time.Duration `json:"ttl" structs:"ttl" mapstructure:"ttl"`
MaxTTL time.Duration `json:"max_ttl" structs:"max_ttl" mapstructure:"max_ttl"`
Period time.Duration `json:"period" mapstructure:"period" structs:"period"`
BoundCIDRs []*sockaddr.SockAddrMarshaler
}
var roleHelp = map[string][2]string{
"role-list": {
"Lists all the roles registered with the backend.",
"The list will contain the names of the roles.",
},
"role": {
"Register an role with the backend.",
`A role is required to authenticate with this backend. The role binds
kubernetes service account metadata with token policies and settings.
The bindings, token polices and token settings can all be configured
using this endpoint`,
},
}