// GetClaims returns the claims on req.Permanode signed by h.owner.
13305
func (h *Handler) GetClaims(req *ClaimsRequest) (*ClaimsResponse, error) {
	if !req.Permanode.Valid() {
		return nil, errors.New("error getting claims: nil permanode")
	}
	h.index.RLock()
	defer h.index.RUnlock()

	ctx := context.TODO()
	var claims []camtypes.Claim
	claims, err := h.index.AppendClaims(ctx, claims, req.Permanode, h.owner.KeyID(), req.AttrFilter)
	if err != nil {
		return nil, fmt.Errorf("Error getting claims of %s: %v", req.Permanode.String(), err)
	}
	sort.Sort(camtypes.ClaimsByDate(claims))
	var jclaims []*ClaimsItem
	for _, claim := range claims {
		jclaim := &ClaimsItem{
			BlobRef:   claim.BlobRef,
			Signer:    claim.Signer,
			Permanode: claim.Permanode,
			Date:      types.Time3339(claim.Date),
			Type:      claim.Type,
			Attr:      claim.Attr,
			Value:     claim.Value,
		}
		jclaims = append(jclaims, jclaim)
	}

	res := &ClaimsResponse{
		Claims: jclaims,
	}
	return res, nil
}
323948
func (g *Generic) GroupFromClaims(claims gojwt.MapClaims) (string, error) {
	if id, ok := claims[g.APIKey].(string); ok {
		email := strings.Split(id, "@")
		if len(email) != 2 {
			g.Logger.Error("malformed email address, expected %q to contain @ symbol", id)
			return "DEFAULT", nil
		}

		return email[1], nil
	}

	return "", fmt.Errorf("no claim for %s", g.APIKey)
}
406133
func (p *Provider) validateClaims(claims map[string]interface{}) (time.Time, error) {
	audience := getClaimValue(claims, []string{audienceClaim})
	if audience != p.ClientKey {
		found := false
		audiences := getClaimValues(claims, []string{audienceClaim})
		for _, aud := range audiences {
			if aud == p.ClientKey {
				found = true
				break
			}
		}
		if !found {
			return time.Time{}, errors.New("audience in token does not match client key")
		}
	}

	issuer := getClaimValue(claims, []string{issuerClaim})
	if issuer != p.openIDConfig.Issuer {
		return time.Time{}, errors.New("issuer in token does not match issuer in OpenIDConfig discovery")
	}

	// expiry is required for JWT, not for UserInfoResponse
	// is actually a int64, so force it in to that type
	expiryClaim := int64(claims[expiryClaim].(float64))
	expiry := time.Unix(expiryClaim, 0)
	if expiry.Add(clockSkew).Before(time.Now()) {
		return time.Time{}, errors.New("user info JWT token is expired")
	}
	return expiry, nil
}
1188250
func getClaimsFromToken(r *http.Request) (map[string]interface{}, error) {
	claims := make(map[string]interface{})
	token := getSessionToken(r)
	if token == "" {
		return claims, nil
	}
	stsTokenCallback := func(jwtToken *jwtgo.Token) (interface{}, error) {
		// JWT token for x-amz-security-token is signed with admin
		// secret key, temporary credentials become invalid if
		// server admin credentials change. This is done to ensure
		// that clients cannot decode the token using the temp
		// secret keys and generate an entirely new claim by essentially
		// hijacking the policies. We need to make sure that this is
		// based an admin credential such that token cannot be decoded
		// on the client side and is treated like an opaque value.
		return []byte(globalServerConfig.GetCredential().SecretKey), nil
	}
	p := &jwtgo.Parser{
		ValidMethods: []string{
			jwtgo.SigningMethodHS256.Alg(),
			jwtgo.SigningMethodHS512.Alg(),
		},
	}
	jtoken, err := p.ParseWithClaims(token, jwtgo.MapClaims(claims), stsTokenCallback)
	if err != nil {
		return nil, err
	}
	if !jtoken.Valid {
		return nil, errAuthentication
	}
	v, ok := claims["accessKey"]
	if !ok {
		return nil, errInvalidAccessKeyID
	}
	if _, ok = v.(string); !ok {
		return nil, errInvalidAccessKeyID
	}
	return claims, nil
}
150636
func (manager *Manager) handleClaim(claim claim) (bool, error) {
	store := manager.config.Store
	request := lease.Request{Holder: claim.holderName, Duration: claim.duration}
	err := lease.ErrInvalid
	action := "unknown"
	select {
	case <-manager.catacomb.Dying():
		return false, manager.catacomb.ErrDying()
	default:
		info, found := manager.lookupLease(claim.leaseKey)
		switch {
		case !found:
			manager.config.Logger.Tracef("[%s] %s asked for lease %s, no lease found, claiming for %s",
				manager.logContext, claim.holderName, claim.leaseKey.Lease, claim.duration)
			action = "claiming"
			err = store.ClaimLease(claim.leaseKey, request, manager.catacomb.Dying())
		case info.Holder == claim.holderName:
			manager.config.Logger.Tracef("[%s] %s extending lease %s for %s",
				manager.logContext, claim.holderName, claim.leaseKey.Lease, claim.duration)
			action = "extending"
			err = store.ExtendLease(claim.leaseKey, request, manager.catacomb.Dying())
		default:
			// Note: (jam) 2017-10-31) We don't check here if the lease has
			// expired for the current holder. Should we?
			remaining := info.Expiry.Sub(manager.config.Clock.Now())
			manager.config.Logger.Tracef("[%s] %s asked for lease %s, held by %s for another %s, rejecting",
				manager.logContext, claim.holderName, claim.leaseKey.Lease, info.Holder, remaining)
			return false, nil
		}
	}
	if lease.IsAborted(err) {
		return false, manager.catacomb.ErrDying()
	}
	if err != nil {
		return false, errors.Trace(err)
	}
	manager.config.Logger.Tracef("[%s] %s %s lease %s for %s successful",
		manager.logContext, claim.holderName, action, claim.leaseKey.Lease, claim.duration)
	return true, nil
}
794846
func (c *ClaimTreeClient) Get(ctx context.Context, orgID *identity.ID,
	ownerID *identity.ID) (*ClaimTree, error) {

	if orgID == nil {
		return nil, errors.New("An org id must be provided")
	}

	cts, err := c.List(ctx, orgID, ownerID)
	if err != nil {
		return nil, err
	}

	if len(cts) != 1 {
		return nil, ErrClaimTreeNotFound
	}

	return &cts[0], nil
}
113500
func getClaimJWT(client *http.Client, url, accessToken string) (string, error) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// TODO: Allow passing request body with configurable information.
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return "", fmt.Errorf("while calling %v: %v", url, err)
	}
	if accessToken != "" {
		req.Header.Set("Authorization", fmt.Sprintf("Bearer %v", accessToken))
	}
	req = req.WithContext(ctx)
	response, err := client.Do(req)
	if err != nil {
		return "", err
	}
	// Report non-OK status code as an error.
	if response.StatusCode < http.StatusOK || response.StatusCode > http.StatusIMUsed {
		return "", fmt.Errorf("error while getting distributed claim JWT: %v", response.Status)
	}
	defer response.Body.Close()
	responseBytes, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return "", fmt.Errorf("could not decode distributed claim response")
	}
	return string(responseBytes), nil
}
36335
func (api *API) Claim(duration time.Duration) error {
	args := params.SingularClaims{
		Claims: []params.SingularClaim{{
			EntityTag:   api.entity.String(),
			ClaimantTag: api.claimant.String(),
			Duration:    duration,
		}},
	}
	var results params.ErrorResults
	err := api.facadeCaller.FacadeCall("Claim", args, &results)
	if err != nil {
		return errors.Trace(err)
	}

	err = results.OneError()
	if err != nil {
		if params.IsCodeLeaseClaimDenied(err) {
			return lease.ErrClaimDenied
		}
		return errors.Trace(err)
	}
	return nil
}
1131277
func (s *Store) ClaimLease(key lease.Key, req lease.Request, stop <-chan struct{}) error {
	return errors.Trace(s.runOnLeader(&Command{
		Version:   CommandVersion,
		Operation: OperationClaim,
		Namespace: key.Namespace,
		ModelUUID: key.ModelUUID,
		Lease:     key.Lease,
		Holder:    req.Holder,
		Duration:  req.Duration,
	}, stop))
}
471893
func ExtractClaimsFromToken(token *jwt.Token) MapClaims {
	if token == nil {
		return make(MapClaims)
	}

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

	return claims
}
252604
func (l *Client) GetAccounts() ([]*Account, error) {
	res := ApiResp{}
	var data []*Account

	// make the request
	err := l.Get(accountListEndpoint, nil, nil, &res, &data)
	if err != nil {
		return data, err
	}

	return data, nil
}
527782
func (g *Generic) PrincipalIDFromClaims(claims gojwt.MapClaims) (string, error) {
	if id, ok := claims[g.APIKey].(string); ok {
		return id, nil
	}
	return "", fmt.Errorf("no claim for %s", g.APIKey)
}
1163109
func (h *headerRule) Claim(ctx context.Context) bool {
	return h.claim(ctx.Request().Header.Get)
}
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)
}
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
}
414477
func (s *Server) UpdateAccountClaims(a *Account, ac *jwt.AccountClaims) {
	s.updateAccountClaims(a, ac)
}
348567
func (l *Client) GetAuths() ([]*Auth, error) {
	res := ApiResp{}
	data := []*Auth{}

	// make the request
	err := l.Get(authListEndpoint, nil, nil, &res, &data)
	if err != nil {
		return data, err
	}

	return data, nil
}