github.com/kyma-incubator/compass/components/director@v0.0.0-20230623144113-d764f56ff805/internal/authenticator/claims/scopes_validator.go (about)

     1  package claims
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"strings"
     7  
     8  	"github.com/kyma-incubator/compass/components/director/pkg/idtokenclaims"
     9  
    10  	"github.com/kyma-incubator/compass/components/director/pkg/apperrors"
    11  	"github.com/pkg/errors"
    12  )
    13  
    14  type scopeBasedClaimsValidator struct {
    15  	requiredScopes []string
    16  }
    17  
    18  // NewScopesValidator creates new scopes validator for given scopes.
    19  func NewScopesValidator(requiredScopes []string) *scopeBasedClaimsValidator {
    20  	return &scopeBasedClaimsValidator{
    21  		requiredScopes: requiredScopes,
    22  	}
    23  }
    24  
    25  // Validate validates the scopes in given token claims.
    26  func (v *scopeBasedClaimsValidator) Validate(_ context.Context, claims idtokenclaims.Claims) error {
    27  	if err := claims.Valid(); err != nil {
    28  		return errors.Wrapf(err, "while validating claims")
    29  	}
    30  
    31  	if !containsAll(v.requiredScopes, claims.Scopes) {
    32  		return apperrors.NewUnauthorizedError(fmt.Sprintf("Not all required scopes %q were found in claim with scopes %q", v.requiredScopes, claims.Scopes))
    33  	}
    34  	return nil
    35  }
    36  
    37  func containsAll(stringSlice []string, str string) bool {
    38  	for _, v := range stringSlice {
    39  		if !strings.Contains(str, v) {
    40  			return false
    41  		}
    42  	}
    43  	return true
    44  }