// ValidateTokenGroups validates token groups
341677
func ValidateTokenGroups(usages []string, groups []string, fldPath *field.Path) field.ErrorList {
	allErrs := field.ErrorList{}

	// adding groups only makes sense for authentication
	usagesSet := sets.NewString(usages...)
	usageAuthentication := strings.TrimPrefix(bootstrapapi.BootstrapTokenUsageAuthentication, bootstrapapi.BootstrapTokenUsagePrefix)
	if len(groups) > 0 && !usagesSet.Has(usageAuthentication) {
		allErrs = append(allErrs, field.Invalid(fldPath, groups, fmt.Sprintf("token groups cannot be specified unless --usages includes %q", usageAuthentication)))
	}

	// validate any extra group names
	for _, group := range groups {
		if err := bootstraputil.ValidateBootstrapGroupName(group); err != nil {
			allErrs = append(allErrs, field.Invalid(fldPath, groups, err.Error()))
		}
	}

	return allErrs
}
141088
func validateStateToken(c context.Context, stateTok string) (map[string]string, error) {
	return openIDStateToken.Validate(c, stateTok, nil)
}
1373022
func (c *GroupsRenameCall) ValidateArgs() error {
	if len(c.channel) <= 0 {
		return errors.New(`required field channel not initialized`)
	}
	if len(c.name) <= 0 {
		return errors.New(`required field name not initialized`)
	}
	return nil
}
431575
func (c *Client) parseGroup(msg osc.Message) (*GroupNode, error) {
	n, _, err := c.parseNodeFrom(msg, 0)
	if err != nil {
		return nil, err
	}
	gn, ok := n.(*GroupNode)
	if !ok {
		return nil, errors.Wrap(err, "type assertion from Node to *GroupNode")
	}
	return gn, nil
}
1306180
func (re *Regexp) GetGroupNumbers() []int {
	var result []int

	if re.caps == nil {
		result = make([]int, re.capsize)

		for i := 0; i < len(result); i++ {
			result[i] = i
		}
	} else {
		result = make([]int, len(re.caps))

		for k, v := range re.caps {
			result[v] = k
		}
	}

	return result
}
643071
func (a *Auth) Validate(authToken string) (*Token, error) {

	if a.TokenCache != nil {
		var cachedToken Token
		if ok := a.TokenCache.Get(authToken, &cachedToken); ok && cachedToken.Valid() {
			Log("Found valid token in cache")
			return &cachedToken, nil
		}
	}

	req, err := http.NewRequest("GET", a.Endpoint+"/auth/tokens?nocatalog", nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("X-Auth-Token", authToken)
	req.Header.Set("X-Subject-Token", authToken)
	req.Header.Set("User-Agent", a.UserAgent)

	r, err := a.Client.Do(req)
	if err != nil {
		return nil, err
	}
	defer r.Body.Close()

	if r.StatusCode >= 400 {
		return nil, errors.New(r.Status)
	}

	var resp authResponse
	if err = json.NewDecoder(r.Body).Decode(&resp); err != nil {
		return nil, err
	}

	if e := resp.Error; e != nil {
		return nil, fmt.Errorf("%s : %s", r.Status, e.Message)
	}
	if r.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("%s", r.Status)
	}
	if resp.Token == nil {
		return nil, errors.New("Response didn't contain token context")
	}
	if !resp.Token.Valid() {
		return nil, errors.New("Returned token is not valid")
	}

	if a.TokenCache != nil {
		ttl := a.CacheTime
		//The expiry date of the token provides an upper bound on the cache time
		if expiresIn := resp.Token.ExpiresAt.Sub(time.Now()); expiresIn < a.CacheTime {
			ttl = expiresIn
		}
		a.TokenCache.Set(authToken, *resp.Token, ttl)
	}

	return resp.Token, nil
}
1289084
func (j *PKIJWTVerifier) Validate(ctx context.Context, tokenString string) ([]string, bool, string, error) {
	if len(tokenString) == 0 {
		return []string{}, false, tokenString, fmt.Errorf("Empty token")
	}
	if len(j.keys) == 0 {
		return []string{}, false, tokenString, fmt.Errorf("No public keys loaded into verifier")
	}

	// iterate over all public keys that we have and try to validate the token
	// the first one to succeed will be used
	var errs []error
	for _, key := range j.keys {
		claims := &jwt.MapClaims{}
		token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
			switch token.Method.(type) {
			case *jwt.SigningMethodECDSA:
				if isECDSAPublicKey(key) {
					return key, nil
				}
			case *jwt.SigningMethodRSA:
				if isRSAPublicKey(key) {
					return key, nil
				}
			default:
				return nil, fmt.Errorf("unsupported signing method '%T'", token.Method)
			}
			return nil, fmt.Errorf("signing method '%T' and public key type '%T' mismatch", token.Method, key)
		})

		// cover all error cases after parsing/verifying
		if err != nil {
			errs = append(errs, err)
			continue
		}
		if token == nil {
			errs = append(errs, fmt.Errorf("no token was parsed"))
			continue
		}
		if !token.Valid {
			errs = append(errs, fmt.Errorf("token failed to verify against public key"))
			continue
		}

		// return successful on match/verification with the first key
		attributes := []string{}
		for k, v := range *claims {
			attributes = append(attributes, common.FlattenClaim(k, v)...)
		}
		return attributes, false, tokenString, nil
	}

	// generate a detailed error
	var detailedError string
	for i, err := range errs {
		detailedError += err.Error()
		if i+1 < len(errs) {
			detailedError += "; "
		}
	}
	return []string{}, false, tokenString, fmt.Errorf("Invalid token - errors: [%s]", detailedError)
}
593324
func (wr *Wrangler) ValidateShard(ctx context.Context, keyspace, shard string, pingTablets bool) error {
	wg := &sync.WaitGroup{}
	results := make(chan error, 16)
	wg.Add(1)
	go func() {
		defer wg.Done()
		wr.validateShard(ctx, keyspace, shard, pingTablets, wg, results)
	}()
	return wr.waitForResults(wg, results)
}
572754
func ValidateTokenRequest(tr *authentication.TokenRequest) field.ErrorList {
	allErrs := field.ErrorList{}
	specPath := field.NewPath("spec")

	const min = 10 * time.Minute
	if tr.Spec.ExpirationSeconds < int64(min.Seconds()) {
		allErrs = append(allErrs, field.Invalid(specPath.Child("expirationSeconds"), tr.Spec.ExpirationSeconds, "may not specify a duration less than 10 minutes"))
	}
	if tr.Spec.ExpirationSeconds > 1<<32 {
		allErrs = append(allErrs, field.Invalid(specPath.Child("expirationSeconds"), tr.Spec.ExpirationSeconds, "may not specify a duration larger than 2^32 seconds"))
	}
	return allErrs
}
305716
func ValidateUsages(usages []string) error {
	validUsages := sets.NewString(api.KnownTokenUsages...)
	invalidUsages := sets.NewString()
	for _, usage := range usages {
		if !validUsages.Has(usage) {
			invalidUsages.Insert(usage)
		}
	}
	if len(invalidUsages) > 0 {
		return fmt.Errorf("invalid bootstrap token usage string: %s, valid usage options: %s", strings.Join(invalidUsages.List(), ","), strings.Join(api.KnownTokenUsages, ","))
	}
	return nil
}
135085
func ValidateInstanceGroup(g *kops.InstanceGroup) error {
	if g.ObjectMeta.Name == "" {
		return field.Required(field.NewPath("Name"), "")
	}

	switch g.Spec.Role {
	case "":
		return field.Required(field.NewPath("Role"), "Role must be set")
	case kops.InstanceGroupRoleMaster:
	case kops.InstanceGroupRoleNode:
	case kops.InstanceGroupRoleBastion:
	default:
		return field.Invalid(field.NewPath("Role"), g.Spec.Role, "Unknown role")
	}

	if g.Spec.Tenancy != "" {
		if g.Spec.Tenancy != "default" && g.Spec.Tenancy != "dedicated" && g.Spec.Tenancy != "host" {
			return field.Invalid(field.NewPath("Tenancy"), g.Spec.Tenancy, "Unknown tenancy. Must be Default, Dedicated or Host.")
		}
	}

	if g.Spec.MaxSize != nil && g.Spec.MinSize != nil {
		if *g.Spec.MaxSize < *g.Spec.MinSize {
			return field.Invalid(field.NewPath("MaxSize"), *g.Spec.MaxSize, "maxSize must be greater than or equal to minSize.")
		}
	}

	if fi.Int32Value(g.Spec.RootVolumeIops) < 0 {
		return field.Invalid(field.NewPath("RootVolumeIops"), g.Spec.RootVolumeIops, "RootVolumeIops must be greater than 0")
	}

	// @check all the hooks are valid in this instancegroup
	for i := range g.Spec.Hooks {
		if errs := validateHookSpec(&g.Spec.Hooks[i], field.NewPath("hooks").Index(i)); len(errs) > 0 {
			return errs.ToAggregate()
		}
	}

	// @check the fileAssets for this instancegroup are valid
	for i := range g.Spec.FileAssets {
		if errs := validateFileAssetSpec(&g.Spec.FileAssets[i], field.NewPath("fileAssets").Index(i)); len(errs) > 0 {
			return errs.ToAggregate()
		}
	}

	if g.IsMaster() {
		if len(g.Spec.Subnets) == 0 {
			return fmt.Errorf("Master InstanceGroup %s did not specify any Subnets", g.ObjectMeta.Name)
		}
	}

	if g.Spec.MixedInstancesPolicy != nil {
		if errs := validatedMixedInstancesPolicy(field.NewPath(g.Name), g.Spec.MixedInstancesPolicy, g); len(errs) > 0 {
			return errs.ToAggregate()
		}
	}

	if len(g.Spec.AdditionalUserData) > 0 {
		for _, UserDataInfo := range g.Spec.AdditionalUserData {
			err := validateExtraUserData(&UserDataInfo)
			if err != nil {
				return err
			}
		}
	}

	// @step: iterate and check the volume specs
	for i, x := range g.Spec.Volumes {
		devices := make(map[string]bool, 0)
		path := field.NewPath("volumes").Index(i)

		if err := validateVolumeSpec(path, x); err != nil {
			return err
		}

		// @check the device name has not been used already
		if _, found := devices[x.Device]; found {
			return field.Invalid(path.Child("device"), x.Device, "duplicate device name found in volumes")
		}

		devices[x.Device] = true
	}

	// @step: iterate and check the volume mount specs
	for i, x := range g.Spec.VolumeMounts {
		used := make(map[string]bool, 0)
		path := field.NewPath("volumeMounts").Index(i)

		if err := validateVolumeMountSpec(path, x); err != nil {
			return err
		}
		if _, found := used[x.Device]; found {
			return field.Invalid(path.Child("device"), x.Device, "duplicate device reference")
		}
		if _, found := used[x.Path]; found {
			return field.Invalid(path.Child("path"), x.Path, "duplicate mount path specified")
		}
	}

	if err := validateInstanceProfile(g.Spec.IAM, field.NewPath("iam")); err != nil {
		return err
	}

	return nil
}
577856
func (v *TokenVerifier) Validate(ctx context.Context, token string) ([]string, bool, string, error) {

	if len(token) == 0 {
		return []string{}, true, token, fmt.Errorf("invalid token presented")
	}

	var tokenData *clientData

	// If it is not found in the cache initiate a call back process.
	data, err := tokenCache.Get(token)
	if err == nil {
		var ok bool
		tokenData, ok = data.(*clientData)
		if !ok {
			return nil, true, token, fmt.Errorf("internal server error")
		}

		// If the cached token hasn't expired yet, we can just accept it and not
		// go through a whole verification process. Nothing new.
		if tokenData.expiry.After(time.Now()) && len(tokenData.attributes) > 0 {
			return tokenData.attributes, false, token, nil
		}
	} else { // No token in the cache. Let's try to see if it is valid and we can cache it now.
		//
		tokenData = &clientData{}
	}

	// The token has expired. Let's try to refresh it.
	tokenData.Lock()
	defer tokenData.Unlock()

	// If it is the first time we are verifying the token, let's do
	// it now. This is possible if the token was created earlier
	// but we never had a chance to verify it. In this case, the
	// attributes were empty.
	idToken, err := v.oauthVerifier.Verify(ctx, token)
	if err != nil {
		var ok bool
		// Token is expired. Let's try to refresh it if we have something
		// in the cache. If we don't have a refresh token, we reject it
		// and ask the client to validate again.
		if tokenData.tokenSource == nil {
			return []string{}, true, token, fmt.Errorf("no cached data and expired token - request authorization: %s", err)
		}
		refreshedToken, err := tokenData.tokenSource.Token()
		if err != nil {
			return []string{}, true, token, fmt.Errorf("token validation failed and cannot refresh: %s", err)
		}
		token, ok = refreshedToken.Extra("id_token").(string)
		if !ok {
			return []string{}, true, token, fmt.Errorf("failed to find id_token - initiate re-authorization")
		}
		idToken, err = v.oauthVerifier.Verify(ctx, token)
		if err != nil {
			return []string{}, true, token, fmt.Errorf("invalid token derived from refresh - manual authorization is required: %s", err)
		}
	}

	// Get the claims out of the token. Use the standard data structure for
	// this and ignore the other fields. We are only interested on the ID.
	resp := struct {
		IDTokenClaims map[string]interface{} // ID Token payload is just JSON.
	}{map[string]interface{}{}}
	if err := idToken.Claims(&resp.IDTokenClaims); err != nil {
		return []string{}, true, token, fmt.Errorf("unable to process claims: %s", err)
	}

	// Flatten the claims in a generic format.
	attributes := []string{}
	for k, v := range resp.IDTokenClaims {
		attributes = append(attributes, common.FlattenClaim(k, v)...)
	}

	tokenData.attributes = attributes
	tokenData.expiry = idToken.Expiry

	// Cache the token and attributes to avoid multiple validations and update the
	// expiration time.
	if err := tokenCache.SetWithExpire(token, tokenData, time.Until(idToken.Expiry.Add(3600*time.Second))); err != nil {
		return []string{}, false, token, fmt.Errorf("cannot cache token: %s", err)
	}

	return attributes, false, token, nil
}
972700
func (c *rackspaceFirewaller) DeleteGroups(ctx context.ProviderCallContext, names ...string) error {
	return nil
}
1137153
func (ref *Config) ValidateConsumerConfig() error {
	if ref.Brokers == nil {
		return errors.New("invalid Brokers - one or more brokers must be specified")
	}
	if ref.GroupID == "" {
		return errors.New("invalid GroupID - no GroupID specified")
	}
	if ref.RecvNotification && ref.RecvNotificationChan == nil {
		return errors.New("notification channel not specified")
	}
	if ref.RecvError && ref.RecvErrorChan == nil {
		return errors.New("error channel not specified")
	}
	if ref.RecvMessageChan == nil {
		return errors.New("recvMessageChan not specified")
	}
	return ref.ConsumerConfig().Validate()
}
757612
func DetachedTokenIsValid(detachedToken, content, tokenID, tokenSecret string) bool {
	newToken, err := computeDetachedSig(content, tokenID, tokenSecret)
	if err != nil {
		return false
	}
	return detachedToken == newToken
}
71302
func ValidKeyTokens(name string, tags Tags) bool {
	if !ValidKeyToken(name) {
		return false
	}
	for _, tag := range tags {
		if !ValidKeyToken(string(tag.Key)) || !ValidKeyToken(string(tag.Value)) {
			return false
		}
	}
	return true
}
945776
func (r *RollingUpdateInstanceGroup) ValidateCluster(rollingUpdateData *RollingUpdateCluster, cluster *api.Cluster, instanceGroupList *api.InstanceGroupList) error {
	if _, err := validation.ValidateCluster(cluster, instanceGroupList, rollingUpdateData.K8sClient); err != nil {
		return fmt.Errorf("cluster %q did not pass validation: %v", cluster.Name, err)
	}

	return nil

}