Pass through to provider VaultLookupSession.get_vaults
516428
def get_vaults(self):
        """"""
        # Implemented from kitosid template for -
        # osid.resource.BinLookupSession.get_bins_template
        catalogs = self._get_provider_session('vault_lookup_session').get_vaults()
        cat_list = []
        for cat in catalogs:
            cat_list.append(Vault(self._provider_manager, cat, self._runtime, self._proxy))
        return VaultList(cat_list)
410888
def _get_secret_from_vault(
        key, environment=None, stage=None, namespace=None,
        wait_exponential_multiplier=50, wait_exponential_max=5000,
        stop_max_delay=10000):
    """"""
    # Get the encrypted secret from DynamoDB
    table_name = _secrets_table_name(environment=environment, stage=stage)

    if namespace:
        key = "{}:{}".format(namespace, key)

    if table_name is None:
        logger.warning("Can't produce secrets table name: unable to retrieve "
                       "secret '{}'".format(key))
        return

    client = boto3.client('dynamodb')
    logger.info("Retriving key '{}' from table '{}'".format(
        key, table_name))

    @retry(retry_on_exception=_is_critical_exception,
           wait_exponential_multiplier=wait_exponential_multiplier,
           wait_exponential_max=wait_exponential_max,
           stop_max_delay=stop_max_delay)
    def get_item():
        try:
            return client.get_item(
                TableName=table_name,
                Key={'id': {'S': key}}).get('Item', {}).get(
                    'value', {}).get('B')
        except Exception as err:
            if _is_dynamodb_critical_exception(err):
                raise CriticalError(err)
            else:
                raise

    encrypted = get_item()

    if encrypted is None:
        return

    # Decrypt using KMS
    client = boto3.client('kms')
    try:
        value = client.decrypt(CiphertextBlob=encrypted)['Plaintext'].decode()
    except ClientError:
        logger.error("KMS error when trying to decrypt secret")
        traceback.print_exc()
        return

    try:
        value = json.loads(value)
    except (TypeError, ValueError):
        # It's ok, the client should know how to deal with the value
        pass

    return value
238610
public ServiceFuture<List<KeyItem>> listKeysAsync(final String vaultBaseUrl,
            final ListOperationCallback<KeyItem> serviceCallback) {
        return getKeysAsync(vaultBaseUrl, serviceCallback);
    }
1124348
def diff(vault_client, opt):
    """"""
    if opt.thaw_from:
        opt.secrets = tempfile.mkdtemp('aomi-thaw')
        auto_thaw(vault_client, opt)

    ctx = Context.load(get_secretfile(opt), opt) \
                 .fetch(vault_client)

    for backend in ctx.mounts():
        diff_a_thing(backend, opt)

    for resource in ctx.resources():
        diff_a_thing(resource, opt)

    if opt.thaw_from:
        rmtree(opt.secrets)
502669
function attemptListIndexesFromVault(state, vault, topic, partialIndex, options, cb) {
	// 0-length array response indicates non-existence in this vault
	// this may be totally acceptable for volatile caches

	if (!vault.archive.list) {
		return state.error(null, 'List-operations not supported on vault ' + vault.name, cb);
	}

	var topicApi = configuration.getTopicApi(topic, vault.name);
	if (!topicApi) {
		// no API available for this topic on this vault

		logger.verbose('No API available for topic', topic, 'on vault', vault.name);
		return cb();
	}

	// check if there even is an index

	if (!topicApi.index) {
		return state.error(null, 'Cannot list indexes on a topic without an index signature', cb);
	}

	// attempt to get from the vault

	logger.verbose('Attempting to list indexes for topic', topic, 'on vault', vault.name);

	var startTime = process.hrtime();

	vault.archive.list(topicApi, topic, partialIndex, options, function (error, indexes) {
		if (error) {
			exports.emit('vaultError', vault.name, 'list');

			// alert the error and mark state as erroneous
			var context = {
				index: partialIndex,
				operation: 'list',
				topic: topic,
				vault: vault.name
			};

			logger.alert.data(context).log(error);

			return state.error(null, null, cb);
		}

		exports.emit('operation', vault.name, 'list', process.hrtime(startTime));

		// value should be undefined to indicate a valid case of non-existing value

		logger.verbose('Found', indexes.length, 'indexes in vault', vault.name);

		cb(null, indexes);
	});
}
488911
def fetch(self, vault_client):
        """"""
        result = self.read(vault_client)
        if result:
            if isinstance(result, dict) and 'data' in result:
                self.existing = result['data']
            else:
                self.existing = result
        else:
            self.existing = None
