-
Notifications
You must be signed in to change notification settings - Fork 22
/
api.go
525 lines (454 loc) · 12.8 KB
/
api.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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
package uaa
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"reflect"
pc "github.com/cloudfoundry-community/go-uaa/passwordcredentials"
"golang.org/x/oauth2"
cc "golang.org/x/oauth2/clientcredentials"
)
//go:generate go run ./generator/generator.go
// API is a client to the UAA API.
type API struct {
Client *http.Client
baseClient *http.Client
baseTransport http.RoundTripper
TargetURL *url.URL
redirectURL *url.URL
skipSSLValidation bool
verbose bool
zoneID string
userAgent string
token *oauth2.Token
target string
mode mode
clientID string
clientSecret string
username string
password string
authorizationCode string
refreshToken string
tokenFormat TokenFormat
clientCredentialsConfig *cc.Config
passwordCredentialsConfig *pc.Config
oauthConfig *oauth2.Config
}
// TokenFormat is the format of a token.
type TokenFormat int
// Valid TokenFormat values.
const (
OpaqueToken TokenFormat = iota
JSONWebToken
)
func (t TokenFormat) String() string {
if t == OpaqueToken {
return "opaque"
}
if t == JSONWebToken {
return "jwt"
}
return ""
}
type mode int
const (
custom mode = iota
token
clientcredentials
passwordcredentials
authorizationcode
refreshtoken
)
type Option interface {
Apply(a *API)
}
type AuthenticationOption interface {
ApplyAuthentication(a *API)
}
func New(target string, authOpt AuthenticationOption, opts ...Option) (*API, error) {
a := &API{
target: target,
mode: custom,
}
authOpt.ApplyAuthentication(a)
defaultClient := &http.Client{Transport: http.DefaultTransport}
defaultClientOption := WithClient(defaultClient)
defaultUserAgentOption := WithUserAgent("go-uaa")
opts = append([]Option{defaultClientOption, defaultUserAgentOption}, opts...)
for _, option := range opts {
option.Apply(a)
}
err := a.configure()
if err != nil {
return nil, err
}
return a, nil
}
func (a *API) Token(ctx context.Context) (*oauth2.Token, error) {
if _, ok := ctx.Value(oauth2.HTTPClient).(*http.Client); !ok {
ctx = context.WithValue(ctx, oauth2.HTTPClient, a.baseClient)
}
switch a.mode {
case token:
if !a.token.Valid() {
return nil, errors.New("you have supplied an empty, invalid, or expired token to go-uaa")
}
return a.token, nil
case clientcredentials:
if a.clientCredentialsConfig == nil {
return nil, errors.New("you have supplied invalid client credentials configuration to go-uaa")
}
return a.clientCredentialsConfig.Token(ctx)
case authorizationcode:
if a.oauthConfig == nil {
return nil, errors.New("you have supplied invalid authorization code configuration to go-uaa")
}
tokenFormatParam := oauth2.SetAuthURLParam("token_format", a.tokenFormat.String())
responseTypeParam := oauth2.SetAuthURLParam("response_type", "token")
return a.oauthConfig.Exchange(ctx, a.authorizationCode, tokenFormatParam, responseTypeParam)
case refreshtoken:
if a.oauthConfig == nil {
return nil, errors.New("you have supplied invalid refresh token configuration to go-uaa")
}
tokenSource := a.oauthConfig.TokenSource(ctx, &oauth2.Token{
RefreshToken: a.refreshToken,
})
token, err := tokenSource.Token()
return token, requestErrorFromOauthError(err)
case passwordcredentials:
token, err := a.passwordCredentialsConfig.TokenSource(ctx).Token()
return token, requestErrorFromOauthError(err)
}
return nil, errors.New("your configuration provides no way for go-uaa to get a token")
}
func (a *API) baseTransportIsNil() bool {
if a.baseTransport == nil || reflect.ValueOf(a.baseTransport).IsNil() {
return true
}
return false
}
func (a *API) configure() error {
err := a.configureTarget()
if err != nil {
return err
}
if a.baseClient == nil {
return errors.New("please ensure you pass a non-nil client to uaa.WithClient, or remove the uaa.WithClient option")
}
if a.baseTransportIsNil() {
a.baseTransport = a.baseClient.Transport
}
if a.baseTransportIsNil() {
a.baseTransport = http.DefaultTransport
}
a.ensureTransport(a.baseClient.Transport)
wrappedTransport := &uaaTransport{
base: a.baseClient.Transport,
LoggingEnabled: a.verbose,
}
a.baseClient.Transport = wrappedTransport
switch a.mode {
case token:
err = a.configureToken()
case clientcredentials:
a.configureClientCredentials()
case passwordcredentials:
a.configurePasswordCredentials()
case authorizationcode:
err = a.configureAuthorizationCode()
case refreshtoken:
err = a.configureRefreshToken()
case custom:
if a.Client == nil {
a.Client = a.baseClient
}
default:
return errors.New("please ensure you pass an AuthenticationOption (e.g. WithClientCredentials, WithPasswordCredentials, WithAuthorizationCode, WithRefreshToken, WithToken) to New(), or manually construct a uaa.API and set uaa.API.Client")
}
if err != nil {
return err
}
if a.Client == nil {
return errors.New("Client is nil; please ensure you pass an AuthenticationOption (e.g. WithClientCredentials, WithPasswordCredentials, WithAuthorizationCode, WithRefreshToken, WithToken) to New(), or manually set Client")
}
a.ensureTransport(a.Client.Transport)
return nil
}
func (a *API) configureTarget() error {
if a.TargetURL != nil {
return nil
}
if a.target == "" && a.TargetURL == nil {
return errors.New("the target is missing")
}
u, err := BuildTargetURL(a.target)
if err != nil {
return err
}
a.TargetURL = u
return nil
}
type withClient struct {
client *http.Client
}
func WithClient(client *http.Client) Option {
return &withClient{client: client}
}
func (w *withClient) Apply(a *API) {
a.baseClient = w.client
}
type withTransport struct {
transport http.RoundTripper
}
func WithTransport(transport http.RoundTripper) Option {
return &withTransport{transport: transport}
}
func (w *withTransport) Apply(a *API) {
a.baseTransport = w.transport
}
type withSkipSSLValidation struct {
skipSSLValidation bool
}
func WithSkipSSLValidation(skipSSLValidation bool) Option {
return &withSkipSSLValidation{skipSSLValidation: skipSSLValidation}
}
func (w *withSkipSSLValidation) Apply(a *API) {
a.skipSSLValidation = w.skipSSLValidation
}
type withUserAgent struct {
userAgent string
}
func WithUserAgent(userAgent string) Option {
return &withUserAgent{userAgent: userAgent}
}
func (w *withUserAgent) Apply(a *API) {
a.userAgent = w.userAgent
}
type withZoneID struct {
zoneID string
}
func WithZoneID(zoneID string) Option {
return &withZoneID{zoneID: zoneID}
}
func (w *withZoneID) Apply(a *API) {
a.zoneID = w.zoneID
}
type withVerbosity struct {
verbose bool
}
func WithVerbosity(verbose bool) Option {
return &withVerbosity{verbose: verbose}
}
func (w *withVerbosity) Apply(a *API) {
a.verbose = w.verbose
}
type withClientCredentials struct {
clientID string
clientSecret string
tokenFormat TokenFormat
}
func WithClientCredentials(clientID string, clientSecret string, tokenFormat TokenFormat) AuthenticationOption {
return &withClientCredentials{clientID: clientID, clientSecret: clientSecret, tokenFormat: tokenFormat}
}
func (w *withClientCredentials) ApplyAuthentication(a *API) {
a.mode = clientcredentials
a.clientID = w.clientID
a.clientSecret = w.clientSecret
a.tokenFormat = w.tokenFormat
}
func (a *API) configureClientCredentials() {
tokenURL := urlWithPath(*a.TargetURL, "/oauth/token")
v := url.Values{}
v.Add("token_format", a.tokenFormat.String())
c := &cc.Config{
ClientID: a.clientID,
ClientSecret: a.clientSecret,
TokenURL: tokenURL.String(),
EndpointParams: v,
AuthStyle: oauth2.AuthStyleInHeader,
}
a.clientCredentialsConfig = c
a.Client = c.Client(context.WithValue(
context.Background(),
oauth2.HTTPClient,
a.baseClient,
))
}
type withPasswordCredentials struct {
clientID string
clientSecret string
username string
password string
tokenFormat TokenFormat
}
func WithPasswordCredentials(clientID string, clientSecret string, username string, password string, tokenFormat TokenFormat) AuthenticationOption {
return &withPasswordCredentials{
clientID: clientID,
clientSecret: clientSecret,
username: username,
password: password,
tokenFormat: tokenFormat,
}
}
func (w *withPasswordCredentials) ApplyAuthentication(a *API) {
a.mode = passwordcredentials
a.clientID = w.clientID
a.clientSecret = w.clientSecret
a.username = w.username
a.password = w.password
a.tokenFormat = w.tokenFormat
}
func (a *API) configurePasswordCredentials() {
tokenURL := urlWithPath(*a.TargetURL, "/oauth/token")
v := url.Values{}
v.Add("token_format", a.tokenFormat.String())
c := &pc.Config{
ClientID: a.clientID,
ClientSecret: a.clientSecret,
Username: a.username,
Password: a.password,
Endpoint: oauth2.Endpoint{
TokenURL: tokenURL.String(),
},
EndpointParams: v,
}
a.passwordCredentialsConfig = c
a.Client = c.Client(context.WithValue(
context.Background(),
oauth2.HTTPClient,
a.baseClient))
}
type withAuthorizationCode struct {
clientID string
clientSecret string
authorizationCode string
redirectURL *url.URL
tokenFormat TokenFormat
}
func WithAuthorizationCode(clientID string, clientSecret string, authorizationCode string, tokenFormat TokenFormat, redirectURL *url.URL) AuthenticationOption {
return &withAuthorizationCode{
clientID: clientID,
clientSecret: clientSecret,
authorizationCode: authorizationCode,
tokenFormat: tokenFormat,
redirectURL: redirectURL,
}
}
func (w *withAuthorizationCode) ApplyAuthentication(a *API) {
a.mode = authorizationcode
a.clientID = w.clientID
a.clientSecret = w.clientSecret
a.authorizationCode = w.authorizationCode
a.tokenFormat = w.tokenFormat
a.redirectURL = w.redirectURL
}
func (a *API) configureAuthorizationCode() error {
tokenURL := urlWithPath(*a.TargetURL, "/oauth/token")
c := &oauth2.Config{
ClientID: a.clientID,
ClientSecret: a.clientSecret,
Endpoint: oauth2.Endpoint{
TokenURL: tokenURL.String(),
AuthStyle: oauth2.AuthStyleInHeader,
},
RedirectURL: a.redirectURL.String(),
}
a.oauthConfig = c
ctx := context.WithValue(context.Background(), oauth2.HTTPClient, a.baseClient)
if !a.token.Valid() {
t, err := a.Token(context.Background())
if err != nil {
return requestErrorFromOauthError(err)
}
a.token = t
}
a.Client = c.Client(ctx, a.token)
return nil
}
type withRefreshToken struct {
clientID string
clientSecret string
refreshToken string
tokenFormat TokenFormat
}
func WithRefreshToken(clientID string, clientSecret string, refreshToken string, tokenFormat TokenFormat) AuthenticationOption {
return &withRefreshToken{
clientID: clientID,
clientSecret: clientSecret,
refreshToken: refreshToken,
tokenFormat: tokenFormat,
}
}
func (w *withRefreshToken) ApplyAuthentication(a *API) {
a.mode = refreshtoken
a.clientID = w.clientID
a.clientSecret = w.clientSecret
a.refreshToken = w.refreshToken
a.tokenFormat = w.tokenFormat
}
func (a *API) configureRefreshToken() error {
tokenURL := urlWithPath(*a.TargetURL, "/oauth/token")
query := tokenURL.Query()
query.Set("token_format", a.tokenFormat.String())
tokenURL.RawQuery = query.Encode()
c := &oauth2.Config{
ClientID: a.clientID,
ClientSecret: a.clientSecret,
Endpoint: oauth2.Endpoint{
TokenURL: tokenURL.String(),
AuthStyle: oauth2.AuthStyleInHeader,
},
}
a.oauthConfig = c
ctx := context.WithValue(context.Background(), oauth2.HTTPClient, a.baseClient)
if !a.token.Valid() {
t, err := a.Token(context.Background())
if err != nil {
return err
}
a.token = t
}
a.Client = c.Client(ctx, a.token)
return nil
}
type withToken struct {
token *oauth2.Token
}
func WithToken(token *oauth2.Token) AuthenticationOption {
return &withToken{token: token}
}
func (w *withToken) ApplyAuthentication(a *API) {
a.mode = token
a.token = w.token
}
func (a *API) configureToken() error {
if !a.token.Valid() {
return errors.New("access token is not valid, or is expired")
}
tokenClient := &http.Client{
Transport: &tokenTransport{
underlyingTransport: a.baseClient.Transport,
token: *a.token,
},
}
a.Client = tokenClient
return nil
}
type tokenTransport struct {
underlyingTransport http.RoundTripper
token oauth2.Token
}
func (t *tokenTransport) RoundTrip(req *http.Request) (*http.Response, error) {
req.Header.Set("Authorization", fmt.Sprintf("%s %s", t.token.Type(), t.token.AccessToken))
return t.underlyingTransport.RoundTrip(req)
}
type withNoAuthentication struct {
}
func WithNoAuthentication() AuthenticationOption {
return &withNoAuthentication{}
}
func (w *withNoAuthentication) ApplyAuthentication(a *API) {
a.mode = custom
}