// renew attempts to renew our Vault token. If the renewal fails, an error is
// returned.  The boolean indicates whether it's safe to attempt to renew again.
// This method updates the currentExpiration time
554427
func (v *vaultClient) renew() (bool, error) {
	// Track how long the request takes
	defer metrics.MeasureSince([]string{"nomad", "vault", "renew"}, time.Now())

	// Attempt to renew the token
	secret, err := v.auth.RenewSelf(v.tokenData.CreationTTL)
	if err != nil {
		// Check if there is a permission denied
		recoverable := !structs.VaultUnrecoverableError.MatchString(err.Error())
		return recoverable, fmt.Errorf("failed to renew the vault token: %v", err)
	}

	if secret == nil {
		// It's possible for RenewSelf to return (nil, nil) if the
		// response body from Vault is empty.
		return true, fmt.Errorf("renewal failed: empty response from vault")
	}

	// these treated as transient errors, where can keep renewing
	auth := secret.Auth
	if auth == nil {
		return true, fmt.Errorf("renewal successful but not auth information returned")
	} else if auth.LeaseDuration == 0 {
		return true, fmt.Errorf("renewal successful but no lease duration returned")
	}

	v.extendExpiration(auth.LeaseDuration)

	v.logger.Debug("successfully renewed server token")
	return true, nil
}
438573
func (c *Client) RenewSession(ctx context.Context, session *platform.Session, newExpiration time.Time) error {
	op := getOp(platform.OpRenewSession)
	if session == nil {
		return &platform.Error{
			Op:  op,
			Msg: "session is nil",
		}
	}
	return c.db.Update(func(tx *bolt.Tx) error {
		session.ExpiresAt = newExpiration
		if err := c.putSession(ctx, tx, session); err != nil {
			return &platform.Error{
				Op:  op,
				Err: err,
			}
		}
		return nil
	})
}
744736
func (h *vaultHook) run(token string) {
	// Helper for stopping token renewal
	stopRenewal := func() {
		if err := h.client.StopRenewToken(h.future.Get()); err != nil {
			h.logger.Warn("failed to stop token renewal", "error", err)
		}
	}

	// updatedToken lets us store state between loops. If true, a new token
	// has been retrieved and we need to apply the Vault change mode
	var updatedToken bool

OUTER:
	for {
		// Check if we should exit
		if h.ctx.Err() != nil {
			stopRenewal()
			return
		}

		// Clear the token
		h.future.Clear()

		// Check if there already is a token which can be the case for
		// restoring the TaskRunner
		if token == "" {
			// Get a token
			var exit bool
			token, exit = h.deriveVaultToken()
			if exit {
				// Exit the manager
				return
			}

			// Write the token to disk
			if err := h.writeToken(token); err != nil {
				errorString := "failed to write Vault token to disk"
				h.logger.Error(errorString, "error", err)
				h.lifecycle.Kill(h.ctx,
					structs.NewTaskEvent(structs.TaskKilling).
						SetFailsTask().
						SetDisplayMessage(fmt.Sprintf("Vault %v", errorString)))
				return
			}
		}

		// Start the renewal process
		renewCh, err := h.client.RenewToken(token, 30)

		// An error returned means the token is not being renewed
		if err != nil {
			h.logger.Error("failed to start renewal of Vault token", "error", err)
			token = ""
			goto OUTER
		}

		// The Vault token is valid now, so set it
		h.future.Set(token)

		if updatedToken {
			switch h.vaultStanza.ChangeMode {
			case structs.VaultChangeModeSignal:
				s, err := signals.Parse(h.vaultStanza.ChangeSignal)
				if err != nil {
					h.logger.Error("failed to parse signal", "error", err)
					h.lifecycle.Kill(h.ctx,
						structs.NewTaskEvent(structs.TaskKilling).
							SetFailsTask().
							SetDisplayMessage(fmt.Sprintf("Vault: failed to parse signal: %v", err)))
					return
				}

				event := structs.NewTaskEvent(structs.TaskSignaling).SetTaskSignal(s).SetDisplayMessage("Vault: new Vault token acquired")
				if err := h.lifecycle.Signal(event, h.vaultStanza.ChangeSignal); err != nil {
					h.logger.Error("failed to send signal", "error", err)
					h.lifecycle.Kill(h.ctx,
						structs.NewTaskEvent(structs.TaskKilling).
							SetFailsTask().
							SetDisplayMessage(fmt.Sprintf("Vault: failed to send signal: %v", err)))
					return
				}
			case structs.VaultChangeModeRestart:
				const noFailure = false
				h.lifecycle.Restart(h.ctx,
					structs.NewTaskEvent(structs.TaskRestartSignal).
						SetDisplayMessage("Vault: new Vault token acquired"), false)
			case structs.VaultChangeModeNoop:
				fallthrough
			default:
				h.logger.Error("invalid Vault change mode", "mode", h.vaultStanza.ChangeMode)
			}

			// We have handled it
			updatedToken = false

			// Call the handler
			h.updater.updatedVaultToken(token)
		}

		// Start watching for renewal errors
		select {
		case err := <-renewCh:
			// Clear the token
			token = ""
			h.logger.Error("failed to renew Vault token", "error", err)
			stopRenewal()

			// Check if we have to do anything
			if h.vaultStanza.ChangeMode != structs.VaultChangeModeNoop {
				updatedToken = true
			}
		case <-h.ctx.Done():
			stopRenewal()
			return
		}
	}
}
1135839
func (counter Counter) Expired() bool {
	if counter.Expiration == 0 {
		return false
	}
	return time.Now().UnixNano() > counter.Expiration
}
21881
func (s *RegistrarService) RenewWhoisPrivacy(accountID string, domainName string) (*whoisPrivacyRenewalResponse, error) {
	path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/whois_privacy/renewals", accountID, domainName))
	privacyRenewalResponse := &whoisPrivacyRenewalResponse{}

	resp, err := s.client.post(path, nil, privacyRenewalResponse)
	if err != nil {
		return nil, err
	}

	privacyRenewalResponse.HttpResponse = resp
	return privacyRenewalResponse, nil
}
427471
func (c *vaultClient) stopRenew(id string) error {
	c.lock.Lock()
	defer c.lock.Unlock()

	if !c.isTracked(id) {
		return nil
	}

	if err := c.heap.Remove(id); err != nil {
		return fmt.Errorf("failed to remove heap entry: %v", err)
	}

	// Signal an update to the renewal loop.
	if c.running {
		select {
		case c.updateCh <- struct{}{}:
		default:
		}
	}

	return nil
}
155800
func (r *Renewer) Renew() {
	var result error
	if r.secret.Auth != nil {
		result = r.renewAuth()
	} else {
		result = r.renewLease()
	}

	r.doneCh <- result
}
990504
func (e *cacheEntryExpiry) Reset() {
	e.Expires = time.Now().Add(e.TTL)
}
841889
func (u *UserV2) Expiry() time.Time {
	if u.Metadata.Expires != nil && !u.Metadata.Expires.IsZero() {
		return *u.Metadata.Expires
	}
	return u.Spec.Expires
}
987009
func (le *LeaderElector) renew(ctx context.Context) {
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()
	wait.Until(func() {
		timeoutCtx, timeoutCancel := context.WithTimeout(ctx, le.config.RenewDeadline)
		defer timeoutCancel()
		err := wait.PollImmediateUntil(le.config.RetryPeriod, func() (bool, error) {
			done := make(chan bool, 1)
			go func() {
				defer close(done)
				done <- le.tryAcquireOrRenew()
			}()

			select {
			case <-timeoutCtx.Done():
				return false, fmt.Errorf("failed to tryAcquireOrRenew %s", timeoutCtx.Err())
			case result := <-done:
				return result, nil
			}
		}, timeoutCtx.Done())

		le.maybeReportTransition()
		desc := le.config.Lock.Describe()
		if err == nil {
			klog.V(5).Infof("successfully renewed lease %v", desc)
			return
		}
		le.config.Lock.RecordEvent("stopped leading")
		le.metrics.leaderOff(le.config.Name)
		klog.Infof("failed to renew lease %v: %v", desc, err)
		cancel()
	}, le.config.RetryPeriod, ctx.Done())

	// if we hold the lease, give it up
	if le.config.ReleaseOnCancel {
		le.release()
	}
}
1296980
func (e *Expiry) IsExpired() bool {
	if e.CurrentTime == nil {
		e.CurrentTime = time.Now
	}
	return e.expiration.Before(e.CurrentTime())
}
33506
func RenewManagedCertificates(allowPrompts bool) (err error) {
	var renewQueue, deleteQueue []Certificate
	visitedNames := make(map[string]struct{})

	certCacheMu.RLock()
	for name, cert := range certCache {
		if !cert.Config.Managed || cert.Config.SelfSigned {
			continue
		}

		// the list of names on this cert should never be empty...
		if cert.Names == nil || len(cert.Names) == 0 {
			log.Printf("[WARNING] Certificate keyed by '%s' has no names: %v - removing from cache", name, cert.Names)
			deleteQueue = append(deleteQueue, cert)
			continue
		}

		// skip names whose certificate we've already renewed
		if _, ok := visitedNames[name]; ok {
			continue
		}
		for _, name := range cert.Names {
			visitedNames[name] = struct{}{}
		}

		// if its time is up or ending soon, we need to try to renew it
		timeLeft := cert.NotAfter.Sub(time.Now().UTC())
		if timeLeft < RenewDurationBefore {
			log.Printf("[INFO] Certificate for %v expires in %v; attempting renewal", cert.Names, timeLeft)

			if cert.Config == nil {
				log.Printf("[ERROR] %s: No associated TLS config; unable to renew", name)
				continue
			}

			// queue for renewal when we aren't in a read lock anymore
			// (the TLS-SNI challenge will need a write lock in order to
			// present the certificate, so we renew outside of read lock)
			renewQueue = append(renewQueue, cert)
		}
	}
	certCacheMu.RUnlock()

	// Perform renewals that are queued
	for _, cert := range renewQueue {
		// Get the name which we should use to renew this certificate;
		// we only support managing certificates with one name per cert,
		// so this should be easy. We can't rely on cert.Config.Hostname
		// because it may be a wildcard value from the Caddyfile (e.g.
		// *.something.com) which, as of Jan. 2017, is not supported by ACME.
		var renewName string
		for _, name := range cert.Names {
			if name != "" {
				renewName = name
				break
			}
		}

		// perform renewal
		err := cert.Config.RenewCert(renewName, allowPrompts)
		if err != nil {
			if allowPrompts {
				// Certificate renewal failed and the operator is present; we should stop
				// immediately and return the error. See a discussion in issue 642
				// about this. For a while, we only stopped if the certificate was
				// expired, but in reality, there is no difference between reporting
				// it now versus later, except that there's somebody present to deal
				// with it now, so require it.
				return err
			}
			log.Printf("[ERROR] %v", err)
			if cert.Config.OnDemand {
				deleteQueue = append(deleteQueue, cert)
			}
		} else {
			// successful renewal, so update in-memory cache by loading
			// renewed certificate so it will be used with handshakes
			// TODO: Not until CA has valid OCSP response ready for the new cert... sigh.
			if cert.Names[len(cert.Names)-1] == "" {
				// Special case: This is the default certificate. We must
				// flush it out of the cache so that we no longer point to
				// the old, un-renewed certificate. Otherwise it will be
				// renewed on every scan, which is too often. The next cert
				// to be cached (probably this one) will become the default.
				certCacheMu.Lock()
				delete(certCache, "")
				certCacheMu.Unlock()
			}
			_, err := CacheManagedCertificate(cert.Names[0], cert.Config)
			if err != nil {
				if allowPrompts {
					return err // operator is present, so report error immediately
				}
				log.Printf("[ERROR] %v", err)
			}
		}
	}

	// Apply queued deletion changes to the cache
	for _, cert := range deleteQueue {
		certCacheMu.Lock()
		for _, name := range cert.Names {
			delete(certCache, name)
		}
		certCacheMu.Unlock()
	}

	return nil
}
910607
func (a *OAuthStrategy) Refresh() error {
	refreshToken := a.RefreshToken()

	if refreshToken == "" {
		return a.requestToken()
	}

	var accessToken string
	var err error

	if a.ClientCredentialRefresh {
		accessToken, err = a.OAuthClient.ClientCredentialGrant(a.ClientId, a.ClientSecret)
	} else {
		accessToken, refreshToken, err = a.OAuthClient.RefreshTokenGrant(a.ClientId, a.ClientSecret, refreshToken)
	}

	if err != nil {
		if strings.Contains(err.Error(), "invalid_token") {
			return errors.New("You are not currently authenticated. Please log in to continue.")
		}
		return err
	}

	a.SetTokens(accessToken, refreshToken)

	return nil
}
317278
func (v *vaultClient) revokeDaemon() {
	ticker := time.NewTicker(vaultRevocationIntv)
	defer ticker.Stop()

	for {
		select {
		case <-v.tomb.Dying():
			return
		case now := <-ticker.C:
			if established, _ := v.ConnectionEstablished(); !established {
				continue
			}

			v.revLock.Lock()

			// Fast path
			if len(v.revoking) == 0 {
				v.revLock.Unlock()
				continue
			}

			// Build the list of allocations that need to revoked while pruning any TTL'd checks
			revoking := make([]*structs.VaultAccessor, 0, len(v.revoking))
			for va, ttl := range v.revoking {
				if now.After(ttl) {
					delete(v.revoking, va)
				} else {
					revoking = append(revoking, va)
				}
			}

			if err := v.parallelRevoke(context.Background(), revoking); err != nil {
				v.logger.Warn("background token revocation errored", "error", err)
				v.revLock.Unlock()
				continue
			}

			// Unlock before a potentially expensive operation
			v.revLock.Unlock()

			// Call the passed in token revocation function
			if err := v.purgeFn(revoking); err != nil {
				// Can continue since revocation is idempotent
				v.logger.Error("token revocation errored", "error", err)
				continue
			}

			// Track that tokens were revoked successfully
			metrics.IncrCounter([]string{"nomad", "vault", "distributed_tokens_revoked"}, float32(len(revoking)))

			// Can delete from the tracked list now that we have purged
			v.revLock.Lock()
			for _, va := range revoking {
				delete(v.revoking, va)
			}
			v.revLock.Unlock()

		}
	}
}
606763
func (v *vaultService) renewToken() {
	retryDelay := v.leaseDuration / 2
	go func() {
		for {
			if v.secret == nil {
				if err := v.authenticate(); err != nil {
					time.Sleep(retryDelay)
					continue
				}
			}
			s, err := v.client.Auth().Token().RenewSelf(int(v.leaseDuration))
			if err != nil || s == nil {
				v.secret = nil
				time.Sleep(retryDelay)
				continue
			}
			if ok, err := s.TokenIsRenewable(); !ok || err != nil {
				v.secret = nil
				continue
			}
			ttl, err := s.TokenTTL()
			if err != nil {
				v.secret = nil
				continue
			}
			v.secret = s
			retryDelay = ttl / 2
			time.Sleep(retryDelay)
		}
	}()
}
1161468
func (s *Session) Renew() error {
	if s.m == nil {
		return ErrNotPassMiddleware
	}
	return s.m.Renew(s)
}
848225
func (kv *consulKV) renewSession(
	pair *api.KVPair,
	ttl uint64,
	noCreate bool,
) (string, error) {
	// Check if there is any previous session with an active TTL
	session, err := kv.getActiveSession(pair.Key)
	if err != nil {
		logrus.Infof("Failed to find session: %v", err)
		return "", err
	}

	if session != "" {
		if noCreate {
			// Do not create new session for the key
			return "", kvdb.ErrModified
		}
		// Destroy the existing session associated with the key
		kv.client.Destroy(session, nil)
	}

	durationTTL := time.Duration(int64(ttl)) * time.Second

	entry := &api.SessionEntry{
		Behavior:  api.SessionBehaviorDelete, // Delete the key when the session expires
		TTL:       durationTTL.String(),
		LockDelay: 0, // Virtually disable lock delay
	}

	// Create the key session
	session, _, err = kv.client.Create(entry, nil)

	// Session timer is started after a call to "Renew"
	kv.client.Renew(session, nil)

	return session, err
}