-
Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathresource_elasticsearch_opendistro_role.go
359 lines (322 loc) · 10.2 KB
/
resource_elasticsearch_opendistro_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
package es
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/olivere/elastic/uritemplates"
elastic7 "github.com/olivere/elastic/v7"
)
func resourceElasticsearchOpenDistroRole() *schema.Resource {
return &schema.Resource{
Create: resourceElasticsearchOpenDistroRoleCreate,
Read: resourceElasticsearchOpenDistroRoleRead,
Update: resourceElasticsearchOpenDistroRoleUpdate,
Delete: resourceElasticsearchOpenDistroRoleDelete,
Schema: map[string]*schema.Schema{
"role_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"cluster_permissions": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"index_permissions": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"index_patterns": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Set: schema.HashString,
},
"document_level_security": {
Type: schema.TypeString,
Optional: true,
},
"fls": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Set: schema.HashString,
Deprecated: "`fls` has been deprecated, please use `field_level_security`",
},
"field_level_security": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Set: schema.HashString,
},
"masked_fields": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Set: schema.HashString,
},
"allowed_actions": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Set: schema.HashString,
},
},
},
Set: indexPermissionsHash,
},
"tenant_permissions": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"tenant_patterns": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Set: schema.HashString,
},
"allowed_actions": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Set: schema.HashString,
},
},
},
Set: tenantPermissionsHash,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
},
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
}
}
func resourceElasticsearchOpenDistroRoleCreate(d *schema.ResourceData, m interface{}) error {
if _, err := resourceElasticsearchPutOpenDistroRole(d, m); err != nil {
log.Printf("[INFO] Failed to create OpenDistroRole: %+v", err)
return err
}
name := d.Get("role_name").(string)
d.SetId(name)
return resourceElasticsearchOpenDistroRoleRead(d, m)
}
func resourceElasticsearchOpenDistroRoleRead(d *schema.ResourceData, m interface{}) error {
res, err := resourceElasticsearchGetOpenDistroRole(d.Id(), m)
if err != nil {
if elastic7.IsNotFound(err) {
log.Printf("[WARN] OpenDistroRole (%s) not found, removing from state", d.Id())
d.SetId("")
return nil
}
return err
}
if err := d.Set("role_name", d.Id()); err != nil {
return fmt.Errorf("error setting role_name: %s", err)
}
if err := d.Set("tenant_permissions", flattenTenantPermissions(res.TenantPermissions)); err != nil {
return fmt.Errorf("error setting tenant_permissions: %s", err)
}
if err := d.Set("cluster_permissions", res.ClusterPermissions); err != nil {
return fmt.Errorf("error setting cluster_permissions: %s", err)
}
if err := d.Set("index_permissions", flattenIndexPermissions(res.IndexPermissions, d)); err != nil {
return fmt.Errorf("error setting index_permissions: %s", err)
}
if err := d.Set("description", res.Description); err != nil {
return fmt.Errorf("error setting description: %s", err)
}
return nil
}
func resourceElasticsearchOpenDistroRoleUpdate(d *schema.ResourceData, m interface{}) error {
if _, err := resourceElasticsearchPutOpenDistroRole(d, m); err != nil {
return err
}
return resourceElasticsearchOpenDistroRoleRead(d, m)
}
func resourceElasticsearchOpenDistroRoleDelete(d *schema.ResourceData, m interface{}) error {
path, err := uritemplates.Expand("/_opendistro/_security/api/roles/{name}", map[string]string{
"name": d.Get("role_name").(string),
})
if err != nil {
return fmt.Errorf("error building URL path for role: %+v", err)
}
esClient, err := getClient(m.(*ProviderConf))
if err != nil {
return err
}
switch client := esClient.(type) {
case *elastic7.Client:
_, err = client.PerformRequest(context.TODO(), elastic7.PerformRequestOptions{
Method: "DELETE",
Path: path,
RetryStatusCodes: []int{http.StatusConflict, http.StatusInternalServerError},
Retrier: elastic7.NewBackoffRetrier(
elastic7.NewExponentialBackoff(100*time.Millisecond, 30*time.Second),
),
})
default:
err = errors.New("role resource not implemented prior to Elastic v7")
}
return err
}
func resourceElasticsearchGetOpenDistroRole(roleID string, m interface{}) (RoleBody, error) {
var err error
role := new(RoleBody)
path, err := uritemplates.Expand("/_opendistro/_security/api/roles/{name}", map[string]string{
"name": roleID,
})
if err != nil {
return *role, fmt.Errorf("error building URL path for role: %+v", err)
}
var body json.RawMessage
esClient, err := getClient(m.(*ProviderConf))
if err != nil {
return *role, err
}
switch client := esClient.(type) {
case *elastic7.Client:
var res *elastic7.Response
res, err = client.PerformRequest(context.TODO(), elastic7.PerformRequestOptions{
Method: "GET",
Path: path,
})
body = res.Body
default:
err = errors.New("role resource not implemented prior to Elastic v7")
}
if err != nil {
return *role, err
}
var roleDefinition map[string]RoleBody
if err := json.Unmarshal(body, &roleDefinition); err != nil {
return *role, fmt.Errorf("error unmarshalling role body: %+v: %+v", err, body)
}
*role = roleDefinition[roleID]
return *role, err
}
func resourceElasticsearchPutOpenDistroRole(d *schema.ResourceData, m interface{}) (*RoleResponse, error) {
response := new(RoleResponse)
indexPermissions, err := expandIndexPermissionsSet(d.Get("index_permissions").(*schema.Set).List())
if err != nil {
fmt.Print("Error in index get : ", err)
}
var indexPermissionsBody []IndexPermissions
for _, idx := range indexPermissions {
putIdx := IndexPermissions{
IndexPatterns: idx.IndexPatterns,
DocumentLevelSecurity: idx.DocumentLevelSecurity,
FieldLevelSecurity: idx.FieldLevelSecurity,
MaskedFields: idx.MaskedFields,
AllowedActions: idx.AllowedActions,
}
indexPermissionsBody = append(indexPermissionsBody, putIdx)
}
tenantPermissions, err := expandTenantPermissionsSet(d.Get("tenant_permissions").(*schema.Set).List())
if err != nil {
fmt.Print("Error in tenant get : ", err)
}
var tenantPermissionsBody []TenantPermissions
for _, tenant := range tenantPermissions {
putTeanant := TenantPermissions{
TenantPatterns: tenant.TenantPatterns,
AllowedActions: tenant.AllowedActions,
}
tenantPermissionsBody = append(tenantPermissionsBody, putTeanant)
}
rolesDefinition := RoleBody{
ClusterPermissions: expandStringList(d.Get("cluster_permissions").(*schema.Set).List()),
IndexPermissions: indexPermissionsBody,
TenantPermissions: tenantPermissionsBody,
Description: d.Get("description").(string),
}
roleJSON, err := json.Marshal(rolesDefinition)
if err != nil {
return response, fmt.Errorf("Body Error : %s", roleJSON)
}
path, err := uritemplates.Expand("/_opendistro/_security/api/roles/{name}", map[string]string{
"name": d.Get("role_name").(string),
})
if err != nil {
return response, fmt.Errorf("error building URL path for role: %+v", err)
}
var body json.RawMessage
esClient, err := getClient(m.(*ProviderConf))
if err != nil {
return nil, err
}
switch client := esClient.(type) {
case *elastic7.Client:
var res *elastic7.Response
res, err = client.PerformRequest(context.TODO(), elastic7.PerformRequestOptions{
Method: "PUT",
Path: path,
Body: string(roleJSON),
// see https://github.com/opendistro-for-
// elasticsearch/security/issues/1095, this should return a 409, but
// retry on the 500 as well. We can't parse the message to only retry on
// the conlict exception becaues the elastic client doesn't directly
// expose the error response body
RetryStatusCodes: []int{http.StatusConflict, http.StatusInternalServerError},
Retrier: elastic7.NewBackoffRetrier(
elastic7.NewExponentialBackoff(100*time.Millisecond, 30*time.Second),
),
})
body = res.Body
default:
err = errors.New("role resource not implemented prior to Elastic v7")
}
if err != nil {
return response, fmt.Errorf("error creating role: %+v: %+v", err, body)
}
if err := json.Unmarshal(body, response); err != nil {
return response, fmt.Errorf("error unmarshalling role body: %+v: %+v", err, body)
}
return response, nil
}
type RoleResponse struct {
Message string `json:"message"`
Status string `json:"status"`
}
type RoleBody struct {
Description string `json:"description"`
ClusterPermissions []string `json:"cluster_permissions,omitempty"`
IndexPermissions []IndexPermissions `json:"index_permissions,omitempty"`
TenantPermissions []TenantPermissions `json:"tenant_permissions,omitempty"`
}
type IndexPermissions struct {
IndexPatterns []string `json:"index_patterns"`
DocumentLevelSecurity string `json:"dls"`
FieldLevelSecurity []string `json:"fls"`
MaskedFields []string `json:"masked_fields"`
AllowedActions []string `json:"allowed_actions"`
}
type TenantPermissions struct {
TenantPatterns []string `json:"tenant_patterns"`
AllowedActions []string `json:"allowed_actions"`
}