// ClaimLeaseOps returns txn.Ops to write a new lease. The txn.Ops
// will fail if the lease document exists, regardless of whether it
// has expired.
973287
func ClaimLeaseOps(
	namespace, name, holder, writer, collection string,
	globalTime time.Time, duration time.Duration,
) ([]txn.Op, error) {
	ops, _, err := claimLeaseOps(
		namespace, name, holder, writer, collection,
		globalTime, duration,
	)
	return ops, errors.Trace(err)
}
923229
func (t *MemoryPool) UpdateLease(lease leasepool.Lease) (bool, error) {
	t.poolLock.Lock()
	defer t.poolLock.Unlock()

	for i := range t.pool {
		if t.pool[i].IP.Equal(lease.IP) {

			t.pool[i].MACAddress = lease.MACAddress
			t.pool[i].ClientID = lease.ClientID
			t.pool[i].Hostname = lease.Hostname
			t.pool[i].Expiry = lease.Expiry
			t.pool[i].Status = lease.Status

			return true, nil
		}
	}
	return false, nil
}
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
}
106547
func LeaseHolders(mongo Mongo, collection, namespace, modelUUID string) (map[string]string, error) {
	coll, closer := mongo.GetCollection(collection)
	defer closer()

	iter := coll.Find(bson.M{
		fieldNamespace: namespace,
		fieldModelUUID: modelUUID,
	}).Iter()
	results := make(map[string]string)
	var doc leaseHolderDoc
	for iter.Next(&doc) {
		results[doc.Lease] = doc.Holder
	}

	if err := iter.Close(); err != nil {
		return nil, errors.Trace(err)
	}
	return results, nil
}
322121
func (c *Coordinator) claimExistingTasks() {
	tasks, _, err := c.TaskService.FindTasks(context.Background(), platform.TaskFilter{})
	if err != nil {
		return
	}
	newLatestCompleted := time.Now().UTC().Format(time.RFC3339)
	for len(tasks) > 0 {
		for _, task := range tasks {

			task, err := c.TaskService.UpdateTask(context.Background(), task.ID, platform.TaskUpdate{LatestCompleted: &newLatestCompleted})
			if err != nil {
				c.logger.Error("failed to set latestCompleted", zap.Error(err))
			}

			if task.Status != string(backend.TaskActive) {
				// Don't claim inactive tasks at startup.
				continue
			}

			// I may need a context with an auth here
			if err := c.sch.ClaimTask(context.Background(), task); err != nil {
				c.logger.Error("failed claim task", zap.Error(err))
				continue
			}
		}
		tasks, _, err = c.TaskService.FindTasks(context.Background(), platform.TaskFilter{
			After: &tasks[len(tasks)-1].ID,
		})
		if err != nil {
			c.logger.Error("failed list additional tasks", zap.Error(err))
			return
		}
	}
}
537324
func (c *GithubConnectorV3) MapClaims(claims GithubClaims) ([]string, []string) {
	var logins, kubeGroups []string
	for _, mapping := range c.GetTeamsToLogins() {
		teams, ok := claims.OrganizationToTeams[mapping.Organization]
		if !ok {
			// the user does not belong to this organization
			continue
		}
		for _, team := range teams {
			// see if the user belongs to this team
			if team == mapping.Team {
				logins = append(logins, mapping.Logins...)
				kubeGroups = append(kubeGroups, mapping.KubeGroups...)
			}
		}
	}
	return utils.Deduplicate(logins), utils.Deduplicate(kubeGroups)
}
1335103
func TokenClaims(rawtoken string) (*Claims, error) {
	parts := strings.Split(rawtoken, ".")

	// There are supposed to be three parts for the token
	if len(parts) < 3 {
		return nil, fmt.Errorf("Token is invalid: %v", rawtoken)
	}

	// Access claims in the token
	claimBytes, err := jwt.DecodeSegment(parts[1])
	if err != nil {
		return nil, fmt.Errorf("Failed to decode claims: %v", err)
	}
	var claims *Claims

	// Unmarshal claims
	err = json.Unmarshal(claimBytes, &claims)
	if err != nil {
		return nil, fmt.Errorf("Unable to get information from the claims in the token: %v", err)
	}

	return claims, nil
}
240389
func (c *chainedRule) Claim(ctx context.Context) bool {
	if !c.Rule.Claim(ctx) {
		return false
	}
	return c.next.Claim(ctx)
}
68743
func (m *leadershipService) ClaimLeadership(args params.ClaimLeadershipBulkParams) (params.ClaimLeadershipBulkResults, error) {

	results := make([]params.ErrorResult, len(args.Params))
	for pIdx, p := range args.Params {

		result := &results[pIdx]
		applicationTag, unitTag, err := parseApplicationAndUnitTags(p.ApplicationTag, p.UnitTag)
		if err != nil {
			result.Error = common.ServerError(err)
			continue
		}
		duration := time.Duration(p.DurationSeconds * float64(time.Second))
		if duration > MaxLeaseRequest || duration < MinLeaseRequest {
			result.Error = common.ServerError(errors.New("invalid duration"))
			continue
		}

		// In the future, situations may arise wherein units will make
		// leadership claims for other units. For now, units can only
		// claim leadership for themselves, for their own service.
		authTag := m.authorizer.GetAuthTag()
		canClaim := false
		switch authTag.(type) {
		case names.UnitTag:
			canClaim = m.authorizer.AuthOwner(unitTag) && m.authMember(applicationTag)
		case names.ApplicationTag:
			canClaim = m.authorizer.AuthOwner(applicationTag)
		}
		if !canClaim {
			result.Error = common.ServerError(common.ErrPerm)
			continue
		}
		if err = m.claimer.ClaimLeadership(applicationTag.Id(), unitTag.Id(), duration); err != nil {
			result.Error = common.ServerError(err)
		}
	}

	return params.ClaimLeadershipBulkResults{results}, nil
}
976803
func (c *Corpus) ForeachClaimBack(value blob.Ref, at time.Time, fn func(*camtypes.Claim) bool) {
	for _, cl := range c.claimBack[value] {
		if !at.IsZero() && cl.Date.After(at) {
			continue
		}
		if !fn(cl) {
			return
		}
	}
}
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
}
1274415
func (manager *Manager) retryingClaim(claim claim) {
	defer manager.wg.Done()
	var (
		err     error
		success bool
	)
	for a := manager.startRetry(); a.Next(); {
		success, err = manager.handleClaim(claim)
		if !lease.IsTimeout(err) && !lease.IsInvalid(err) {
			break
		}
		if a.More() {
			if lease.IsInvalid(err) {
				manager.config.Logger.Tracef("[%s] request by %s for lease %s %v, retrying...",
					manager.logContext, claim.holderName, claim.leaseKey.Lease, err)
			} else {
				manager.config.Logger.Tracef("[%s] timed out handling claim by %s for lease %s, retrying...",
					manager.logContext, claim.holderName, claim.leaseKey.Lease)
			}
		}
	}

	if err == nil {
		if !success {
			claim.respond(lease.ErrClaimDenied)
			return
		}
		// now, this isn't strictly true, as the lease can be given for longer
		// than the requested duration. However, it cannot be shorter.
		// Doing it this way, we'll wake up, and then see we can sleep
		// for a bit longer. But we'll always wake up in time.
		manager.ensureNextTimeout(claim.duration)
		// respond after ensuring the timeout, at least for the test suite to be sure
		// the timer has been updated by the time it gets Claim() to return.
		claim.respond(nil)
	} else {
		switch {
		case lease.IsTimeout(err):
			claim.respond(lease.ErrTimeout)
			manager.config.Logger.Warningf("[%s] retrying timed out while handling claim %q for %q",
				manager.logContext, claim.leaseKey, claim.holderName)
		case lease.IsInvalid(err):
			// we want to see this, but it doesn't indicate something a user can do something about
			manager.config.Logger.Infof("[%s] got %v after %d retries, denying claim %q for %q",
				manager.logContext, err, maxRetries, claim.leaseKey, claim.holderName)
			claim.respond(lease.ErrClaimDenied)
		default:
			// Stop the main loop because we got an abnormal error
			manager.catacomb.Kill(errors.Trace(err))
		}
	}
}
1026206
func (s *store) ttlOpts(ctx context.Context, ttl int64) ([]clientv3.OpOption, error) {
	if ttl == 0 {
		return nil, nil
	}
	id, err := s.leaseManager.GetLease(ctx, ttl)
	if err != nil {
		return nil, err
	}
	return []clientv3.OpOption{clientv3.WithLease(id)}, nil
}
54734
func (store *store) ClaimLease(key lease.Key, request lease.Request, _ <-chan struct{}) error {
	return store.request(key.Lease, request, store.claimLeaseOps, "claiming")
}
397521
func newLeaseHolderDoc(namespace, modelUUID, name, holder string) (*leaseHolderDoc, error) {
	doc := &leaseHolderDoc{
		Id:        leaseHolderDocId(namespace, modelUUID, name),
		Namespace: namespace,
		ModelUUID: modelUUID,
		Lease:     name,
		Holder:    holder,
	}
	if err := doc.validate(); err != nil {
		return nil, errors.Trace(err)
	}
	return doc, nil
}
785825
func (s *TestInvokeAuthorizerOutput) SetClaims(v map[string]*string) *TestInvokeAuthorizerOutput {
	s.Claims = v
	return s
}
967111
func (st *State) suspendRevokedRelationsOps(offerUUID, userId string) ([]txn.Op, error) {
	conns, err := st.OfferConnections(offerUUID)
	if err != nil {
		return nil, errors.Trace(err)
	}

	var ops []txn.Op
	relIdsToSuspend := make(set.Ints)
	for _, oc := range conns {
		if oc.UserName() == userId {
			rel, err := st.Relation(oc.RelationId())
			if err != nil {
				return nil, errors.Trace(err)
			}
			if rel.Suspended() {
				continue
			}
			relIdsToSuspend.Add(rel.Id())
			suspendOp := txn.Op{
				C:      relationsC,
				Id:     rel.doc.DocID,
				Assert: txn.DocExists,
				Update: bson.D{{"$set", bson.D{{"suspended", true}}}},
			}
			ops = append(ops, suspendOp)
		}
	}

	// Add asserts that the relations against the offered application don't change.
	// This is broader than what we need but it's all that's possible.
	ao := NewApplicationOffers(st)
	offer, err := ao.ApplicationOfferForUUID(offerUUID)
	if err != nil {
		return nil, errors.Trace(err)
	}
	app, err := st.Application(offer.ApplicationName)
	if err != nil {
		return nil, errors.Trace(err)
	}
	relations, err := app.Relations()
	if err != nil {
		return nil, errors.Trace(err)
	}
	sameRelCount := bson.D{{"relationcount", len(relations)}}
	ops = append(ops, txn.Op{
		C:      applicationsC,
		Id:     app.doc.DocID,
		Assert: sameRelCount,
	})
	// Ensure any relations not being updated still exist.
	for _, r := range relations {
		if relIdsToSuspend.Contains(r.Id()) {
			continue
		}
		ops = append(ops, txn.Op{
			C:      relationsC,
			Id:     r.doc.DocID,
			Assert: txn.DocExists,
		})
	}

	return ops, nil
}