// FromTokenWithoutValidation parses a token into its corresponding claims,
// without checking the token signature
506033
func FromTokenWithoutValidation(accessToken string) (*Claims, error) {
	claims := &Claims{}
	return claims, fromTokenWithoutValidation(accessToken, claims)
}
1021148
func (r *MintOAuthTokenViaGrantRPC) decodeAndValidateToken(c context.Context, grantToken string) (*tokenserver.OAuthTokenGrantBody, error) {
	// Attempt to decode the grant and log all information we can get (even if the
	// token is no longer technically valid). This information helps to debug
	// invalid tokens. InspectGrant returns an error only if the inspection
	// operation itself fails. If the token is invalid, it returns an inspection
	// with non-empty InvalidityReason.
	inspection, err := InspectGrant(c, r.Signer, grantToken)
	if err != nil {
		return nil, status.Errorf(codes.Internal, err.Error())
	}

	// This is non-nil for tokens with a valid body, even if they aren't properly
	// signed or they have already expired. These additional checks are handled
	// below after we log the body.
	grantBody, _ := inspection.Body.(*tokenserver.OAuthTokenGrantBody)
	if grantBody == nil {
		logging.Errorf(c, "Malformed grant token - %s", inspection.InvalidityReason)
		return nil, status.Errorf(codes.InvalidArgument, "malformed grant token - %s", inspection.InvalidityReason)
	}
	if logging.IsLogging(c, logging.Debug) {
		m := jsonpb.Marshaler{Indent: "  "}
		dump, _ := m.MarshalToString(grantBody)
		logging.Debugf(c, "OAuthTokenGrantBody:\n%s", dump)
	}

	if inspection.InvalidityReason != "" {
		logging.Errorf(c, "Invalid grant token - %s", inspection.InvalidityReason)
		return nil, status.Errorf(codes.InvalidArgument, "invalid grant token - %s", inspection.InvalidityReason)
	}

	// At this point we've verified 'grantToken' was issued by us (it is signed)
	// and it hasn't expired yet. Assert this.
	if !inspection.Signed || !inspection.NonExpired {
		panic(fmt.Sprintf("assertion failure Signed=%v, NonExpired=%v", inspection.Signed, inspection.NonExpired))
	}

	return grantBody, nil
}
412321
func newAsyncIDTokenVerifier(ctx context.Context, c *oidc.Config, iss string) *asyncIDTokenVerifier {
	t := &asyncIDTokenVerifier{}

	sync := make(chan struct{})
	// Polls indefinitely in an attempt to initialize the distributed claims
	// verifier, or until context canceled.
	initFn := func() (done bool, err error) {
		klog.V(4).Infof("oidc authenticator: attempting init: iss=%v", iss)
		v, err := initVerifier(ctx, c, iss)
		if err != nil {
			klog.Errorf("oidc authenticator: async token verifier for issuer: %q: %v", iss, err)
			return false, nil
		}
		t.m.Lock()
		defer t.m.Unlock()
		t.v = v
		close(sync)
		return true, nil
	}

	go func() {
		if done, _ := initFn(); !done {
			go wait.PollUntil(time.Second*10, initFn, ctx.Done())
		}
	}()

	if synchronizeTokenIDVerifierForTest {
		<-sync
	}

	return t
}
828852
func (c *JWTClaims) FromMap(m map[string]interface{}) {
	c.Extra = make(map[string]interface{})
	for k, v := range m {
		switch k {
		case "jti":
			if s, ok := v.(string); ok {
				c.JTI = s
			}
		case "sub":
			if s, ok := v.(string); ok {
				c.Subject = s
			}
		case "iss":
			if s, ok := v.(string); ok {
				c.Issuer = s
			}
		case "aud":
			if s, ok := v.(string); ok {
				c.Audience = []string{s}
			} else if s, ok := v.([]string); ok {
				c.Audience = s
			}
		case "iat":
			switch v.(type) {
			case float64:
				c.IssuedAt = time.Unix(int64(v.(float64)), 0).UTC()
			case int64:
				c.IssuedAt = time.Unix(v.(int64), 0).UTC()
			}
		case "nbf":
			switch v.(type) {
			case float64:
				c.NotBefore = time.Unix(int64(v.(float64)), 0).UTC()
			case int64:
				c.NotBefore = time.Unix(v.(int64), 0).UTC()
			}
		case "exp":
			switch v.(type) {
			case float64:
				c.ExpiresAt = time.Unix(int64(v.(float64)), 0).UTC()
			case int64:
				c.ExpiresAt = time.Unix(v.(int64), 0).UTC()
			}
		case "scp":
			switch v.(type) {
			case []string:
				c.Scope = v.([]string)
			case []interface{}:
				c.Scope = make([]string, len(v.([]interface{})))
				for i, vi := range v.([]interface{}) {
					if s, ok := vi.(string); ok {
						c.Scope[i] = s
					}
				}
			}
		default:
			c.Extra[k] = v
		}
	}
}
72395
func untrustedIssuer(token string) (string, error) {
	parts := strings.Split(token, ".")
	if len(parts) != 3 {
		return "", fmt.Errorf("malformed token")
	}
	payload, err := base64.RawURLEncoding.DecodeString(parts[1])
	if err != nil {
		return "", fmt.Errorf("error decoding token: %v", err)
	}
	claims := struct {
		// WARNING: this JWT is not verified. Do not trust these claims.
		Issuer string `json:"iss"`
	}{}
	if err := json.Unmarshal(payload, &claims); err != nil {
		return "", fmt.Errorf("while unmarshaling token: %v", err)
	}
	// Coalesce the legacy GoogleIss with the new one.
	//
	// http://openid.net/specs/openid-connect-core-1_0.html#GoogleIss
	if claims.Issuer == "accounts.google.com" {
		return "https://accounts.google.com", nil
	}
	return claims.Issuer, nil
}
888316
func (s *AuthServer) ValidateToken(token string) (roles teleport.Roles, e error) {
	tkns, err := s.GetCache().GetStaticTokens()
	if err != nil {
		return nil, trace.Wrap(err)
	}

	// First check if the token is a static token. If it is, return right away.
	// Static tokens have no expiration.
	for _, st := range tkns.GetStaticTokens() {
		if st.GetName() == token {
			return st.GetRoles(), nil
		}
	}

	// If it's not a static token, check if it's a ephemeral token in the backend.
	// If a ephemeral token is found, make sure it's still valid.
	tok, err := s.GetCache().GetToken(token)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	if !s.checkTokenTTL(tok) {
		return nil, trace.AccessDenied("token expired")
	}

	return tok.GetRoles(), nil
}
1285510
func (f *UintFlag) ApplyWithError(set *flag.FlagSet) error {
	f.set = set
	return f.UintFlag.ApplyWithError(set)
}
799654
func (m *Middleware) VerifyToken(token string, v VerifyClaimsFunc, r *http.Request) (int, string, error) {
	tokenParts := strings.Split(token, ".")
	if len(tokenParts) != 3 {
		return http.StatusUnauthorized, "", ErrMalformedToken
	}

	// First, verify JOSE header
	header, err := decode(tokenParts[0])
	if err != nil {
		return http.StatusInternalServerError, fmt.Sprintf("decoding header (%v)", tokenParts[0]), err
	}
	var t struct {
		Typ string
		Alg string
	}
	err = json.Unmarshal(header, &t)
	if err != nil {
		return http.StatusInternalServerError, fmt.Sprintf("unmarshalling header (%s)", header), ErrMalformedToken
	}

	// Then, verify signature
	mac := hmac.New(sha256.New, []byte(m.secret))
	message := []byte(strings.Join([]string{tokenParts[0], tokenParts[1]}, "."))
	mac.Write(message)
	expectedMac, err := encode(mac.Sum(nil))
	if err != nil {
		return http.StatusInternalServerError, "", err
	}
	if !hmac.Equal([]byte(tokenParts[2]), []byte(expectedMac)) {
		return http.StatusUnauthorized, fmt.Sprintf("checking signature (%v)", tokenParts[2]), ErrInvalidSignature
	}

	// Finally, check claims
	claimSet, err := decode(tokenParts[1])
	if err != nil {
		return http.StatusInternalServerError, "decoding claims", ErrDecoding
	}
	err = v(claimSet, r)
	if err != nil {
		return http.StatusUnauthorized, "handling claims callback", err
	}

	return 200, "", nil
}
426071
func verifyToken() error {
	// get the token
	tokData, err := loadData(*flagVerify)
	if err != nil {
		return fmt.Errorf("Couldn't read token: %v", err)
	}

	// trim possible whitespace from token
	tokData = regexp.MustCompile(`\s*$`).ReplaceAll(tokData, []byte{})
	if *flagDebug {
		fmt.Fprintf(os.Stderr, "Token len: %v bytes\n", len(tokData))
	}

	// Parse the token.  Load the key from command line option
	token, err := jwt.Parse(string(tokData), func(t *jwt.Token) (interface{}, error) {
		data, err := loadData(*flagKey)
		if err != nil {
			return nil, err
		}
		if isEs() {
			return jwt.ParseECPublicKeyFromPEM(data)
		} else if isRs() {
			return jwt.ParseRSAPublicKeyFromPEM(data)
		}
		return data, nil
	})

	// Print some debug data
	if *flagDebug && token != nil {
		fmt.Fprintf(os.Stderr, "Header:\n%v\n", token.Header)
		fmt.Fprintf(os.Stderr, "Claims:\n%v\n", token.Claims)
	}

	// Print an error if we can't parse for some reason
	if err != nil {
		return fmt.Errorf("Couldn't parse token: %v", err)
	}

	// Is token invalid?
	if !token.Valid {
		return fmt.Errorf("Token is invalid")
	}

	// Print the token details
	if err := printJSON(token.Claims); err != nil {
		return fmt.Errorf("Failed to output claims: %v", err)
	}

	return nil
}
1094370
func ValidateToken(token string, fldPath *field.Path) field.ErrorList {
	allErrs := field.ErrorList{}

	if !bootstraputil.IsValidBootstrapToken(token) {
		allErrs = append(allErrs, field.Invalid(fldPath, token, "the bootstrap token is invalid"))
	}

	return allErrs
}
1142768
func (p *tokenManager) CreateTokenFromCertificate(cert *x509.Certificate, tags []string) ([]byte, error) {

	// Combine the application claims with the standard claims
	claims := &verifierClaims{
		X:    cert.PublicKey.(*ecdsa.PublicKey).X,
		Y:    cert.PublicKey.(*ecdsa.PublicKey).Y,
		Tags: tags,
	}
	claims.ExpiresAt = cert.NotAfter.Unix()

	// Create the token and sign with our key
	strtoken, err := jwt.NewWithClaims(p.signMethod, claims).SignedString(p.privateKey)
	if err != nil {
		return []byte{}, err
	}

	return []byte(strtoken), nil
}
1208970
func FromToken(provider tokenkey.Provider, accessToken string) (*Claims, error) {
	claims := &Claims{}
	return claims, fromToken(provider, accessToken, claims)
}
1135070
func (c *Component) ValidateTTNAuthContext(ctx context.Context) (*claims.Claims, error) {
	token, err := ttnctx.TokenFromIncomingContext(ctx)
	if err != nil {
		return nil, err
	}

	if c.TokenKeyProvider == nil {
		return nil, errors.NewErrInternal("No token provider configured")
	}

	claims, err := claims.FromToken(c.TokenKeyProvider, token)
	if err != nil {
		return nil, errors.NewErrPermissionDenied(err.Error())
	}

	return claims, nil
}
762755
func (opts *ListOpts) WithValidator(validator ValidatorFctType) *ListOpts {
	opts.validator = validator
	return opts
}
1253779
func FromError(err error) (s *Status, ok bool) {
	if err == nil {
		return &Status{Code: codes.OK}, true
	}
	if s, ok := err.(*Status); ok {
		return s, true
	}
	return nil, false
}
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
}
1306841
func parseVaultTokenFromJWT(token string) *string {
	if strings.Count(token, ".") != 2 {
		return nil
	}

	parsedJWT, err := squarejwt.ParseSigned(token)
	if err != nil {
		return nil
	}

	var claims squarejwt.Claims
	if err = parsedJWT.UnsafeClaimsWithoutVerification(&claims); err != nil {
		return nil
	}

	return &claims.ID
}