-
Notifications
You must be signed in to change notification settings - Fork 351
/
auth_middleware.go
396 lines (371 loc) · 13.7 KB
/
auth_middleware.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
package api
import (
"context"
"errors"
"fmt"
"net/http"
"strings"
"time"
"github.com/getkin/kin-openapi/openapi3"
"github.com/getkin/kin-openapi/routers"
"github.com/getkin/kin-openapi/routers/legacy"
"github.com/gorilla/sessions"
"github.com/treeverse/lakefs/pkg/api/apigen"
"github.com/treeverse/lakefs/pkg/auth"
"github.com/treeverse/lakefs/pkg/auth/model"
oidcencoding "github.com/treeverse/lakefs/pkg/auth/oidc/encoding"
"github.com/treeverse/lakefs/pkg/logging"
)
const (
TokenSessionKeyName = "token"
InternalAuthSessionName = "internal_auth_session"
IDTokenClaimsSessionKey = "id_token_claims"
OIDCAuthSessionName = "oidc_auth_session"
SAMLTokenClaimsSessionKey = "saml_token_claims"
SAMLAuthSessionName = "saml_auth_session"
)
// extractSecurityRequirements using Swagger returns an array of security requirements set for the request.
func extractSecurityRequirements(router routers.Router, r *http.Request) (openapi3.SecurityRequirements, error) {
// Find route
route, _, err := router.FindRoute(r)
if err != nil {
return nil, err
}
if route.Operation.Security == nil {
return route.Swagger.Security, nil
}
return *route.Operation.Security, nil
}
type OIDCConfig struct {
ValidateIDTokenClaims map[string]string
DefaultInitialGroups []string
InitialGroupsClaimName string
FriendlyNameClaimName string
}
type CookieAuthConfig struct {
ValidateIDTokenClaims map[string]string
DefaultInitialGroups []string
InitialGroupsClaimName string
FriendlyNameClaimName string
ExternalUserIDClaimName string
AuthSource string
}
func GenericAuthMiddleware(logger logging.Logger, authenticator auth.Authenticator, authService auth.Service, oidcConfig *OIDCConfig, cookieAuthConfig *CookieAuthConfig) (func(next http.Handler) http.Handler, error) {
swagger, err := apigen.GetSwagger()
if err != nil {
return nil, err
}
sessionStore := sessions.NewCookieStore(authService.SecretStore().SharedSecret())
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, err := checkSecurityRequirements(r, swagger.Security, logger, authenticator, authService, sessionStore, oidcConfig, cookieAuthConfig)
if err != nil {
writeError(w, r, http.StatusUnauthorized, err)
return
}
if user != nil {
ctx := logging.AddFields(r.Context(), logging.Fields{logging.UserFieldKey: user.Username})
r = r.WithContext(auth.WithUser(ctx, user))
}
next.ServeHTTP(w, r)
})
}, nil
}
func AuthMiddleware(logger logging.Logger, swagger *openapi3.Swagger, authenticator auth.Authenticator, authService auth.Service, sessionStore sessions.Store, oidcConfig *OIDCConfig, cookieAuthConfig *CookieAuthConfig) func(next http.Handler) http.Handler {
router, err := legacy.NewRouter(swagger)
if err != nil {
panic(err)
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// if request already authenticated
if _, userNotFoundErr := auth.GetUser(r.Context()); userNotFoundErr == nil {
next.ServeHTTP(w, r)
return
}
securityRequirements, err := extractSecurityRequirements(router, r)
if err != nil {
writeError(w, r, http.StatusBadRequest, err)
return
}
user, err := checkSecurityRequirements(r, securityRequirements, logger, authenticator, authService, sessionStore, oidcConfig, cookieAuthConfig)
if err != nil {
writeError(w, r, http.StatusUnauthorized, err)
return
}
if user != nil {
ctx := logging.AddFields(r.Context(), logging.Fields{logging.UserFieldKey: user.Username})
r = r.WithContext(auth.WithUser(ctx, user))
}
next.ServeHTTP(w, r)
})
}
}
// checkSecurityRequirements goes over the security requirements and check the authentication. returns the user information and error if the security check was required.
// it will return nil user and error in case of no security checks to match.
func checkSecurityRequirements(r *http.Request,
securityRequirements openapi3.SecurityRequirements,
logger logging.Logger,
authenticator auth.Authenticator,
authService auth.Service,
sessionStore sessions.Store,
oidcConfig *OIDCConfig,
cookieAuthConfig *CookieAuthConfig,
) (*model.User, error) {
ctx := r.Context()
var user *model.User
var err error
logger = logger.WithContext(ctx)
for _, securityRequirement := range securityRequirements {
for provider := range securityRequirement {
switch provider {
case "jwt_token":
// validate jwt token from header
authHeaderValue := r.Header.Get("Authorization")
if authHeaderValue == "" {
continue
}
parts := strings.Fields(authHeaderValue)
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
continue
}
token := parts[1]
user, err = userByToken(ctx, logger, authService, token)
case "basic_auth":
// validate using basic auth
accessKey, secretKey, ok := r.BasicAuth()
if !ok {
continue
}
user, err = userByAuth(ctx, logger, authenticator, authService, accessKey, secretKey)
case "cookie_auth":
var internalAuthSession *sessions.Session
internalAuthSession, _ = sessionStore.Get(r, InternalAuthSessionName)
token := ""
if internalAuthSession != nil {
token, _ = internalAuthSession.Values[TokenSessionKeyName].(string)
}
if token == "" {
continue
}
user, err = userByToken(ctx, logger, authService, token)
case "oidc_auth":
var oidcSession *sessions.Session
oidcSession, err = sessionStore.Get(r, OIDCAuthSessionName)
if err != nil {
return nil, err
}
user, err = userFromOIDC(ctx, logger, authService, oidcSession, oidcConfig)
case "saml_auth":
var samlSession *sessions.Session
samlSession, err = sessionStore.Get(r, SAMLAuthSessionName)
if err != nil {
return nil, err
}
user, err = userFromSAML(ctx, logger, authService, samlSession, cookieAuthConfig)
default:
// unknown security requirement to check
logger.WithField("provider", provider).Error("Authentication middleware unknown security requirement provider")
return nil, ErrAuthenticatingRequest
}
if err != nil {
return nil, err
}
if user != nil {
return user, nil
}
}
}
return nil, nil
}
func enhanceWithFriendlyName(user *model.User, friendlyName string) *model.User {
if friendlyName != "" {
user.FriendlyName = &friendlyName
}
return user
}
// userFromSAML returns a user from an existing SAML session.
// If the user doesn't exist on the lakeFS side, it is created.
// This function does not make any calls to an external provider.
func userFromSAML(ctx context.Context, logger logging.Logger, authService auth.Service, authSession *sessions.Session, cookieAuthConfig *CookieAuthConfig) (*model.User, error) {
idTokenClaims, ok := authSession.Values[SAMLTokenClaimsSessionKey].(oidcencoding.Claims)
if idTokenClaims == nil {
return nil, nil
}
if !ok {
logger.WithField("claims", authSession.Values[SAMLTokenClaimsSessionKey]).Debug("failed decoding tokens")
return nil, fmt.Errorf("getting token claims: %w", ErrAuthenticatingRequest)
}
logger.WithField("claims", idTokenClaims).Debug("Success decoding token claims")
idKey := cookieAuthConfig.ExternalUserIDClaimName
externalID, ok := idTokenClaims[idKey].(string)
if !ok {
logger.WithField(idKey, idTokenClaims[idKey]).Error("Failed type assertion for sub claim")
return nil, ErrAuthenticatingRequest
}
log := logger.WithField("external_id", externalID)
for claimName, expectedValue := range cookieAuthConfig.ValidateIDTokenClaims {
actualValue, ok := idTokenClaims[claimName]
if !ok || actualValue != expectedValue {
log.WithFields(logging.Fields{
"claim_name": claimName,
"actual_value": actualValue,
"expected_value": expectedValue,
"missing": !ok,
}).Error("authentication failed on validating ID token claims")
return nil, ErrAuthenticatingRequest
}
}
// update user
// TODO(isan) consolidate userFromOIDC and userFromSAML below here internal db handling code
friendlyName := ""
if cookieAuthConfig.FriendlyNameClaimName != "" {
friendlyName, _ = idTokenClaims[cookieAuthConfig.FriendlyNameClaimName].(string)
}
log = log.WithField("friendly_name", friendlyName)
user, err := authService.GetUserByExternalID(ctx, externalID)
if err == nil {
log.Info("Found user")
return enhanceWithFriendlyName(user, friendlyName), nil
}
if !errors.Is(err, auth.ErrNotFound) {
log.WithError(err).Error("Failed while searching if user exists in database")
return nil, ErrAuthenticatingRequest
}
log.Info("User not found; creating them")
u := model.User{
CreatedAt: time.Now().UTC(),
Source: cookieAuthConfig.AuthSource,
Username: externalID,
ExternalID: &externalID,
}
_, err = authService.CreateUser(ctx, &u)
if err != nil {
if !errors.Is(err, auth.ErrAlreadyExists) {
log.WithError(err).Error("Failed to create external user in database")
return nil, ErrAuthenticatingRequest
}
// user already exists - get it:
user, err = authService.GetUserByExternalID(ctx, externalID)
if err != nil {
log.WithError(err).Error("failed to get external user from database")
return nil, ErrAuthenticatingRequest
}
return enhanceWithFriendlyName(user, friendlyName), nil
}
initialGroups := cookieAuthConfig.DefaultInitialGroups
if userInitialGroups, ok := idTokenClaims[cookieAuthConfig.InitialGroupsClaimName].(string); ok {
initialGroups = strings.Split(userInitialGroups, ",")
}
for _, g := range initialGroups {
err = authService.AddUserToGroup(ctx, u.Username, strings.TrimSpace(g))
if err != nil {
log.WithError(err).Error("Failed to add external user to group")
}
}
return enhanceWithFriendlyName(&u, friendlyName), nil
}
// userFromOIDC returns a user from an existing OIDC session.
// If the user doesn't exist on the lakeFS side, it is created.
// This function does not make any calls to an external provider.
func userFromOIDC(ctx context.Context, logger logging.Logger, authService auth.Service, authSession *sessions.Session, oidcConfig *OIDCConfig) (*model.User, error) {
idTokenClaims, ok := authSession.Values[IDTokenClaimsSessionKey].(oidcencoding.Claims)
if idTokenClaims == nil {
return nil, nil
}
if !ok || idTokenClaims == nil {
return nil, ErrAuthenticatingRequest
}
externalID, ok := idTokenClaims["sub"].(string)
if !ok {
logger.WithField("sub", idTokenClaims["sub"]).Error("Failed type assertion for sub claim")
return nil, ErrAuthenticatingRequest
}
for claimName, expectedValue := range oidcConfig.ValidateIDTokenClaims {
actualValue, ok := idTokenClaims[claimName]
if !ok || actualValue != expectedValue {
logger.WithFields(logging.Fields{
"claim_name": claimName,
"actual_value": actualValue,
"expected_value": expectedValue,
"missing": !ok,
}).Error("Authentication failed on validating ID token claims")
return nil, ErrAuthenticatingRequest
}
}
friendlyName := ""
if oidcConfig.FriendlyNameClaimName != "" {
friendlyName, _ = idTokenClaims[oidcConfig.FriendlyNameClaimName].(string)
}
user, err := authService.GetUserByExternalID(ctx, externalID)
if err == nil {
return enhanceWithFriendlyName(user, friendlyName), nil
}
if !errors.Is(err, auth.ErrNotFound) {
logger.WithError(err).Error("Failed to get external user from database")
return nil, ErrAuthenticatingRequest
}
u := model.User{
CreatedAt: time.Now().UTC(),
Source: "oidc",
Username: externalID,
ExternalID: &externalID,
}
_, err = authService.CreateUser(ctx, &u)
if err != nil {
if !errors.Is(err, auth.ErrAlreadyExists) {
logger.WithError(err).Error("Failed to create external user in database")
return nil, ErrAuthenticatingRequest
}
// user already exists - get it:
user, err = authService.GetUserByExternalID(ctx, externalID)
if err != nil {
logger.WithError(err).Error("Failed to get external user from database")
return nil, ErrAuthenticatingRequest
}
return enhanceWithFriendlyName(user, friendlyName), nil
}
initialGroups := oidcConfig.DefaultInitialGroups
if userInitialGroups, ok := idTokenClaims[oidcConfig.InitialGroupsClaimName].(string); ok {
initialGroups = strings.Split(userInitialGroups, ",")
}
for _, g := range initialGroups {
err = authService.AddUserToGroup(ctx, u.Username, strings.TrimSpace(g))
if err != nil {
logger.WithError(err).Error("Failed to add external user to group")
}
}
return enhanceWithFriendlyName(&u, friendlyName), nil
}
func userByToken(ctx context.Context, logger logging.Logger, authService auth.Service, tokenString string) (*model.User, error) {
claims, err := auth.VerifyToken(authService.SecretStore().SharedSecret(), tokenString)
// make sure no audience is set for login token
if err != nil || !claims.VerifyAudience(LoginAudience, false) {
return nil, ErrAuthenticatingRequest
}
username := claims.Subject
userData, err := authService.GetUser(ctx, username)
if err != nil {
logger.WithFields(logging.Fields{
"token_id": claims.Id,
"username": username,
"subject": claims.Subject,
}).Debug("could not find user id by credentials")
return nil, ErrAuthenticatingRequest
}
return userData, nil
}
func userByAuth(ctx context.Context, logger logging.Logger, authenticator auth.Authenticator, authService auth.Service, accessKey string, secretKey string) (*model.User, error) {
// TODO(ariels): Rename keys.
username, err := authenticator.AuthenticateUser(ctx, accessKey, secretKey)
if err != nil {
logger.WithError(err).WithField("user", accessKey).Error("authenticate")
return nil, ErrAuthenticatingRequest
}
user, err := authService.GetUser(ctx, username)
if err != nil {
logger.WithError(err).WithFields(logging.Fields{"user_name": username}).Debug("could not find user id by credentials")
return nil, ErrAuthenticatingRequest
}
return user, nil
}