-
Notifications
You must be signed in to change notification settings - Fork 0
/
path_roles.go
359 lines (301 loc) · 10.2 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
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
package vault_plugin_secrets_grafana
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/logical"
)
const (
roleCloudAccessPolicy = "cloud_access_policy"
roleGrafanaServiceAccount = "grafana_service_account"
)
type realm struct {
RealmType string `json:"type"`
Identifier string `json:"identifier"`
LabelPolicies []struct {
Selector string `json:"selector"`
} `json:"labelPolicies"`
}
type grafanaRoleEntry struct {
Type string `json:"type"` // Set when configuration type is "cloud". Should be "cloud_access_policy" or "grafana_service_account"
Stack string `json:"stack"` // For Grafana service accounts where configuration type is "cloud"
Region string `json:"region"` // For Grafana Cloud access policies
Scopes []string `json:"scopes"` // For Grafana Cloud access policies
Realms string `json:"realms"` // For Grafana Cloud access policies
AllowedSubnets []string `json:"allowed_subnets"` // For Grafana Cloud access policies
Role string `json:"role"` // For Grafana service accounts
RBACRoles []string `json:"rbac_roles"` // For Grafana service accounts
TTL time.Duration `json:"ttl"`
MaxTTL time.Duration `json:"max_ttl"`
}
func (r *grafanaRoleEntry) validate(configType string) error {
if configType == GrafanaCloudType {
if r.Type != roleCloudAccessPolicy && r.Type != roleGrafanaServiceAccount {
return fmt.Errorf(`type must be "%s" or "%s"`, roleCloudAccessPolicy, roleGrafanaServiceAccount)
}
if r.Type == roleGrafanaServiceAccount && r.Stack == "" {
return fmt.Errorf(`stack_id must be set when type is "%s"`, roleGrafanaServiceAccount)
}
if r.Type == roleCloudAccessPolicy {
if r.Region == "" {
return fmt.Errorf(`region must be set when type is "%s"`, roleCloudAccessPolicy)
}
if len(r.Scopes) <= 0 {
return fmt.Errorf(`at least one scope must be set when type is "%s"`, roleCloudAccessPolicy)
}
var realms []realm
if err := json.Unmarshal([]byte(r.Realms), &realms); err != nil {
return fmt.Errorf("realms must be a valid JSON string")
}
if len(realms) <= 0 {
return fmt.Errorf(`at least one realm must be set when type is "%s"`, roleCloudAccessPolicy)
}
}
}
return nil
}
func (r *grafanaRoleEntry) toResponseData() map[string]interface{} {
respData := map[string]interface{}{
"type": r.Type,
"stack": r.Stack,
"region": r.Region,
"scopes": r.Scopes,
"realms": r.Realms,
"role": r.Role,
"rbac_roles": r.RBACRoles,
"ttl": r.TTL.Seconds(),
"max_ttl": r.MaxTTL.Seconds(),
}
return respData
}
func pathRole(b *grafanaBackend) []*framework.Path {
return []*framework.Path{
{
Pattern: "roles/" + framework.GenericNameRegex("name"),
Fields: map[string]*framework.FieldSchema{
"name": {
Type: framework.TypeString,
Description: "Name of the role",
Required: true,
},
"type": {
Type: framework.TypeString,
Description: `The type of Grafana Cloud credentials generated by the role, "cloud_access_policy" or "grafana_service_account"`,
Required: false,
},
"stack": {
Type: framework.TypeString,
Description: "The stack slug of the Grafana Cloud instance to generate credentials for",
Required: false,
},
"region": {
Type: framework.TypeString,
Description: "The region where the Grafana Cloud API is deployed, generally where the stack is deployed",
Required: false,
},
"scopes": {
Type: framework.TypeCommaStringSlice,
Description: "The scopes to grant to the Grafana Cloud access policy",
Required: false,
},
"realms": {
Type: framework.TypeString,
Description: "The realms to grant to the Grafana Cloud access policy",
Required: false,
},
"allowed_subnets": {
Type: framework.TypeCommaStringSlice,
Description: "The allowed subnets to grant to the Grafana Cloud access policy",
Required: false,
},
"role": {
Type: framework.TypeString,
Description: "The role to grant to the Grafana service account",
Required: false,
},
"rbac_roles": {
Type: framework.TypeCommaStringSlice,
Description: "The RBAC roles to grant to the Grafana service account",
Required: false,
},
"ttl": {
Type: framework.TypeDurationSecond,
Description: "Default lease for generated credentials. If not set or set to 0, will use system default.",
},
"max_ttl": {
Type: framework.TypeDurationSecond,
Description: "Maximum time for role. If not set or set to 0, will use system default.",
},
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.ReadOperation: &framework.PathOperation{
Callback: b.pathRolesRead,
},
logical.CreateOperation: &framework.PathOperation{
Callback: b.pathRolesWrite,
},
logical.UpdateOperation: &framework.PathOperation{
Callback: b.pathRolesWrite,
},
logical.DeleteOperation: &framework.PathOperation{
Callback: b.pathRolesDelete,
},
},
ExistenceCheck: b.pathRoleExistenceCheck,
HelpSynopsis: pathRoleHelpSynopsis,
HelpDescription: pathRoleHelpDescription,
},
{
Pattern: "roles/?$",
Operations: map[logical.Operation]framework.OperationHandler{
logical.ListOperation: &framework.PathOperation{
Callback: b.pathRolesList,
},
},
HelpSynopsis: pathRoleListHelpSynopsis,
HelpDescription: pathRoleListHelpDescription,
},
}
}
func (b *grafanaBackend) pathRoleExistenceCheck(ctx context.Context, req *logical.Request, d *framework.FieldData) (bool, error) {
entry, err := b.getRole(ctx, req.Storage, d.Get("name").(string))
if err != nil {
return false, err
}
return entry != nil, nil
}
func (b *grafanaBackend) pathRolesList(ctx context.Context, req *logical.Request, _ *framework.FieldData) (*logical.Response, error) {
entries, err := req.Storage.List(ctx, "roles/")
if err != nil {
return nil, err
}
return logical.ListResponse(entries), nil
}
func (b *grafanaBackend) pathRolesRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
entry, err := b.getRole(ctx, req.Storage, d.Get("name").(string))
if err != nil {
return nil, err
}
if entry == nil {
return nil, nil
}
return &logical.Response{
Data: entry.toResponseData(),
}, nil
}
func (b *grafanaBackend) pathRolesWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
name, ok := d.GetOk("name")
if !ok {
return logical.ErrorResponse("missing role name"), nil
}
config, err := getConfig(ctx, req.Storage)
if err != nil {
return nil, err
}
if config == nil {
return nil, fmt.Errorf("cannot write role when backend configuration is unset")
}
roleEntry, err := b.getRole(ctx, req.Storage, name.(string))
if err != nil {
return nil, err
}
if roleEntry == nil {
roleEntry = &grafanaRoleEntry{}
}
createOperation := req.Operation == logical.CreateOperation
if roleType, ok := d.GetOk("type"); ok {
roleEntry.Type = roleType.(string)
}
if stack, ok := d.GetOk("stack"); ok {
roleEntry.Stack = stack.(string)
}
if region, ok := d.GetOk("region"); ok {
roleEntry.Region = region.(string)
}
if roleType, ok := d.GetOk("scopes"); ok {
roleEntry.Scopes = roleType.([]string)
}
if roleType, ok := d.GetOk("realms"); ok {
roleEntry.Realms = roleType.(string)
}
if roleType, ok := d.GetOk("allowed_subnets"); ok {
roleEntry.AllowedSubnets = roleType.([]string)
}
if roleType, ok := d.GetOk("role"); ok {
roleEntry.Role = roleType.(string)
}
if roleType, ok := d.GetOk("rbac_roles"); ok {
roleEntry.RBACRoles = roleType.([]string)
}
if err := roleEntry.validate(config.Type); err != nil {
return logical.ErrorResponse(err.Error()), nil
}
if ttlRaw, ok := d.GetOk("ttl"); ok {
roleEntry.TTL = time.Duration(ttlRaw.(int)) * time.Second
} else if createOperation {
roleEntry.TTL = time.Duration(d.Get("ttl").(int)) * time.Second
}
if maxTTLRaw, ok := d.GetOk("max_ttl"); ok {
roleEntry.MaxTTL = time.Duration(maxTTLRaw.(int)) * time.Second
} else if createOperation {
roleEntry.MaxTTL = time.Duration(d.Get("max_ttl").(int)) * time.Second
}
if roleEntry.MaxTTL != 0 && roleEntry.TTL > roleEntry.MaxTTL {
return logical.ErrorResponse("ttl cannot be greater than max_ttl"), nil
}
if err := setRole(ctx, req.Storage, name.(string), roleEntry); err != nil {
return nil, err
}
return nil, nil
}
func (b *grafanaBackend) pathRolesDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
roleName := d.Get("name").(string)
if roleName == "" {
return logical.ErrorResponse("missing role"), nil
}
err := req.Storage.Delete(ctx, "roles/"+roleName)
if err != nil {
return nil, fmt.Errorf("error deleting grafana role: %w", err)
}
return nil, nil
}
func setRole(ctx context.Context, s logical.Storage, name string, roleEntry *grafanaRoleEntry) error {
entry, err := logical.StorageEntryJSON("roles/"+name, roleEntry)
if err != nil {
return err
}
if entry == nil {
return fmt.Errorf("failed to create storage entry for role")
}
if err := s.Put(ctx, entry); err != nil {
return err
}
return nil
}
func (b *grafanaBackend) getRole(ctx context.Context, s logical.Storage, name string) (*grafanaRoleEntry, error) {
if name == "" {
return nil, fmt.Errorf("missing role name")
}
entry, err := s.Get(ctx, "roles/"+name)
if err != nil {
return nil, err
}
if entry == nil {
return nil, nil
}
var role grafanaRoleEntry
if err := entry.DecodeJSON(&role); err != nil {
return nil, err
}
return &role, nil
}
const (
pathRoleHelpSynopsis = `Manages the Vault role for generating Grafana Cloud and Grafana credentials.`
pathRoleHelpDescription = `
This path allows you to read and write roles used to generate Grafana Cloud and Grafana credentials.
`
pathRoleListHelpSynopsis = `List the existing roles in Grafana backend`
pathRoleListHelpDescription = `Roles will be listed by the role name.`
)