Convenience method: renew Vault token
498404
def renew_token(self):
        """"""
        url = _url_joiner(self._vault_url, 'v1/auth/token/renew-self')
        resp = requests.get(url, headers=self._headers)
        resp.raise_for_status()
        data = resp.json()
        if data.get('errors'):
            raise VaultException(u'Error renewing Vault token: {}'.format(data['errors']))
        return data
547231
@Override
    public void renew(Map<String, String> credentials, Map topologyConf) {
        renew(credentials, topologyConf, null);
    }
187015
def _requires_refresh_token(self):
        
        expires_on = datetime.datetime.strptime(
            self.login_data['token']['expiresOn'], '%Y-%m-%dT%H:%M:%SZ')
        refresh = datetime.datetime.utcnow() + datetime.timedelta(seconds=30)
        return expires_on < refresh
451809
def update(vault_id, name)
      options = default_options_to_merge_with.merge({ query: { name: name } })
      self.class.put("/#{@api_ver}/vaults/#{vault_id}", options)
    end
1248356
def _refresh_token(self):
        

        # use basic auth with API key and secret
        client_auth = requests.auth.HTTPBasicAuth(self.api_key, self.api_secret)

        # make request
        post_data = {"grant_type": "client_credentials"}
        response = requests.post(self.auth, auth=client_auth, data=post_data, proxies=self.proxies)
        self.last_response = response

        # raise exception if status code indicates an error
        if 400 <= response.status_code < 600:
            message = "{} {} Error (Trace-Id: {}): {}".format(response.status_code,
                                                              "Client" if response.status_code < 500 else "Server",
                                                              self._get_trace_id(response),
                                                              "unable to get token")
            raise HTTPError(message, response=response)

        # set token property to the received token
        self.token = response.json()["access_token"]
295424
@Subscribe
    public synchronized void renew(final MasterSlaveRuleChangedEvent masterSlaveRuleChangedEvent) {
        if (getName().equals(masterSlaveRuleChangedEvent.getShardingSchemaName())) {
            masterSlaveRule = new OrchestrationMasterSlaveRule(masterSlaveRuleChangedEvent.getMasterSlaveRuleConfiguration());
        }
    }
1133229
def renew(id, increment = 0)
      json = client.put("/v1/sys/renew/#{id}", JSON.fast_generate(
        increment: increment,
      ))
      return Secret.decode(json)
    end
603653
public function renew()
    {
        $hash = $this->getNewHash($this->Member());
        $this->Hash = $hash;
        $this->extend('onAfterRenewToken');
        $this->write();
        return $this;
    }
1244156
def refresh_async(custom_headers:nil)
      # Send request
      promise = begin_refresh_async(custom_headers:custom_headers)

      promise = promise.then do |response|
        # Defining deserialization method.
        deserialize_method = lambda do |parsed_response|
          result_mapper = Azure::RecoveryServicesSiteRecovery::Mgmt::V2018_01_10::Models::VaultHealthDetails.mapper()
          parsed_response = @client.deserialize(result_mapper, parsed_response)
        end

        # Waiting for response.
        @client.get_long_running_operation_result(response, deserialize_method)
      end

      promise
    end
470721
def _renew_token(self, retry=True):
        """"""
        self.renewing = True
        self.log.info('Renewing ThreatConnect Token')
        self.log.info('Current Token Expiration: {}'.format(self._token_expiration))
        try:
            params = {'expiredToken': self._token}
            url = '{}/appAuth'.format(self._token_url)
            r = get(url, params=params, verify=self._session.verify)
            if not r.ok or 'application/json' not in r.headers.get('content-type', ''):
                if (
                    r.status_code == 401
                    and 'application/json' in r.headers.get('content-type', '')
                    and 'Retry token is invalid' in r.json().get('message')
                ):
                    # TODO: remove this once token renewal issue is fixed
                    self.log.error('params: {}'.format(params))
                    self.log.error('url: {}'.format(r.url))

                    # log failure
                    err_reason = r.text or r.reason
                    err_msg = 'Token Retry Error. API status code: {}, API message: {}.'
                    raise RuntimeError(1042, err_msg.format(r.status_code, err_reason))
                elif retry:
                    warn_msg = 'Token Retry Error. API status code: {}, API message: {}.'
                    self.log.warning(warn_msg.format(r.status_code, r.text))
                    # delay and retry token renewal
                    time.sleep(15)
                    self._renew_token(False)
                else:
                    err_reason = r.text or r.reason
                    err_msg = 'Token Retry Error. API status code: {}, API message: {}.'
                    raise RuntimeError(1042, err_msg.format(r.status_code, err_reason))
            data = r.json()
            if retry and (data.get('apiToken') is None or data.get('apiTokenExpires') is None):
                # add retry logic to handle case if the token renewal doesn't return valid data
                warn_msg = 'Token Retry Error: no values for apiToken or apiTokenExpires ({}).'
                self.log.warning(warn_msg.format(r.text))
                self._renew_token(False)
            else:
                self._token = data.get('apiToken')
                self._token_expiration = int(data.get('apiTokenExpires'))
                self.log.info('New Token Expiration: {}'.format(self._token_expiration))
            self.renewing = False
        except exceptions.SSLError:
            self.log.error(u'SSL Error during token renewal.')
            self.renewing = False
413595
def use_plenary_vault_view(self):
        """"""
        self._vault_view = PLENARY
        # self._get_provider_session('authorization_vault_session') # To make sure the session is tracked
        for session in self._get_provider_sessions():
            try:
                session.use_plenary_vault_view()
            except AttributeError:
                pass
