/
handler.go
453 lines (378 loc) · 14.9 KB
/
handler.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
/*
* Copyright 2020 The Compass Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package authnmappinghandler
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"sync"
"github.com/kyma-incubator/compass/components/director/pkg/httputils"
cfg "github.com/kyma-incubator/compass/components/hydrator/internal/config"
"github.com/kyma-incubator/compass/components/hydrator/pkg/authenticator"
"golang.org/x/oauth2"
"github.com/gorilla/mux"
"github.com/tidwall/gjson"
goidc "github.com/coreos/go-oidc/v3/oidc"
"github.com/kyma-incubator/compass/components/director/pkg/log"
"github.com/kyma-incubator/compass/components/hydrator/pkg/oathkeeper"
"github.com/pkg/errors"
)
// TokenData represents the authentication token
//
//go:generate mockery --name=TokenData --output=automock --outpkg=automock --case=underscore --disable-version-string
type TokenData interface {
// Claims reads the Claims from the token into the specified struct
Claims(v interface{}) error
}
// TokenVerifier attempts to verify a token and returns it or an error if the verification was not successful
//
//go:generate mockery --name=TokenVerifier --output=automock --outpkg=automock --case=underscore --disable-version-string
type TokenVerifier interface {
// Verify verifies that the token is valid and returns a token if so, otherwise returns an error
Verify(ctx context.Context, token string) (TokenData, error)
}
// ReqDataParser parses request data
//
//go:generate mockery --name=ReqDataParser --output=automock --outpkg=automock --case=underscore --disable-version-string
type ReqDataParser interface {
Parse(req *http.Request) (oathkeeper.ReqData, error)
}
// TokenVerifierProvider defines different ways by which one can provide a TokenVerifier
type TokenVerifierProvider func(ctx context.Context, metadata OpenIDMetadata) TokenVerifier
// Handler is the base struct definition of the AuthenticationMappingHandler
type Handler struct {
reqDataParser ReqDataParser
httpClient *http.Client
tokenVerifierProvider TokenVerifierProvider
verifiers map[string]TokenVerifier
verifiersMutex sync.RWMutex
authenticators []authenticator.Config
}
// OpenIDMetadata contains basic metadata for OIDC provider needed during request authentication
type OpenIDMetadata struct {
Issuer string `json:"issuer"`
JWKSURL string `json:"jwks_uri"`
}
// oidcVerifier wraps the default goidc.IDTokenVerifier
type oidcVerifier struct {
*goidc.IDTokenVerifier
}
// Verify implements security.TokenVerifier and delegates to oidc.IDTokenVerifier
func (v *oidcVerifier) Verify(ctx context.Context, idToken string) (TokenData, error) {
return v.IDTokenVerifier.Verify(ctx, idToken)
}
// DefaultTokenVerifierProvider is the default TokenVerifierProvider which leverages goidc liberay
func DefaultTokenVerifierProvider(ctx context.Context, metadata OpenIDMetadata) TokenVerifier {
keySet := goidc.NewRemoteKeySet(ctx, metadata.JWKSURL)
verifier := &oidcVerifier{
IDTokenVerifier: goidc.NewVerifier(metadata.Issuer, keySet, &goidc.Config{SkipClientIDCheck: true}),
}
return verifier
}
// NewHandler constructs the AuthenticationMappingHandler
func NewHandler(ctx context.Context, reqDataParser ReqDataParser, httpClient *http.Client, tokenVerifierProvider TokenVerifierProvider, authenticators []authenticator.Config, initialSubdomainsForAuthenticators []cfg.AuthenticatorSubdomainMapping) *Handler {
handler := &Handler{
reqDataParser: reqDataParser,
httpClient: httpClient,
tokenVerifierProvider: tokenVerifierProvider,
verifiers: make(map[string]TokenVerifier),
verifiersMutex: sync.RWMutex{},
authenticators: authenticators,
}
handler.loadVerifiers(ctx, initialSubdomainsForAuthenticators)
return handler
}
type authenticationError struct {
Message string `json:"message"`
}
// ServeHTTP missing godoc
func (h *Handler) ServeHTTP(writer http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPost {
http.Error(writer, fmt.Sprintf("Bad request method. Got %s, expected POST", req.Method), http.StatusOK)
return
}
ctx := context.WithValue(req.Context(), oauth2.HTTPClient, h.httpClient)
reqData, err := h.reqDataParser.Parse(req)
if err != nil {
h.logError(ctx, err, "An error has occurred while parsing the request")
http.Error(writer, "Unable to parse request data", http.StatusOK)
return
}
vars := mux.Vars(req)
matchedAuthenticator, ok := vars["authenticator"]
if !ok {
h.logError(ctx, errors.New("authenticator not found in path"), "An error has occurred while extracting authenticator name")
reqData.Body.Extra["error"] = authenticationError{Message: "Missing authenticator"}
h.respond(ctx, writer, reqData.Body)
return
}
log.C(ctx).Infof("Matched authenticator is %s", matchedAuthenticator)
claims, authCoordinates, err := h.verifyToken(ctx, reqData, matchedAuthenticator)
if err != nil {
h.logError(ctx, err, "An error has occurred while processing the request")
reqData.Body.Extra["error"] = authenticationError{Message: "Token validation failed"}
h.respond(ctx, writer, reqData.Body)
return
}
if err := claims.Claims(&reqData.Body.Extra); err != nil {
h.logError(ctx, err, "An error has occurred while extracting claims to request body.extra")
reqData.Body.Extra["error"] = authenticationError{Message: "Token claims extraction failed"}
h.respond(ctx, writer, reqData.Body)
return
}
reqData.Body.Extra[authenticator.CoordinatesKey] = authCoordinates
h.respond(ctx, writer, reqData.Body)
}
func (h *Handler) verifyToken(ctx context.Context, reqData oathkeeper.ReqData, authenticatorName string) (TokenData, authenticator.Coordinates, error) {
authorizationHeader := reqData.Header.Get("Authorization")
if authorizationHeader == "" || !strings.HasPrefix(strings.ToLower(authorizationHeader), "bearer ") {
return nil, authenticator.Coordinates{}, errors.Errorf("unexpected or empty authorization header with length %d", len(authorizationHeader))
}
token := strings.TrimSpace(authorizationHeader[len("Bearer "):])
tokenPayload, err := getTokenPayload(token)
if err != nil {
return nil, authenticator.Coordinates{}, errors.Wrapf(err, "while getting token payload")
}
issuerSubdomain, err := extractTokenIssuerSubdomain(tokenPayload)
if err != nil {
return nil, authenticator.Coordinates{}, errors.Wrap(err, "error while extracting token issuer subdomain")
}
config, err := h.getAuthenticatorConfig(authenticatorName, tokenPayload)
if err != nil {
return nil, authenticator.Coordinates{}, errors.Wrapf(err, "while getting matched authenticator config")
}
index := -1
var claims TokenData
aggregatedErr := errors.New("aggregated error for all issuers")
for i, issuer := range config.TrustedIssuers {
protocol := "https"
if len(issuer.Protocol) > 0 {
protocol = issuer.Protocol
}
issuerURL := fmt.Sprintf("%s://%s.%s%s", protocol, issuerSubdomain, issuer.DomainURL, "/oauth/token")
h.verifiersMutex.RLock()
verifier, found := h.verifiers[issuerURL]
h.verifiersMutex.RUnlock()
if found {
log.C(ctx).Infof("Verifier for issuer %q exists", issuerURL)
claims, err = verifier.Verify(ctx, token)
if err != nil {
aggregatedErr = errors.Wrapf(aggregatedErr, "unable to verify token with issuer %q: %s", issuerURL, err)
continue
}
index = i
break
}
}
for i, issuer := range config.TrustedIssuers {
if index != -1 {
// The token is already verified successfully
break
}
protocol := "https"
if len(issuer.Protocol) > 0 {
protocol = issuer.Protocol
}
issuerURL := fmt.Sprintf("%s://%s.%s%s", protocol, issuerSubdomain, issuer.DomainURL, "/oauth/token")
log.C(ctx).Infof("Verifier for issuer %q not found. Attempting to construct new verifier from well-known endpoint", issuerURL)
resp, err := h.getOpenIDConfig(ctx, issuerURL)
if err != nil {
aggregatedErr = errors.Wrapf(aggregatedErr, "error while getting OpenIDCOnfig for issuer %q: %s", issuerURL, err)
continue
}
if resp.StatusCode != http.StatusOK {
aggregatedErr = errors.Wrapf(aggregatedErr, "error for issuer %q: %s", issuerURL, handleResponseError(ctx, resp))
continue
}
var m OpenIDMetadata
if err := json.NewDecoder(resp.Body).Decode(&m); err != nil {
aggregatedErr = errors.Wrapf(aggregatedErr, "while decoding body of response for issuer %q: %s", issuerURL, err)
continue
}
defer httputils.Close(ctx, resp.Body)
verifier := h.tokenVerifierProvider(ctx, m)
h.verifiersMutex.Lock()
h.verifiers[issuerURL] = verifier
h.verifiersMutex.Unlock()
log.C(ctx).Infof("Successfully constructed verifier for issuer %q", issuerURL)
claims, err = verifier.Verify(ctx, token)
if err != nil {
aggregatedErr = errors.Wrapf(aggregatedErr, "unable to verify token with issuer %q: %s", issuerURL, err)
continue
}
index = i
break
}
if index == -1 {
return nil, authenticator.Coordinates{}, aggregatedErr
}
if config.CheckSuffix {
c := make(map[string]interface{})
if err = claims.Claims(&c); err != nil {
return nil, authenticator.Coordinates{}, err
}
for _, suffix := range config.ClientIDSuffixes {
if strings.HasSuffix(c[config.Attributes.ClientID.Key].(string), suffix) {
return claims, authenticator.Coordinates{
Name: config.Name,
Index: index,
}, nil
}
}
return nil, authenticator.Coordinates{}, errors.Wrapf(aggregatedErr, "client suffix mismatch")
}
return claims, authenticator.Coordinates{
Name: config.Name,
Index: index,
}, nil
}
func (h *Handler) logError(ctx context.Context, err error, message string) {
log.C(ctx).WithError(err).Error(message)
}
func (h *Handler) respond(ctx context.Context, writer http.ResponseWriter, body oathkeeper.ReqBody) {
writer.Header().Set("Content-Type", "application/json")
err := json.NewEncoder(writer).Encode(body)
if err != nil {
h.logError(ctx, err, "An error has occurred while encoding data")
}
}
func (h *Handler) getOpenIDConfig(ctx context.Context, issuerURL string) (*http.Response, error) {
// Work around for UAA until https://github.com/cloudfoundry/uaa/issues/805 is fixed
// Then goidc.NewProvider(ctx, options.IssuerURL) should be used
if _, err := url.ParseRequestURI(issuerURL); err != nil {
return nil, err
}
wellKnown := strings.TrimSuffix(strings.TrimSuffix(issuerURL, "/"), "/oauth/token") + "/.well-known/openid-configuration"
req, err := http.NewRequest(http.MethodGet, wellKnown, nil)
if err != nil {
return nil, err
}
resp, err := h.httpClient.Do(req.WithContext(ctx))
if err != nil {
return nil, err
}
return resp, nil
}
func (h *Handler) loadVerifiers(ctx context.Context, initialSubdomainsForAuthenticators []cfg.AuthenticatorSubdomainMapping) {
for _, subdomainAuthenticatorMapping := range initialSubdomainsForAuthenticators {
authenticatorName := subdomainAuthenticatorMapping.Authenticator
issuerSubdomain := subdomainAuthenticatorMapping.Subdomain
var authConfig *authenticator.Config
for i, authn := range h.authenticators {
if authn.Name == authenticatorName {
authConfig = &h.authenticators[i]
break
}
}
if authConfig == nil {
log.C(ctx).Infof("could not find authenticator with name %q in order to load subdomain %q", authenticatorName, issuerSubdomain)
continue
}
for _, issuer := range authConfig.TrustedIssuers {
protocol := "https"
if len(issuer.Protocol) > 0 {
protocol = issuer.Protocol
}
issuerURL := fmt.Sprintf("%s://%s.%s%s", protocol, issuerSubdomain, issuer.DomainURL, "/oauth/token")
log.C(ctx).Infof("Verifier for issuer %q not found. Attempting to construct new verifier from well-known endpoint", issuerURL)
resp, err := h.getOpenIDConfig(ctx, issuerURL)
if err != nil {
log.C(ctx).Errorf("error while getting OpenIDCOnfig for issuer %q: %s", issuerURL, err)
continue
}
if resp.StatusCode != http.StatusOK {
log.C(ctx).Errorf("error for issuer %q: %s", issuerURL, handleResponseError(ctx, resp))
continue
}
var m OpenIDMetadata
if err := json.NewDecoder(resp.Body).Decode(&m); err != nil {
log.C(ctx).Errorf("while decoding body of response for issuer %q: %s", issuerURL, err)
continue
}
defer httputils.Close(ctx, resp.Body)
verifier := h.tokenVerifierProvider(ctx, m)
h.verifiersMutex.Lock()
h.verifiers[issuerURL] = verifier
h.verifiersMutex.Unlock()
log.C(ctx).Infof("Successfully constructed verifier for issuer %q", issuerURL)
}
}
}
func (h *Handler) getAuthenticatorConfig(matchedAuthenticatorName string, payload []byte) (*authenticator.Config, error) {
var authConfig *authenticator.Config
for i, authn := range h.authenticators {
if authn.Name == matchedAuthenticatorName {
uniqueAttribute := gjson.GetBytes(payload, authn.Attributes.UniqueAttribute.Key).String()
if uniqueAttribute == "" || uniqueAttribute != authn.Attributes.UniqueAttribute.Value {
return nil, errors.New("unique attribute mismatch")
}
authConfig = &h.authenticators[i]
break
}
}
if authConfig == nil {
return nil, errors.New("could not find authenticator for token")
}
return authConfig, nil
}
func getTokenPayload(token string) ([]byte, error) {
// JWT format: <header>.<payload>.<signature>
tokenParts := strings.Split(token, ".")
if len(tokenParts) != 3 {
return nil, errors.New("invalid token format")
}
payload := tokenParts[1]
return base64.RawURLEncoding.DecodeString(payload)
}
func extractTokenIssuerSubdomain(payload []byte) (string, error) {
data := &struct {
IssuerURL string `json:"iss"`
}{}
if err := json.Unmarshal(payload, data); err != nil {
return "", err
}
parsedIssuer, err := url.Parse(data.IssuerURL)
if err != nil {
return "", err
}
s := strings.Split(parsedIssuer.Hostname(), ".")
if len(s) < 2 || s[0] == "" {
return "", fmt.Errorf("could not extract subdomain from issuer URL %s", data.IssuerURL)
}
return s[0], nil
}
// handleResponseError builds an error from the given response
func handleResponseError(ctx context.Context, response *http.Response) error {
defer func() {
if err := response.Body.Close(); err != nil {
log.C(ctx).Errorf("ReadCloser couldn't be closed: %v", err)
}
}()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
body = []byte(fmt.Sprintf("error reading response body: %s", err))
}
err = fmt.Errorf("StatusCode: %d Body: %s", response.StatusCode, body)
if response.Request != nil {
return fmt.Errorf("request %s %s failed: %s", response.Request.Method, response.Request.URL, err)
}
return fmt.Errorf("request failed: %s", err)
}