-
Notifications
You must be signed in to change notification settings - Fork 7
/
client.go
254 lines (213 loc) · 6.87 KB
/
client.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package elasticsearch
/*
This lightweight client implements only the methods needed for this secrets engine.
It consumes this API:
https://www.elastic.co/guide/en/elasticsearch/reference/6.6/security-api.html
*/
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"path"
"github.com/hashicorp/go-retryablehttp"
"github.com/hashicorp/go-rootcerts"
)
const (
// defaultSecurityAPIPath is the security API path for Elasticsearch 7+
defaultSecurityAPIPath = "/_security"
// oldSecurityPath is the security API path for Elasticsearch <=6
oldSecurityAPIPath = "/_xpack/security"
)
type ClientConfig struct {
Username, Password, BaseURL string
// Leave this nil to flag that TLS is not desired
TLSConfig *TLSConfig
UseOldSecurityPath bool
}
// TLSConfig contains the parameters needed to configure TLS on the HTTP client
// used to communicate with Elasticsearch.
type TLSConfig struct {
// CACert is the path to a PEM-encoded CA cert file to use to verify theHTTPClient
// Elasticsearch server SSL certificate.
CACert string
// CAPath is the path to a directory of PEM-encoded CA cert files to verify
// the Elasticsearch server SSL certificate.
CAPath string
// ClientCert is the path to the certificate for Elasticsearch communication
ClientCert string
// ClientKey is the path to the private key for Elasticsearch communication
ClientKey string
// TLSServerName, if set, is used to set the SNI host when connecting via
// TLS.
TLSServerName string
// Insecure enables or disables SSL verification
Insecure bool
}
func NewClient(config *ClientConfig) (*Client, error) {
client := retryablehttp.NewClient()
if config.TLSConfig != nil {
conf := &tls.Config{
ServerName: config.TLSConfig.TLSServerName,
InsecureSkipVerify: config.TLSConfig.Insecure,
MinVersion: tls.VersionTLS12,
}
if config.TLSConfig.ClientCert != "" && config.TLSConfig.ClientKey != "" {
clientCertificate, err := tls.LoadX509KeyPair(config.TLSConfig.ClientCert, config.TLSConfig.ClientKey)
if err != nil {
return nil, err
}
conf.Certificates = append(conf.Certificates, clientCertificate)
}
if config.TLSConfig.CACert != "" || config.TLSConfig.CAPath != "" {
rootConfig := &rootcerts.Config{
CAFile: config.TLSConfig.CACert,
CAPath: config.TLSConfig.CAPath,
}
if err := rootcerts.ConfigureTLS(conf, rootConfig); err != nil {
return nil, err
}
}
client.HTTPClient.Transport = &http.Transport{TLSClientConfig: conf}
}
c := &Client{
username: config.Username,
password: config.Password,
baseURL: config.BaseURL,
client: client,
securityPath: defaultSecurityAPIPath,
}
if config.UseOldSecurityPath {
c.securityPath = oldSecurityAPIPath
}
return c, nil
}
type Client struct {
username string
password string
baseURL string
securityPath string
client *retryablehttp.Client
}
// Role management
func (c *Client) CreateRole(ctx context.Context, name string, role map[string]interface{}) error {
endpoint := path.Join(c.securityPath, "role", name)
method := http.MethodPost
roleBytes, err := json.Marshal(role)
if err != nil {
return err
}
req, err := http.NewRequest(method, c.baseURL+endpoint, bytes.NewReader(roleBytes))
if err != nil {
return err
}
return c.do(ctx, req, nil)
}
// GetRole returns nil, nil if role is unfound.
func (c *Client) GetRole(ctx context.Context, name string) (map[string]interface{}, error) {
endpoint := path.Join(c.securityPath, "role", name)
method := http.MethodGet
req, err := http.NewRequest(method, c.baseURL+endpoint, nil)
if err != nil {
return nil, err
}
var roles map[string]map[string]interface{}
if err := c.do(ctx, req, &roles); err != nil {
return nil, err
}
return roles[name], nil
}
func (c *Client) DeleteRole(ctx context.Context, name string) error {
endpoint := path.Join(c.securityPath, "role", name)
method := http.MethodDelete
req, err := http.NewRequest(method, c.baseURL+endpoint, nil)
if err != nil {
return err
}
return c.do(ctx, req, nil)
}
// User management
type User struct {
Password string `json:"password"` // Passwords must be at least 6 characters long.
Roles []string `json:"roles"`
}
func (c *Client) CreateUser(ctx context.Context, name string, user *User) error {
endpoint := path.Join(c.securityPath, "user", name)
method := http.MethodPost
userJson, err := json.Marshal(user)
if err != nil {
return err
}
req, err := http.NewRequest(method, c.baseURL+endpoint, bytes.NewReader(userJson))
if err != nil {
return err
}
return c.do(ctx, req, nil)
}
func (c *Client) ChangePassword(ctx context.Context, name, newPassword string) error {
endpoint := path.Join(c.securityPath, "user", name, "_password")
method := http.MethodPost
pwdChangeBodyJson, err := json.Marshal(map[string]string{"password": newPassword})
if err != nil {
return err
}
req, err := http.NewRequest(method, c.baseURL+endpoint, bytes.NewReader(pwdChangeBodyJson))
if err != nil {
return err
}
return c.do(ctx, req, nil)
}
func (c *Client) DeleteUser(ctx context.Context, name string) error {
endpoint := path.Join(c.securityPath, "user", name)
method := http.MethodDelete
req, err := http.NewRequest(method, c.baseURL+endpoint, nil)
if err != nil {
return err
}
return c.do(ctx, req, nil)
}
// Low-level request handling
func (c *Client) do(ctx context.Context, req *http.Request, ret interface{}) error {
// Prepare the request.
retryableReq, err := retryablehttp.NewRequest(req.Method, req.URL.String(), req.Body)
if err != nil {
return err
}
retryableReq.SetBasicAuth(c.username, c.password)
retryableReq.Header.Add("Content-Type", "application/json")
// Execute the request.
resp, err := c.client.Do(retryableReq.WithContext(ctx))
if err != nil {
return err
}
defer resp.Body.Close()
// Read the body once so it can be retained for error output if needed.
// Since no responses are list responses, response bodies should have a small footprint
// and are very useful for debugging.
body, _ := ioutil.ReadAll(resp.Body)
// If we were successful, try to unmarshal the body if the caller wants it.
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
if ret == nil {
// No body to read out.
return nil
}
if err := json.Unmarshal(body, ret); err != nil {
// We received a success response from the ES API but the body was in an unexpected format.
return fmt.Errorf("unexpected format from elasticsearch api: %s; %d", err, resp.StatusCode)
}
// Body has been successfully read out.
return nil
}
// 404 is actually another form of success in the ES API. It just means that an object we were searching
// for wasn't found.
if resp.StatusCode == 404 {
return nil
}
// We received some sort of API error. Let's return it.
return fmt.Errorf("error returned from elasticsearch api: %d", resp.StatusCode)
}