// Claims helps implements jwt.JWT.
502294
func (j *jws) Claims() jwt.Claims {
	if j.isJWT {
		if c, ok := j.payload.v.(Claims); ok {
			return jwt.Claims(c)
		}
	}
	return nil
}
587316
func (s *Server) updateAccountClaims(a *Account, ac *jwt.AccountClaims) {
	if a == nil {
		return
	}
	s.Debugf("Updating account claims: %s", a.Name)
	a.checkExpiration(ac.Claims())

	a.mu.Lock()
	// Clone to update, only select certain fields.
	old := &Account{Name: a.Name, imports: a.imports, exports: a.exports, limits: a.limits, signingKeys: a.signingKeys}

	// Reset exports and imports here.
	a.exports = exportMap{}
	a.imports = importMap{}

	// update account signing keys
	a.signingKeys = nil
	signersChanged := false
	if len(ac.SigningKeys) > 0 {
		// insure copy the new keys and sort
		a.signingKeys = append(a.signingKeys, ac.SigningKeys...)
		sort.Strings(a.signingKeys)
	}
	if len(a.signingKeys) != len(old.signingKeys) {
		signersChanged = true
	} else {
		for i := 0; i < len(old.signingKeys); i++ {
			if a.signingKeys[i] != old.signingKeys[i] {
				signersChanged = true
				break
			}
		}
	}
	a.mu.Unlock()

	gatherClients := func() []*client {
		a.mu.RLock()
		clients := make([]*client, 0, len(a.clients))
		for _, c := range a.clients {
			clients = append(clients, c)
		}
		a.mu.RUnlock()
		return clients
	}

	for _, e := range ac.Exports {
		switch e.Type {
		case jwt.Stream:
			s.Debugf("Adding stream export %q for %s", e.Subject, a.Name)
			if err := a.AddStreamExport(string(e.Subject), authAccounts(e.TokenReq)); err != nil {
				s.Debugf("Error adding stream export to account [%s]: %v", a.Name, err.Error())
			}
		case jwt.Service:
			s.Debugf("Adding service export %q for %s", e.Subject, a.Name)
			if err := a.AddServiceExport(string(e.Subject), authAccounts(e.TokenReq)); err != nil {
				s.Debugf("Error adding service export to account [%s]: %v", a.Name, err.Error())
			}
		}
	}
	for _, i := range ac.Imports {
		var acc *Account
		if v, ok := s.accounts.Load(i.Account); ok {
			acc = v.(*Account)
		}
		if acc == nil {
			if acc, _ = s.fetchAccount(i.Account); acc == nil {
				s.Debugf("Can't locate account [%s] for import of [%v] %s", i.Account, i.Subject, i.Type)
				continue
			}
		}
		switch i.Type {
		case jwt.Stream:
			s.Debugf("Adding stream import %s:%q for %s:%q", acc.Name, i.Subject, a.Name, i.To)
			if err := a.AddStreamImportWithClaim(acc, string(i.Subject), string(i.To), i); err != nil {
				s.Debugf("Error adding stream import to account [%s]: %v", a.Name, err.Error())
			}
		case jwt.Service:
			s.Debugf("Adding service import %s:%q for %s:%q", acc.Name, i.Subject, a.Name, i.To)
			if err := a.AddServiceImportWithClaim(acc, string(i.Subject), string(i.To), i); err != nil {
				s.Debugf("Error adding service import to account [%s]: %v", a.Name, err.Error())
			}
		}
	}
	// Now let's apply any needed changes from import/export changes.
	if !a.checkStreamImportsEqual(old) {
		awcsti := map[string]struct{}{a.Name: struct{}{}}
		for _, c := range gatherClients() {
			c.processSubsOnConfigReload(awcsti)
		}
	}
	// Now check if stream exports have changed.
	if !a.checkStreamExportsEqual(old) || signersChanged {
		clients := make([]*client, 0, 16)
		// We need to check all accounts that have an import claim from this account.
		awcsti := map[string]struct{}{}
		s.accounts.Range(func(k, v interface{}) bool {
			acc := v.(*Account)
			acc.mu.Lock()
			for _, im := range acc.imports.streams {
				if im != nil && im.acc.Name == a.Name {
					// Check for if we are still authorized for an import.
					im.invalid = !a.checkStreamImportAuthorizedNoLock(im.acc, im.from, im.claim)
					awcsti[acc.Name] = struct{}{}
					for _, c := range acc.clients {
						clients = append(clients, c)
					}
				}
			}
			acc.mu.Unlock()
			return true
		})
		// Now walk clients.
		for _, c := range clients {
			c.processSubsOnConfigReload(awcsti)
		}
	}
	// Now check if service exports have changed.
	if !a.checkServiceExportsEqual(old) || signersChanged {
		s.accounts.Range(func(k, v interface{}) bool {
			acc := v.(*Account)
			acc.mu.Lock()
			for _, im := range acc.imports.services {
				if im != nil && im.acc.Name == a.Name {
					// Check for if we are still authorized for an import.
					im.invalid = !a.checkServiceImportAuthorizedNoLock(a, im.to, im.claim)
				}
			}
			acc.mu.Unlock()
			return true
		})
	}

	// Now do limits if they are present.
	a.mu.Lock()
	a.msubs = int32(ac.Limits.Subs)
	a.mpay = int32(ac.Limits.Payload)
	a.mconns = int32(ac.Limits.Conn)
	a.mleafs = int32(ac.Limits.LeafNodeConn)
	a.mu.Unlock()

	clients := gatherClients()
	// Sort if we are over the limit.
	if a.maxTotalConnectionsReached() {
		sort.Slice(clients, func(i, j int) bool {
			return clients[i].start.After(clients[j].start)
		})
	}
	for i, c := range clients {
		if a.mconns != jwt.NoLimit && i >= int(a.mconns) {
			c.maxAccountConnExceeded()
			continue
		}
		c.mu.Lock()
		c.applyAccountLimits()
		c.mu.Unlock()
	}

	// Check if the signing keys changed, might have to evict
	if signersChanged {
		for _, c := range clients {
			c.mu.Lock()
			sk := c.user.SigningKey
			c.mu.Unlock()
			if sk != "" && !a.hasIssuer(sk) {
				c.closeConnection(AuthenticationViolation)
			}
		}
	}
}
503782
func (c Claims) SetJWTID(uniqueID string) {
	jwt.Claims(c).SetJWTID(uniqueID)
}
729348
func (o *OIDCConnectorV2) MapClaims(claims jose.Claims) []string {
	var roles []string
	for _, mapping := range o.Spec.ClaimsToRoles {
		for claimName := range claims {
			if claimName != mapping.Claim {
				continue
			}
			var claimValues []string
			claimValue, ok, _ := claims.StringClaim(claimName)
			if ok {
				claimValues = []string{claimValue}
			} else {
				claimValues, _, _ = claims.StringsClaim(claimName)
			}
		claimLoop:
			for _, claimValue := range claimValues {
				for _, role := range mapping.Roles {
					outRole, err := utils.ReplaceRegexp(mapping.Value, role, claimValue)
					switch {
					case err != nil:
						if trace.IsNotFound(err) {
							log.Debugf("Failed to match expression %v, replace with: %v input: %v, err: %v", mapping.Value, role, claimValue, err)
						}
						// this claim value clearly did not match, move on to another
						continue claimLoop
						// skip empty replacement or empty role
					case outRole == "":
					case outRole != "":
						roles = append(roles, outRole)
					}
				}
			}
		}
	}
	return utils.Deduplicate(roles)
}
1168321
func (v *validatorRule) Claim(ctx context.Context) bool {
	// check for pre-cache validators, if at least one of them return false
	// for this specific request, then skip the whole cache
	for _, shouldProcess := range v.preValidators {
		if !shouldProcess(ctx) {
			return false
		}
	}
	return true
}
1227048
func Claim(mctx libkb.MetaContext, walletState *WalletState,
	txID string, into stellar1.AccountID, dir *stellar1.RelayDirection,
	autoClaimToken *string) (res stellar1.RelayClaimResult, err error) {
	defer mctx.TraceTimed("Stellar.Claim", func() error { return err })()
	mctx.Debug("Stellar.Claim(txID:%v, into:%v, dir:%v, autoClaimToken:%v)", txID, into, dir, autoClaimToken)
	details, err := walletState.PaymentDetailsGeneric(mctx.Ctx(), txID)
	if err != nil {
		return res, err
	}
	p := details.Summary
	typ, err := p.Typ()
	if err != nil {
		return res, fmt.Errorf("error getting payment details: %v", err)
	}
	switch typ {
	case stellar1.PaymentSummaryType_STELLAR:
		return res, fmt.Errorf("Payment cannot be claimed. It was found on the Stellar network but not in Keybase.")
	case stellar1.PaymentSummaryType_DIRECT:
		p := p.Direct()
		switch p.TxStatus {
		case stellar1.TransactionStatus_SUCCESS:
			return res, fmt.Errorf("Payment cannot be claimed. The direct transfer already happened.")
		case stellar1.TransactionStatus_PENDING:
			return res, fmt.Errorf("Payment cannot be claimed. It is currently pending.")
		default:
			return res, fmt.Errorf("Payment cannot be claimed. The payment failed anyway.")
		}
	case stellar1.PaymentSummaryType_RELAY:
		return claimPaymentWithDetail(mctx, walletState, p.Relay(), into, dir)
	default:
		return res, fmt.Errorf("unrecognized payment type: %v", typ)
	}
}
516864
func (a *AuthServer) getClaims(oidcClient *oidc.Client, issuerURL string, scope []string, code string) (jose.Claims, error) {
	var err error

	oac, err := oidcClient.OAuthClient()
	if err != nil {
		return nil, trace.Wrap(err)
	}

	t, err := oac.RequestToken(oauth2.GrantTypeAuthCode, code)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	idTokenClaims, err := claimsFromIDToken(oidcClient, t.IDToken)
	if err != nil {
		log.Debugf("Unable to fetch OIDC ID token claims: %v.", err)
		return nil, trace.Wrap(err)
	}
	log.Debugf("OIDC ID Token claims: %v.", idTokenClaims)

	userInfoClaims, err := claimsFromUserInfo(oidcClient, issuerURL, t.AccessToken)
	if err != nil {
		if trace.IsNotFound(err) {
			log.Debugf("OIDC provider doesn't offer UserInfo endpoint. Returning token claims: %v.", idTokenClaims)
			return idTokenClaims, nil
		}
		log.Debugf("Unable to fetch UserInfo claims: %v.", err)
		return nil, trace.Wrap(err)
	}
	log.Debugf("UserInfo claims: %v.", userInfoClaims)

	// make sure that the subject in the userinfo claim matches the subject in
	// the id token otherwise there is the possibility of a token substitution attack.
	// see section 16.11 of the oidc spec for more details.
	var idsub string
	var uisub string
	var exists bool
	if idsub, exists, err = idTokenClaims.StringClaim("sub"); err != nil || !exists {
		log.Debugf("Unable to extract OIDC sub claim from ID token.")
		return nil, trace.Wrap(err)
	}
	if uisub, exists, err = userInfoClaims.StringClaim("sub"); err != nil || !exists {
		log.Debugf("Unable to extract OIDC sub claim from UserInfo.")
		return nil, trace.Wrap(err)
	}
	if idsub != uisub {
		log.Debugf("OIDC claim subjects don't match '%v' != '%v'.", idsub, uisub)
		return nil, trace.BadParameter("invalid subject in UserInfo")
	}

	claims, err := mergeClaims(idTokenClaims, userInfoClaims)
	if err != nil {
		log.Debugf("Unable to merge OIDC claims: %v.", err)
		return nil, trace.Wrap(err)
	}

	// for GSuite users, fetch extra data from the proprietary google API
	// only if scope includes admin groups readonly scope
	if issuerURL == teleport.GSuiteIssuerURL && utils.SliceContainsStr(scope, teleport.GSuiteGroupsScope) {
		email, _, err := claims.StringClaim("email")
		if err != nil {
			return nil, trace.Wrap(err)
		}
		gsuiteClaims, err := a.claimsFromGSuite(oidcClient, issuerURL, email, t.AccessToken)
		if err != nil {
			if !trace.IsNotFound(err) {
				return nil, trace.Wrap(err)
			}
			log.Debugf("Found no GSuite claims.")
		} else {
			if gsuiteClaims != nil {
				log.Debugf("Got GSuiteclaims: %v.", gsuiteClaims)
			}
			claims, err = mergeClaims(claims, gsuiteClaims)
			if err != nil {
				return nil, trace.Wrap(err)
			}
		}
	}

	return claims, nil
}
274633
func (mgr *SessionManager) Parse(tokenString string) (jwt.Claims, error) {
	// Parse takes the token string and a function for looking up the key. The latter is especially
	// useful if you use multiple keys for your application.  The standard is to use 'kid' in the
	// head of the token to identify which key to use, but the parsed token (head and claims) is provided
	// to the callback, providing flexibility.
	var claims jwt.MapClaims
	settings, err := mgr.settingsMgr.GetSettings()
	if err != nil {
		return nil, err
	}
	token, err := jwt.ParseWithClaims(tokenString, &claims, func(token *jwt.Token) (interface{}, error) {
		// Don't forget to validate the alg is what you expect:
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		return settings.ServerSignature, nil
	})
	if err != nil {
		return nil, err
	}

	issuedAt := time.Unix(int64(claims["iat"].(float64)), 0)
	if issuedAt.Before(settings.AdminPasswordMtime) {
		return nil, fmt.Errorf("Password for superuser has changed since token issued")
	}
	return token.Claims, nil
}
23136
func JWT(username, sharedSecret string, now Now) (string, error) {
	token := &jwt.Token{
		Header: map[string]interface{}{
			"typ": "JWT",
			"alg": jwt.SigningMethodHS512.Alg(),
		},
		Claims: jwt.MapClaims{
			"username": username,
			"exp":      now().Add(time.Minute).Unix(),
		},
		Method: jwt.SigningMethodHS512,
	}
	return token.SignedString([]byte(sharedSecret))
}
1030783
func MapClaims(claims jwtgo.Claims) (jwtgo.MapClaims, error) {
	claimsBytes, err := json.Marshal(claims)
	if err != nil {
		return nil, err
	}
	var mapClaims jwtgo.MapClaims
	err = json.Unmarshal(claimsBytes, &mapClaims)
	if err != nil {
		return nil, err
	}
	return mapClaims, nil
}
237385
func getAuthenticatedUser(ctx context.Context) string {
	claimsIf := ctx.Value("claims")
	if claimsIf == nil {
		return ""
	}
	claims, ok := claimsIf.(jwt.Claims)
	if !ok {
		return ""
	}
	mapClaims, err := jwtutil.MapClaims(claims)
	if err != nil {
		return ""
	}
	return jwtutil.GetField(mapClaims, "sub")
}
721325
func (a *AccessToken) ToJWT() (string, error) {
	claims := &twilioClaims{
		jwt.StandardClaims{
			Id:        a.APIKeySid + fmt.Sprintf("-%d", time.Now().UnixNano()),
			Issuer:    a.APIKeySid,
			Subject:   a.AccountSid,
			NotBefore: a.NotBefore.Unix(),
			ExpiresAt: a.ExpiresAt.Unix(),
		},
		&grantsClaim{
			Identity: a.Identity,
			Grants:   a.Grants,
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	token.Header = map[string]interface{}{
		"typ": "JWT",
		"alg": "HS256",
		"cty": "twilio-fpa;v=1",
	}

	ss, err := token.SignedString([]byte(a.APIKeySecret))

	return ss, err
}
1307778
func (mw *GinJWTMiddleware) GetClaimsFromJWT(c *gin.Context) (MapClaims, error) {
	token, err := mw.ParseToken(c)

	if err != nil {
		return nil, err
	}

	if mw.SendAuthorization {
		if v, ok := c.Get("JWT_TOKEN"); ok {
			c.Header("Authorization", mw.TokenHeadName+" "+v.(string))
		}
	}

	claims := MapClaims{}
	for key, value := range token.Claims.(jwt.MapClaims) {
		claims[key] = value
	}

	return claims, nil
}
35792
func (c Claims) Expiration() (time.Time, bool) {
	return jwt.Claims(c).Expiration()
}
230477
func Claim(nodeAvailableResources, taskAssigned *[]*api.GenericResource,
	taskReservations []*api.GenericResource) error {
	var resSelected []*api.GenericResource

	for _, res := range taskReservations {
		tr := res.GetDiscreteResourceSpec()
		if tr == nil {
			return fmt.Errorf("task should only hold Discrete type")
		}

		// Select the resources
		nrs, err := selectNodeResources(*nodeAvailableResources, tr)
		if err != nil {
			return err
		}

		resSelected = append(resSelected, nrs...)
	}

	ClaimResources(nodeAvailableResources, taskAssigned, resSelected)
	return nil
}
630312
func ClaimResources(nodeAvailableResources, taskAssigned *[]*api.GenericResource,
	resSelected []*api.GenericResource) {
	*taskAssigned = append(*taskAssigned, resSelected...)
	ConsumeNodeResources(nodeAvailableResources, resSelected)
}
150026
func (consumer *Consumer) ConsumeClaim(session sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error {

	// NOTE:
	// Do not move the code below to a goroutine.
	// The `ConsumeClaim` itself is called within a goroutine, see:
	// https://github.com/Shopify/sarama/blob/master/consumer_group.go#L27-L29
	for message := range claim.Messages() {
		log.Printf("Message claimed: value = %s, timestamp = %v, topic = %s", string(message.Value), message.Timestamp, message.Topic)
		session.MarkMessage(message, "")
	}

	return nil
}