-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathpath_token_role.go
212 lines (189 loc) · 7.73 KB
/
path_token_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
package gitlab
import (
"cmp"
"context"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/helper/locksutil"
"github.com/hashicorp/vault/sdk/logical"
)
const (
pathTokenRolesHelpSyn = `Generate an access token based on the specified role`
pathTokenRolesHelpDesc = `
This path allows you to generate an access token based on a predefined role. The role must be created beforehand in
the ^roles/(?P<role_name>\w(([\w-.@]+)?\w)?)$ path, where its parameters, such as token permissions, scopes, and
expiration, are defined. When you request an access token through this path, Vault will use the predefined
role's parameters to create a new access token.`
PathTokenRoleStorage = "token"
)
var (
FieldSchemaTokenRole = map[string]*framework.FieldSchema{
"role_name": {
Type: framework.TypeString,
Description: "Role name",
Required: true,
},
}
)
func (b *Backend) pathTokenRoleCreate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
var resp *logical.Response
var err error
var role *EntryRole
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 nil, fmt.Errorf("error getting role: %w", err)
}
if role == nil {
return nil, fmt.Errorf("%s: %w", roleName, ErrRoleNotFound)
}
b.Logger().Debug("Creating token for role", "role_name", roleName, "token_type", role.TokenType.String())
defer b.Logger().Debug("Created token for role", "role_name", roleName, "token_type", role.TokenType.String())
var name string
var token *EntryToken
var expiresAt time.Time
var startTime = TimeFromContext(ctx).UTC()
name, err = TokenName(role)
if err != nil {
return nil, fmt.Errorf("error generating token name: %w", err)
}
var client Client
var gitlabRevokesTokens = role.GitlabRevokesTokens
var vaultRevokesTokens = !role.GitlabRevokesTokens
_, expiresAt, _ = calculateGitlabTTL(role.TTL, startTime)
client, err = b.getClient(ctx, req.Storage, role.ConfigName)
if err != nil {
return nil, err
}
switch role.TokenType {
case TokenTypeGroup:
b.Logger().Debug("Creating group access token for role", "path", role.Path, "name", name, "expiresAt", expiresAt, "scopes", role.Scopes, "accessLevel", role.AccessLevel)
token, err = client.CreateGroupAccessToken(ctx, role.Path, name, expiresAt, role.Scopes, role.AccessLevel)
case TokenTypeProject:
b.Logger().Debug("Creating project access token for role", "path", role.Path, "name", name, "expiresAt", expiresAt, "scopes", role.Scopes, "accessLevel", role.AccessLevel)
token, err = client.CreateProjectAccessToken(ctx, role.Path, name, expiresAt, role.Scopes, role.AccessLevel)
case TokenTypePersonal:
var userId int
userId, err = client.GetUserIdByUsername(ctx, role.Path)
if err == nil {
b.Logger().Debug("Creating personal access token for role", "path", role.Path, "userId", userId, "name", name, "expiresAt", expiresAt, "scopes", role.Scopes)
token, err = client.CreatePersonalAccessToken(ctx, role.Path, userId, name, expiresAt, role.Scopes)
}
case TokenTypeUserServiceAccount:
var userId int
if userId, err = client.GetUserIdByUsername(ctx, role.Path); err == nil {
b.Logger().Debug("Creating user service account access token for role", "path", role.Path, "userId", userId, "name", name, "expiresAt", expiresAt, "scopes", role.Scopes)
token, err = client.CreateUserServiceAccountAccessToken(ctx, role.Path, userId, name, expiresAt, role.Scopes)
}
case TokenTypeGroupServiceAccount:
var serviceAccount, groupId string
{
parts := strings.Split(role.Path, "/")
groupId, serviceAccount = parts[0], parts[1]
}
var userId int
if userId, err = client.GetUserIdByUsername(ctx, serviceAccount); err == nil {
b.Logger().Debug("Creating group service account access token for role", "path", role.Path, "groupId", groupId, "userId", userId, "name", name, "expiresAt", expiresAt, "scopes", role.Scopes)
token, err = client.CreateGroupServiceAccountAccessToken(ctx, role.Path, groupId, userId, name, expiresAt, role.Scopes)
}
case TokenTypeProjectDeploy:
var projectId int
if projectId, err = client.GetProjectIdByPath(ctx, role.Path); err == nil {
token, err = client.CreateProjectDeployToken(ctx, role.Path, projectId, name, &expiresAt, role.Scopes)
}
case TokenTypeGroupDeploy:
var groupId int
if groupId, err = client.GetGroupIdByPath(ctx, role.Path); err == nil {
token, err = client.CreateGroupDeployToken(ctx, role.Path, groupId, name, &expiresAt, role.Scopes)
}
case TokenTypePipelineProjectTrigger:
var projectId int
if projectId, err = client.GetProjectIdByPath(ctx, role.Path); err == nil {
token, err = client.CreatePipelineProjectTriggerAccessToken(ctx, role.Path, name, projectId, name, &expiresAt)
}
default:
return logical.ErrorResponse("invalid token type"), fmt.Errorf("%s: %w", role.TokenType.String(), ErrUnknownTokenType)
}
if err != nil || token == nil {
return nil, cmp.Or(err, fmt.Errorf("%w: token is nil", ErrNilValue))
}
token.ConfigName = cmp.Or(role.ConfigName, DefaultConfigName)
token.RoleName = role.RoleName
token.GitlabRevokesToken = role.GitlabRevokesTokens
if vaultRevokesTokens {
// since vault is controlling the expiry we need to override here
// and make the expiry time accurate
expiresAt = startTime.Add(role.TTL)
token.ExpiresAt = &expiresAt
}
var secretData, secretInternal = token.SecretResponse()
resp = b.Secret(SecretAccessTokenType).Response(secretData, secretInternal)
resp.Secret.MaxTTL = role.TTL
resp.Secret.TTL = role.TTL
resp.Secret.IssueTime = startTime
if gitlabRevokesTokens {
resp.Secret.TTL = token.ExpiresAt.Sub(*token.CreatedAt)
}
event(ctx, b.Backend, "token-write", map[string]string{
"path": fmt.Sprintf("%s/%s", PathRoleStorage, roleName),
"name": name,
"parent_id": role.Path,
"ttl": resp.Secret.TTL.String(),
"role_name": roleName,
"token_id": strconv.Itoa(token.TokenID),
"token_type": role.TokenType.String(),
"scopes": strings.Join(role.Scopes, ","),
"access_level": role.AccessLevel.String(),
"config_name": token.ConfigName,
})
return resp, nil
}
func pathTokenRoles(b *Backend) *framework.Path {
return &framework.Path{
HelpSynopsis: strings.TrimSpace(pathTokenRolesHelpSyn),
HelpDescription: strings.TrimSpace(pathTokenRolesHelpDesc),
Pattern: fmt.Sprintf("%s/%s", PathTokenRoleStorage, framework.GenericNameRegex("role_name")),
Fields: FieldSchemaTokenRole,
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: operationPrefixGitlabAccessTokens,
OperationSuffix: "generate",
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.ReadOperation: &framework.PathOperation{
Callback: b.pathTokenRoleCreate,
Summary: "Create an access token based on a predefined role",
DisplayAttrs: &framework.DisplayAttributes{
OperationVerb: "generate",
OperationSuffix: "credentials",
},
Responses: map[int][]framework.Response{
http.StatusOK: {{
Description: http.StatusText(http.StatusOK),
Fields: fieldSchemaAccessTokens,
}},
},
},
logical.UpdateOperation: &framework.PathOperation{
Callback: b.pathTokenRoleCreate,
Summary: "Create an access token based on a predefined role",
DisplayAttrs: &framework.DisplayAttributes{
OperationSuffix: "credentials-with-parameters",
OperationVerb: "generate-with-parameters",
},
Responses: map[int][]framework.Response{
http.StatusOK: {{
Description: http.StatusText(http.StatusOK),
Fields: fieldSchemaAccessTokens,
}},
},
},
},
}
}