-
Notifications
You must be signed in to change notification settings - Fork 16
/
client.go
369 lines (320 loc) · 9.51 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
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
360
361
362
363
364
365
366
367
368
369
package gogobosh
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
boshhttp "github.com/cloudfoundry/bosh-utils/httpclient"
"golang.org/x/net/context"
"golang.org/x/oauth2"
"golang.org/x/oauth2/clientcredentials"
)
// Client used to communicate with BOSH
type Client struct {
config Config
Endpoint Endpoint
}
// Config is used to configure the creation of a client
type Config struct {
BOSHAddress string
Username string
Password string
ClientID string
ClientSecret string
UAAAuth bool
HttpClient *http.Client
SkipSslValidation bool
TokenSource oauth2.TokenSource
Endpoint *Endpoint
}
type Endpoint struct {
URL string `json:"doppler_logging_endpoint"`
}
// request is used to help build up a request
type request struct {
method string
url string
header map[string]string
params url.Values
body io.Reader
obj interface{}
}
// DefaultConfig configuration for client
func DefaultConfig() *Config {
return &Config{
BOSHAddress: "https://192.168.50.4:25555", // bosh-lite default IP:PORT
Username: "admin",
Password: "admin",
HttpClient: http.DefaultClient,
SkipSslValidation: true,
}
}
func DefaultEndpoint() *Endpoint {
return &Endpoint{
URL: "https://192.168.50.4:8443",
}
}
// NewClient returns a new client
func NewClient(config *Config) (*Client, error) {
// bootstrap the config
defConfig := DefaultConfig()
if len(config.BOSHAddress) == 0 {
config.BOSHAddress = defConfig.BOSHAddress
}
if len(config.Username) == 0 {
config.Username = defConfig.Username
}
if len(config.Password) == 0 {
config.Password = defConfig.Password
}
// Save the configured HTTP Client timeout for later
var timeout time.Duration
if config.HttpClient != nil {
timeout = config.HttpClient.Timeout
}
// Skip TLS cert validation and respect BOSH_ALL_PROXY env var
config.HttpClient = boshhttp.CreateDefaultClientInsecureSkipVerify()
endpoint := &Endpoint{}
authType, err := getAuthType(config.BOSHAddress, config.HttpClient)
if err != nil {
return nil, fmt.Errorf("could not get client auth type: %w", err)
}
if authType != "uaa" {
config.HttpClient.CheckRedirect = func(req *http.Request, via []*http.Request) error {
if len(via) > 10 {
return fmt.Errorf("stopped after 10 redirects")
}
req.URL.Host = strings.TrimPrefix(config.BOSHAddress, req.URL.Scheme+"://")
req.SetBasicAuth(config.Username, config.Password)
req.Header.Add("User-Agent", "gogo-bosh")
req.Header.Del("Referer")
return nil
}
} else {
ctx := getContext(*config)
endpoint, err := getUAAEndpoint(config.BOSHAddress, oauth2.NewClient(ctx, nil))
if err != nil {
return nil, fmt.Errorf("could not get api /info: %w", err)
}
config.Endpoint = endpoint
if config.ClientID == "" { //No ClientID? Do UAA User auth
authConfig, token, err := getToken(ctx, *config)
if err != nil {
return nil, fmt.Errorf("error getting token: %w", err)
}
config.TokenSource = authConfig.TokenSource(ctx, token)
config.HttpClient = oauth2.NewClient(ctx, config.TokenSource)
} else { //Got a ClientID? Do UAA Client Auth (two-legged auth)
authConfig := &clientcredentials.Config{
ClientID: config.ClientID,
ClientSecret: config.ClientSecret,
TokenURL: endpoint.URL + "/oauth/token",
}
config.TokenSource = authConfig.TokenSource(ctx)
config.HttpClient = authConfig.Client(ctx)
}
config.HttpClient.CheckRedirect = func(req *http.Request, via []*http.Request) error {
if len(via) > 10 {
return fmt.Errorf("stopped after 10 redirects")
}
req.URL.Host = strings.TrimPrefix(config.BOSHAddress, req.URL.Scheme+"://")
req.Header.Add("User-Agent", "gogo-bosh")
req.Header.Del("Referer")
return nil
}
}
//Restore the timeout from the provided HTTP Client
config.HttpClient.Timeout = timeout
client := &Client{
config: *config,
Endpoint: *endpoint,
}
return client, nil
}
func getAuthType(api string, httpClient *http.Client) (string, error) {
info, err := getInfo(api, httpClient)
return info.UserAuthentication.Type, err
}
func getInfo(api string, httpClient *http.Client) (*Info, error) {
if api == "" {
return &Info{}, nil
}
resp, err := httpClient.Get(api + "/info")
if err != nil {
return &Info{}, err
}
defer func() { _ = resp.Body.Close() }()
var info Info
err = json.NewDecoder(resp.Body).Decode(&info)
if err != nil {
return &Info{}, fmt.Errorf("error unmarshalling info response: %w", err)
}
return &info, err
}
func getUAAEndpoint(api string, httpClient *http.Client) (*Endpoint, error) {
if api == "" {
return DefaultEndpoint(), nil
}
info, err := getInfo(api, httpClient)
URL := info.UserAuthentication.Options.URL
return &Endpoint{URL: URL}, err
}
// NewRequest is used to create a new request
func (c *Client) NewRequest(method, path string) *request {
r := &request{
method: method,
url: c.config.BOSHAddress + path,
params: make(map[string][]string),
header: make(map[string]string),
}
return r
}
func (c *Client) DoRequestAndUnmarshal(r *request, objPtr interface{}) error {
resp, err := c.DoRequest(r)
if err != nil {
return err
}
defer func() { _ = resp.Body.Close() }()
err = json.NewDecoder(resp.Body).Decode(objPtr)
if err != nil {
return fmt.Errorf("error unmarshalling http response: %w", err)
}
return nil
}
// DoRequest runs a request with our client
func (c *Client) DoRequest(r *request) (*http.Response, error) {
req, err := r.toHTTP()
if err != nil {
return nil, err
}
for key, value := range r.header {
req.Header.Add(key, value)
}
req.SetBasicAuth(c.config.Username, c.config.Password)
req.Header.Add("User-Agent", "gogo-bosh")
resp, err := c.config.HttpClient.Do(req)
if err != nil {
if strings.Contains(err.Error(), "oauth2: cannot fetch token") {
err = c.refreshClient()
if err != nil {
return nil, fmt.Errorf("error refreshing UAA client: %w", err)
}
resp, err = c.config.HttpClient.Do(req)
} else {
// errors are only returned for very bad things, not 400s etc
return nil, fmt.Errorf("error making bosh client http request: %w", err)
}
} else if resp.StatusCode >= 400 {
if strings.Contains(resp.Status, "Unauthorized") {
err = c.refreshClient()
if err != nil {
return nil, fmt.Errorf("error refreshing UAA client from 400: %w", err)
}
resp, err = c.config.HttpClient.Do(req)
} else {
return nil, fmt.Errorf("http %s request to %s failed with %s", req.Method, req.URL, resp.Status)
}
}
return resp, err
}
// GetUUID returns the BOSH UUID
func (c *Client) GetUUID() (string, error) {
info, err := c.GetInfo()
if err != nil {
return "", fmt.Errorf("error getting the UUID: %w", err)
}
return info.UUID, nil
}
// UUID returns the BOSH uuid
// Deprecated: Use GetUUID and check for errors
func (c *Client) UUID() string {
uuid, _ := c.GetUUID()
return uuid
}
// GetInfo returns BOSH Info
func (c *Client) GetInfo() (Info, error) {
info, err := getInfo(c.config.BOSHAddress, c.config.HttpClient)
if err != nil {
return Info{}, err
}
return *info, nil
}
func (c *Client) refreshClient() error {
// Create a new http client to avoid authentication failure when getting a new
// token as the oauth2 client passes along the expired/revoked refresh token.
c.config.HttpClient = &http.Client{
Timeout: c.config.HttpClient.Timeout,
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: c.config.SkipSslValidation,
},
},
}
ctx := getContext(c.config)
authConfig, token, err := getToken(ctx, c.config)
if err != nil {
return fmt.Errorf("error getting token to refresh client: %w", err)
}
c.config.TokenSource = authConfig.TokenSource(ctx, token)
c.config.HttpClient = oauth2.NewClient(ctx, c.config.TokenSource)
c.config.HttpClient.CheckRedirect = func(req *http.Request, via []*http.Request) error {
if len(via) > 10 {
return fmt.Errorf("stopped after 10 redirects")
}
req.URL.Host = strings.TrimPrefix(c.config.BOSHAddress, req.URL.Scheme+"://")
req.Header.Add("User-Agent", "gogo-bosh")
req.Header.Del("Referer")
return nil
}
return nil
}
func getToken(ctx context.Context, config Config) (*oauth2.Config, *oauth2.Token, error) {
authConfig := &oauth2.Config{
ClientID: "bosh_cli",
Scopes: []string{""},
Endpoint: oauth2.Endpoint{
AuthURL: config.Endpoint.URL + "/oauth/authorize",
TokenURL: config.Endpoint.URL + "/oauth/token",
},
}
token, err := authConfig.PasswordCredentialsToken(ctx, config.Username, config.Password)
return authConfig, token, err
}
func getContext(config Config) context.Context {
return context.WithValue(context.Background(), oauth2.HTTPClient, config.HttpClient)
}
// toHTTP converts the request to an HTTP request
func (r *request) toHTTP() (*http.Request, error) {
// Check if we should encode the body
if r.body == nil && r.obj != nil {
if b, err := encodeBody(r.obj); err != nil {
return nil, err
} else {
r.body = b
}
}
// Create the HTTP request
return http.NewRequest(r.method, r.url, r.body)
}
// GetToken - returns the current token bearer
func (c *Client) GetToken() (string, error) {
token, err := c.config.TokenSource.Token()
if err != nil {
return "", fmt.Errorf("error getting bearer token: %w", err)
}
return "bearer " + token.AccessToken, nil
}
// encodeBody is used to encode a request body
func encodeBody(obj interface{}) (io.Reader, error) {
buf := bytes.NewBuffer(nil)
enc := json.NewEncoder(buf)
if err := enc.Encode(obj); err != nil {
return nil, err
}
return buf, nil
}