github.com/weaviate/weaviate@v1.24.6/usecases/auth/authentication/composer/token_validation.go (about)

     1  //                           _       _
     2  // __      _____  __ ___   ___  __ _| |_ ___
     3  // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
     4  //  \ V  V /  __/ (_| |\ V /| | (_| | ||  __/
     5  //   \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
     6  //
     7  //  Copyright © 2016 - 2024 Weaviate B.V. All rights reserved.
     8  //
     9  //  CONTACT: hello@weaviate.io
    10  //
    11  
    12  package composer
    13  
    14  import (
    15  	"github.com/golang-jwt/jwt/v4"
    16  	"github.com/pkg/errors"
    17  	"github.com/weaviate/weaviate/entities/models"
    18  	"github.com/weaviate/weaviate/usecases/config"
    19  )
    20  
    21  type TokenFunc func(token string, scopes []string) (*models.Principal, error)
    22  
    23  // New provides an OpenAPI compatible token validation
    24  // function that validates the token either as OIDC or as an APIKey token
    25  // depending on which is configured. If both are configured, the scheme is
    26  // figured out at runtime.
    27  func New(config config.Authentication,
    28  	apikey apiKeyValidator, oidc oidcValidator,
    29  ) TokenFunc {
    30  	if config.APIKey.Enabled && config.OIDC.Enabled {
    31  		return pickAuthSchemeDynamically(apikey, oidc)
    32  	}
    33  
    34  	if config.APIKey.Enabled {
    35  		return apikey.ValidateAndExtract
    36  	}
    37  
    38  	// default to OIDC, even if no scheme is enabled, then it can deal with this
    39  	// scenario itself. This is the backward-compatible scenario.
    40  	return oidc.ValidateAndExtract
    41  }
    42  
    43  func pickAuthSchemeDynamically(
    44  	apiKey apiKeyValidator, oidc oidcValidator,
    45  ) TokenFunc {
    46  	return func(token string, scopes []string) (*models.Principal, error) {
    47  		_, err := jwt.Parse(token, func(t *jwt.Token) (interface{}, error) {
    48  			return nil, nil
    49  		})
    50  
    51  		if err != nil && errors.Is(err, jwt.ErrTokenMalformed) {
    52  			return apiKey.ValidateAndExtract(token, scopes)
    53  		}
    54  
    55  		return oidc.ValidateAndExtract(token, scopes)
    56  	}
    57  }
    58  
    59  type oidcValidator interface {
    60  	ValidateAndExtract(token string, scopes []string) (*models.Principal, error)
    61  }
    62  
    63  type apiKeyValidator interface {
    64  	ValidateAndExtract(token string, scopes []string) (*models.Principal, error)
    65  }