forked from hashicorp/vault-plugin-auth-azure
-
Notifications
You must be signed in to change notification settings - Fork 0
/
path_role.go
384 lines (334 loc) · 12.4 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
package azureauth
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"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 *azureAuthBackend) []*framework.Path {
p := []*framework.Path{
&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]),
},
&framework.Path{
Pattern: "role/" + framework.GenericNameRegex("name"),
Fields: map[string]*framework.FieldSchema{
"name": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Name of the role.",
},
"policies": &framework.FieldSchema{
Type: framework.TypeCommaStringSlice,
Description: tokenutil.DeprecationText("token_policies"),
Deprecated: true,
},
"num_uses": &framework.FieldSchema{
Type: framework.TypeInt,
Description: tokenutil.DeprecationText("token_num_uses"),
Deprecated: true,
},
"ttl": &framework.FieldSchema{
Type: framework.TypeDurationSecond,
Description: tokenutil.DeprecationText("token_ttl"),
Deprecated: true,
},
"max_ttl": &framework.FieldSchema{
Type: framework.TypeDurationSecond,
Description: tokenutil.DeprecationText("token_max_ttl"),
Deprecated: true,
},
"period": &framework.FieldSchema{
Type: framework.TypeDurationSecond,
Description: tokenutil.DeprecationText("token_period"),
Deprecated: true,
},
"bound_subscription_ids": &framework.FieldSchema{
Type: framework.TypeCommaStringSlice,
Description: `Comma-separated list of subscription ids that login
is restricted to.`,
},
"bound_resource_groups": &framework.FieldSchema{
Type: framework.TypeCommaStringSlice,
Description: `Comma-separated list of resource groups that login
is restricted to.`,
},
"bound_group_ids": &framework.FieldSchema{
Type: framework.TypeCommaStringSlice,
Description: `Comma-separated list of group ids that login
is restricted to.`,
},
"bound_service_principal_ids": &framework.FieldSchema{
Type: framework.TypeCommaStringSlice,
Description: `Comma-separated list of service principal ids that login
is restricted to.`,
},
"bound_locations": &framework.FieldSchema{
Type: framework.TypeCommaStringSlice,
Description: `Comma-separated list of locations that login
is restricted to.`,
},
"bound_scale_sets": &framework.FieldSchema{
Type: framework.TypeCommaStringSlice,
Description: `Comma-separated list of scale sets that login
is restricted to.`,
},
},
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]),
},
}
tokenutil.AddTokenFields(p[1].Fields)
return p
}
type azureRole struct {
tokenutil.TokenParams
// Policies that are to be required by the token to access this role
Policies []string `json:"policies"`
// TokenNumUses defines the number of allowed uses of the token issued
NumUses int `json:"num_uses"`
// Duration before which an issued token must be renewed
TTL time.Duration `json:"ttl"`
// Duration after which an issued token should not be allowed to be renewed
MaxTTL time.Duration `json:"max_ttl"`
// Period, if set, indicates that the token generated using this role
// should never expire. The token should be renewed within the duration
// specified by this value. The renewal duration will be fixed if the
// value is not modified on the role. If the `Period` in the role is modified,
// a token will pick up the new value during its next renewal.
Period time.Duration `json:"period"`
// Role binding properties
BoundServicePrincipalIDs []string `json:"bound_service_principal_ids"`
BoundGroupIDs []string `json:"bound_group_ids"`
BoundResourceGroups []string `json:"bound_resource_groups"`
BoundSubscriptionsIDs []string `json:"bound_subscription_ids"`
BoundLocations []string `json:"bound_locations"`
BoundScaleSets []string `json:"bound_scale_sets"`
}
// role takes a storage backend and the name and returns the role's storage
// entryÍ
func (b *azureAuthBackend) role(ctx context.Context, s logical.Storage, name string) (*azureRole, error) {
raw, err := s.Get(ctx, "role/"+strings.ToLower(name))
if err != nil {
return nil, err
}
if raw == nil {
return nil, nil
}
role := new(azureRole)
if err := json.Unmarshal(raw.Value, role); err != nil {
return nil, err
}
if role.TokenTTL == 0 && role.TTL > 0 {
role.TokenTTL = role.TTL
}
if role.TokenMaxTTL == 0 && role.MaxTTL > 0 {
role.TokenMaxTTL = role.MaxTTL
}
if role.TokenPeriod == 0 && role.Period > 0 {
role.TokenPeriod = role.Period
}
if role.TokenNumUses == 0 && role.NumUses > 0 {
role.TokenNumUses = role.NumUses
}
if len(role.TokenPolicies) == 0 && len(role.Policies) > 0 {
role.TokenPolicies = role.Policies
}
return role, nil
}
// pathRoleExistenceCheck returns whether the role with the given name exists or not.
func (b *azureAuthBackend) pathRoleExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) {
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 *azureAuthBackend) pathRoleList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
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 *azureAuthBackend) 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
}
role, err := b.role(ctx, req.Storage, roleName)
if err != nil {
return nil, err
}
if role == nil {
return nil, nil
}
d := map[string]interface{}{
"bound_service_principal_ids": role.BoundServicePrincipalIDs,
"bound_group_ids": role.BoundGroupIDs,
"bound_subscription_ids": role.BoundSubscriptionsIDs,
"bound_resource_groups": role.BoundResourceGroups,
"bound_locations": role.BoundLocations,
"bound_scale_sets": role.BoundScaleSets,
}
role.PopulateTokenData(d)
if len(role.Policies) > 0 {
d["policies"] = d["token_policies"]
}
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
}
return &logical.Response{
Data: d,
}, nil
}
// pathRoleDelete removes the role from storage
func (b *azureAuthBackend) pathRoleDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roleName := data.Get("name").(string)
if roleName == "" {
return logical.ErrorResponse("role name required"), nil
}
// 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 *azureAuthBackend) 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
}
// 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 {
if req.Operation == logical.UpdateOperation {
return nil, errors.New("role entry not found during update operation")
}
role = new(azureRole)
}
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, "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("token period of %q is greater than the backend's maximum lease TTL of %q", role.TokenPeriod.String(), b.System().MaxLeaseTTL().String()), nil
}
if role.TokenNumUses < 0 {
return logical.ErrorResponse("token num uses cannot be negative"), nil
}
if boundServicePrincipalIDs, ok := data.GetOk("bound_service_principal_ids"); ok {
role.BoundServicePrincipalIDs = boundServicePrincipalIDs.([]string)
}
if boundGroupIDs, ok := data.GetOk("bound_group_ids"); ok {
role.BoundGroupIDs = boundGroupIDs.([]string)
}
if boundSubscriptionsIDs, ok := data.GetOk("bound_subscription_ids"); ok {
role.BoundSubscriptionsIDs = boundSubscriptionsIDs.([]string)
}
if boundResourceGroups, ok := data.GetOk("bound_resource_groups"); ok {
role.BoundResourceGroups = boundResourceGroups.([]string)
}
if boundLocations, ok := data.GetOk("bound_locations"); ok {
role.BoundLocations = boundLocations.([]string)
}
if boundScaleSets, ok := data.GetOk("bound_scale_sets"); ok {
role.BoundScaleSets = boundScaleSets.([]string)
}
if len(role.BoundServicePrincipalIDs) == 0 &&
len(role.BoundGroupIDs) == 0 &&
len(role.BoundSubscriptionsIDs) == 0 &&
len(role.BoundResourceGroups) == 0 &&
len(role.BoundLocations) == 0 &&
len(role.BoundScaleSets) == 0 {
return logical.ErrorResponse("must have at least one bound constraint when creating/updating a role"), 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 > 0 && role.TokenTTL > role.TokenMaxTTL {
return logical.ErrorResponse("ttl should not be greater than 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")
}
// 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
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
Azure instance metadata with token policies and settings.
The bindings, token polices and token settings can all be configured
using this endpoint`,
},
}