-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpath_roles.go
304 lines (265 loc) · 9.76 KB
/
path_roles.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
package ibmcloudsecrets
import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/helper/strutil"
"github.com/hashicorp/vault/sdk/logical"
)
// pathsRoles returns the path configurations for the CRUD operations on roles
func pathsRoles(b *ibmCloudSecretBackend) []*framework.Path {
p := []*framework.Path{
{
Pattern: "roles/?",
Operations: map[logical.Operation]framework.OperationHandler{
logical.ListOperation: &framework.PathOperation{
Callback: b.pathRoleList,
},
},
HelpSynopsis: strings.TrimSpace(roleListHelpSyn),
HelpDescription: strings.TrimSpace(roleListHelpDesc),
},
{
Pattern: "roles/" + framework.GenericNameRegex(nameField),
Fields: map[string]*framework.FieldSchema{
nameField: {
Type: framework.TypeString,
Description: "Name of the role.",
},
accessGroupIDsField: {
Type: framework.TypeCommaStringSlice,
Description: `Comma-separated list of IAM Access Group ids that the generated service ID will be added to.`,
},
serviceIDField: {
Type: framework.TypeString,
Description: `A service ID to generate API keys for.`,
},
ttlField: {
Type: framework.TypeDurationSecond,
Description: "Default lease for generated credentials. If not set or set to 0, will use system default.",
},
maxTTLField: {
Type: framework.TypeDurationSecond,
Description: "Maximum lifetime of generated credentials. If not set or set to 0, will use system default.",
},
},
ExistenceCheck: b.pathRoleExistenceCheck(nameField),
Operations: map[logical.Operation]framework.OperationHandler{
logical.CreateOperation: &framework.PathOperation{
Callback: b.pathRoleCreateUpdate,
},
logical.UpdateOperation: &framework.PathOperation{
Callback: b.pathRoleCreateUpdate,
},
logical.ReadOperation: &framework.PathOperation{
Callback: b.pathRoleRead,
},
logical.DeleteOperation: &framework.PathOperation{
Callback: b.pathRoleDelete,
},
},
HelpSynopsis: strings.TrimSpace(roleHelpSyn),
HelpDescription: strings.TrimSpace(roleHelpDesc),
},
}
return p
}
type ibmCloudRole struct {
AccessGroupIDs []string `json:"access_group_ids"`
ServiceID string `json:"service_id"`
TTL time.Duration `json:"ttl"`
MaxTTL time.Duration `json:"max_ttl"`
BindingHash string `json:"binding_hash"`
}
func getStringHash(bindingsRaw string) string {
ssum := sha256.Sum256([]byte(bindingsRaw)[:])
return base64.StdEncoding.EncodeToString(ssum[:])
}
// role takes a storage backend and the name and returns the role's storage
// entry
func getRole(ctx context.Context, s logical.Storage, name string) (*ibmCloudRole, error) {
raw, err := s.Get(ctx, fmt.Sprintf("%s/%s", rolesStoragePath, name))
if err != nil {
return nil, err
}
if raw == nil {
return nil, nil
}
role := new(ibmCloudRole)
if err := json.Unmarshal(raw.Value, role); err != nil {
return nil, err
}
return role, nil
}
// pathRoleExistenceCheck returns whether the role with the given name exists or not.
func (b *ibmCloudSecretBackend) pathRoleExistenceCheck(rolesetFieldName string) framework.ExistenceFunc {
return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (bool, error) {
role, err := getRole(ctx, req.Storage, d.Get(rolesetFieldName).(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 *ibmCloudSecretBackend) pathRoleList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roles, err := req.Storage.List(ctx, rolesStoragePath+"/")
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 *ibmCloudSecretBackend) pathRoleRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roleName := data.Get(nameField).(string)
if roleName == "" {
return logical.ErrorResponse("missing name"), nil
}
role, err := getRole(ctx, req.Storage, roleName)
if err != nil {
return nil, err
}
if role == nil {
return nil, nil
}
d := map[string]interface{}{
accessGroupIDsField: role.AccessGroupIDs,
serviceIDField: role.ServiceID,
ttlField: role.TTL / time.Second,
maxTTLField: role.MaxTTL / time.Second,
}
return &logical.Response{
Data: d,
}, nil
}
// pathRoleDelete removes the role from storage
func (b *ibmCloudSecretBackend) pathRoleDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roleName := data.Get(nameField).(string)
if roleName == "" {
return logical.ErrorResponse("role name required"), nil
}
// Delete the role itself
if err := req.Storage.Delete(ctx, fmt.Sprintf("%s/%s", rolesStoragePath, 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 *ibmCloudSecretBackend) pathRoleCreateUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
config, resp := b.getConfig(ctx, req.Storage)
if resp != nil {
return resp, nil
}
roleName := d.Get(nameField).(string)
if roleName == "" {
return logical.ErrorResponse("missing role name"), nil
}
// Check if the role already exists
role, err := getRole(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(ibmCloudRole)
}
accessGroups, ok := d.GetOk(accessGroupIDsField)
if ok {
role.AccessGroupIDs = accessGroups.([]string)
role.BindingHash = getStringHash(fmt.Sprintf("%s", role.AccessGroupIDs))
}
serviceID, ok := d.GetOk(serviceIDField)
if ok {
role.ServiceID = serviceID.(string)
role.BindingHash = getStringHash(role.ServiceID)
}
if len(role.AccessGroupIDs) == 0 && len(role.ServiceID) == 0 {
return logical.ErrorResponse("either a service ID or a non empty access group list are required"), nil
}
if len(role.AccessGroupIDs) != 0 && len(role.ServiceID) != 0 {
if req.Operation == logical.UpdateOperation {
return logical.ErrorResponse("to change the role binding between service IDs and access groups you must explicitly set the unused binding to the empty string"), nil
}
return logical.ErrorResponse("either an access group list or service ID should be provided, not both"), nil
}
if len(role.AccessGroupIDs) > maxGroupsPerRole {
return logical.ErrorResponse(fmt.Sprintf("the maximum number of access groups per role is: %d", maxGroupsPerRole)), nil
}
if strutil.StrListContains(role.AccessGroupIDs, "AccessGroupId-PublicAccess") {
return logical.ErrorResponse("the AccessGroupId-PublicAccess access group is not allowed on roles"), nil
}
// load and validate TTLs
if ttlRaw, ok := d.GetOk(ttlField); ok {
role.TTL = time.Duration(ttlRaw.(int)) * time.Second
} else if req.Operation == logical.CreateOperation {
role.TTL = time.Duration(d.Get(ttlField).(int)) * time.Second
}
if maxTTLRaw, ok := d.GetOk(maxTTLField); ok {
role.MaxTTL = time.Duration(maxTTLRaw.(int)) * time.Second
} else if req.Operation == logical.CreateOperation {
role.MaxTTL = time.Duration(d.Get(maxTTLField).(int)) * time.Second
}
if role.MaxTTL != 0 && role.TTL > role.MaxTTL {
return logical.ErrorResponse("ttl cannot be greater than max_ttl"), nil
}
adminToken, err := b.getAdminToken(ctx, req.Storage)
if err != nil {
b.Logger().Error("error obtaining the token for the configured API key", "error", err)
return nil, err
}
iam, resp := b.getIAMHelper(ctx, req.Storage)
if resp != nil {
b.Logger().Error("failed to retrieve an IAM helper", "error", resp.Error())
return resp, nil
}
for _, group := range role.AccessGroupIDs {
resp := iam.VerifyAccessGroupExists(adminToken, group, config.Account)
if resp != nil {
return resp, nil
}
}
if len(role.ServiceID) != 0 {
_, resp := iam.CheckServiceIDAccount(adminToken, role.ServiceID, config.Account)
if resp != nil {
return resp, nil
}
}
// Store the entry.
entry, err := logical.StorageEntryJSON(fmt.Sprintf("%s/%s", rolesStoragePath, 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 nil, nil
}
const roleHelpSyn = `Manage the Vault roles used to generate IBM Cloud credentials.`
const roleHelpDesc = `
This path allows you to read and write roles that are used to generate IBM Cloud login
credentials. These roles are associated with one or more access groups, which are used to
control permissions to IBM Cloud resources.
If the backend is mounted at "ibmcloud", you would create a Vault role at "ibmcloud/roles/my_role",
and request credentials from "ibmcloud/creds/my_role".
Each Vault role is configured with the standard ttl parameters and one or more access groups
to make the service ID member of. During the Vault role creation, all access groups specified
will be fetched and verified, and therefore must exist for the request
to succeed. When a user requests credentials against the Vault role, a new
service ID and API key will be created. The service ID will be added to the configured
access groups.
`
const roleListHelpSyn = `Lists all the roles registered with the backend.`
const roleListHelpDesc = `List existing roles by name.`