1193432
def get_all
      raise yellow(
        "Vault prefix: '#{prefix}' does not exist, or doesn't contain any secrets to pull/check"\
        "\nEnsure mount is enabled and use `sanctum create`, and `sanctum push` to add secrets"
      ) if invalid_prefix?

      secrets_from_vault = Hash.new
      secrets_from_vault[prefix] = JSON(list_recursive(list_prefix).to_json)
      secrets_from_vault
    end
1364378
def get(self, entry):
        
        if self.apiVersion == 1:
            path = self.secretsmount + '/' + entry
        else:
            path = self.secretsmount + '/data/' + entry

        # note that the HTTP path contains v1 for both versions of the key-value
        # secret engine. Different versions of the key-value engine are
        # effectively separate secret engines in vault, with the same base HTTP
        # API, but with different paths within it.
        proj = yield self._http.get('/v1/{0}'.format(path))
        code = yield proj.code
        if code != 200:
            raise KeyError("The key %s does not exist in Vault provider: request"
                           " return code:%d." % (entry, code))
        json = yield proj.json()
        if self.apiVersion == 1:
            ret = json.get('data', {}).get('value')
        else:
            ret = json.get('data', {}).get('data', {}).get('value')
        return ret
383555
def _fetch_app_role_token(vault_url, role_id, secret_id):
        """"""
        url = _url_joiner(vault_url, 'v1/auth/approle/login')
        resp = requests.post(url, data={'role_id': role_id, 'secret_id': secret_id})
        resp.raise_for_status()
        data = resp.json()
        if data.get('errors'):
            raise VaultException(u'Error fetching Vault token: {}'.format(data['errors']))
        return data['auth']['client_token']
36598
def write_secret(path, **kwargs):
    '''
    
    '''
    log.debug('Writing vault secrets for %s at %s', __grains__['id'], path)
    data = dict([(x, y) for x, y in kwargs.items() if not x.startswith('__')])
    try:
        url = 'v1/{0}'.format(path)
        response = __utils__['vault.make_request']('POST', url, json=data)
        if response.status_code == 200:
            return response.json()['data']
        elif response.status_code != 204:
            response.raise_for_status()
        return True
    except Exception as err:
        log.error('Failed to write secret! %s: %s', type(err).__name__, err)
        return False
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
792571
def extract_file_args(subparsers):
    """"""
    extract_parser = subparsers.add_parser('extract_file',
                                           help='Extract a single secret from'
                                           'Vault to a local file')
    extract_parser.add_argument('vault_path',
                                help='Full path (including key) to secret')
    extract_parser.add_argument('destination',
                                help='Location of destination file')
    base_args(extract_parser)
335478
def password_args(subparsers):
    """"""
    password_parser = subparsers.add_parser('set_password')
    password_parser.add_argument('vault_path',
                                 help='Path which contains password'
                                 'secret to be udpated')
    base_args(password_parser)
