/
oauthclient.go
228 lines (179 loc) · 8.13 KB
/
oauthclient.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
package oauth
import (
"context"
"crypto/sha256"
"crypto/tls"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
"github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors"
"github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/oauth/tokencache"
"github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/util"
"github.com/kyma-project/kyma/components/central-application-gateway/pkg/httpconsts"
"github.com/kyma-project/kyma/components/central-application-gateway/pkg/httptools"
)
type oauthResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
Scope string `json:"scope"`
}
//go:generate mockery --name=Client
type Client interface {
GetToken(clientID, clientSecret, authURL string, headers, queryParameters *map[string][]string, skipVerify bool) (string, apperrors.AppError)
GetTokenMTLS(clientID, authURL string, certificate, privateKey []byte, headers, queryParameters *map[string][]string, skipVerify bool) (string, apperrors.AppError)
InvalidateTokenCache(clientID string, clientSecret string, authURL string)
InvalidateTokenCacheMTLS(clientID, authURL string, certificate, privateKey []byte)
}
type client struct {
timeoutDuration int
tokenCache tokencache.TokenCache
}
func NewOauthClient(timeoutDuration int, tokenCache tokencache.TokenCache) Client {
return &client{
timeoutDuration: timeoutDuration,
tokenCache: tokenCache,
}
}
func (c *client) GetToken(clientID, clientSecret, authURL string, headers, queryParameters *map[string][]string, skipVerify bool) (string, apperrors.AppError) {
token, found := c.tokenCache.Get(c.makeOAuthTokenCacheKey(clientID, clientSecret, authURL))
if found {
return token, nil
}
tokenResponse, err := c.requestToken(clientID, clientSecret, authURL, headers, queryParameters, skipVerify)
if err != nil {
return "", err
}
c.tokenCache.Add(c.makeOAuthTokenCacheKey(clientID, clientSecret, authURL), tokenResponse.AccessToken, tokenResponse.ExpiresIn)
return tokenResponse.AccessToken, nil
}
func (c *client) GetTokenMTLS(clientID, authURL string, certificate, privateKey []byte, headers, queryParameters *map[string][]string, skipVerify bool) (string, apperrors.AppError) {
token, found := c.tokenCache.Get(c.makeMTLSOAuthTokenCacheKey(clientID, authURL, certificate, privateKey))
if found {
return token, nil
}
cert, err := tls.X509KeyPair(certificate, privateKey)
if err != nil {
return "", apperrors.Internal("Failed to prepare certificate, %s", err.Error())
}
tokenResponse, requestError := c.requestTokenMTLS(clientID, authURL, cert, headers, queryParameters, skipVerify)
if err != nil {
return "", requestError
}
if tokenResponse == nil {
return "", apperrors.Internal("Failed to fetch token, possible certificate problem")
}
c.tokenCache.Add(c.makeMTLSOAuthTokenCacheKey(clientID, authURL, certificate, privateKey), tokenResponse.AccessToken, tokenResponse.ExpiresIn)
return tokenResponse.AccessToken, nil
}
func (c *client) InvalidateTokenCache(clientID, clientSecret, authURL string) {
c.tokenCache.Remove(c.makeOAuthTokenCacheKey(clientID, clientSecret, authURL))
}
func (c *client) InvalidateTokenCacheMTLS(clientID, authURL string, certificate, privateKey []byte) {
c.tokenCache.Remove(c.makeMTLSOAuthTokenCacheKey(clientID, authURL, certificate, privateKey))
}
// to avoid case of single clientID and different endpoints for MTLS and standard oauth
func (c *client) makeOAuthTokenCacheKey(clientID, clientSecret, authURL string) string {
return clientID + clientSecret + authURL
}
func (c *client) makeMTLSOAuthTokenCacheKey(clientID, authURL string, certificate, privateKey []byte) string {
certificateSha := sha256.Sum256(certificate)
keySha := sha256.Sum256(privateKey)
hashedCertificate := hex.EncodeToString(certificateSha[:])
hashedKey := hex.EncodeToString(keySha[:])
return fmt.Sprintf("%v-%v-%v-%v", clientID, hashedCertificate, hashedKey, authURL)
}
func (c *client) requestToken(clientID, clientSecret, authURL string, headers, queryParameters *map[string][]string, skipVerify bool) (*oauthResponse, apperrors.AppError) {
transport := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: skipVerify},
}
client := &http.Client{Transport: transport}
form := url.Values{}
form.Add("client_id", clientID)
form.Add("client_secret", clientSecret)
form.Add("grant_type", "client_credentials")
req, err := http.NewRequest(http.MethodPost, authURL, strings.NewReader(form.Encode()))
if err != nil {
return nil, apperrors.Internal("failed to create token request: %s", err.Error())
}
util.AddBasicAuthHeader(req, clientID, clientSecret)
req.Header.Add(httpconsts.HeaderContentType, httpconsts.ContentTypeApplicationURLEncoded)
setCustomQueryParameters(req.URL, queryParameters)
setCustomHeaders(req.Header, headers)
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(c.timeoutDuration)*time.Second)
defer cancel()
requestWithContext := req.WithContext(ctx)
response, err := client.Do(requestWithContext)
if err != nil {
return nil, apperrors.UpstreamServerCallFailed("failed to make a request to '%s': %s", authURL, err.Error())
}
if response.StatusCode != http.StatusOK {
return nil, apperrors.UpstreamServerCallFailed("incorrect response code '%d' while getting token from %s", response.StatusCode, authURL)
}
body, err := ioutil.ReadAll(response.Body)
defer response.Body.Close()
if err != nil {
return nil, apperrors.UpstreamServerCallFailed("failed to read token response body from '%s': %s", authURL, err.Error())
}
tokenResponse := &oauthResponse{}
err = json.Unmarshal(body, tokenResponse)
if err != nil {
return nil, apperrors.UpstreamServerCallFailed("failed to unmarshal token response body: %s", err.Error())
}
return tokenResponse, nil
}
func (c *client) requestTokenMTLS(clientID, authURL string, cert tls.Certificate, headers, queryParameters *map[string][]string, skipVerify bool) (*oauthResponse, apperrors.AppError) {
transport := &http.Transport{
TLSClientConfig: &tls.Config{
Certificates: []tls.Certificate{cert},
InsecureSkipVerify: skipVerify,
},
}
client := &http.Client{Transport: transport}
form := url.Values{}
form.Add("client_id", clientID)
form.Add("grant_type", "client_credentials")
req, err := http.NewRequest(http.MethodPost, authURL, strings.NewReader(form.Encode()))
if err != nil {
return nil, apperrors.Internal("failed to create token request: %s", err.Error())
}
req.Header.Add(httpconsts.HeaderContentType, httpconsts.ContentTypeApplicationURLEncoded)
setCustomQueryParameters(req.URL, queryParameters)
setCustomHeaders(req.Header, headers)
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(c.timeoutDuration)*time.Second)
defer cancel()
requestWithContext := req.WithContext(ctx)
response, err := client.Do(requestWithContext)
if err != nil {
return nil, apperrors.UpstreamServerCallFailed("failed to make a request to '%s': %s", authURL, err.Error())
}
if response.StatusCode != http.StatusOK {
return nil, apperrors.UpstreamServerCallFailed("incorrect response code '%d' while getting token from %s", response.StatusCode, authURL)
}
body, err := ioutil.ReadAll(response.Body)
defer response.Body.Close()
if err != nil {
return nil, apperrors.UpstreamServerCallFailed("failed to read token response body from '%s': %s", authURL, err.Error())
}
tokenResponse := &oauthResponse{}
err = json.Unmarshal(body, tokenResponse)
if err != nil {
return nil, apperrors.UpstreamServerCallFailed("failed to unmarshal token response body: %s", err.Error())
}
return tokenResponse, nil
}
func setCustomQueryParameters(reqURL *url.URL, customQueryParams *map[string][]string) {
httptools.SetQueryParameters(reqURL, customQueryParams)
}
func setCustomHeaders(reqHeaders http.Header, customHeaders *map[string][]string) {
if _, ok := reqHeaders[httpconsts.HeaderUserAgent]; !ok {
// explicitly disable User-Agent so it's not set to default value
reqHeaders.Set(httpconsts.HeaderUserAgent, "")
}
httptools.SetHeaders(reqHeaders, customHeaders)
}