-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
204 lines (173 loc) · 5.36 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
package eventstore
/*
This lightweight client implements only the methods needed for this secrets engine.
It consumes this API:
*/
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/hashicorp/go-retryablehttp"
"github.com/hashicorp/go-rootcerts"
)
type ClientConfig struct {
Username, Password, BaseURL string
// Leave this nil to flag that TLS is not desired
TLSConfig *TLSConfig
}
// TLSConfig contains the parameters needed to configure TLS on the HTTP client
// used to communicate with Eventstore.
type TLSConfig struct {
// CACert is the path to a PEM-encoded CA cert file to use to verify theHTTPClient
// Eventstore server SSL certificate.
CACert string
// CAPath is the path to a directory of PEM-encoded CA cert files to verify
// the Eventstore server SSL certificate.
CAPath string
// ClientCert is the path to the certificate for Eventstore communication
ClientCert string
// ClientKey is the path to the private key for Eventstore 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}
}
return &Client{
username: config.Username,
password: config.Password,
baseURL: config.BaseURL,
client: client,
}, nil
}
type Client struct {
username, password, baseURL string
client *retryablehttp.Client
}
// User management
type User struct {
LoginName string
Password string
Groups []string
FullName string
}
//
func (c *Client) UserExists(ctx context.Context, name string) (bool, error) {
endpoint := "/users/" + name
method := http.MethodGet
req, err := http.NewRequest(method, c.baseURL+endpoint, nil)
if err != nil {
return false, err
}
var resp map[string]interface{}
if err := c.do(ctx, req, &resp); err != nil {
return false, err
}
return (resp["success"] == "true"), nil
}
func (c *Client) CreateUser(ctx context.Context, name string, user *User) error {
endpoint := "/users"
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 := "/users/" + name + "/command/reset-password"
method := http.MethodPost
pwdChangeBodyJson, err := json.Marshal(map[string]string{"NewPassword": 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 := "/users/" + 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("%s; %d: %s", err, resp.StatusCode, body)
}
// 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("%d: %s", resp.StatusCode, body)
}