// mintTokenWithRetries calls provider's MintToken() retrying on transient
// errors a bunch of times. Called only for non-interactive providers.
974893
func (t *tokenWithProvider) mintTokenWithRetries(ctx context.Context, base *internal.Token) (tok *internal.Token, err error) {
	err = retry.Retry(ctx, transient.Only(retryParams), func() error {
		tok, err = t.provider.MintToken(ctx, base)
		return err
	}, nil)
	return
}
159171
func (p *Provider) RefreshToken(refreshToken string) (*oauth2.Token, error) {
	t := &oauth2.Token{RefreshToken: refreshToken}
	ts := p.oauthConfig.TokenSource(goth.ContextForClient(p.Client()), t)

	return ts.Token()
}
1001127
func WithBeforeRetry(beforeRetry retry.BeforeRetryHandler) RequestOption {
	return func(ctx context.Client, o *requestOptions) error {
		o.BeforeRetry = beforeRetry
		return nil
	}
}
683781
func WithRetentionEnforcer(finder BucketFinder) Option {
	return func(e *Engine) {
		e.retentionEnforcer = newRetentionEnforcer(e, finder)
	}
}
766077
func (bt *BaseTask) WithRetriers(retries ...*TaskRetry) *BaseTask {
	if bt.Retriers == nil {
		bt.Retriers = make([]*TaskRetry, 0)
	}
	bt.Retriers = append(bt.Retriers, retries...)
	return bt
}
255714
func (c *client) withRetry(ctx context.Context, f func() error) error {
	var lastError error
	for {
		select {
		case <-ctx.Done():
			return fmt.Errorf("%v: %v", ctx.Err(), lastError)
		default:
		}
		if err := f(); err != nil {
			if st, ok := status.FromError(err); ok {
				code := st.Code()
				if code == codes.Unavailable {
					lastError = err
					time.Sleep(100 * time.Millisecond)
					continue
				}
			}
			return err
		}
		return nil
	}
}
1110784
func WithReturnNew(parent context.Context, result interface{}) context.Context {
	return context.WithValue(contextOrBackground(parent), keyReturnNew, result)
}
659254
func (builder *StoreBucketTypePropsCommandBuilder) WithR(r uint32) *StoreBucketTypePropsCommandBuilder {
	builder.props.R = &r
	return builder
}
289564
func NewTokenProvider(opts ...TokenProviderOption) (*TokenProvider, error) {
	provider := new(TokenProvider)
	for _, opt := range opts {
		err := opt(provider)
		if err != nil {
			return nil, err
		}
	}
	return provider, nil
}
517721
func (s *Sender) ExecWithRetry(name string, fn func() (*http.Response, error)) (resp *http.Response, err error) {
	// Loop
	// We start at retryMax + 1 so that it runs at least once even if retryMax == 0
	tries := 0
	for retriesLeft := s.retryMax + 1; retriesLeft > 0; retriesLeft-- {
		// Get request name
		nr := fmt.Sprintf("%s (%d/%d)", name, s.retryMax-retriesLeft+2, s.retryMax+1)
		tries++

		// Send request
		var retry bool
		astilog.Debugf("astihttp: sending %s", nr)
		if resp, err = fn(); err != nil {
			// If error is temporary, retry
			if netError, ok := err.(net.Error); ok && netError.Temporary() {
				astilog.Debugf("astihttp: temporary error when sending %s", nr)
				retry = true
			} else {
				err = errors.Wrapf(err, "astihttp: sending %s failed", nr)
				return
			}
		}

		// Retry
		if retry || s.retryFunc(nr, resp) {
			if retriesLeft > 1 {
				astilog.Debugf("astihttp: sleeping %s and retrying... (%d retries left)", s.retrySleep, retriesLeft-1)
				time.Sleep(s.retrySleep)
			}
			continue
		}

		// Return if conditions for retrying were not met
		return
	}

	// Max retries limit reached
	err = fmt.Errorf("astihttp: sending %s failed after %d tries", name, tries)
	return
}
1283091
func (r *MintDelegationTokenRPC) MintDelegationToken(c context.Context, req *minter.MintDelegationTokenRequest) (*minter.MintDelegationTokenResponse, error) {
	state := auth.GetState(c)

	// Dump the whole request and relevant auth state to the debug log.
	if logging.IsLogging(c, logging.Debug) {
		m := jsonpb.Marshaler{Indent: "  "}
		dump, _ := m.MarshalToString(req)
		logging.Debugf(c, "PeerIdentity: %s", state.PeerIdentity())
		logging.Debugf(c, "MintDelegationTokenRequest:\n%s", dump)
	}

	// Validate the request authentication context: not an anonymous call, no
	// delegation is used.
	callerID := state.User().Identity
	if callerID != state.PeerIdentity() {
		logging.Errorf(c, "Trying to use delegation, it's forbidden")
		return nil, status.Errorf(codes.PermissionDenied, "delegation is forbidden for this API call")
	}
	if callerID == identity.AnonymousIdentity {
		logging.Errorf(c, "Unauthenticated request")
		return nil, status.Errorf(codes.Unauthenticated, "authentication required")
	}

	// Grab a string that identifies token server version. This almost always
	// just hits local memory cache.
	serviceVer, err := utils.ServiceVersion(c, r.Signer)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "can't grab service version - %s", err)
	}

	rules, err := r.Rules(c)
	if err != nil {
		// Don't put error details in the message, it may be returned to
		// unauthorized callers.
		logging.WithError(err).Errorf(c, "Failed to load delegation rules")
		return nil, status.Errorf(codes.Internal, "failed to load delegation rules")
	}

	// Make sure the caller is mentioned in the config before doing anything else.
	// This rejects unauthorized callers early. Passing this check doesn't mean
	// that there's a matching rule though, so the request still can be rejected
	// later.
	switch ok, err := rules.IsAuthorizedRequestor(c, callerID); {
	case err != nil:
		logging.WithError(err).Errorf(c, "IsAuthorizedRequestor failed")
		return nil, status.Errorf(codes.Internal, "failed to check authorization")
	case !ok:
		logging.Errorf(c, "Didn't pass initial authorization")
		return nil, status.Errorf(codes.PermissionDenied, "not authorized")
	}

	// Validate requested token lifetime. It's not part of the rules query.
	if req.ValidityDuration == 0 {
		req.ValidityDuration = 3600
	}
	if req.ValidityDuration < 0 {
		err = fmt.Errorf("invalid 'validity_duration' (%d)", req.ValidityDuration)
		logging.WithError(err).Errorf(c, "Bad request")
		return nil, status.Errorf(codes.InvalidArgument, "bad request - %s", err)
	}

	// Same for tags, they are transferred intact to the final token.
	if err := utils.ValidateTags(req.Tags); err != nil {
		err = fmt.Errorf("invalid 'tags': %s", err)
		logging.WithError(err).Errorf(c, "Bad request")
		return nil, status.Errorf(codes.InvalidArgument, "bad request - %s", err)
	}

	// Validate and normalize the request. This may do relatively expensive calls
	// to resolve "https://<service-url>" entries to "service:<id>" entries.
	query, err := buildRulesQuery(c, req, callerID)
	if err != nil {
		if transient.Tag.In(err) {
			logging.WithError(err).Errorf(c, "buildRulesQuery failed")
			return nil, status.Errorf(codes.Internal, "failure when resolving target service ID - %s", err)
		}
		logging.WithError(err).Errorf(c, "Bad request")
		return nil, status.Errorf(codes.InvalidArgument, "bad request - %s", err)
	}

	// Consult the config to find the rule that allows this operation (if any).
	rule, err := rules.FindMatchingRule(c, query)
	if err != nil {
		if transient.Tag.In(err) {
			logging.WithError(err).Errorf(c, "FindMatchingRule failed")
			return nil, status.Errorf(codes.Internal, "failure when checking rules - %s", err)
		}
		logging.WithError(err).Errorf(c, "Didn't pass rules check")
		return nil, status.Errorf(codes.PermissionDenied, "forbidden - %s", err)
	}
	logging.Infof(c, "Found the matching rule %q in the config rev %s", rule.Name, rules.ConfigRevision())

	// Make sure the requested token lifetime is allowed by the rule.
	if req.ValidityDuration > rule.MaxValidityDuration {
		err = fmt.Errorf(
			"the requested validity duration (%d sec) exceeds the maximum allowed one (%d sec)",
			req.ValidityDuration, rule.MaxValidityDuration)
		logging.WithError(err).Errorf(c, "Validity duration check didn't pass")
		return nil, status.Errorf(codes.PermissionDenied, "forbidden - %s", err)
	}

	var resp *minter.MintDelegationTokenResponse
	p := mintParams{
		request:    req,
		query:      query,
		rule:       rule,
		serviceVer: serviceVer,
	}
	if r.mintMock != nil {
		resp, err = r.mintMock(c, &p)
	} else {
		resp, err = r.mint(c, &p)
	}
	if err != nil {
		return nil, err
	}

	if r.LogToken != nil {
		// Errors during logging are considered not fatal. bqlog library has
		// a monitoring counter that tracks number of errors, so they are not
		// totally invisible.
		tokInfo := MintedTokenInfo{
			Request:   req,
			Response:  resp,
			ConfigRev: rules.ConfigRevision(),
			Rule:      rule,
			PeerIP:    state.PeerIP(),
			RequestID: info.RequestID(c),
			AuthDBRev: authdb.Revision(state.DB()),
		}
		if logErr := r.LogToken(c, &tokInfo); logErr != nil {
			logging.WithError(logErr).Errorf(c, "Failed to insert the delegation token into the BigQuery log")
		}
	}

	return resp, nil
}
1231778
func DoRetryWithRegistration(client autorest.Client) autorest.SendDecorator {
	return func(s autorest.Sender) autorest.Sender {
		return autorest.SenderFunc(func(r *http.Request) (resp *http.Response, err error) {
			rr := autorest.NewRetriableRequest(r)
			for currentAttempt := 0; currentAttempt < client.RetryAttempts; currentAttempt++ {
				err = rr.Prepare()
				if err != nil {
					return resp, err
				}

				resp, err = autorest.SendWithSender(s, rr.Request(),
					autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...),
				)
				if err != nil {
					return resp, err
				}

				if resp.StatusCode != http.StatusConflict || client.SkipResourceProviderRegistration {
					return resp, err
				}
				var re RequestError
				err = autorest.Respond(
					resp,
					autorest.ByUnmarshallingJSON(&re),
				)
				if err != nil {
					return resp, err
				}
				err = re

				if re.ServiceError != nil && re.ServiceError.Code == "MissingSubscriptionRegistration" {
					regErr := register(client, r, re)
					if regErr != nil {
						return resp, fmt.Errorf("failed auto registering Resource Provider: %s. Original error: %s", regErr, err)
					}
				}
			}
			return resp, err
		})
	}
}
668134
func WithProviders(providers ...common.Provider) *ProviderList {
	GetSecurityKey()
	list := &ProviderList{providers}
	SharedProviderList = list
	return list
}
810467
func (o *RevokeOAuth2TokenParams) WithToken(token string) *RevokeOAuth2TokenParams {
	o.SetToken(token)
	return o
}
1124402
func (r *MintOAuthTokenGrantRPC) MintOAuthTokenGrant(c context.Context, req *minter.MintOAuthTokenGrantRequest) (*minter.MintOAuthTokenGrantResponse, error) {
	state := auth.GetState(c)

	// Don't allow delegation tokens here to reduce total number of possible
	// scenarios. Proxies aren't expected to use delegation for these tokens.
	callerID := state.User().Identity
	if callerID != state.PeerIdentity() {
		logging.Errorf(c, "Trying to use delegation, it's forbidden")
		return nil, status.Errorf(codes.PermissionDenied, "delegation is forbidden for this API call")
	}

	// Check that the request is allowed by the rules, fill in defaults.
	rule, err := r.validateRequest(c, req, callerID)
	if err != nil {
		return nil, err // the error is already logged
	}
	if req.ValidityDuration == 0 {
		if rule.Rule.MaxGrantValidityDuration > 3600 {
			req.ValidityDuration = 3600
		} else {
			req.ValidityDuration = rule.Rule.MaxGrantValidityDuration
		}
	}

	// Grab a string that identifies token server version. This almost always
	// just hits local memory cache.
	serviceVer, err := utils.ServiceVersion(c, r.Signer)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "can't grab service version - %s", err)
	}

	// Generate and sign the token.
	var resp *minter.MintOAuthTokenGrantResponse
	var body *tokenserver.OAuthTokenGrantBody
	p := mintParams{
		serviceAccount:   req.ServiceAccount,
		proxyID:          callerID,
		endUserID:        identity.Identity(req.EndUser), // already validated
		validityDuration: req.ValidityDuration,
		serviceVer:       serviceVer,
	}
	if r.mintMock != nil {
		resp, body, err = r.mintMock(c, &p)
	} else {
		resp, body, err = r.mint(c, &p)
	}
	if err != nil {
		return nil, err
	}

	// Log it to BigQuery.
	if r.LogGrant != nil {
		// Errors during logging are considered not fatal. bqlog library has
		// a monitoring counter that tracks number of errors, so they are not
		// totally invisible.
		info := MintedGrantInfo{
			Request:   req,
			Response:  resp,
			GrantBody: body,
			ConfigRev: rule.Revision,
			Rule:      rule.Rule,
			PeerIP:    state.PeerIP(),
			RequestID: info.RequestID(c),
			AuthDBRev: authdb.Revision(state.DB()),
		}
		if logErr := r.LogGrant(c, &info); logErr != nil {
			logging.WithError(logErr).Errorf(c, "Failed to insert the grant token into the BigQuery log")
		}
	}

	return resp, nil
}
204447
func TokenProviderWithKey(keyName, key string) TokenProviderOption {
	return func(provider *TokenProvider) error {
		provider.signer = NewSigner(keyName, key)
		return nil
	}
}
734622
func WithRetryOpts(value retry.Opts) copts.Opt {
	return func(p copts.Params) {
		if setter, ok := p.(retryOptsSetter); ok {
			setter.SetRetryOpts(value)
		}
	}
}