2023-03-30 10:54:09 +02:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/golang-jwt/jwt"
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
|
|
|
|
"github.com/netbirdio/netbird/management/server"
|
2024-07-03 11:33:02 +02:00
|
|
|
nbContext "github.com/netbirdio/netbird/management/server/context"
|
2024-02-22 12:27:08 +01:00
|
|
|
"github.com/netbirdio/netbird/management/server/http/middleware/bypass"
|
2023-03-30 10:54:09 +02:00
|
|
|
"github.com/netbirdio/netbird/management/server/http/util"
|
|
|
|
"github.com/netbirdio/netbird/management/server/jwtclaims"
|
|
|
|
"github.com/netbirdio/netbird/management/server/status"
|
|
|
|
)
|
|
|
|
|
2023-03-30 17:32:44 +02:00
|
|
|
// GetAccountFromPATFunc function
|
2024-07-03 11:33:02 +02:00
|
|
|
type GetAccountFromPATFunc func(ctx context.Context, token string) (*server.Account, *server.User, *server.PersonalAccessToken, error)
|
2023-03-30 17:32:44 +02:00
|
|
|
|
|
|
|
// ValidateAndParseTokenFunc function
|
2024-07-03 11:33:02 +02:00
|
|
|
type ValidateAndParseTokenFunc func(ctx context.Context, token string) (*jwt.Token, error)
|
2023-03-30 17:32:44 +02:00
|
|
|
|
|
|
|
// MarkPATUsedFunc function
|
2024-07-03 11:33:02 +02:00
|
|
|
type MarkPATUsedFunc func(ctx context.Context, token string) error
|
2023-03-30 10:54:09 +02:00
|
|
|
|
2023-12-13 11:18:35 +01:00
|
|
|
// CheckUserAccessByJWTGroupsFunc function
|
2024-07-03 11:33:02 +02:00
|
|
|
type CheckUserAccessByJWTGroupsFunc func(ctx context.Context, claims jwtclaims.AuthorizationClaims) error
|
2023-12-11 16:59:15 +01:00
|
|
|
|
2023-03-30 10:54:09 +02:00
|
|
|
// AuthMiddleware middleware to verify personal access tokens (PAT) and JWT tokens
|
|
|
|
type AuthMiddleware struct {
|
2023-12-13 11:18:35 +01:00
|
|
|
getAccountFromPAT GetAccountFromPATFunc
|
|
|
|
validateAndParseToken ValidateAndParseTokenFunc
|
|
|
|
markPATUsed MarkPATUsedFunc
|
|
|
|
checkUserAccessByJWTGroups CheckUserAccessByJWTGroupsFunc
|
|
|
|
claimsExtractor *jwtclaims.ClaimsExtractor
|
|
|
|
audience string
|
|
|
|
userIDClaim string
|
2023-03-30 10:54:09 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
const (
|
2023-03-30 18:54:55 +02:00
|
|
|
userProperty = "user"
|
2023-03-30 10:54:09 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
// NewAuthMiddleware instance constructor
|
2023-12-11 16:59:15 +01:00
|
|
|
func NewAuthMiddleware(getAccountFromPAT GetAccountFromPATFunc, validateAndParseToken ValidateAndParseTokenFunc,
|
2023-12-13 11:18:35 +01:00
|
|
|
markPATUsed MarkPATUsedFunc, checkUserAccessByJWTGroups CheckUserAccessByJWTGroupsFunc, claimsExtractor *jwtclaims.ClaimsExtractor,
|
2023-12-11 16:59:15 +01:00
|
|
|
audience string, userIdClaim string) *AuthMiddleware {
|
2023-09-01 18:09:59 +02:00
|
|
|
if userIdClaim == "" {
|
|
|
|
userIdClaim = jwtclaims.UserIDClaim
|
|
|
|
}
|
2023-12-11 16:59:15 +01:00
|
|
|
|
2023-03-30 10:54:09 +02:00
|
|
|
return &AuthMiddleware{
|
2023-12-13 11:18:35 +01:00
|
|
|
getAccountFromPAT: getAccountFromPAT,
|
|
|
|
validateAndParseToken: validateAndParseToken,
|
|
|
|
markPATUsed: markPATUsed,
|
|
|
|
checkUserAccessByJWTGroups: checkUserAccessByJWTGroups,
|
|
|
|
claimsExtractor: claimsExtractor,
|
|
|
|
audience: audience,
|
|
|
|
userIDClaim: userIdClaim,
|
2023-03-30 10:54:09 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Handler method of the middleware which authenticates a user either by JWT claims or by PAT
|
2023-03-30 17:32:44 +02:00
|
|
|
func (m *AuthMiddleware) Handler(h http.Handler) http.Handler {
|
2023-03-30 10:54:09 +02:00
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
2024-02-22 12:27:08 +01:00
|
|
|
|
|
|
|
if bypass.ShouldBypass(r.URL.Path, h, w, r) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-03-30 10:54:09 +02:00
|
|
|
auth := strings.Split(r.Header.Get("Authorization"), " ")
|
2023-10-17 17:19:47 +02:00
|
|
|
authType := strings.ToLower(auth[0])
|
|
|
|
|
|
|
|
// fallback to token when receive pat as bearer
|
|
|
|
if len(auth) >= 2 && authType == "bearer" && strings.HasPrefix(auth[1], "nbp_") {
|
|
|
|
authType = "token"
|
|
|
|
auth[0] = authType
|
|
|
|
}
|
|
|
|
|
|
|
|
switch authType {
|
2023-03-30 10:54:09 +02:00
|
|
|
case "bearer":
|
2023-10-17 17:19:47 +02:00
|
|
|
err := m.checkJWTFromRequest(w, r, auth)
|
2023-03-30 10:54:09 +02:00
|
|
|
if err != nil {
|
2024-07-03 11:33:02 +02:00
|
|
|
log.WithContext(r.Context()).Errorf("Error when validating JWT claims: %s", err.Error())
|
|
|
|
util.WriteError(r.Context(), status.Errorf(status.Unauthorized, "token invalid"), w)
|
2023-03-30 10:54:09 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
case "token":
|
2023-10-17 17:19:47 +02:00
|
|
|
err := m.checkPATFromRequest(w, r, auth)
|
2023-03-30 10:54:09 +02:00
|
|
|
if err != nil {
|
2024-07-03 11:33:02 +02:00
|
|
|
log.WithContext(r.Context()).Debugf("Error when validating PAT claims: %s", err.Error())
|
|
|
|
util.WriteError(r.Context(), status.Errorf(status.Unauthorized, "token invalid"), w)
|
2023-03-30 10:54:09 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
default:
|
2024-07-03 11:33:02 +02:00
|
|
|
util.WriteError(r.Context(), status.Errorf(status.Unauthorized, "no valid authentication provided"), w)
|
2023-03-30 10:54:09 +02:00
|
|
|
return
|
|
|
|
}
|
2024-07-03 11:33:02 +02:00
|
|
|
claims := m.claimsExtractor.FromRequestContext(r)
|
|
|
|
//nolint
|
|
|
|
ctx := context.WithValue(r.Context(), nbContext.UserIDKey, claims.UserId)
|
|
|
|
//nolint
|
|
|
|
ctx = context.WithValue(ctx, nbContext.AccountIDKey, claims.AccountId)
|
|
|
|
h.ServeHTTP(w, r.WithContext(ctx))
|
2023-03-30 10:54:09 +02:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// CheckJWTFromRequest checks if the JWT is valid
|
2023-10-17 17:19:47 +02:00
|
|
|
func (m *AuthMiddleware) checkJWTFromRequest(w http.ResponseWriter, r *http.Request, auth []string) error {
|
|
|
|
token, err := getTokenFromJWTRequest(auth)
|
2023-03-30 10:54:09 +02:00
|
|
|
|
|
|
|
// If an error occurs, call the error handler and return an error
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Error extracting token: %w", err)
|
|
|
|
}
|
|
|
|
|
2024-07-03 11:33:02 +02:00
|
|
|
validatedToken, err := m.validateAndParseToken(r.Context(), token)
|
2023-03-30 10:54:09 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if validatedToken == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-07-03 11:33:02 +02:00
|
|
|
if err := m.verifyUserAccess(r.Context(), validatedToken); err != nil {
|
2023-12-11 16:59:15 +01:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2023-03-30 10:54:09 +02:00
|
|
|
// If we get here, everything worked and we can set the
|
|
|
|
// user property in context.
|
2023-03-31 10:30:05 +02:00
|
|
|
newRequest := r.WithContext(context.WithValue(r.Context(), userProperty, validatedToken)) //nolint
|
2023-03-30 10:54:09 +02:00
|
|
|
// Update the current request with the new context information.
|
|
|
|
*r = *newRequest
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-12-11 16:59:15 +01:00
|
|
|
// verifyUserAccess checks if a user, based on a validated JWT token,
|
|
|
|
// is allowed access, particularly in cases where the admin enabled JWT
|
|
|
|
// group propagation and designated certain groups with access permissions.
|
2024-07-03 11:33:02 +02:00
|
|
|
func (m *AuthMiddleware) verifyUserAccess(ctx context.Context, validatedToken *jwt.Token) error {
|
2023-12-11 16:59:15 +01:00
|
|
|
authClaims := m.claimsExtractor.FromToken(validatedToken)
|
2024-07-03 11:33:02 +02:00
|
|
|
return m.checkUserAccessByJWTGroups(ctx, authClaims)
|
2023-12-11 16:59:15 +01:00
|
|
|
}
|
|
|
|
|
2023-03-30 10:54:09 +02:00
|
|
|
// CheckPATFromRequest checks if the PAT is valid
|
2023-10-17 17:19:47 +02:00
|
|
|
func (m *AuthMiddleware) checkPATFromRequest(w http.ResponseWriter, r *http.Request, auth []string) error {
|
|
|
|
token, err := getTokenFromPATRequest(auth)
|
2023-03-30 10:54:09 +02:00
|
|
|
|
|
|
|
// If an error occurs, call the error handler and return an error
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Error extracting token: %w", err)
|
|
|
|
}
|
|
|
|
|
2024-07-03 11:33:02 +02:00
|
|
|
account, user, pat, err := m.getAccountFromPAT(r.Context(), token)
|
2023-03-30 10:54:09 +02:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("invalid Token: %w", err)
|
|
|
|
}
|
|
|
|
if time.Now().After(pat.ExpirationDate) {
|
|
|
|
return fmt.Errorf("token expired")
|
|
|
|
}
|
|
|
|
|
2024-07-03 11:33:02 +02:00
|
|
|
err = m.markPATUsed(r.Context(), pat.ID)
|
2023-03-30 10:54:09 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
claimMaps := jwt.MapClaims{}
|
2023-09-01 18:09:59 +02:00
|
|
|
claimMaps[m.userIDClaim] = user.Id
|
2023-03-30 18:54:55 +02:00
|
|
|
claimMaps[m.audience+jwtclaims.AccountIDSuffix] = account.Id
|
|
|
|
claimMaps[m.audience+jwtclaims.DomainIDSuffix] = account.Domain
|
|
|
|
claimMaps[m.audience+jwtclaims.DomainCategorySuffix] = account.DomainCategory
|
2023-03-30 10:54:09 +02:00
|
|
|
jwtToken := jwt.NewWithClaims(jwt.SigningMethodHS256, claimMaps)
|
2023-03-31 10:30:05 +02:00
|
|
|
newRequest := r.WithContext(context.WithValue(r.Context(), jwtclaims.TokenUserProperty, jwtToken)) //nolint
|
2023-03-30 10:54:09 +02:00
|
|
|
// Update the current request with the new context information.
|
|
|
|
*r = *newRequest
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-10-17 17:19:47 +02:00
|
|
|
// getTokenFromJWTRequest is a "TokenExtractor" that takes auth header parts and extracts
|
2023-03-30 10:54:09 +02:00
|
|
|
// the JWT token from the Authorization header.
|
2023-10-17 17:19:47 +02:00
|
|
|
func getTokenFromJWTRequest(authHeaderParts []string) (string, error) {
|
2023-03-30 10:54:09 +02:00
|
|
|
if len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != "bearer" {
|
|
|
|
return "", errors.New("Authorization header format must be Bearer {token}")
|
|
|
|
}
|
|
|
|
|
|
|
|
return authHeaderParts[1], nil
|
|
|
|
}
|
|
|
|
|
2023-10-17 17:19:47 +02:00
|
|
|
// getTokenFromPATRequest is a "TokenExtractor" that takes auth header parts and extracts
|
2023-03-30 10:54:09 +02:00
|
|
|
// the PAT token from the Authorization header.
|
2023-10-17 17:19:47 +02:00
|
|
|
func getTokenFromPATRequest(authHeaderParts []string) (string, error) {
|
2023-03-30 10:54:09 +02:00
|
|
|
if len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != "token" {
|
|
|
|
return "", errors.New("Authorization header format must be Token {token}")
|
|
|
|
}
|
|
|
|
|
|
|
|
return authHeaderParts[1], nil
|
|
|
|
}
|