-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpath_credentials.go
367 lines (286 loc) · 10.3 KB
/
path_credentials.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
package vault_plugin_secrets_grafana
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/Boostport/vault-plugin-secrets-grafana/client"
"github.com/google/uuid"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/logical"
)
func pathCredentials(b *grafanaBackend) *framework.Path {
return &framework.Path{
Pattern: "creds/" + framework.GenericNameRegex("name"),
Fields: map[string]*framework.FieldSchema{
"name": {
Type: framework.TypeLowerCaseString,
Description: "Name of the role",
Required: true,
},
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.ReadOperation: &framework.PathOperation{
Callback: b.pathCredentialsRead,
},
logical.UpdateOperation: &framework.PathOperation{
Callback: b.pathCredentialsRead,
},
},
HelpSynopsis: pathCredentialsHelpSyn,
HelpDescription: pathCredentialsHelpDesc,
}
}
func (b *grafanaBackend) pathCredentialsRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
roleName := d.Get("name").(string)
return b.createUserCreds(ctx, req, roleName)
}
func (b *grafanaBackend) createUserCreds(ctx context.Context, req *logical.Request, roleName string) (*logical.Response, error) {
role, err := b.getRole(ctx, req.Storage, roleName)
if err != nil {
return nil, fmt.Errorf("error retrieving role: %w", err)
}
if role == nil {
return nil, errors.New("error retrieving role: role is nil")
}
config, err := getConfig(ctx, req.Storage)
if err != nil {
return nil, fmt.Errorf("error reading config: %w", err)
}
if err := role.validate(config.Type); err != nil {
return logical.ErrorResponse("role configuration not compatible with mount configuration: %w", err.Error()), nil
}
token, err := b.createToken(ctx, req.Storage, config.Type, role)
if err != nil {
return nil, err
}
// The response is divided into two objects (1) internal data and (2) data.
// If you want to reference any information in your code, you need to
// store it in internal data!
resp := b.Secret(grafanaTokenType).Response(map[string]interface{}{
"token": token.Token,
}, map[string]interface{}{
"is_cloud": token.IsCloud,
"stack": token.Stack,
"region": token.Region,
"access_policy_id": token.AccessPolicyID,
"service_account_id": token.ServiceAccountID,
"vault_role": roleName,
})
if role.TTL > 0 {
resp.Secret.TTL = role.TTL
}
if role.MaxTTL > 0 {
resp.Secret.MaxTTL = role.MaxTTL
}
return resp, nil
}
func (b *grafanaBackend) createToken(ctx context.Context, s logical.Storage, configType string, roleEntry *grafanaRoleEntry) (*grafanaToken, error) {
c, err := b.getClient(ctx, s)
if err != nil {
return nil, err
}
credentialName := fmt.Sprintf("vault-%s", uuid.New())
if configType == GrafanaCloudType {
if roleEntry.Type == roleCloudAccessPolicy {
return createCloudAccessPolicyToken(c, credentialName, roleEntry)
} else if roleEntry.Type == roleGrafanaServiceAccount {
return createCloudServiceAccountToken(c, credentialName, roleEntry)
}
} else if configType == GrafanaType {
return createServiceAccountToken(c, credentialName, roleEntry)
}
return nil, errors.New("cannot create token due to inconsistent mount configuration and role configuration")
}
func createCloudAccessPolicyToken(c *client.Grafana, credentialName string, roleEntry *grafanaRoleEntry) (*grafanaToken, error) {
cloudAccessPolicyInput := client.CreateCloudAccessPolicyInput{
Name: credentialName,
DisplayName: credentialName,
Scopes: roleEntry.Scopes,
}
if roleEntry.Realms != "" {
realms, err := realmsStringToStruct(roleEntry.Realms)
if err != nil {
return nil, fmt.Errorf("error converting realms string to struct: %w", err)
}
cloudAccessPolicyInput.Realms = realms
}
if len(roleEntry.AllowedSubnets) > 0 {
cloudAccessPolicyInput.Conditions.AllowedSubnets = roleEntry.AllowedSubnets
}
cloudAccessPolicy, err := c.CreateCloudAccessPolicy(roleEntry.Region, cloudAccessPolicyInput)
if err != nil {
return nil, fmt.Errorf("error creating cloud access policy: %w", err)
}
token, err := c.CreateCloudAccessPolicyToken(roleEntry.Region, client.CreateCloudAccessPolicyTokenInput{
AccessPolicyID: cloudAccessPolicy.ID,
Name: credentialName,
DisplayName: credentialName,
})
if err != nil {
err := c.DeleteCloudAccessPolicy(roleEntry.Region, cloudAccessPolicy.ID)
if err != nil {
return nil, fmt.Errorf("error deleting cloud access policy after error creating token: %w", err)
}
return nil, fmt.Errorf("error creating cloud access policy token: %w", err)
}
return &grafanaToken{
IsCloud: true,
Token: token.Token,
Region: roleEntry.Region,
AccessPolicyID: cloudAccessPolicy.ID,
}, nil
}
func createCloudServiceAccountToken(c *client.Grafana, credentialName string, roleEntry *grafanaRoleEntry) (*grafanaToken, error) {
role := "None"
if roleEntry.Role != "" {
role = roleEntry.Role
}
serviceAccount, err := c.CreateGrafanaServiceAccountFromCloud(roleEntry.Stack, client.CreateServiceAccountInput{
Name: credentialName,
Role: role,
})
if err != nil {
return nil, fmt.Errorf("error creating service account: %w", err)
}
if len(roleEntry.RBACRoles) > 0 {
instanceClient, cleanup, err := c.CreateTemporaryStackGrafanaClient(roleEntry.Stack, "vault-temp-service-account-", 5*time.Minute)
if err != nil {
err := c.DeleteGrafanaServiceAccountFromCloud(roleEntry.Stack, serviceAccount.ID)
if err != nil {
return nil, fmt.Errorf("error deleting service account after error creating temporary client: %w", err)
}
return nil, fmt.Errorf("error creating temporary client: %w", err)
}
defer cleanup()
roleUIDs, err := customRBACRoleNamesToIDs(instanceClient, roleEntry.RBACRoles)
if err != nil {
err := c.DeleteGrafanaServiceAccountFromCloud(roleEntry.Stack, serviceAccount.ID)
if err != nil {
return nil, fmt.Errorf("error deleting service account after error converting role names to IDs: %w", err)
}
return nil, fmt.Errorf("error converting role names to IDs: %w", err)
}
err = instanceClient.SetServiceAccountRoleAssignments(client.ServiceAccountRoleAssignmentsInput{
ServiceAccountID: serviceAccount.ID,
RoleUIDs: roleUIDs,
})
if err != nil {
err := c.DeleteGrafanaServiceAccountFromCloud(roleEntry.Stack, serviceAccount.ID)
if err != nil {
return nil, fmt.Errorf("error deleting service account after error setting role assignments: %w", err)
}
return nil, fmt.Errorf("error setting service account role assignments: %w", err)
}
}
token, err := c.CreateGrafanaServiceAccountTokenFromCloud(roleEntry.Stack, client.CreateServiceAccountTokenInput{
Name: credentialName,
ServiceAccountID: serviceAccount.ID,
})
if err != nil {
err := c.DeleteGrafanaServiceAccountFromCloud(roleEntry.Stack, serviceAccount.ID)
if err != nil {
return nil, fmt.Errorf("error deleting service account after error creating token: %w", err)
}
return nil, fmt.Errorf("error creating service account token: %w", err)
}
return &grafanaToken{
IsCloud: true,
Token: token.Key,
Stack: roleEntry.Stack,
ServiceAccountID: serviceAccount.ID,
}, nil
}
func createServiceAccountToken(c *client.Grafana, credentialName string, roleEntry *grafanaRoleEntry) (*grafanaToken, error) {
role := "None"
if roleEntry.Role != "" {
role = roleEntry.Role
}
serviceAccount, err := c.CreateServiceAccount(client.CreateServiceAccountInput{
Name: credentialName,
Role: role,
})
if err != nil {
return nil, fmt.Errorf("error creating service account: %w", err)
}
if len(roleEntry.RBACRoles) > 0 {
roleUIDs, err := customRBACRoleNamesToIDs(c, roleEntry.RBACRoles)
if err != nil {
err := deleteServiceAccount(c, serviceAccount.ID)
if err != nil {
return nil, fmt.Errorf("error deleting service account after error converting role names to IDs: %w", err)
}
return nil, fmt.Errorf("error converting role names to IDs: %w", err)
}
err = c.SetServiceAccountRoleAssignments(client.ServiceAccountRoleAssignmentsInput{
ServiceAccountID: serviceAccount.ID,
RoleUIDs: roleUIDs,
})
if err != nil {
err := deleteServiceAccount(c, serviceAccount.ID)
if err != nil {
return nil, fmt.Errorf("error deleting service account after error setting role assignments: %w", err)
}
return nil, fmt.Errorf("error setting service account role assignments: %w", err)
}
}
token, err := c.CreateServiceAccountToken(client.CreateServiceAccountTokenInput{
Name: credentialName,
ServiceAccountID: serviceAccount.ID,
})
if err != nil {
err := deleteServiceAccount(c, serviceAccount.ID)
if err != nil {
return nil, fmt.Errorf("error deleting service account after error creating token: %w", err)
}
return nil, fmt.Errorf("error creating service account token: %w", err)
}
return &grafanaToken{
IsCloud: false,
Token: token.Key,
ServiceAccountID: serviceAccount.ID,
}, nil
}
func deleteServiceAccount(c *client.Grafana, serviceAccountID int64) error {
err := c.DeleteServiceAccount(serviceAccountID)
if err != nil {
return fmt.Errorf("error deleting service account: %w", err)
}
return nil
}
func customRBACRoleNamesToIDs(c *client.Grafana, roleNames []string) ([]string, error) {
var roleIDs []string
allRoles, err := c.GetAllRoles()
if err != nil {
return nil, fmt.Errorf("error getting all roles: %w", err)
}
for _, roleName := range roleNames {
found := false
for _, role := range allRoles {
if role.Name == roleName && role.UID != "" {
roleIDs = append(roleIDs, role.UID)
found = true
break
}
}
if !found {
return nil, fmt.Errorf("rbac role does not exist: %s", roleName)
}
}
return roleIDs, nil
}
func realmsStringToStruct(realms string) ([]client.CloudAccessPolicyRealm, error) {
var result []client.CloudAccessPolicyRealm
if err := json.Unmarshal([]byte(realms), &result); err != nil {
return result, fmt.Errorf("unable to unmarshall realms string: %w", err)
}
return result, nil
}
const pathCredentialsHelpSyn = `
Generate a Grafana Cloud or Grafana token from a specific Vault role.
`
const pathCredentialsHelpDesc = `
This path generates a Grafana Cloud or Grafana tokens
based on a particular role.
`