Read a secret from Vault REST endpoint
770544
def read(path):
    """"""
    url = '{}/{}/{}'.format(settings.VAULT_BASE_URL.rstrip('/'),
                            settings.VAULT_BASE_SECRET_PATH.strip('/'),
                            path.lstrip('/'))

    headers = {'X-Vault-Token': settings.VAULT_ACCESS_TOKEN}
    resp = requests.get(url, headers=headers)
    if resp.ok:
        return resp.json()['data']
    else:
        log.error('Failed VAULT GET request: %s %s', resp.status_code, resp.text)
        raise Exception('Failed Vault GET request: {} {}'.format(resp.status_code, resp.text))
1194932
private void downloadOneChunk(String accountId, String vaultName,
            String jobId, RandomAccessFile output, long currentPosition,
            long endPosition, ProgressListener progressListener) {
        final long chunkSize = endPosition - currentPosition + 1;
        TreeHashInputStream input = null;
        int retries = 0;
        while (true) {
            try {
                GetJobOutputRequest req = new GetJobOutputRequest()
                    .withAccountId(accountId)
                    .withVaultName(vaultName)
                    .withRange("bytes=" + currentPosition + "-" + endPosition)
                    .withJobId(jobId)
                    .withGeneralProgressListener(progressListener)
                    ;
                GetJobOutputResult jobOutputResult = glacier.getJobOutput(req);
                try {
                    input = new TreeHashInputStream(new BufferedInputStream(jobOutputResult.getBody()));
                    appendToFile(output, input);
                } catch (NoSuchAlgorithmException e) {
                    throw failure(e, "Unable to compute hash for data integrity");
                } finally {
                    closeQuietly(input, log);
                }

                // Only do tree-hash check when the output checksum is returned from Glacier
                if (null != jobOutputResult.getChecksum()) {
                    // Checksum does not match
                    if (!input.getTreeHash().equalsIgnoreCase(jobOutputResult.getChecksum())) {
                        // Discard the chunk of bytes received 
                        publishResponseBytesDiscarded(progressListener, chunkSize);
                        if (log.isDebugEnabled())
                            log.debug("reverting " + chunkSize);
                        throw new IOException("Client side computed hash doesn't match server side hash; possible data corruption");
                    }
                } else {
                    log.warn("Cannot validate the downloaded output since no tree-hash checksum is returned from Glacier. "
                            + "Make sure the InitiateJob and GetJobOutput requests use tree-hash-aligned ranges.");
                }
                // Successfully download
                return;
                // We will retry IO exception
            } catch (IOException ioe) {
                if (retries < DEFAULT_MAX_RETRIES) {
                    retries++;
                    if (log.isDebugEnabled()) {
                        log.debug(retries
                                + " retry downloadOneChunk accountId="
                                + accountId + ", vaultName=" + vaultName
                                + ", jobId=" + jobId + ", currentPosition="
                                + currentPosition + " endPosition="
                                + endPosition);
                    }
                    try {
                        output.seek(currentPosition);
                    } catch (IOException e) {
                        throw new AmazonClientException("Unable to download the archive: " + ioe.getMessage(), e);
                    }
                } else {
                    throw new AmazonClientException("Unable to download the archive: " + ioe.getMessage(), ioe);
                }
            }
        }
    }
1144671
def _secret_yaml(loader, node):
    """"""
    fname = os.path.join(os.path.dirname(loader.name), "secrets.yaml")

    try:
        with open(fname, encoding="utf-8") as secret_file:
            secrets = YAML(typ="safe").load(secret_file)
    except FileNotFoundError:
        raise ValueError("Secrets file {} not found".format(fname)) from None

    try:
        return secrets[node.value]
    except KeyError:
        raise ValueError("Secret {} not found".format(node.value)) from None
144018
def get(cls, credential_password_ip_id, permitted_ip_id,
            custom_headers=None):
        

        if custom_headers is None:
            custom_headers = {}

        api_client = client.ApiClient(cls._get_api_context())
        endpoint_url = cls._ENDPOINT_URL_READ.format(cls._determine_user_id(),
                                                     credential_password_ip_id,
                                                     permitted_ip_id)
        response_raw = api_client.get(endpoint_url, {}, custom_headers)

        return BunqResponsePermittedIp.cast_from_bunq_response(
            cls._from_json(response_raw, cls._OBJECT_TYPE_GET)
        )
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
608695
def lookup_token(self):
        """"""
        url = _url_joiner(self._vault_url, 'v1/auth/token/lookup-self')
        resp = requests.get(url, headers=self._headers)
        resp.raise_for_status()
        data = resp.json()
        if data.get('errors'):
            raise VaultException(u'Error looking up Vault token: {}'.format(data['errors']))
        return data
258635
def _load_secret(self, creds_file):
        ''''''
        try:
            with open(creds_file) as fp:
                creds = json.load(fp)
            return creds
        except Exception as e:
            sys.stderr.write("Error loading oauth secret from local file called '{0}'\n".format(creds_file))
            sys.stderr.write("\tThere should be a local OAuth credentials file \n")
            sys.stderr.write("\twhich has contents like this:\n")
            sys.stderr.write("""
                {
                "account_id": "1234567890001",
                "client_id": "30ff0909-0909-33d3-ae88-c9887777a7b7",
                "client_secret": "mzKKjZZyeW5YgsdfBD37c5730g397agU35-Dsgeox6-73giehbt0996nQ"
                }

              """)
            sys.stderr.write("\n")
            raise e