1102411
def fromenv() -> 'VaultAuth12Factor':
        
        i = None  # type: VaultAuth12Factor
        if os.getenv("VAULT_TOKEN", None):
            i = VaultAuth12Factor.token(os.getenv("VAULT_TOKEN"))
        elif os.getenv("VAULT_APPID", None) and os.getenv("VAULT_USERID", None):
            i = VaultAuth12Factor.app_id(os.getenv("VAULT_APPID"), os.getenv("VAULT_USERID"))
        elif os.getenv("VAULT_ROLEID", None) and os.getenv("VAULT_SECRETID", None):
            i = VaultAuth12Factor.approle(os.getenv("VAULT_ROLEID"), os.getenv("VAULT_SECRETID"))
        elif os.getenv("VAULT_SSLCERT", None) and os.getenv("VAULT_SSLKEY", None):
            i = VaultAuth12Factor.ssl_client_cert(os.getenv("VAULT_SSLCERT"), os.getenv("VAULT_SSLKEY"))

        if i:
            e = os.getenv("VAULT_UNWRAP", "False")
            if e.lower() in ["true", "1", "yes"]:
                i.unwrap_response = True
            return i

        raise VaultCredentialProviderException("Unable to configure Vault authentication from the environment")
1221914
def vaults(options = {})
      batches = Enumerator.new do |y|
        options = options.merge(account_id: @id)
        resp = @client.list_vaults(options)
        resp.each_page do |page|
          batch = []
          page.data.vault_list.each do |v|
            batch << Vault.new(
              account_id: @id,
              name: v.vault_name,
              data: v,
              client: @client
            )
          end
          y.yield(batch)
        end
      end
      Vault::Collection.new(batches)
    end
52859
def pool
      @lock.synchronize do
        return @nhp if @nhp

        @nhp = PersistentHTTP.new("vault-ruby", nil, pool_size)

        if proxy_address
          proxy_uri = URI.parse "http://#{proxy_address}"

          proxy_uri.port = proxy_port if proxy_port

          if proxy_username
            proxy_uri.user = proxy_username
            proxy_uri.password = proxy_password
          end

          @nhp.proxy = proxy_uri
        end

        # Use a custom open timeout
        if open_timeout || timeout
          @nhp.open_timeout = (open_timeout || timeout).to_i
        end

        # Use a custom read timeout
        if read_timeout || timeout
          @nhp.read_timeout = (read_timeout || timeout).to_i
        end

        @nhp.verify_mode = OpenSSL::SSL::VERIFY_PEER

        # Vault requires TLS1.2
        @nhp.ssl_version = "TLSv1_2"

        # Only use secure ciphers
        @nhp.ciphers = ssl_ciphers

        # Custom pem files, no problem!
        pem = ssl_pem_contents || (ssl_pem_file ? File.read(ssl_pem_file) : nil)
        if pem
          @nhp.cert = OpenSSL::X509::Certificate.new(pem)
          @nhp.key = OpenSSL::PKey::RSA.new(pem, ssl_pem_passphrase)
        end

        # Use custom CA cert for verification
        if ssl_ca_cert
          @nhp.ca_file = ssl_ca_cert
        end

        # Use custom CA path that contains CA certs
        if ssl_ca_path
          @nhp.ca_path = ssl_ca_path
        end

        if ssl_cert_store
          @nhp.cert_store = ssl_cert_store
        end

        # Naughty, naughty, naughty! Don't blame me when someone hops in
        # and executes a MITM attack!
        if !ssl_verify
          @nhp.verify_mode = OpenSSL::SSL::VERIFY_NONE
        end

        # Use custom timeout for connecting and verifying via SSL
        if ssl_timeout || timeout
          @nhp.ssl_timeout = (ssl_timeout || timeout).to_i
        end

        @nhp
      end
    end
902202
public void renew() {
    if (state != RESET) {
      throw new NotResetException();
    }
    state = DONE;
    checkRc(LIB.mdb_txn_renew(ptr));
    state = READY;
  }
462042
def renew(key, write = true, options = {})
      new_version = (Time.current.to_f * 10000).to_i
      seconds = options[:ttl] ? options[:ttl] + (rand(options[:ttl] / 2) * [1, -1].sample) : nil
      written = @store.write(key, new_version, {:expires_in => seconds})
      @on_write_failure.call(key) if !written && write && @on_write_failure
      RecordCache::Base.logger.debug{ "Version Store: renew #{key}: nil => #{new_version}" }
      new_version
    end
245746
def renew_secret(client, creds, opt):
    """"""
    if opt.reuse_token:
        return

    seconds = grok_seconds(opt.lease)
    if not seconds:
        raise aomi.exceptions.AomiCommand("invalid lease %s" % opt.lease)

    renew = None
    if client.version:
        v_bits = client.version.split('.')
        if int(v_bits[0]) == 0 and \
           int(v_bits[1]) <= 8 and \
           int(v_bits[2]) <= 0:
            r_obj = {
                'increment': seconds
            }
            r_path = "v1/sys/renew/{0}".format(creds['lease_id'])
            # Pending discussion on https://github.com/ianunruh/hvac/issues/148
            # pylint: disable=protected-access
            renew = client._post(r_path, json=r_obj).json()

    if not renew:
        renew = client.renew_secret(creds['lease_id'], seconds)

    # sometimes it takes a bit for vault to respond
    # if we are within 5s then we are fine
    if not renew or (seconds - renew['lease_duration'] >= 5):
        client.revoke_self_token()
        e_msg = 'Unable to renew with desired lease'
        raise aomi.exceptions.VaultConstraint(e_msg)