-
Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathresource_elasticsearch_opendistro_user.go
266 lines (230 loc) · 7.26 KB
/
resource_elasticsearch_opendistro_user.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
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 resourceElasticsearchOpenDistroUser() *schema.Resource {
return &schema.Resource{
Create: resourceElasticsearchOpenDistroUserCreate,
Read: resourceElasticsearchOpenDistroUserRead,
Update: resourceElasticsearchOpenDistroUserUpdate,
Delete: resourceElasticsearchOpenDistroUserDelete,
Schema: map[string]*schema.Schema{
"username": {
Type: schema.TypeString,
Required: true,
},
"password": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
StateFunc: hashSum,
ConflictsWith: []string{"password_hash"},
},
"password_hash": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
StateFunc: hashSum,
ConflictsWith: []string{"password"},
},
"backend_roles": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"attributes": {
Type: schema.TypeMap,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"description": {
Type: schema.TypeString,
Optional: true,
},
},
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
}
}
func resourceElasticsearchOpenDistroUserCreate(d *schema.ResourceData, m interface{}) error {
_, err := resourceElasticsearchPutOpenDistroUser(d, m)
if err != nil {
return err
}
name := d.Get("username").(string)
d.SetId(name)
return resourceElasticsearchOpenDistroUserRead(d, m)
}
func resourceElasticsearchOpenDistroUserRead(d *schema.ResourceData, m interface{}) error {
res, err := resourceElasticsearchGetOpenDistroUser(d.Id(), m)
if err != nil {
if elastic7.IsNotFound(err) {
log.Printf("[WARN] OdfeUser (%s) not found, removing from state", d.Id())
d.SetId("")
return nil
}
return err
}
ds := &resourceDataSetter{d: d}
ds.set("backend_roles", res.BackendRoles)
ds.set("attributes", res.Attributes)
ds.set("description", res.Description)
return ds.err
}
func resourceElasticsearchOpenDistroUserUpdate(d *schema.ResourceData, m interface{}) error {
if _, err := resourceElasticsearchPutOpenDistroUser(d, m); err != nil {
return err
}
return resourceElasticsearchOpenDistroUserRead(d, m)
}
func resourceElasticsearchOpenDistroUserDelete(d *schema.ResourceData, m interface{}) error {
var err error
path, err := uritemplates.Expand("/_opendistro/_security/api/internalusers/{name}", map[string]string{
"name": d.Get("username").(string),
})
if err != nil {
return fmt.Errorf("Error building URL path for user: %+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 resourceElasticsearchGetOpenDistroUser(userID string, m interface{}) (UserBody, error) {
var err error
user := new(UserBody)
path, err := uritemplates.Expand("/_opendistro/_security/api/internalusers/{name}", map[string]string{
"name": userID,
})
if err != nil {
return *user, fmt.Errorf("Error building URL path for user: %+v", err)
}
var body json.RawMessage
esClient, err := getClient(m.(*ProviderConf))
if err != nil {
return *user, 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 *user, err
}
var userDefinition map[string]UserBody
if err := json.Unmarshal(body, &userDefinition); err != nil {
return *user, fmt.Errorf("Error unmarshalling user body: %+v: %+v", err, body)
}
*user = userDefinition[userID]
return *user, err
}
func resourceElasticsearchPutOpenDistroUser(d *schema.ResourceData, m interface{}) (*UserResponse, error) {
response := new(UserResponse)
userDefinition := UserBody{
BackendRoles: d.Get("backend_roles").(*schema.Set).List(),
Description: d.Get("description").(string),
Attributes: d.Get("attributes").(map[string]interface{}),
}
if d.HasChange("password") {
userDefinition.Password = d.Get("password").(string)
}
if d.HasChange("password_hash") {
userDefinition.PasswordHash = d.Get("password_hash").(string)
}
userJSON, err := json.Marshal(userDefinition)
if err != nil {
return response, fmt.Errorf("Body Error : %s", userJSON)
}
path, err := uritemplates.Expand("/_opendistro/_security/api/internalusers/{name}", map[string]string{
"name": d.Get("username").(string),
})
if err != nil {
return response, fmt.Errorf("Error building URL path for user: %+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
log.Printf("[INFO] put opendistro user: %+v", userDefinition)
res, err = client.PerformRequest(context.TODO(), elastic7.PerformRequestOptions{
Method: "PUT",
Path: path,
Body: string(userJSON),
// 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),
),
})
if err != nil {
e, ok := err.(*elastic7.Error)
if !ok {
log.Printf("[INFO] expected error to be of type *elastic.Error")
} else {
log.Printf("[INFO] error creating user: %v %v %v", res, res.Body, e)
}
}
body = res.Body
default:
err = errors.New("User resource not implemented prior to Elastic v7")
}
if err != nil {
return response, fmt.Errorf("Error creating user: %+v: %+v: %+v", err, body, string(userJSON))
}
if err := json.Unmarshal(body, response); err != nil {
return response, fmt.Errorf("Error unmarshalling user body: %+v: %+v", err, body)
}
return response, nil
}
// UserBody used by the odfe's API
type UserBody struct {
BackendRoles []interface{} `json:"backend_roles"`
Attributes map[string]interface{} `json:"attributes"`
Description string `json:"description"`
Password string `json:"password,omitempty"`
PasswordHash string `json:"hash,omitempty"`
}
// UserResponse sent by the odfe's API
type UserResponse struct {
Message string `json:"message"`
Status string `json:"status"`
}