// Validate checks the token against the Keys for this OpenIDProvider.
// It is assumed that a user will invoke FetchKey before calling this
// function.
515700
func (op *OpenIDProvider) Validate(token string) (bool, error) {
	jws, err := jose.ParseSigned(token)
	if err != nil {
		return false, errors.NewNotValid(err, "Couldn't parse the token")
	}

	for _, sig := range jws.Signatures {
		keyID := sig.Header.KeyID
		opKeys := op.Keys.Key(keyID)
		if len(opKeys) < 1 {
			// Can't find the server key that this token claims to be signed with
			return false, errors.NotFoundf("Couldn't find KeyID %s in the server's keys", keyID)
		}
		opKey := opKeys[0]
		_, err = jws.Verify(opKey.Key)
		if err != nil {
			// Couldn't verify the signature
			return false, errors.NotValidf("Signature failed validation")
		}
	}
	return true, nil
}
1246449
func (id *MockIdentity) Validate() error {
	if id.Err != nil && id.Err.Error() == "Validate" {
		return id.Err
	}
	return nil
}
71908
func (d *API) validate() error {
	var consumes []string
	for k := range d.consumers {
		consumes = append(consumes, k)
	}

	var produces []string
	for k := range d.producers {
		produces = append(produces, k)
	}

	var authenticators []string
	for k := range d.authenticators {
		authenticators = append(authenticators, k)
	}

	var operations []string
	for m, v := range d.operations {
		for p := range v {
			operations = append(operations, fmt.Sprintf("%s %s", strings.ToUpper(m), p))
		}
	}

	var definedAuths []string
	for k := range d.spec.Spec().SecurityDefinitions {
		definedAuths = append(definedAuths, k)
	}

	if err := d.verify("consumes", consumes, d.analyzer.RequiredConsumes()); err != nil {
		return err
	}
	if err := d.verify("produces", produces, d.analyzer.RequiredProduces()); err != nil {
		return err
	}
	if err := d.verify("operation", operations, d.analyzer.OperationMethodPaths()); err != nil {
		return err
	}

	requiredAuths := d.analyzer.RequiredSecuritySchemes()
	if err := d.verify("auth scheme", authenticators, requiredAuths); err != nil {
		return err
	}
	if err := d.verify("security definitions", definedAuths, requiredAuths); err != nil {
		return err
	}
	return nil
}
412806
func (k *Key) Validate(fn func(string) string) string {
	return fn(k.String())
}
448050
func (m *AuthorizationRequest) Validate() error {
	if m == nil {
		return nil
	}

	{
		tmp := m.GetAllowedHeaders()

		if v, ok := interface{}(tmp).(interface{ Validate() error }); ok {

			if err := v.Validate(); err != nil {
				return AuthorizationRequestValidationError{
					field:  "AllowedHeaders",
					reason: "embedded message failed validation",
					cause:  err,
				}
			}
		}
	}

	for idx, item := range m.GetHeadersToAdd() {
		_, _ = idx, item

		{
			tmp := item

			if v, ok := interface{}(tmp).(interface{ Validate() error }); ok {

				if err := v.Validate(); err != nil {
					return AuthorizationRequestValidationError{
						field:  fmt.Sprintf("HeadersToAdd[%v]", idx),
						reason: "embedded message failed validation",
						cause:  err,
					}
				}
			}
		}

	}

	return nil
}
157414
func (constraints *tokenConstraints) validate() (err error) {
	keys := 0
	if constraints.key != nil {
		keys++
	}
	if constraints.secret != "" {
		keys++
	}
	if keys > 1 {
		err = fmt.Errorf("duplicate key constraints")
		return
	}
	if keys < 1 {
		err = fmt.Errorf("no key constraint")
		return
	}
	return
}
513156
func (domain *TypedDataDomain) validate() error {
	if domain.ChainId == big.NewInt(0) {
		return errors.New("chainId must be specified according to EIP-155")
	}

	if len(domain.Name) == 0 && len(domain.Version) == 0 && len(domain.VerifyingContract) == 0 && len(domain.Salt) == 0 {
		return errors.New("domain is undefined")
	}

	return nil
}
840074
func (r *GetOAuthTokenRequest) Validate() error {
	switch {
	case len(r.Scopes) == 0:
		return errors.New(`field "scopes" is required`)
	case len(r.Secret) == 0:
		return errors.New(`field "secret" is required`)
	case r.AccountID == "":
		return errors.New(`field "account_id" is required`)
	}
	return nil
}
413178
func (p *AllIssuingValidator) Validate(creator identity.PublicInfo, tokenType string) error {
	// Deserialize identity
	identity, err := p.Deserializer.DeserializeIdentity(creator.Public())
	if err != nil {
		return errors.Wrapf(err, "identity [0x%x] cannot be deserialised", creator.Public())
	}

	// Check identity validity - in this simple policy, all valid identities are issuers.
	if err := identity.Validate(); err != nil {
		return errors.Wrapf(err, "identity [0x%x] cannot be validated", creator.Public())
	}

	return nil
}
1085533
func (s SecretForDockerRegistryGeneratorV1) validate() error {
	if len(s.Name) == 0 {
		return fmt.Errorf("name must be specified")
	}

	if len(s.FileSources) == 0 {
		if len(s.Username) == 0 {
			return fmt.Errorf("username must be specified")
		}
		if len(s.Password) == 0 {
			return fmt.Errorf("password must be specified")
		}
		if len(s.Server) == 0 {
			return fmt.Errorf("server must be specified")
		}
	}
	return nil
}
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
}
85919
func (s userIdentityMappingStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {
	return validation.ValidateUserIdentityMapping(obj.(*userapi.UserIdentityMapping))
}
10294
func (a *ACLToken) Validate() error {
	var mErr multierror.Error
	if len(a.Name) > maxTokenNameLength {
		mErr.Errors = append(mErr.Errors, fmt.Errorf("token name too long"))
	}
	switch a.Type {
	case ACLClientToken:
		if len(a.Policies) == 0 {
			mErr.Errors = append(mErr.Errors, fmt.Errorf("client token missing policies"))
		}
	case ACLManagementToken:
		if len(a.Policies) != 0 {
			mErr.Errors = append(mErr.Errors, fmt.Errorf("management token cannot be associated with policies"))
		}
	default:
		mErr.Errors = append(mErr.Errors, fmt.Errorf("token type must be client or management"))
	}
	return mErr.ErrorOrNil()
}
665232
func (j *JwtConf) Validate() error {
	if j.PrivateKeyDeprecated != "" {
		j.PrivateKey = j.PrivateKeyDeprecated
		j.PrivateKeyDeprecated = ""
	}
	j.fixKey()
	if j.KeyTypeDeprecated != "" {
		j.Type = j.KeyTypeDeprecated
		j.KeyTypeDeprecated = ""
	}
	_, err := j.KeyBytes()
	if err != nil {
		return fmt.Errorf("Invalid JwtConf.PrivateKeyBase64  (error trying to decode base64 err: %v", err)
	}
	return nil
}
999374
func Validate(c Config) error {
	if v, ok := c[IdentityPublicKey].(string); ok {
		var key bakery.PublicKey
		if err := key.UnmarshalText([]byte(v)); err != nil {
			return errors.Annotate(err, "invalid identity public key")
		}
	}

	if v, ok := c[IdentityURL].(string); ok {
		u, err := url.Parse(v)
		if err != nil {
			return errors.Annotate(err, "invalid identity URL")
		}
		// If we've got an identity public key, we allow an HTTP
		// scheme for the identity server because we won't need
		// to rely on insecure transport to obtain the public
		// key.
		if _, ok := c[IdentityPublicKey]; !ok && u.Scheme != "https" {
			return errors.Errorf("URL needs to be https when %s not provided", IdentityPublicKey)
		}
	}

	caCert, caCertOK := c.CACert()
	if !caCertOK {
		return errors.Errorf("missing CA certificate")
	}
	if _, err := utilscert.ParseCert(caCert); err != nil {
		return errors.Annotate(err, "bad CA certificate in configuration")
	}

	if uuid, ok := c[ControllerUUIDKey].(string); ok && !utils.IsValidUUIDString(uuid) {
		return errors.Errorf("controller-uuid: expected UUID, got string(%q)", uuid)
	}

	if mgoMemProfile, ok := c[MongoMemoryProfile].(string); ok {
		if mgoMemProfile != MongoProfLow && mgoMemProfile != MongoProfDefault {
			return errors.Errorf("mongo-memory-profile: expected one of %q or %q got string(%q)", MongoProfLow, MongoProfDefault, mgoMemProfile)
		}
	}

	if v, ok := c[MaxLogsAge].(string); ok {
		if _, err := time.ParseDuration(v); err != nil {
			return errors.Annotate(err, "invalid logs prune interval in configuration")
		}
	}

	if v, ok := c[MaxLogsSize].(string); ok {
		if _, err := utils.ParseSize(v); err != nil {
			return errors.Annotate(err, "invalid max logs size in configuration")
		}
	}

	if v, ok := c[MaxTxnLogSize].(string); ok {
		if _, err := utils.ParseSize(v); err != nil {
			return errors.Annotate(err, "invalid max txn log size in configuration")
		}
	}

	if v, ok := c[PruneTxnSleepTime].(string); ok {
		if _, err := time.ParseDuration(v); err != nil {
			return errors.Annotatef(err, `%s must be a valid duration (eg "10ms")`, PruneTxnSleepTime)
		}
	}

	if err := c.validateSpaceConfig(JujuHASpace, "juju HA"); err != nil {
		return errors.Trace(err)
	}

	if err := c.validateSpaceConfig(JujuManagementSpace, "juju mgmt"); err != nil {
		return errors.Trace(err)
	}

	if v, ok := c[CAASOperatorImagePath].(string); ok && v != "" {
		if err := resources.ValidateDockerRegistryPath(v); err != nil {
			return errors.Trace(err)
		}
	}

	if v, ok := c[CAASImageRepo].(string); ok && v != "" {
		if err := resources.ValidateDockerRegistryPath(v); err != nil {
			return errors.Trace(err)
		}
	}

	var auditLogMaxSize int
	if v, ok := c[AuditLogMaxSize].(string); ok {
		if size, err := utils.ParseSize(v); err != nil {
			return errors.Annotate(err, "invalid audit log max size in configuration")
		} else {
			auditLogMaxSize = int(size)
		}
	}

	if v, ok := c[AuditingEnabled].(bool); ok {
		if v && auditLogMaxSize == 0 {
			return errors.Errorf("invalid audit log max size: can't be 0 if auditing is enabled")
		}
	}

	if v, ok := c[AuditLogMaxBackups].(int); ok {
		if v < 0 {
			return errors.Errorf("invalid audit log max backups: should be a number of files (or 0 to keep all), got %d", v)
		}
	}

	if v, ok := c[AuditLogExcludeMethods].([]interface{}); ok {
		for i, name := range v {
			name := name.(string)
			if name != ReadOnlyMethodsWildcard && !methodNameRE.MatchString(name) {
				return errors.Errorf(
					`invalid audit log exclude methods: should be a list of "Facade.Method" names (or "ReadOnlyMethods"), got %q at position %d`,
					name,
					i+1,
				)
			}
		}
	}

	if v, ok := c[ControllerAPIPort].(int); ok {
		// TODO: change the validation so 0 is invalide and --reset is used.
		// However that doesn't exist yet.
		if v < 0 {
			return errors.NotValidf("non-positive integer for controller-api-port")
		}
		if v == c.APIPort() {
			return errors.NotValidf("controller-api-port matching api-port")
		}
		if v == c.StatePort() {
			return errors.NotValidf("controller-api-port matching state-port")
		}
	}
	if v, ok := c[APIPortOpenDelay].(string); ok {
		_, err := time.ParseDuration(v)
		if err != nil {
			return errors.Errorf("%s value %q must be a valid duration", APIPortOpenDelay, v)
		}
	}

	return nil
}
324581
func (strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {
	token := obj.(*oauthapi.OAuthClient)
	return validation.ValidateClient(token)
}
932703
func (p *JWT) Validate(token, dsecs string) (map[string]interface{}, error) {
	jp := new(jwtgo.Parser)
	jp.ValidMethods = []string{"RS256", "RS384", "RS512", "ES256", "ES384", "ES512"}

	keyFuncCallback := func(jwtToken *jwtgo.Token) (interface{}, error) {
		kid, ok := jwtToken.Header["kid"].(string)
		if !ok {
			return nil, fmt.Errorf("Invalid kid value %v", jwtToken.Header["kid"])
		}
		return p.args.publicKeys[kid], nil
	}

	var claims jwtgo.MapClaims
	jwtToken, err := jp.ParseWithClaims(token, &claims, keyFuncCallback)
	if err != nil {
		if err = p.args.PopulatePublicKey(); err != nil {
			return nil, err
		}
		jwtToken, err = jwtgo.ParseWithClaims(token, &claims, keyFuncCallback)
		if err != nil {
			return nil, err
		}
	}

	if !jwtToken.Valid {
		return nil, ErrTokenExpired
	}

	expAt, err := expToInt64(claims["exp"])
	if err != nil {
		return nil, err
	}

	defaultExpiryDuration, err := GetDefaultExpiration(dsecs)
	if err != nil {
		return nil, err
	}

	if time.Unix(expAt, 0).UTC().Sub(time.Now().UTC()) < defaultExpiryDuration {
		defaultExpiryDuration = time.Unix(expAt, 0).UTC().Sub(time.Now().UTC())
	}

	expiry := time.Now().UTC().Add(defaultExpiryDuration).Unix()
	if expAt < expiry {
		claims["exp"] = strconv.FormatInt(expAt, 64)
	}

	return claims, nil

}