-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathpath_role.go
454 lines (404 loc) · 14.5 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
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
package gitlab
import (
"cmp"
"context"
"fmt"
"net/http"
"slices"
"strings"
"text/template"
"time"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/helper/locksutil"
"github.com/hashicorp/vault/sdk/logical"
)
const (
PathRoleStorage = "roles"
TypeConfigDefault = DefaultConfigName
)
var (
FieldSchemaRoles = map[string]*framework.FieldSchema{
"role_name": {
Type: framework.TypeString,
Description: "Role name",
Required: true,
DisplayAttrs: &framework.DisplayAttributes{
Name: "Role Name",
},
},
"path": {
Type: framework.TypeString,
Description: "Project/Group path to create an access token for. If the token type is set to personal then write the username here.",
Required: true,
DisplayAttrs: &framework.DisplayAttributes{
Name: "path",
},
},
"name": {
Type: framework.TypeString,
Description: "The name of the access token",
Required: true,
DisplayAttrs: &framework.DisplayAttributes{
Name: "Name",
},
},
"scopes": {
Type: framework.TypeCommaStringSlice,
Description: "List of scopes",
Required: false,
DisplayAttrs: &framework.DisplayAttributes{
Name: "Scopes",
},
AllowedValues: allowedValues(append(validTokenScopes, ValidPersonalTokenScopes...)...),
},
"ttl": {
Type: framework.TypeDurationSecond,
Description: "The TTL of the token",
Required: false,
DisplayAttrs: &framework.DisplayAttributes{
Name: "Token TTL",
},
},
"access_level": {
Type: framework.TypeString,
Description: "access level of access token (only required for Group and Project access tokens)",
Required: false,
DisplayAttrs: &framework.DisplayAttributes{
Name: "Access Level",
},
AllowedValues: allowedValues(ValidAccessLevels...),
},
"token_type": {
Type: framework.TypeString,
Description: "access token type",
Required: true,
AllowedValues: allowedValues(validTokenTypes...),
DisplayAttrs: &framework.DisplayAttributes{
Name: "Token Type",
},
},
"gitlab_revokes_token": {
Type: framework.TypeBool,
Default: false,
Required: false,
Description: `Gitlab revokes the token when it's time. Vault will not revoke the token when the lease expires.`,
DisplayAttrs: &framework.DisplayAttributes{
Name: "Gitlab revokes token.",
},
},
"config_name": {
Type: framework.TypeString,
Default: TypeConfigDefault,
Required: false,
Description: "The config we use when interacting with the role, this can be specified if you want to use a specific config for the role, otherwise it uses the default one.",
DisplayAttrs: &framework.DisplayAttributes{
Name: "Configuration.",
},
},
}
)
func (b *Backend) pathRolesList(ctx context.Context, req *logical.Request, data *framework.FieldData) (l *logical.Response, err error) {
var roles []string
defer func() {
b.Logger().Debug("Available", "roles", roles, "err", err)
}()
l = logical.ErrorResponse("Error listing roles")
if roles, err = req.Storage.List(ctx, fmt.Sprintf("%s/", PathRoleStorage)); err == nil {
l = logical.ListResponse(roles)
}
return l, err
}
func pathListRoles(b *Backend) *framework.Path {
return &framework.Path{
HelpSynopsis: strings.TrimSpace(pathListRolesHelpSyn),
HelpDescription: strings.TrimSpace(pathListRolesHelpDesc),
Pattern: fmt.Sprintf("%s?/?$", PathRoleStorage),
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: operationPrefixGitlabAccessTokens,
OperationSuffix: "roles",
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.ListOperation: &framework.PathOperation{
Callback: b.pathRolesList,
DisplayAttrs: &framework.DisplayAttributes{
OperationVerb: "list",
},
Responses: map[int][]framework.Response{
http.StatusOK: {{
Description: http.StatusText(http.StatusOK),
Fields: map[string]*framework.FieldSchema{
"role_name": FieldSchemaRoles["role_name"],
},
}},
},
},
},
}
}
func (b *Backend) pathRolesDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
var resp *logical.Response
var err error
var roleName = data.Get("role_name").(string)
lock := locksutil.LockForKey(b.roleLocks, roleName)
lock.RLock()
defer lock.RUnlock()
_, err = getRole(ctx, roleName, req.Storage)
if err != nil {
return nil, fmt.Errorf("error getting role: %w", err)
}
err = req.Storage.Delete(ctx, fmt.Sprintf("%s/%s", PathRoleStorage, roleName))
if err != nil {
return nil, fmt.Errorf("error deleting role: %w", err)
}
event(ctx, b.Backend, "role-delete", map[string]string{
"path": "roles",
"role_name": roleName,
})
b.Logger().Debug("Role deleted", "role", roleName)
return resp, nil
}
func (b *Backend) pathRolesRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
var roleName = data.Get("role_name").(string)
lock := locksutil.LockForKey(b.roleLocks, roleName)
lock.RLock()
defer lock.RUnlock()
role, err := getRole(ctx, roleName, req.Storage)
if err != nil {
return logical.ErrorResponse("error reading role"), err
}
if role == nil {
return nil, nil
}
b.Logger().Debug("Role read", "role", roleName)
return &logical.Response{
Data: role.LogicalResponseData(),
}, nil
}
func (b *Backend) pathRolesWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
var roleName = data.Get("role_name").(string)
var config *EntryConfig
var err error
var warnings []string
var tokenType TokenType
var accessLevel AccessLevel
var configName = cmp.Or(data.Get("config_name").(string), TypeConfigDefault)
b.lockClientMutex.RLock()
defer b.lockClientMutex.RUnlock()
config, err = getConfig(ctx, req.Storage, configName)
if err != nil {
return logical.ErrorResponse(fmt.Sprintf("missing %s configuration for gitlab", configName)), err
}
if config == nil {
return logical.ErrorResponse(ErrBackendNotConfigured.Error()), nil
}
tokenType, _ = TokenTypeParse(data.Get("token_type").(string))
accessLevel, _ = AccessLevelParse(data.Get("access_level").(string))
var role = EntryRole{
RoleName: roleName,
TTL: time.Duration(data.Get("ttl").(int)) * time.Second,
Path: data.Get("path").(string),
Name: data.Get("name").(string),
Scopes: data.Get("scopes").([]string),
AccessLevel: accessLevel,
TokenType: tokenType,
GitlabRevokesTokens: data.Get("gitlab_revokes_token").(bool),
ConfigName: configName,
}
// validate name of the entry role
if _, e := template.New("name").Funcs(tplFuncMap).Parse(role.Name); e != nil {
err = multierror.Append(err, fmt.Errorf("invalid template %s for name: %w", role.Name, e))
}
// validate token type
if !slices.Contains(validTokenTypes, tokenType.String()) {
err = multierror.Append(err, fmt.Errorf("token_type='%s', should be one of %v: %w", data.Get("token_type").(string), validTokenTypes, ErrFieldInvalidValue))
}
var skipFields = []string{"config_name"}
// validate access level and which fields to skip for validation
var validAccessLevels []string
var invalidScopes []string
var validScopes []string
var noEmptyScopes bool
switch tokenType {
case TokenTypePersonal:
validAccessLevels = ValidPersonalAccessLevels
validScopes = slices.Concat(validTokenScopes, ValidPersonalTokenScopes)
skipFields = append(skipFields, "access_level")
case TokenTypeGroup:
validAccessLevels = ValidGroupAccessLevels
validScopes = validTokenScopes
case TokenTypeProject:
validAccessLevels = ValidProjectAccessLevels
validScopes = validTokenScopes
case TokenTypeUserServiceAccount:
validAccessLevels = ValidUserServiceAccountAccessLevels
validScopes = slices.Concat(validTokenScopes, ValidPersonalTokenScopes, ValidUserServiceAccountTokenScopes)
skipFields = append(skipFields, "access_level")
case TokenTypeGroupServiceAccount:
validAccessLevels = ValidGroupServiceAccountAccessLevels
validScopes = slices.Concat(validTokenScopes, ValidPersonalTokenScopes, ValidGroupServiceAccountTokenScopes)
skipFields = append(skipFields, "access_level")
case TokenTypePipelineProjectTrigger:
validAccessLevels = ValidPipelineProjectTriggerAccessLevels
validScopes = []string{}
skipFields = append(skipFields, "access_level", "scopes")
case TokenTypeProjectDeploy:
validAccessLevels = ValidProjectDeployAccessLevels
validScopes = ValidProjectDeployTokenScopes
skipFields = append(skipFields, "access_level")
noEmptyScopes = true
case TokenTypeGroupDeploy:
validAccessLevels = ValidGroupDeployAccessLevels
validScopes = ValidGroupDeployTokenScopes
skipFields = append(skipFields, "access_level")
noEmptyScopes = true
}
// check if all required fields are set
for name, field := range FieldSchemaRoles {
if slices.Contains(skipFields, name) {
continue
}
val, ok, _ := data.GetOkErr(name)
if (tokenType == TokenTypePersonal && name == "access_level") ||
name == "gitlab_revokes_token" {
continue
}
var required = field.Required
if name == "ttl" && !slices.Contains([]TokenType{TokenTypePipelineProjectTrigger}, tokenType) {
required = true
}
if required && !ok {
err = multierror.Append(err, fmt.Errorf("%s: %w", name, ErrFieldRequired))
} else if !required && val == nil {
warnings = append(warnings, fmt.Sprintf("field '%s' is using expected default value of %v", name, val))
}
if required && name == "ttl" {
if role.TTL > DefaultAccessTokenMaxPossibleTTL {
err = multierror.Append(err, fmt.Errorf("ttl = %s [ttl <= max_ttl = %s]: %w", role.TTL.String(), DefaultAccessTokenMaxPossibleTTL, ErrInvalidValue))
}
if role.GitlabRevokesTokens && role.TTL < 24*time.Hour {
err = multierror.Append(err, fmt.Errorf("ttl = %s [%s <= ttl <= %s]: %w", role.TTL, DefaultAccessTokenMinTTL, DefaultAccessTokenMaxPossibleTTL, ErrInvalidValue))
}
if !role.GitlabRevokesTokens && role.TTL < time.Hour {
err = multierror.Append(err, fmt.Errorf("ttl = %s [ttl >= 1h]: %w", role.TTL, ErrInvalidValue))
}
}
}
if !slices.Contains(validAccessLevels, accessLevel.String()) {
err = multierror.Append(err, fmt.Errorf("access_level='%s', should be one of %v: %w", data.Get("access_level").(string), validAccessLevels, ErrFieldInvalidValue))
}
for _, scope := range role.Scopes {
if !slices.Contains(validScopes, scope) {
invalidScopes = append(invalidScopes, scope)
}
}
if len(invalidScopes) > 0 {
err = multierror.Append(err, fmt.Errorf("scopes='%v', should be one or more of '%v': %w", invalidScopes, validScopes, ErrFieldInvalidValue))
}
if noEmptyScopes && len(role.Scopes) == 0 {
err = multierror.Append(err, fmt.Errorf("should be one or more of '%v': %w", validScopes, ErrFieldInvalidValue))
}
if tokenType == TokenTypeUserServiceAccount && (config.Type == TypeSaaS || config.Type == TypeDedicated) {
err = multierror.Append(err, fmt.Errorf("cannot create %s with %s: %w", tokenType, config.Type, ErrInvalidValue))
}
if err != nil {
return logical.ErrorResponse(err.Error()), err
}
lock := locksutil.LockForKey(b.roleLocks, roleName)
lock.Lock()
defer lock.Unlock()
entry, err := logical.StorageEntryJSON(fmt.Sprintf("%s/%s", PathRoleStorage, role.RoleName), role)
if err != nil {
return nil, err
}
if err := req.Storage.Put(ctx, entry); err != nil {
return nil, err
}
event(ctx, b.Backend, "role-write", map[string]string{
"path": "roles",
"role_name": roleName,
"config_name": role.ConfigName,
})
b.Logger().Debug("Role written", "role", roleName)
return &logical.Response{
Data: role.LogicalResponseData(),
Warnings: warnings,
}, nil
}
func (b *Backend) pathRoleExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) {
name := data.Get("role_name").(string)
role, err := getRole(ctx, name, req.Storage)
if err != nil {
if strings.Contains(err.Error(), logical.ErrReadOnly.Error()) {
return false, nil
}
return false, fmt.Errorf("error reading role: %w", err)
}
return role != nil, nil
}
func pathRoles(b *Backend) *framework.Path {
return &framework.Path{
HelpSynopsis: strings.TrimSpace(pathRolesHelpSyn),
HelpDescription: strings.TrimSpace(pathRolesHelpDesc),
Pattern: fmt.Sprintf("%s/%s", PathRoleStorage, framework.GenericNameRegex("role_name")),
Fields: FieldSchemaRoles,
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: operationPrefixGitlabAccessTokens,
OperationSuffix: "role",
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.DeleteOperation: &framework.PathOperation{
Callback: b.pathRolesDelete,
Summary: "Deletes a role",
Responses: map[int][]framework.Response{
http.StatusNoContent: {{
Description: http.StatusText(http.StatusNoContent),
}},
},
},
logical.CreateOperation: &framework.PathOperation{
Callback: b.pathRolesWrite,
Summary: "Creates a new role",
Responses: map[int][]framework.Response{
http.StatusNoContent: {{
Description: http.StatusText(http.StatusNoContent),
}},
},
},
logical.UpdateOperation: &framework.PathOperation{
Callback: b.pathRolesWrite,
Summary: "Updates an existing role",
Responses: map[int][]framework.Response{
http.StatusNoContent: {{
Description: http.StatusText(http.StatusNoContent),
}},
},
},
logical.ReadOperation: &framework.PathOperation{
Callback: b.pathRolesRead,
Summary: "Reads an existing role",
Responses: map[int][]framework.Response{
http.StatusNotFound: {{
Description: http.StatusText(http.StatusNotFound),
}},
http.StatusOK: {{
Fields: FieldSchemaRoles,
}},
},
},
},
ExistenceCheck: b.pathRoleExistenceCheck,
}
}
const (
pathRolesHelpSyn = `Create a role with parameters that are used to generate a various access tokens.`
pathRolesHelpDesc = `
This path allows you to create a role with predefined parameters that will be used to generate tokens for different
access types in GitLab. The role defines the configuration for generating project, group, personal access tokens,
user service accounts, or group service accounts.`
pathListRolesHelpSyn = `Lists existing roles`
pathListRolesHelpDesc = `
This path allows you to list all available roles that have been created within the GitLab Access Tokens Backend.
Each role defines a set of parameters, such as token permissions, scopes, and expiration settings, which are used
when generating access tokens.`
)