1045091
function createAgentRequest ( config, vault, params ) {
  if (!vault || !config || !params)
    throw new Error('"config", "vault", "params" are required) ')
  if (!params.returnURL && !params.callbackURL)
    throw new Error('params must have either "returnURL" or "callbackURL"')
  config = _init( config, vault )
  var credentials = vault[ config.ix ].latest
  var details =
    { header:
      { typ: 'JWS'
      , alg: ALG_REQUEST
      }
    , payload:
      { 'iss': config.appID
      , 'aud': config.ix
      , 'iat': jwt.iat()
      , 'request.a2p3.org':
        { 'resources': params.resources || []
        , 'auth': config.auth
        , 'ix': 'a2p3.net'
        }
      }
    , credentials: credentials
    }
  if ( params.returnURL )
    details.payload['request.a2p3.org'].returnURL = params.returnURL
  else if ( params.callbackURL )
    details.payload['request.a2p3.org'].callbackURL = params.callbackURL
  this.agentRequest = jwt.jws( details )
  return this.agentRequest
}
477544
def get_vault(self):
        
        if self._lookup_session is None:
            mgr = get_provider_manager('AUTHORIZATION', runtime=self._runtime, proxy=self._proxy)
            self._lookup_session = mgr.get_vault_lookup_session(proxy=getattr(self, "_proxy", None))
        return self._lookup_session.get_vault(Id(self._my_map['id']))
542123
def sync(self, vault_client):
        """"""
        if self.present and not self.existing:
            LOG.info("Writing new %s to %s",
                     self.secret_format, self)
            self.write(vault_client)
        elif self.present and self.existing:
            if self.diff() == CHANGED or self.diff() == OVERWRITE:
                LOG.info("Updating %s in %s",
                         self.secret_format, self)
                self.write(vault_client)
        elif not self.present and not self.existing:
            LOG.info("No %s to remove from %s",
                     self.secret_format, self)
        elif not self.present and self.existing:
            LOG.info("Removing %s from %s",
                     self.secret_format, self)
            self.delete(vault_client)
825005
function (callback) {
    fs.readFile(clientSecretPath, function processClientSecrets(err, content) {
        if (err) {
            debug('Error loading client secret file: ' + err);
            return callback(err);
        } else {
            credentials = JSON.parse(content);
            return callback();
        }
    });
}
575580
public PagedList<SecretItem> listSecretVersions(final String vaultBaseUrl, final String secretName) {
        return getSecretVersions(vaultBaseUrl, secretName);
    }
1332570
def vault_relation_complete(backend=None):
    """"""
    vault_kv = VaultKVContext(secret_backend=backend or VAULTLOCKER_BACKEND)
    vault_kv()
    return vault_kv.complete
638762
def list_keyvaults_sub(access_token, subscription_id):
    '''
    '''
    endpoint = ''.join([get_rm_endpoint(),
                        '/subscriptions/', subscription_id,
                        '/providers/Microsoft.KeyVault/vaults',
                        '?api-version=', KEYVAULT_API])
    return do_get_next(endpoint, access_token)
938739
def make_request(method, resource, token=None, vault_url=None, get_token_url=False, **args):
    '''
    
    '''
    if not token or not vault_url:
        connection = get_vault_connection()
        token, vault_url = connection['token'], connection['url']
        if 'verify' not in args:
            args['verify'] = connection['verify']

    url = "{0}/{1}".format(vault_url, resource)
    headers = {'X-Vault-Token': token, 'Content-Type': 'application/json'}
    response = requests.request(method, url, headers=headers, **args)

    if get_token_url:
        return response, token, vault_url
    else:
        return response
58457
def secretfile_args(parser):
    """"""
    parser.add_argument('--secrets',
                        dest='secrets',
                        help='Path where secrets are stored',
                        default=os.path.join(os.getcwd(), ".secrets"))
    parser.add_argument('--policies',
                        dest='policies',
                        help='Path where policies are stored',
                        default=os.path.join(os.getcwd(), "vault", ""))
    parser.add_argument('--secretfile',
                        dest='secretfile',
                        help='Secretfile to use',
                        default=os.path.join(os.getcwd(), "Secretfile"))
    parser.add_argument('--tags',
                        dest='tags',
                        help='Tags of things to seed',
                        default=[],
                        type=str,
                        action='append')
    parser.add_argument('--include',
                        dest='include',
                        help='Specify paths to include',
                        default=[],
                        type=str,
                        action='append')
    parser.add_argument('--exclude',
                        dest='exclude',
                        help='Specify paths to exclude',
                        default=[],
                        type=str,
                        action='append')
502738
def _fetch_secret(pass_path):
    '''
    
    '''
    cmd = "pass show {0}".format(pass_path.strip())
    log.debug('Fetching secret: %s', cmd)

    proc = Popen(cmd.split(' '), stdout=PIPE, stderr=PIPE)
    pass_data, pass_error = proc.communicate()

    # The version of pass used during development sent output to
    # stdout instead of stderr even though its returncode was non zero.
    if proc.returncode or not pass_data:
        log.warning('Could not fetch secret: %s %s', pass_data, pass_error)
        pass_data = pass_path
    return pass_data.strip()