This repository has been archived by the owner on Oct 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 62
/
handlers.go
435 lines (364 loc) · 17.9 KB
/
handlers.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
package auth
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"github.com/flyteorg/flyteidl/gen/pb-go/flyteidl/service"
"golang.org/x/oauth2"
"github.com/flyteorg/flyteadmin/pkg/audit"
"github.com/flyteorg/flyteadmin/pkg/common"
"google.golang.org/grpc/peer"
"github.com/grpc-ecosystem/go-grpc-middleware/util/metautils"
"github.com/flyteorg/flyteadmin/auth/interfaces"
"github.com/flyteorg/flytestdlib/errors"
"github.com/flyteorg/flytestdlib/logger"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
const (
RedirectURLParameter = "redirect_url"
FromHTTPKey = "from_http"
FromHTTPVal = "true"
)
type HTTPRequestToMetadataAnnotator func(ctx context.Context, request *http.Request) metadata.MD
func RegisterHandlers(ctx context.Context, handler interfaces.HandlerRegisterer, authCtx interfaces.AuthenticationContext) {
// Add HTTP handlers for OAuth2 endpoints
handler.HandleFunc("/login", RefreshTokensIfExists(ctx, authCtx,
GetLoginHandler(ctx, authCtx)))
handler.HandleFunc("/callback", GetCallbackHandler(ctx, authCtx))
// The metadata endpoint is an RFC-defined constant, but we need a leading / for the handler to pattern match correctly.
handler.HandleFunc(fmt.Sprintf("/%s", OIdCMetadataEndpoint), GetOIdCMetadataEndpointRedirectHandler(ctx, authCtx))
// These endpoints require authentication
handler.HandleFunc("/logout", GetLogoutEndpointHandler(ctx, authCtx))
}
// Look for access token and refresh token, if both are present and the access token is expired, then attempt to
// refresh. Otherwise do nothing and proceed to the next handler. If successfully refreshed, proceed to the landing page.
func RefreshTokensIfExists(ctx context.Context, authCtx interfaces.AuthenticationContext, authHandler http.HandlerFunc) http.HandlerFunc {
return func(writer http.ResponseWriter, request *http.Request) {
// Since we only do one thing if there are no errors anywhere along the chain, we can save code by just
// using one variable and checking for errors at the end.
idToken, accessToken, refreshToken, err := authCtx.CookieManager().RetrieveTokenValues(ctx, request)
if err != nil {
logger.Errorf(ctx, "Failed to retrieve tokens from request, redirecting to login handler. Error: %s", err)
authHandler(writer, request)
return
}
_, err = ParseIDTokenAndValidate(ctx, authCtx.Options().UserAuth.OpenID.ClientID, idToken, authCtx.OidcProvider())
if err != nil && errors.IsCausedBy(err, ErrTokenExpired) && len(refreshToken) > 0 {
logger.Debugf(ctx, "Expired id token found, attempting to refresh")
newToken, err := GetRefreshedToken(ctx, authCtx.OAuth2ClientConfig(GetPublicURL(ctx, request, authCtx.Options())), accessToken, refreshToken)
if err != nil {
logger.Infof(ctx, "Failed to refresh tokens. Restarting login flow. Error: %s", err)
authHandler(writer, request)
return
}
logger.Debugf(ctx, "Tokens are refreshed. Saving new tokens into cookies.")
err = authCtx.CookieManager().SetTokenCookies(ctx, writer, newToken)
if err != nil {
logger.Infof(ctx, "Failed to set token cookies. Restarting login flow. Error: %s", err)
authHandler(writer, request)
return
}
userInfo, err := QueryUserInfoUsingAccessToken(ctx, request, authCtx, newToken.AccessToken)
if err != nil {
logger.Infof(ctx, "Failed to query user info. Restarting login flow. Error: %s", err)
authHandler(writer, request)
return
}
err = authCtx.CookieManager().SetUserInfoCookie(ctx, writer, userInfo)
if err != nil {
logger.Infof(ctx, "Failed to set user info cookie. Restarting login flow. Error: %s", err)
authHandler(writer, request)
return
}
} else if err != nil {
logger.Infof(ctx, "Failed to validate tokens. Restarting login flow. Error: %s", err)
authHandler(writer, request)
return
}
redirectURL := getAuthFlowEndRedirect(ctx, authCtx, request)
http.Redirect(writer, request, redirectURL, http.StatusTemporaryRedirect)
}
}
// GetLoginHandler builds an http handler that handles authentication calls. Before redirecting to the authentication
// provider, it saves a cookie that contains the redirect url for after the authentication flow is done.
func GetLoginHandler(ctx context.Context, authCtx interfaces.AuthenticationContext) http.HandlerFunc {
return func(writer http.ResponseWriter, request *http.Request) {
csrfCookie := NewCsrfCookie()
csrfToken := csrfCookie.Value
http.SetCookie(writer, &csrfCookie)
state := HashCsrfState(csrfToken)
logger.Debugf(ctx, "Setting CSRF state cookie to %s and state to %s\n", csrfToken, state)
url := authCtx.OAuth2ClientConfig(GetPublicURL(ctx, request, authCtx.Options())).AuthCodeURL(state)
queryParams := request.URL.Query()
if flowEndRedirectURL := queryParams.Get(RedirectURLParameter); flowEndRedirectURL != "" {
redirectCookie := NewRedirectCookie(ctx, flowEndRedirectURL)
if redirectCookie != nil {
http.SetCookie(writer, redirectCookie)
} else {
logger.Errorf(ctx, "Was not able to create a redirect cookie")
}
}
http.Redirect(writer, request, url, http.StatusTemporaryRedirect)
}
}
// GetCallbackHandler returns a handler that is called by the OIdC provider with the authorization code to complete
// the user authentication flow.
func GetCallbackHandler(ctx context.Context, authCtx interfaces.AuthenticationContext) http.HandlerFunc {
return func(writer http.ResponseWriter, request *http.Request) {
logger.Debugf(ctx, "Running callback handler... for RequestURI %v", request.RequestURI)
authorizationCode := request.FormValue(AuthorizationResponseCodeType)
err := VerifyCsrfCookie(ctx, request)
if err != nil {
logger.Errorf(ctx, "Invalid CSRF token cookie %s", err)
writer.WriteHeader(http.StatusUnauthorized)
return
}
token, err := authCtx.OAuth2ClientConfig(GetPublicURL(ctx, request, authCtx.Options())).Exchange(ctx, authorizationCode)
if err != nil {
logger.Errorf(ctx, "Error when exchanging code %s", err)
writer.WriteHeader(http.StatusForbidden)
return
}
err = authCtx.CookieManager().SetTokenCookies(ctx, writer, token)
if err != nil {
logger.Errorf(ctx, "Error setting encrypted JWT cookie %s", err)
writer.WriteHeader(http.StatusForbidden)
return
}
userInfo, err := QueryUserInfoUsingAccessToken(ctx, request, authCtx, token.AccessToken)
if err != nil {
logger.Errorf(ctx, "Failed to query user info. Error: %v", err)
writer.WriteHeader(http.StatusForbidden)
return
}
err = authCtx.CookieManager().SetUserInfoCookie(ctx, writer, userInfo)
if err != nil {
logger.Errorf(ctx, "Error setting encrypted user info cookie. Error: %v", err)
writer.WriteHeader(http.StatusForbidden)
return
}
redirectURL := getAuthFlowEndRedirect(ctx, authCtx, request)
http.Redirect(writer, request, redirectURL, http.StatusTemporaryRedirect)
}
}
func AuthenticationLoggingInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
// Invoke 'handler' to use your gRPC server implementation and get
// the response.
identityContext := IdentityContextFromContext(ctx)
logger.Debugf(ctx, "gRPC server info in logging interceptor [%s] method [%s]\n", identityContext.UserID(), info.FullMethod)
return handler(ctx, req)
}
// GetAuthenticationCustomMetadataInterceptor produces a gRPC middleware interceptor intended to be used when running
// authentication with non-default gRPC headers (metadata). Because the default `authorization` header is reserved for
// use by Envoy, clients wishing to pass tokens to Admin will need to use a different string, specified in this
// package's Config object. This interceptor will scan for that arbitrary string, and then rename it to the default
// string, which the downstream auth/auditing interceptors will detect and validate.
func GetAuthenticationCustomMetadataInterceptor(authCtx interfaces.AuthenticationContext) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
if authCtx.Options().GrpcAuthorizationHeader != DefaultAuthorizationHeader {
md, ok := metadata.FromIncomingContext(ctx)
if ok {
existingHeader := md.Get(authCtx.Options().GrpcAuthorizationHeader)
if len(existingHeader) > 0 {
logger.Debugf(ctx, "Found existing metadata %s", existingHeader[0])
newAuthorizationMetadata := metadata.Pairs(DefaultAuthorizationHeader, existingHeader[0])
joinedMetadata := metadata.Join(md, newAuthorizationMetadata)
newCtx := metadata.NewIncomingContext(ctx, joinedMetadata)
return handler(newCtx, req)
}
} else {
logger.Debugf(ctx, "Could not extract incoming metadata from context, continuing with original ctx...")
}
}
return handler(ctx, req)
}
}
func SetContextForIdentity(ctx context.Context, identityContext interfaces.IdentityContext) context.Context {
email := identityContext.UserInfo().GetEmail()
newCtx := identityContext.WithContext(ctx)
if len(email) > 0 {
newCtx = WithUserEmail(newCtx, identityContext.UserID())
}
return WithAuditFields(newCtx, identityContext.UserID(), []string{identityContext.AppID()}, identityContext.AuthenticatedAt())
}
// GetAuthenticationInterceptor chooses to enforce or not enforce authentication. It will attempt to get the token
// from the incoming context, validate it, and decide whether or not to let the request through.
func GetAuthenticationInterceptor(authCtx interfaces.AuthenticationContext) func(context.Context) (context.Context, error) {
return func(ctx context.Context) (context.Context, error) {
logger.Debugf(ctx, "Running authentication gRPC interceptor")
fromHTTP := metautils.ExtractIncoming(ctx).Get(FromHTTPKey)
isFromHTTP := fromHTTP == FromHTTPVal
identityContext, err := GRPCGetIdentityFromAccessToken(ctx, authCtx)
if err == nil {
return SetContextForIdentity(ctx, identityContext), nil
}
logger.Infof(ctx, "Failed to parse Access Token from context. Will attempt to find IDToken. Error: %v", err)
identityContext, err = GRPCGetIdentityFromIDToken(ctx, authCtx.Options().UserAuth.OpenID.ClientID,
authCtx.OidcProvider())
if err == nil {
return SetContextForIdentity(ctx, identityContext), nil
}
// Only enforcement logic is present. The default case is to let things through.
if (isFromHTTP && !authCtx.Options().DisableForHTTP) ||
(!isFromHTTP && !authCtx.Options().DisableForGrpc) {
return ctx, status.Errorf(codes.Unauthenticated, "token parse error %s", err)
}
return ctx, nil
}
}
func WithUserEmail(ctx context.Context, email string) context.Context {
return context.WithValue(ctx, common.PrincipalContextKey, email)
}
func WithAuditFields(ctx context.Context, subject string, clientIds []string, tokenIssuedAt time.Time) context.Context {
var clientIP string
peerInfo, ok := peer.FromContext(ctx)
if ok {
clientIP = peerInfo.Addr.String()
}
return context.WithValue(ctx, common.AuditFieldsContextKey, audit.AuthenticatedClientMeta{
ClientIds: clientIds,
TokenIssuedAt: tokenIssuedAt,
ClientIP: clientIP,
Subject: subject,
})
}
// This is effectively middleware for the grpc gateway, it allows us to modify the translation between HTTP request
// and gRPC request. There are two potential sources for bearer tokens, it can come from an authorization header (not
// yet implemented), or encrypted cookies. Note that when deploying behind Envoy, you have the option to look for a
// configurable, non-standard header name. The token is extracted and turned into a metadata object which is then
// attached to the request, from which the token is extracted later for verification.
func GetHTTPRequestCookieToMetadataHandler(authCtx interfaces.AuthenticationContext) HTTPRequestToMetadataAnnotator {
return func(ctx context.Context, request *http.Request) metadata.MD {
// TODO: Improve error handling
idToken, _, _, _ := authCtx.CookieManager().RetrieveTokenValues(ctx, request)
if len(idToken) == 0 {
// If no token was found in the cookies, look for an authorization header, starting with a potentially
// custom header set in the Config object
if len(authCtx.Options().HTTPAuthorizationHeader) > 0 {
header := authCtx.Options().HTTPAuthorizationHeader
// TODO: There may be a potential issue here when running behind a service mesh that uses the default Authorization
// header. The grpc-gateway code will automatically translate the 'Authorization' header into the appropriate
// metadata object so if two different tokens are presented, one with the default name and one with the
// custom name, AuthFromMD will find the wrong one.
return metadata.MD{
DefaultAuthorizationHeader: []string{request.Header.Get(header)},
}
}
logger.Infof(ctx, "Could not find access token cookie while requesting %s", request.RequestURI)
return nil
}
meta := metadata.MD{
DefaultAuthorizationHeader: []string{fmt.Sprintf("%s %s", IDTokenScheme, idToken)},
}
userInfo, err := authCtx.CookieManager().RetrieveUserInfo(ctx, request)
if err != nil {
logger.Infof(ctx, "Failed to retrieve user info cookie. Ignoring. Error: %v", err)
}
raw, err := json.Marshal(userInfo)
if err != nil {
logger.Infof(ctx, "Failed to marshal user info. Ignoring. Error: %v", err)
}
if len(raw) > 0 {
meta.Set(UserInfoMDKey, string(raw))
}
return meta
}
}
// Intercepts the incoming HTTP requests and marks it as such so that the downstream code can use it to enforce auth.
// See the enforceHTTP/Grpc options for more information.
func GetHTTPMetadataTaggingHandler() HTTPRequestToMetadataAnnotator {
return func(ctx context.Context, request *http.Request) metadata.MD {
return metadata.MD{
FromHTTPKey: []string{FromHTTPVal},
}
}
}
func IdentityContextFromRequest(ctx context.Context, req *http.Request, authCtx interfaces.AuthenticationContext) (
interfaces.IdentityContext, error) {
authHeader := DefaultAuthorizationHeader
if len(authCtx.Options().HTTPAuthorizationHeader) > 0 {
authHeader = authCtx.Options().HTTPAuthorizationHeader
}
headerValue := req.Header.Get(authHeader)
if len(headerValue) == 0 {
headerValue = req.Header.Get(DefaultAuthorizationHeader)
}
if len(headerValue) > 0 {
logger.Debugf(ctx, "Found authorization header at [%v] header. Validating.", authHeader)
if strings.HasPrefix(headerValue, BearerScheme+" ") {
expectedAudience := GetPublicURL(ctx, req, authCtx.Options()).String()
return authCtx.OAuth2ResourceServer().ValidateAccessToken(ctx, expectedAudience, strings.TrimPrefix(headerValue, BearerScheme+" "))
}
}
idToken, _, _, err := authCtx.CookieManager().RetrieveTokenValues(ctx, req)
if err != nil || len(idToken) == 0 {
return nil, fmt.Errorf("unauthenticated request. IDToken Len [%v], Error: %w", len(idToken), err)
}
userInfo, err := authCtx.CookieManager().RetrieveUserInfo(ctx, req)
if err != nil {
logger.Infof(ctx, "Failed to retrieve user info cookie from request. Error: %v", err)
return nil, fmt.Errorf("unauthenticated request. Error: %w", err)
}
return IdentityContextFromIDTokenToken(ctx, idToken, authCtx.Options().UserAuth.OpenID.ClientID,
authCtx.OidcProvider(), userInfo)
}
func QueryUserInfo(ctx context.Context, identityContext interfaces.IdentityContext, request *http.Request,
authCtx interfaces.AuthenticationContext) (*service.UserInfoResponse, error) {
if identityContext.IsEmpty() {
return &service.UserInfoResponse{}, fmt.Errorf("request is unauthenticated, try /login in again")
}
if len(identityContext.UserInfo().GetName()) > 0 {
return identityContext.UserInfo(), nil
}
_, accessToken, _, err := authCtx.CookieManager().RetrieveTokenValues(ctx, request)
if err != nil {
return &service.UserInfoResponse{}, fmt.Errorf("error decoding identify token, try /login in again")
}
return QueryUserInfoUsingAccessToken(ctx, request, authCtx, accessToken)
}
func QueryUserInfoUsingAccessToken(ctx context.Context, originalRequest *http.Request, authCtx interfaces.AuthenticationContext, accessToken string) (
*service.UserInfoResponse, error) {
originalToken := oauth2.Token{
AccessToken: accessToken,
}
tokenSource := authCtx.OAuth2ClientConfig(GetPublicURL(ctx, originalRequest, authCtx.Options())).TokenSource(ctx, &originalToken)
// TODO: Investigate improving transparency of errors. The errors from this call may be just a local error, or may
// be an error from the HTTP request to the IDP. In the latter case, consider passing along the error code/msg.
userInfo, err := authCtx.OidcProvider().UserInfo(ctx, tokenSource)
if err != nil {
logger.Errorf(ctx, "Error getting user info from IDP %s", err)
return &service.UserInfoResponse{}, fmt.Errorf("error getting user info from IDP")
}
resp := &service.UserInfoResponse{}
err = userInfo.Claims(&resp)
if err != nil {
logger.Errorf(ctx, "Error getting user info from IDP %s", err)
return &service.UserInfoResponse{}, fmt.Errorf("error getting user info from IDP")
}
return resp, err
}
// This returns a handler that will redirect (303) to the well-known metadata endpoint for the OAuth2 authorization server
// See https://tools.ietf.org/html/rfc8414 for more information.
func GetOIdCMetadataEndpointRedirectHandler(ctx context.Context, authCtx interfaces.AuthenticationContext) http.HandlerFunc {
return func(writer http.ResponseWriter, request *http.Request) {
metadataURL := authCtx.Options().UserAuth.OpenID.BaseURL.ResolveReference(authCtx.GetOIdCMetadataURL())
http.Redirect(writer, request, metadataURL.String(), http.StatusSeeOther)
}
}
func GetLogoutEndpointHandler(ctx context.Context, authCtx interfaces.AuthenticationContext) http.HandlerFunc {
return func(writer http.ResponseWriter, request *http.Request) {
logger.Debugf(ctx, "Deleting auth cookies")
authCtx.CookieManager().DeleteCookies(ctx, writer)
// Redirect if one was given
queryParams := request.URL.Query()
if redirectURL := queryParams.Get(RedirectURLParameter); redirectURL != "" {
http.Redirect(writer, request, redirectURL, http.StatusTemporaryRedirect)
}
}
}