758558
def multipart_uplaods(options = {})
      batches = Enumerator.new do |y|
        options = options.merge(
          vault_name: @name,
          account_id: @account_id
        )
        resp = @client.list_multipart_uploads(options)
        resp.each_page do |page|
          batch = []
          page.data.uploads_list.each do |u|
            batch << MultipartUpload.new(
              account_id: @account_id,
              vault_name: @name,
              id: u.multipart_upload_id,
              data: u,
              client: @client
            )
          end
          y.yield(batch)
        end
      end
      MultipartUpload::Collection.new(batches)
    end
1326702
def connect(self, opt):
        """"""
        if not self._kwargs['verify']:
            LOG.warning('Skipping SSL Validation!')

        self.version = self.server_version()
        self.token = self.init_token()
        my_token = self.lookup_token()
        if not my_token or 'data' not in my_token:
            raise aomi.exceptions.AomiCredentials('initial token')

        display_name = my_token['data']['display_name']
        vsn_string = ""
        if self.version:
            vsn_string = ", v%s" % self.version
        else:
            LOG.warning("Unable to deterine Vault version. Not all "
                        "functionality is supported")

        LOG.info("Connected to %s as %s%s",
                 self._url,
                 display_name,
                 vsn_string)

        if opt.reuse_token:
            LOG.debug("Not creating operational token")
            self.initial_token = self.token
            self.operational_token = self.token
        else:
            self.initial_token = self.token
            self.operational_token = self.op_token(display_name, opt)
            if not self.is_authenticated():
                raise aomi.exceptions.AomiCredentials('operational token')

            self.token = self.operational_token

        return self
977616
def use_isolated_vault_view(self):
        """"""
        self._vault_view = ISOLATED
        # self._get_provider_session('authorization_lookup_session') # To make sure the session is tracked
        for session in self._get_provider_sessions():
            try:
                session.use_isolated_vault_view()
            except AttributeError:
                pass
1041711
def init_token(self):
        """"""

        app_filename = appid_file()
        token_filename = token_file()
        approle_filename = approle_file()
        token = None
        if 'VAULT_ROLE_ID' in os.environ and \
           'VAULT_SECRET_ID' in os.environ and \
           os.environ['VAULT_ROLE_ID'] and os.environ['VAULT_SECRET_ID']:
            token = approle_token(self,
                                  os.environ['VAULT_ROLE_ID'],
                                  os.environ['VAULT_SECRET_ID'])
            LOG.debug("Token derived from VAULT_ROLE_ID and VAULT_SECRET_ID")
        elif 'VAULT_TOKEN' in os.environ and os.environ['VAULT_TOKEN']:
            LOG.debug('Token derived from VAULT_TOKEN environment variable')
            token = os.environ['VAULT_TOKEN'].strip()
        elif 'VAULT_USER_ID' in os.environ and \
             'VAULT_APP_ID' in os.environ and \
             os.environ['VAULT_USER_ID'] and os.environ['VAULT_APP_ID']:
            LOG.debug("Token derived from VAULT_APP_ID and VAULT_USER_ID")
            token = app_token(self,
                              os.environ['VAULT_APP_ID'].strip(),
                              os.environ['VAULT_USER_ID'].strip())
        elif approle_filename:
            creds = yaml.safe_load(open(approle_filename).read().strip())
            if 'role_id' in creds and 'secret_id' in creds:
                LOG.debug("Token derived from approle file")
                token = approle_token(self,
                                      creds['role_id'],
                                      creds['secret_id'])
        elif token_filename:
            LOG.debug("Token derived from %s", token_filename)
            try:
                token = open(token_filename, 'r').read().strip()
            except IOError as os_exception:
                if os_exception.errno == 21:
                    raise aomi.exceptions.AomiFile('Bad Vault token file')

                raise
        elif app_filename:
            token = yaml.safe_load(open(app_filename).read().strip())
            if 'app_id' in token and 'user_id' in token:
                LOG.debug("Token derived from %s", app_filename)
                token = app_token(self,
                                  token['app_id'],
                                  token['user_id'])
        else:
            raise aomi.exceptions.AomiCredentials('unknown method')

        return token