forked from cloudfoundry/go-cfclient
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
407 lines (340 loc) · 9.95 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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
package cfclient
import (
"bytes"
"crypto/tls"
"encoding/json"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
"github.com/pkg/errors"
"golang.org/x/net/context"
"golang.org/x/oauth2"
"golang.org/x/oauth2/clientcredentials"
)
//Client used to communicate with Cloud Foundry
type Client struct {
Config Config
Endpoint Endpoint
}
type Endpoint struct {
DopplerEndpoint string `json:"doppler_logging_endpoint"`
LoggingEndpoint string `json:"logging_endpoint"`
AuthEndpoint string `json:"authorization_endpoint"`
TokenEndpoint string `json:"token_endpoint"`
}
//Config is used to configure the creation of a client
type Config struct {
ApiAddress string `json:"api_url"`
Username string `json:"user"`
Password string `json:"password"`
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
SkipSslValidation bool `json:"skip_ssl_validation"`
HttpClient *http.Client
Token string `json:"auth_token"`
TokenSource oauth2.TokenSource
tokenSourceDeadline *time.Time
UserAgent string `json:"user_agent"`
}
// Request is used to help build up a request
type Request struct {
method string
url string
params url.Values
body io.Reader
obj interface{}
}
//DefaultConfig configuration for client
//Keep LoginAdress for backward compatibility
//Need to be remove in close future
func DefaultConfig() *Config {
return &Config{
ApiAddress: "http://api.bosh-lite.com",
Username: "admin",
Password: "admin",
Token: "",
SkipSslValidation: false,
HttpClient: http.DefaultClient,
UserAgent: "Go-CF-client/1.1",
}
}
func DefaultEndpoint() *Endpoint {
return &Endpoint{
DopplerEndpoint: "wss://doppler.10.244.0.34.xip.io:443",
LoggingEndpoint: "wss://loggregator.10.244.0.34.xip.io:443",
TokenEndpoint: "https://uaa.10.244.0.34.xip.io",
AuthEndpoint: "https://login.10.244.0.34.xip.io",
}
}
// NewClient returns a new client
func NewClient(config *Config) (client *Client, err error) {
// bootstrap the config
defConfig := DefaultConfig()
if len(config.ApiAddress) == 0 {
config.ApiAddress = defConfig.ApiAddress
}
if len(config.Username) == 0 {
config.Username = defConfig.Username
}
if len(config.Password) == 0 {
config.Password = defConfig.Password
}
if len(config.Token) == 0 {
config.Token = defConfig.Token
}
if len(config.UserAgent) == 0 {
config.UserAgent = defConfig.UserAgent
}
if config.HttpClient == nil {
config.HttpClient = defConfig.HttpClient
}
if config.HttpClient.Transport == nil {
config.HttpClient.Transport = shallowDefaultTransport()
}
var tp *http.Transport
switch t := config.HttpClient.Transport.(type) {
case *http.Transport:
tp = t
case *oauth2.Transport:
if bt, ok := t.Base.(*http.Transport); ok {
tp = bt
}
}
if tp != nil {
if tp.TLSClientConfig == nil {
tp.TLSClientConfig = &tls.Config{}
}
tp.TLSClientConfig.InsecureSkipVerify = config.SkipSslValidation
}
config.ApiAddress = strings.TrimRight(config.ApiAddress, "/")
client = &Client{
Config: *config,
}
if err := client.refreshEndpoint(); err != nil {
return nil, err
}
return client, nil
}
func shallowDefaultTransport() *http.Transport {
defaultTransport := http.DefaultTransport.(*http.Transport)
return &http.Transport{
Proxy: defaultTransport.Proxy,
TLSHandshakeTimeout: defaultTransport.TLSHandshakeTimeout,
ExpectContinueTimeout: defaultTransport.ExpectContinueTimeout,
}
}
func getUserAuth(ctx context.Context, config Config, endpoint *Endpoint) (Config, error) {
authConfig := &oauth2.Config{
ClientID: "cf",
Scopes: []string{""},
Endpoint: oauth2.Endpoint{
AuthURL: endpoint.AuthEndpoint + "/oauth/auth",
TokenURL: endpoint.AuthEndpoint + "/oauth/token",
},
}
token, err := authConfig.PasswordCredentialsToken(ctx, config.Username, config.Password)
if err != nil {
return config, errors.Wrap(err, "Error getting token")
}
config.tokenSourceDeadline = &token.Expiry
config.TokenSource = authConfig.TokenSource(ctx, token)
config.HttpClient = oauth2.NewClient(ctx, config.TokenSource)
return config, err
}
func getClientAuth(ctx context.Context, config Config, endpoint *Endpoint) Config {
authConfig := &clientcredentials.Config{
ClientID: config.ClientID,
ClientSecret: config.ClientSecret,
TokenURL: endpoint.TokenEndpoint + "/oauth/token",
}
config.TokenSource = authConfig.TokenSource(ctx)
config.HttpClient = authConfig.Client(ctx)
return config
}
// getUserTokenAuth initializes client credentials from existing bearer token.
func getUserTokenAuth(ctx context.Context, config Config, endpoint *Endpoint) Config {
authConfig := &oauth2.Config{
ClientID: "cf",
Scopes: []string{""},
Endpoint: oauth2.Endpoint{
AuthURL: endpoint.AuthEndpoint + "/oauth/auth",
TokenURL: endpoint.TokenEndpoint + "/oauth/token",
},
}
// Token is expected to have no "bearer" prefix
token := &oauth2.Token{
AccessToken: config.Token,
TokenType: "Bearer"}
config.TokenSource = authConfig.TokenSource(ctx, token)
config.HttpClient = oauth2.NewClient(ctx, config.TokenSource)
return config
}
func getInfo(api string, httpClient *http.Client) (*Endpoint, error) {
var endpoint Endpoint
if api == "" {
return DefaultEndpoint(), nil
}
resp, err := httpClient.Get(api + "/v2/info")
if err != nil {
return nil, err
}
defer resp.Body.Close()
err = decodeBody(resp, &endpoint)
if err != nil {
return nil, err
}
return &endpoint, err
}
// NewRequest is used to create a new Request
func (c *Client) NewRequest(method, path string) *Request {
r := &Request{
method: method,
url: c.Config.ApiAddress + path,
params: make(map[string][]string),
}
return r
}
// NewRequestWithBody is used to create a new request with
// arbigtrary body io.Reader.
func (c *Client) NewRequestWithBody(method, path string, body io.Reader) *Request {
r := c.NewRequest(method, path)
// Set request body
r.body = body
return r
}
// 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
}
return c.Do(req)
}
// DoRequestWithoutRedirects executes the request without following redirects
func (c *Client) DoRequestWithoutRedirects(r *Request) (*http.Response, error) {
prevCheckRedirect := c.Config.HttpClient.CheckRedirect
c.Config.HttpClient.CheckRedirect = func(httpReq *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
defer func() {
c.Config.HttpClient.CheckRedirect = prevCheckRedirect
}()
return c.DoRequest(r)
}
func (c *Client) Do(req *http.Request) (*http.Response, error) {
req.Header.Set("User-Agent", c.Config.UserAgent)
if req.Body != nil && req.Header.Get("Content-type") == "" {
req.Header.Set("Content-type", "application/json")
}
resp, err := c.Config.HttpClient.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode >= http.StatusBadRequest {
return c.handleError(resp)
}
return resp, nil
}
func (c *Client) handleError(resp *http.Response) (*http.Response, error) {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return resp, CloudFoundryHTTPError{
StatusCode: resp.StatusCode,
Status: resp.Status,
Body: body,
}
}
defer resp.Body.Close()
// Unmarshal V2 error response
if strings.HasPrefix(resp.Request.URL.Path, "/v2/") {
var cfErr CloudFoundryError
if err := json.Unmarshal(body, &cfErr); err != nil {
return resp, CloudFoundryHTTPError{
StatusCode: resp.StatusCode,
Status: resp.Status,
Body: body,
}
}
return nil, cfErr
}
// Unmarshal a V3 error response and convert it into a V2 model
var cfErrorsV3 CloudFoundryErrorsV3
if err := json.Unmarshal(body, &cfErrorsV3); err != nil {
return resp, CloudFoundryHTTPError{
StatusCode: resp.StatusCode,
Status: resp.Status,
Body: body,
}
}
return nil, NewCloudFoundryErrorFromV3Errors(cfErrorsV3)
}
func (c *Client) refreshEndpoint() error {
// we want to keep the Timeout value from config.HttpClient
timeout := c.Config.HttpClient.Timeout
ctx := context.Background()
ctx = context.WithValue(ctx, oauth2.HTTPClient, c.Config.HttpClient)
endpoint, err := getInfo(c.Config.ApiAddress, oauth2.NewClient(ctx, nil))
if err != nil {
return errors.Wrap(err, "Could not get api /v2/info")
}
switch {
case c.Config.Token != "":
c.Config = getUserTokenAuth(ctx, c.Config, endpoint)
case c.Config.ClientID != "":
c.Config = getClientAuth(ctx, c.Config, endpoint)
default:
c.Config, err = getUserAuth(ctx, c.Config, endpoint)
if err != nil {
return err
}
}
// make sure original Timeout value will be used
if c.Config.HttpClient.Timeout != timeout {
c.Config.HttpClient.Timeout = timeout
}
c.Endpoint = *endpoint
return nil
}
// 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 {
b, err := encodeBody(r.obj)
if err != nil {
return nil, err
}
r.body = b
}
// Create the HTTP Request
return http.NewRequest(r.method, r.url, r.body)
}
// decodeBody is used to JSON decode a body
func decodeBody(resp *http.Response, out interface{}) error {
defer resp.Body.Close()
dec := json.NewDecoder(resp.Body)
return dec.Decode(out)
}
// 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
}
func (c *Client) GetToken() (string, error) {
if c.Config.tokenSourceDeadline != nil && c.Config.tokenSourceDeadline.Before(time.Now()) {
if err := c.refreshEndpoint(); err != nil {
return "", err
}
}
token, err := c.Config.TokenSource.Token()
if err != nil {
return "", errors.Wrap(err, "Error getting bearer token")
}
return "bearer " + token.AccessToken, nil
}