-
Notifications
You must be signed in to change notification settings - Fork 84
/
token_utils.go
314 lines (252 loc) · 10.4 KB
/
token_utils.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
package token
import (
"bytes"
"context"
"crypto/tls"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"testing"
"time"
"github.com/pkg/errors"
"github.com/kyma-incubator/compass/components/external-services-mock/pkg/claims"
"github.com/kyma-incubator/compass/tests/pkg/util"
"github.com/tidwall/sjson"
"github.com/kyma-incubator/compass/components/director/pkg/log"
"github.com/tidwall/gjson"
"github.com/kyma-incubator/compass/components/director/pkg/graphql"
"github.com/stretchr/testify/require"
)
type HydraToken struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
Scope string `json:"scope"`
TokenType string `json:"token_type"`
}
type OauthConfig struct {
TokenURL string
ClientID string
ClientSecret string
Data url.Values
}
const (
RuntimeScopes = "webhook:write runtime:read runtime:write application:read runtime.auths:read bundle.instance_auths:read"
ApplicationScopes = "webhook:write application:read application:write application.auths:read application.webhooks:read application.application_template:read bundle.instance_auths:read document.fetch_request:read event_spec.fetch_request:read api_spec.fetch_request:read fetch-request.auth:read"
IntegrationSystemScopes = "application.local_tenant_id:write webhook:write application:read application:write application_template:read application_template:write runtime:read runtime:write integration_system:read label_definition:read label_definition:write automatic_scenario_assignment:read integration_system.auths:read application_template.webhooks:read internal_visibility:read application.auths:read formation:write"
IntegrationSystemScopesWithoutInternalVisibility = "application.local_tenant_id:write webhook:write application:read application:write application_template:read application_template:write runtime:read runtime:write integration_system:read label_definition:read label_definition:write automatic_scenario_assignment:read integration_system.auths:read application_template.webhooks:read"
grantTypeFieldName = "grant_type"
passwordGrantType = "password"
credentialsGrantType = "client_credentials"
clientIDKey = "client_id"
clientSecretKey = "client_secret"
scopeKey = "scope"
userNameKey = "username"
passwordKey = "password"
)
func FetchHydraAccessToken(t *testing.T, encodedCredentials string, tokenURL string, scopes string) (*HydraToken, error) {
form := url.Values{}
form.Set(grantTypeFieldName, credentialsGrantType)
form.Set(scopeKey, scopes)
req, err := http.NewRequest("POST", tokenURL, strings.NewReader(form.Encode()))
require.NoError(t, err)
req.Header.Add(util.ContentTypeHeader, util.ContentTypeApplicationURLEncoded)
req.Header.Add("Authorization", fmt.Sprintf("Basic %s", encodedCredentials))
transport := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{
Transport: transport,
}
resp, err := client.Do(req)
require.NoError(t, err)
defer HttpRequestBodyCloser(t, resp)
token, err := ioutil.ReadAll(resp.Body)
require.NoError(t, err)
hydraToken := HydraToken{}
err = json.Unmarshal(token, &hydraToken)
require.NoError(t, err)
if resp.StatusCode != http.StatusOK {
return nil, errors.Errorf("response status code is %d", resp.StatusCode)
}
return &hydraToken, nil
}
func FetchHydraAccessTokenBench(b *testing.B, encodedCredentials string, tokenURL string, scopes string) (*HydraToken, error) {
form := url.Values{}
form.Set(grantTypeFieldName, credentialsGrantType)
form.Set(scopeKey, scopes)
req, err := http.NewRequest("POST", tokenURL, strings.NewReader(form.Encode()))
require.NoError(b, err)
req.Header.Add(util.ContentTypeHeader, util.ContentTypeApplicationURLEncoded)
req.Header.Add("Authorization", fmt.Sprintf("Basic %s", encodedCredentials))
transport := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{
Transport: transport,
}
resp, err := client.Do(req)
require.NoError(b, err)
defer HttpRequestBodyCloserBench(b, resp)
token, err := ioutil.ReadAll(resp.Body)
require.NoError(b, err)
hydraToken := HydraToken{}
err = json.Unmarshal(token, &hydraToken)
require.NoError(b, err)
if resp.StatusCode != http.StatusOK {
return nil, errors.Errorf("response status code is %d", resp.StatusCode)
}
return &hydraToken, nil
}
func GetAccessToken(t *testing.T, oauthCredentialData *graphql.OAuthCredentialData, scopes string) string {
oauthCredentials := fmt.Sprintf("%s:%s", oauthCredentialData.ClientID, oauthCredentialData.ClientSecret)
encodedCredentials := base64.StdEncoding.EncodeToString([]byte(oauthCredentials))
hydraToken, err := FetchHydraAccessToken(t, encodedCredentials, oauthCredentialData.URL, scopes)
require.NoError(t, err)
return hydraToken.AccessToken
}
func GetAccessTokenBench(b *testing.B, oauthCredentialData *graphql.OAuthCredentialData, scopes string) string {
oauthCredentials := fmt.Sprintf("%s:%s", oauthCredentialData.ClientID, oauthCredentialData.ClientSecret)
encodedCredentials := base64.StdEncoding.EncodeToString([]byte(oauthCredentials))
hydraToken, err := FetchHydraAccessTokenBench(b, encodedCredentials, oauthCredentialData.URL, scopes)
require.NoError(b, err)
return hydraToken.AccessToken
}
func HttpRequestBodyCloser(t *testing.T, resp *http.Response) {
err := resp.Body.Close()
require.NoError(t, err)
}
func HttpRequestBodyCloserBench(b *testing.B, resp *http.Response) {
err := resp.Body.Close()
require.NoError(b, err)
}
func GetClientCredentialsToken(t *testing.T, ctx context.Context, tokenURL, clientID, clientSecret, staticMappingClaimsKey string) string {
log.C(ctx).Info("Issuing client_credentials token...")
data := url.Values{}
data.Add(grantTypeFieldName, credentialsGrantType)
data.Add(clientIDKey, clientID)
data.Add(clientSecretKey, clientSecret)
data.Add(claims.ClaimsKey, staticMappingClaimsKey)
token := GetToken(t, ctx, tokenURL, clientID, clientSecret, data)
log.C(ctx).Info("Successfully issued client_credentials token")
return token
}
func GetClientCredentialsTokenWithClient(t *testing.T, ctx context.Context, client *http.Client, tokenURL, clientID, clientSecret, staticMappingClaimsKey string) string {
log.C(ctx).Info("Issuing client_credentials token...")
data := url.Values{}
data.Add(grantTypeFieldName, credentialsGrantType)
data.Add(clientIDKey, clientID)
data.Add(clientSecretKey, clientSecret)
data.Add(claims.ClaimsKey, staticMappingClaimsKey)
oauthConfig := OauthConfig{
TokenURL: tokenURL,
ClientID: clientID,
ClientSecret: clientSecret,
Data: data,
}
token := GetTokenWithClient(t, ctx, client, oauthConfig)
log.C(ctx).Info("Successfully issued client_credentials token")
return token
}
func GetUserToken(t *testing.T, ctx context.Context, tokenURL, clientID, clientSecret, username, password, staticMappingClaimsKey string) string {
log.C(ctx).Info("Issuing user token...")
data := url.Values{}
data.Add(grantTypeFieldName, passwordGrantType)
data.Add(clientIDKey, clientID)
data.Add(claims.ClaimsKey, staticMappingClaimsKey)
data.Add(userNameKey, username)
data.Add(passwordKey, password)
token := GetToken(t, ctx, tokenURL, clientID, clientSecret, data)
log.C(ctx).Info("Successfully issued user token")
return token
}
func GetToken(t *testing.T, ctx context.Context, tokenURL, clientID, clientSecret string, data url.Values) string {
httpClient := &http.Client{
Timeout: 10 * time.Second,
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
},
}
oauthConfig := OauthConfig{
TokenURL: tokenURL,
ClientID: clientID,
ClientSecret: clientSecret,
Data: data,
}
return GetTokenWithClient(t, ctx, httpClient, oauthConfig)
}
func GetTokenWithClient(t *testing.T, ctx context.Context, client *http.Client, oauthConfig OauthConfig) string {
req, err := http.NewRequest(http.MethodPost, oauthConfig.TokenURL, bytes.NewBuffer([]byte(oauthConfig.Data.Encode())))
require.NoError(t, err)
if oauthConfig.Data.Get(userNameKey) != "" && oauthConfig.Data.Get(passwordKey) != "" {
req.SetBasicAuth(oauthConfig.ClientID, oauthConfig.ClientSecret)
}
req.Header.Add(util.ContentTypeHeader, util.ContentTypeApplicationURLEncoded)
resp, err := client.Do(req)
defer func() {
if err := resp.Body.Close(); err != nil {
log.C(ctx).WithError(err).Errorf("An error has occurred while closing response body: %v", err)
}
}()
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode, fmt.Sprintf("failed to get token: unexpected status code: expected: %d, actual: %d", http.StatusOK, resp.StatusCode))
require.NotEmpty(t, resp.Body)
body, err := ioutil.ReadAll(resp.Body)
require.NoError(t, err)
tkn := gjson.GetBytes(body, "access_token")
require.True(t, tkn.Exists())
require.NotEmpty(t, tkn)
return tkn.String()
}
func FlattenTokenClaims(stdT *testing.T, consumerToken string) string {
consumerTokenPayload := getTokenPayload(stdT, consumerToken)
var jsonMap map[string]interface{}
err := json.Unmarshal([]byte(consumerTokenPayload), &jsonMap)
require.NoError(stdT, err)
fm := flatten(jsonMap)
claims := "{}"
for k, v := range fm {
claims, err = sjson.Set(claims, k, v)
require.NoError(stdT, err)
}
return claims
}
func ChangeSubdomain(tokenURL, newSubdomain, oauthTokenPath string) (string, error) {
baseTokenURL, err := url.Parse(tokenURL)
if err != nil {
return "", errors.Errorf("failed to parse auth url '%s': %v", tokenURL, err)
}
parts := strings.Split(baseTokenURL.Hostname(), ".")
if len(parts) < 2 {
return "", errors.Errorf("auth url '%s' should have a subdomain", tokenURL)
}
originalSubdomain := parts[0]
return strings.Replace(tokenURL, originalSubdomain, newSubdomain, 1) + oauthTokenPath, nil
}
func getTokenPayload(t *testing.T, token string) string {
// JWT format: <header>.<payload>.<signature>
tokenParts := strings.Split(token, ".")
require.Equal(t, 3, len(tokenParts), "invalid token format")
payload := tokenParts[1]
b, err := base64.RawURLEncoding.DecodeString(payload)
require.NoError(t, err)
return string(b)
}
func flatten(m map[string]interface{}) map[string]interface{} {
o := make(map[string]interface{})
for k, v := range m {
switch child := v.(type) {
case map[string]interface{}:
nm := flatten(child)
for nk, nv := range nm {
o[nk] = nv
}
default:
o[k] = v
}
}
return o
}