-
Notifications
You must be signed in to change notification settings - Fork 4
/
bearer.go
111 lines (93 loc) · 3.46 KB
/
bearer.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
// SPDX-FileCopyrightText: 2021 Comcast Cable Communications Management, LLC
// SPDX-License-Identifier: Apache-2.0
package acquire
import (
"fmt"
"io"
"net/http"
"sync"
"time"
)
// RemoteBearerTokenAcquirerOptions provides configuration for the RemoteBearerTokenAcquirer.
type RemoteBearerTokenAcquirerOptions struct {
AuthURL string `json:"authURL"`
Timeout time.Duration `json:"timeout"`
Buffer time.Duration `json:"buffer"`
RequestHeaders map[string]string `json:"requestHeaders"`
GetToken TokenParser
GetExpiration ParseExpiration
}
// RemoteBearerTokenAcquirer implements Acquirer and fetches the tokens from a remote location with caching strategy.
type RemoteBearerTokenAcquirer struct {
options RemoteBearerTokenAcquirerOptions
authValue string
authValueExpiration time.Time
httpClient *http.Client
nonExpiringSpecialCase time.Time
lock sync.RWMutex
}
// SimpleBearer defines the field name mappings used by the default bearer token and expiration parsers.
type SimpleBearer struct {
ExpiresInSeconds float64 `json:"expires_in"`
Token string `json:"serviceAccessToken"`
}
// NewRemoteBearerTokenAcquirer returns a RemoteBearerTokenAcquirer configured with the given options.
func NewRemoteBearerTokenAcquirer(options RemoteBearerTokenAcquirerOptions) (*RemoteBearerTokenAcquirer, error) {
if options.GetToken == nil {
options.GetToken = DefaultTokenParser
}
if options.GetExpiration == nil {
options.GetExpiration = DefaultExpirationParser
}
// TODO: we should inject timeout and buffer defaults values as well.
return &RemoteBearerTokenAcquirer{
options: options,
authValueExpiration: time.Now(),
httpClient: &http.Client{
Timeout: options.Timeout,
},
nonExpiringSpecialCase: time.Unix(0, 0),
}, nil
}
// Acquire provides the cached token or, if it's near its expiry time, contacts
// the server for a new token to cache.
func (acquirer *RemoteBearerTokenAcquirer) Acquire() (string, error) {
acquirer.lock.RLock()
if time.Now().Add(acquirer.options.Buffer).Before(acquirer.authValueExpiration) {
defer acquirer.lock.RUnlock()
return acquirer.authValue, nil
}
acquirer.lock.RUnlock()
acquirer.lock.Lock()
defer acquirer.lock.Unlock()
req, err := http.NewRequest("GET", acquirer.options.AuthURL, nil)
if err != nil {
return "", fmt.Errorf("failed to create new request for Bearer: %v", err)
}
for key, value := range acquirer.options.RequestHeaders {
req.Header.Set(key, value)
}
resp, errHTTP := acquirer.httpClient.Do(req)
if errHTTP != nil {
return "", fmt.Errorf("error making request to '%v' to acquire bearer token: %v",
acquirer.options.AuthURL, errHTTP)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("received non 200 code acquiring Bearer: code %v", resp.Status)
}
respBody, errRead := io.ReadAll(resp.Body)
if errRead != nil {
return "", fmt.Errorf("error reading HTTP response body: %v", errRead)
}
token, err := acquirer.options.GetToken(respBody)
if err != nil {
return "", fmt.Errorf("error parsing bearer token from http response body: %v", err)
}
expiration, err := acquirer.options.GetExpiration(respBody)
if err != nil {
return "", fmt.Errorf("error parsing bearer token expiration from http response body: %v", err)
}
acquirer.authValue, acquirer.authValueExpiration = "Bearer "+token, expiration
return acquirer.authValue, nil
}