// Validate validates the JWT based on the expected claims in v.
// Note: it only validates the registered claims per
// https://tools.ietf.org/html/rfc7519#section-4.1
//
// Custom claims should be validated using v's Fn member.
432968
func (v *Validator) Validate(j JWT) error {
	if iss, ok := v.Expected.Issuer(); ok &&
		j.Claims().Get("iss") != iss {
		return ErrInvalidISSClaim
	}
	if sub, ok := v.Expected.Subject(); ok &&
		j.Claims().Get("sub") != sub {
		return ErrInvalidSUBClaim
	}
	if iat, ok := v.Expected.IssuedAt(); ok {
		if t, ok := j.Claims().GetTime("iat"); !t.Equal(iat) || !ok {
			return ErrInvalidIATClaim
		}
	}
	if jti, ok := v.Expected.JWTID(); ok &&
		j.Claims().Get("jti") != jti {
		return ErrInvalidJTIClaim
	}

	if aud, ok := v.Expected.Audience(); ok {
		aud2, ok := j.Claims().Audience()
		if !ok || !ValidAudience(aud, aud2) {
			return ErrInvalidAUDClaim
		}
	}

	if v.Fn != nil {
		return v.Fn(j.Claims())
	}
	return nil
}
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
}
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

}
638746
func (e *Error) Validate(r *http.Request, response bool) *Error {

	switch {
	case e.Status == 0:
		return ISE(fmt.Sprintf("No HTTP Status set for error %+v\n", e))
	case e.Status < 400 || e.Status > 600:
		return ISE(fmt.Sprintf("HTTP Status out of valid range for error %+v\n", e))
	case e.Status == 422 && e.Source.Pointer == "":
		return ISE(fmt.Sprintf("Source Pointer must be set for 422 Status error"))
	}

	return nil
}
480402
func (m *HttpService) Validate() error {
	if m == nil {
		return nil
	}

	{
		tmp := m.GetServerUri()

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

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

	// no validation rules for PathPrefix

	{
		tmp := m.GetAuthorizationRequest()

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

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

	{
		tmp := m.GetAuthorizationResponse()

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

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

	return nil
}
1050466
func (mt *Account) Validate() (err error) {

	if mt.Href == "" {
		err = goa.MergeErrors(err, goa.MissingAttributeError(`response`, "href"))
	}
	if mt.Name == "" {
		err = goa.MergeErrors(err, goa.MissingAttributeError(`response`, "name"))
	}

	if mt.CreatedBy == "" {
		err = goa.MergeErrors(err, goa.MissingAttributeError(`response`, "created_by"))
	}
	if err2 := goa.ValidateFormat(goa.FormatEmail, mt.CreatedBy); err2 != nil {
		err = goa.MergeErrors(err, goa.InvalidFormatError(`response.created_by`, mt.CreatedBy, goa.FormatEmail, err2))
	}
	return
}
356242
func (m *JwtRequirementAndList) Validate() error {
	if m == nil {
		return nil
	}

	if len(m.GetRequirements()) < 2 {
		return JwtRequirementAndListValidationError{
			field:  "Requirements",
			reason: "value must contain at least 2 item(s)",
		}
	}

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

		{
			tmp := item

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

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

	}

	return nil
}
483378
func (a *authenticator) Validate(provider http.HandlerFunc) http.HandlerFunc {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		// Token may be accessed via cookie, or from authentication header
		tokenString, errCode, err := a.getTokenStringFromRequest(req)
		if err != nil {
			a.formatter.Text(w, errCode, err.Error())
			return
		}
		// Retrieve token object from raw string
		token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
			if _, ok := jwt.GetSigningMethod(token.Header["alg"].(string)).(*jwt.SigningMethodHMAC); !ok {
				return nil, fmt.Errorf("error parsing token")
			}
			return []byte(signature), nil
		})
		if err != nil {
			errStr := fmt.Sprintf("500 internal server error: %s", err)
			a.formatter.Text(w, http.StatusInternalServerError, errStr)
			return
		}
		// Validate token claims
		if token.Claims != nil {
			if err := token.Claims.Valid(); err != nil {
				errStr := fmt.Sprintf("401 Unauthorized: %v", err)
				a.formatter.Text(w, http.StatusUnauthorized, errStr)
				return
			}
		}
		// Validate token itself
		if err := a.validateToken(token, req.URL.Path, req.Method); err != nil {
			errStr := fmt.Sprintf("401 Unauthorized: %v", err)
			a.formatter.Text(w, http.StatusUnauthorized, errStr)
			return
		}

		provider.ServeHTTP(w, req)
	})
}
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
}
1248901
func (p *Pushover) validate() error {
	// Check empty token
	if p.token == "" {
		return ErrEmptyToken
	}

	// Check invalid token
	if tokenRegexp.MatchString(p.token) == false {
		return ErrInvalidToken
	}
	return nil
}
377746
func (u User) Validate() error {
	if u.Login == "" {
		return NewValidationError(errors.New("invalid user login"))
	}
	if u.Email != "" {
		if _, err := mail.ParseAddress(u.Email); err != nil {
			return NewValidationError(err)
		}
	}

	return nil
}
469421
func ValidateAuthTokenWithJWT(
	ctx types.Context,
	config *types.AuthConfig,
	encJWT string) (*types.AuthToken, error) {

	lf := map[string]interface{}{"encJWT": encJWT}
	ctx.WithFields(lf).Debug("validating jwt")

	jwt, err := jws.ParseJWT([]byte(encJWT))
	if err != nil {
		ctx.WithFields(lf).WithError(err).Error("error parsing jwt")
		return nil, &types.ErrSecTokInvalid{InvalidToken: true, InnerError: err}
	}

	sm := parseSigningMethod(config.Alg)
	lf["signingMethod"] = sm.Alg()
	ctx.WithFields(lf).Debug("parsed jwt signing method")

	if err := jwt.Validate(config.Key, sm); err != nil {
		ctx.WithFields(lf).WithError(err).Error("error validating jwt")
		return nil, &types.ErrSecTokInvalid{InvalidSig: true, InnerError: err}
	}

	ctx.WithFields(lf).Debug("validated jwt signature")

	if len(jwt.Claims()) == 0 {
		ctx.WithFields(lf).Error("jwt missing claims")
		return nil, &types.ErrSecTokInvalid{}
	}

	var (
		sub string
		iat time.Time
		exp time.Time
		nbf time.Time
		ok  bool
	)

	if sub, ok = jwt.Claims().Subject(); !ok {
		ctx.WithFields(lf).Error("jwt missing sub claim")
		return nil, &types.ErrSecTokInvalid{MissingClaim: "sub"}
	}

	if iat, ok = jwt.Claims().IssuedAt(); !ok {
		ctx.WithFields(lf).Error("jwt missing iat claim")
		return nil, &types.ErrSecTokInvalid{MissingClaim: "iat"}
	}

	if exp, ok = jwt.Claims().Expiration(); !ok {
		ctx.WithFields(lf).Error("jwt missing exp claim")
		return nil, &types.ErrSecTokInvalid{MissingClaim: "exp"}
	}

	if nbf, ok = jwt.Claims().NotBefore(); !ok {
		ctx.WithFields(lf).Error("jwt missing nbf claim")
		return nil, &types.ErrSecTokInvalid{MissingClaim: "nbf"}
	}

	tok := &types.AuthToken{
		Subject:   sub,
		IssuedAt:  iat.UTC().Unix(),
		Expires:   exp.UTC().Unix(),
		NotBefore: nbf.UTC().Unix(),
	}

	lf["sub"] = tok.Subject
	lf["iat"] = tok.IssuedAt
	lf["exp"] = tok.Expires
	lf["nbf"] = tok.NotBefore

	if err := validateAuthTokenAllowed(ctx, config, lf, tok); err != nil {
		return nil, err
	}

	ctx.WithFields(lf).Info("validated security token")
	return tok, nil
}
511503
func (m *SwaggerJwkUpdateSet) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateBody(formats); err != nil {
		res = append(res, err)
	}

	if err := m.validateSet(formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}
498504
func Validate(v string, ctx *Context) error {
	return (&I{Value: v}).Validate(ctx)
}
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
}
419344
func (m *Mark) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateRemains(formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}
1217156
func (d multiValidator) Validate(s interface{}) error {
	for _, validator := range d {
		if err := validator.Validate(s); err != nil {
			return err
		}
	}

	return nil
}