Skip to content

API reference

Generated reference documentation for each package. The pages are rebuilt and published with this site from main.

Language Reference Generated by
TypeScript TypeScript API TypeDoc
Rust Rust API · docs.rs rustdoc
Go pkg.go.dev Go doc comments
Python below mkdocstrings
Java Java API Javadoc

Build them locally with make docs (per language: make -C <lang> docs).

Python

Grow Codes SDK for HashiCorp Vault.

from grow_hashicorp_vault import VaultClient, VaultConfig client = VaultClient.from_env() # doctest: +SKIP

Modules hang off the client: client.auth, client.sys, client.wrapping, client.leases, client.kv(), client.transit(), client.database(), client.pki() and client.secrets() (the SecretsProvider). Server lifecycle helpers (init/unseal) live in :mod:grow_hashicorp_vault.testing.lifecycle.

CAPABILITY_CREATE module-attribute

CAPABILITY_CREATE = 'create'

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

CAPABILITY_DELETE module-attribute

CAPABILITY_DELETE = 'delete'

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

CAPABILITY_DENY module-attribute

CAPABILITY_DENY = 'deny'

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

CAPABILITY_LIST module-attribute

CAPABILITY_LIST = 'list'

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

CAPABILITY_PATCH module-attribute

CAPABILITY_PATCH = 'patch'

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

CAPABILITY_READ module-attribute

CAPABILITY_READ = 'read'

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

CAPABILITY_ROOT module-attribute

CAPABILITY_ROOT = 'root'

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

CAPABILITY_SUDO module-attribute

CAPABILITY_SUDO = 'sudo'

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

CAPABILITY_UPDATE module-attribute

CAPABILITY_UPDATE = 'update'

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

DEFAULT_KV_MOUNT module-attribute

DEFAULT_KV_MOUNT = 'secret'

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

DEFAULT_URL module-attribute

DEFAULT_URL = 'http://127.0.0.1:8200'

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

DEFAULT_VALUE_FIELD module-attribute

DEFAULT_VALUE_FIELD = 'value'

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

ENV_PREFIX module-attribute

ENV_PREFIX = 'GROW_HASHICORP_VAULT_'

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

LOGGER_NAME module-attribute

LOGGER_NAME = 'grow_hashicorp_vault'

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

REDACTED module-attribute

REDACTED = '[REDACTED]'

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

REQUEST_ID_HEADERS module-attribute

REQUEST_ID_HEADERS = ('x-request-id', 'x-amzn-requestid', 'x-amz-request-id', 'x-datadog-request-id', 'request-id', 'x-correlation-id')

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

RETRY_AFTER_HEADERS module-attribute

RETRY_AFTER_HEADERS = ('retry-after',)

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

SDK_NAME module-attribute

SDK_NAME = 'grow-codes-hashicorp-vault'

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

VENDOR_ENV module-attribute

VENDOR_ENV = {'URL': ('VAULT_ADDR',), 'TOKEN': ('VAULT_TOKEN',), 'NAMESPACE': ('VAULT_NAMESPACE',), 'CA_CERT': ('VAULT_CACERT',), 'CLIENT_CERT': ('VAULT_CLIENT_CERT',), 'CLIENT_KEY': ('VAULT_CLIENT_KEY',), 'INSECURE_SKIP_VERIFY': ('VAULT_SKIP_VERIFY',)}

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

AppRoleAuth

Bases: grow_hashicorp_vault.auth.AuthMethod

AppRole login: POST auth/<mount>/login {role_id, secret_id}.

secret_id may be omitted for roles with bind_secret_id=false.

method class-attribute

method = 'approle'

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

AsyncAuth

Bases: grow_hashicorp_vault._api.AsyncModule

Async :class:Auth: async_client.auth.

active_renewers property

active_renewers

Number of active renewers.

create_token

create_token(*, policies: Sequence[str] | None = None, ttl_s: Duration | None = None, explicit_max_ttl_s: Duration | None = None, renewable: bool | None = None, display_name: str | None = None, meta: Mapping[str, str] | None = None, num_uses: int | None = None, no_parent: bool | None = None, no_default_policy: bool | None = None, period_s: Duration | None = None, role: str | None = None) -> AuthInfo

See :meth:Auth.create_token.

login

login(method: AuthMethod, *, set_token: bool = True, auto_renew: bool | Mapping[str, Any] = False) -> AuthInfo

See :meth:Auth.login.

lookup_self

lookup_self() -> TokenInfo

See :meth:Auth.lookup_self.

renew_self

renew_self(increment_s: Duration | None = None) -> AuthInfo

See :meth:Auth.renew_self.

revoke_self

revoke_self() -> None

See :meth:Auth.revoke_self.

start_renewer

start_renewer(**options: Any) -> AsyncTokenRenewer

See :meth:Auth.start_renewer (call from a running event loop).

stop_renewers

stop_renewers() -> None

Stop every renewer started through this API (idempotent).

AsyncBaseSecretsProvider

Bases: abc.ABC

Async counterpart of :class:BaseSecretsProvider (async primitives).

After :meth:aclose every call raises :class:CancelledError ("client is closed").

closed property

closed

True once :meth:aclose was called.

aclose

aclose() -> None

Stop every watcher started by this provider; later calls raise CANCELLED (idempotent).

ensure_open

ensure_open(op: str) -> None

Raise :class:CancelledError (": client is closed") after :meth:aclose.

Service methods that do not go through the base operations can call it first.

load_env

load_env(source: str | Mapping[str, str], *, override: bool = False, prefix: str = '', environ: MutableMapping[str, str] | None = None) -> dict[str, str]

See :meth:BaseSecretsProvider.load_env.

watch

watch(name: str, interval_s: float | timedelta, on_change: Callable, *, on_error: Callable | None = None, version: str | None = None, path: str | None = None) -> AsyncWatchHandle

Start an asyncio task polling name (call from a running event loop).

AsyncDatabase

Bases: grow_hashicorp_vault._api.AsyncModule

Async :class:Database.

configure_connection

configure_connection(name: str, *, plugin_name: str, connection_url: str, username: str | None = None, password: str | Secret | None = None, allowed_roles: Sequence[str] | None = None, verify_connection: bool | None = None, extra: Mapping[str, Any] | None = None) -> None

Create or replace a connection (POST <mount>/config/<name>, verified by default).

connection_url uses {{username}}/{{password}} templates; extra holds plugin-specific fields sent as is (snake_case).

create_role

create_role(name: str, *, db_name: str, creation_statements: Sequence[str], revocation_statements: Sequence[str] | None = None, renew_statements: Sequence[str] | None = None, rollback_statements: Sequence[str] | None = None, default_ttl_s: Duration | None = None, max_ttl_s: Duration | None = None) -> None

Create or replace a dynamic role (POST <mount>/roles/<name>).

Statements use {{name}}, {{password}} and {{expiration}}.

delete_connection

delete_connection(name: str) -> None

Delete a connection.

delete_role

delete_role(name: str) -> None

Delete a role.

get_credentials

get_credentials(role: str) -> Lease[DatabaseCredentials]

Generate credentials for a role (GET <mount>/creds/<role>).

Keep them alive with client.leases.manage(lease, on_expire=...). Unknown roles raise :class:ValidationError. Never retried (every call creates new credentials).

read_connection

read_connection(name: str) -> ConnectionInfo

Read a connection (without its password); :class:NotFoundError when missing.

read_role

read_role(name: str) -> RoleInfo

Read a role; :class:NotFoundError when missing.

AsyncHttpTransport

Asynchronous transport (one per async client); options as for :class:HttpTransport.

Cancelling the calling task raises :class:CancelledError (an asyncio.CancelledError subclass) so asyncio's cancellation machinery keeps working. Every call after :meth:aclose raises :class:CancelledError ("client is closed").

aclose

aclose() -> None

Close the connection pool and abort backoff sleeps (idempotent).

request

request(req: Request) -> Response

Send req with retries; return the response or raise the mapped error.

AsyncKvMount

Bases: grow_hashicorp_vault._api.AsyncModule, grow_hashicorp_vault.kv._KvBase

Async :class:KvMount.

delete

delete(path: str) -> None

Delete the secret (v2: soft-delete latest).

delete_metadata

delete_metadata(path: str) -> None

Delete all versions (KV v2 only).

delete_versions

delete_versions(path: str, versions: Sequence[int]) -> None

Soft-delete versions (KV v2 only).

destroy

destroy(path: str, versions: Sequence[int]) -> None

Destroy versions (KV v2 only).

list

list(path: str = '') -> list[str]

Keys directly under a folder (sub-folders end in /); [] when there is none.

Vault OSS has no list pagination: every key of the folder is returned.

patch

patch(path: str, data: Mapping[str, Any], *, cas: int | None = None) -> KvVersionMetadata

Merge keys into the latest version (RFC 7386: a None value removes the key).

read

read(path: str, *, version: int | None = None) -> KvSecret

Read the latest (or a given) version; :class:NotFoundError when missing, deleted or destroyed.

read_metadata

read_metadata(path: str) -> KvMetadata

Metadata of all versions (KV v2 only).

undelete

undelete(path: str, versions: Sequence[int]) -> None

Restore versions (KV v2 only).

version

version(path: str = '') -> KvVersion

The KV version of the mount (detected on first use).

write

write(path: str, data: Mapping[str, Any], *, cas: int | None = None) -> KvVersionMetadata | None

Write a new version (cas: the current version must equal it, 0 = create only).

A CAS mismatch raises :class:ConflictError.

write_metadata

write_metadata(path: str, *, max_versions: int | None = None, cas_required: bool | None = None, delete_version_after_s: Duration | None = None, custom_metadata: Mapping[str, str] | None = None) -> None

Update metadata settings (KV v2 only).

AsyncKvV1

Bases: grow_hashicorp_vault._api.AsyncModule, grow_hashicorp_vault.kv._KvBase

Async :class:KvV1.

version class-attribute

version = 1

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.int(). For floating-point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral.

int('0b100', base=0) 4

delete

delete(path: str) -> None

Delete a secret (missing paths are not an error).

delete_metadata

delete_metadata(*args: Any, **kwargs: Any) -> Any

Not supported by KV version 1 (:class:UnsupportedError): deleteMetadata.

delete_versions

delete_versions(*args: Any, **kwargs: Any) -> Any

Not supported by KV version 1 (:class:UnsupportedError): deleteVersions.

destroy

destroy(*args: Any, **kwargs: Any) -> Any

Not supported by KV version 1 (:class:UnsupportedError): destroy.

list

list(path: str = '') -> list[str]

Keys directly under a folder (sub-folders end in /); [] when there is none.

patch

patch(*args: Any, **kwargs: Any) -> Any

Not supported by KV version 1 (:class:UnsupportedError): patch.

read

read(path: str, *, version: int | None = None) -> KvSecret

Read a secret; :class:NotFoundError when missing (version is v2 only).

read_metadata

read_metadata(*args: Any, **kwargs: Any) -> Any

Not supported by KV version 1 (:class:UnsupportedError): readMetadata.

undelete

undelete(*args: Any, **kwargs: Any) -> Any

Not supported by KV version 1 (:class:UnsupportedError): undelete.

write

write(path: str, data: Mapping[str, Any], *, cas: int | None = None) -> KvVersionMetadata | None

Write (replace) a secret; returns None on KV v1 (cas is v2 only).

write_metadata

write_metadata(*args: Any, **kwargs: Any) -> Any

Not supported by KV version 1 (:class:UnsupportedError): writeMetadata.

AsyncKvV2

Bases: grow_hashicorp_vault._api.AsyncModule, grow_hashicorp_vault.kv._KvBase

Async :class:KvV2.

version class-attribute

version = 2

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.int(). For floating-point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral.

int('0b100', base=0) 4

delete

delete(path: str) -> None

Soft-delete the latest version (missing paths are not an error).

delete_metadata

delete_metadata(path: str) -> None

Delete the secret with all versions and metadata.

delete_versions

delete_versions(path: str, versions: Sequence[int]) -> None

Soft-delete the given versions.

destroy

destroy(path: str, versions: Sequence[int]) -> None

Permanently destroy versions.

list

list(path: str = '') -> list[str]

Keys directly under a folder (sub-folders end in /); [] when there is none.

Vault OSS has no list pagination: every key of the folder is returned.

patch

patch(path: str, data: Mapping[str, Any], *, cas: int | None = None) -> KvVersionMetadata

Merge keys into the latest version (RFC 7386: a None value removes the key).

read

read(path: str, *, version: int | None = None) -> KvSecret

Read the latest (or a given) version; :class:NotFoundError when missing, deleted or destroyed.

read_metadata

read_metadata(path: str) -> KvMetadata

Metadata of all versions; :class:NotFoundError when missing.

undelete

undelete(path: str, versions: Sequence[int]) -> None

Restore soft-deleted versions.

write

write(path: str, data: Mapping[str, Any], *, cas: int | None = None) -> KvVersionMetadata | None

Write a new version (cas: the current version must equal it, 0 = create only).

A CAS mismatch raises :class:ConflictError.

write_metadata

write_metadata(path: str, *, max_versions: int | None = None, cas_required: bool | None = None, delete_version_after_s: Duration | None = None, custom_metadata: Mapping[str, str] | None = None) -> None

Update the metadata settings of a secret.

AsyncLeaseManager

Bases: grow_hashicorp_vault._api.AsyncModule

Async :class:LeaseManager: async_client.leases.

active_leases property

active_leases

Number of managed leases.

lookup

lookup(lease_id: str) -> LeaseInfo

Lease details (PUT sys/leases/lookup); unknown leases raise :class:ValidationError.

manage

manage(lease: Lease[Any], *, increment_s: Duration | None = None, renew_fraction: float = 0.6666666666666666, min_delay_s: float = 0.5, on_renew: Callable[[LeaseRenewal], None] | None = None, on_error: Callable[[BaseException], None] | None = None, on_expire: Callable[[], None] | None = None, revoke_on_stop: bool = False, clock: Callable[[], float] | None = None, sleep: Callable[[float], Any] | None = None) -> AsyncManagedLease

See :meth:LeaseManager.manage (an asyncio task; call from a running loop).

renew

renew(lease_id: str, increment_s: Duration | None = None) -> LeaseRenewal

Renew a lease (PUT sys/leases/renew).

A TTL beyond the maximum is capped (see warnings); unknown or revoked leases raise :class:ValidationError.

revoke

revoke(lease_id: str) -> None

Revoke a lease now (PUT sys/leases/revoke).

revoke_prefix

revoke_prefix(prefix: str) -> None

Revoke every lease under a prefix (PUT sys/leases/revoke-prefix/<prefix>).

stop_all

stop_all() -> None

Stop every managed lease (revoking those with revoke_on_stop). Idempotent.

AsyncManagedLease

Handle of a lease kept alive by :meth:AsyncLeaseManager.manage.

expired property

expired

Whether on_expire fired.

expires_at property

expires_at

Expiry of the current lease.

running property

running

Whether renewal is still active.

stop

stop() -> None

Stop renewing (and revoke when revoke_on_stop). Idempotent.

AsyncPki

Bases: grow_hashicorp_vault._api.AsyncModule

Async :class:Pki.

issue_certificate

issue_certificate(role: str, common_name: str, *, alt_names: Sequence[str] | None = None, ip_sans: Sequence[str] | None = None, uri_sans: Sequence[str] | None = None, ttl_s: Duration | None = None, format: Literal[pem, der, pem_bundle] | None = None, private_key_format: Literal[der, pkcs8] | None = None, exclude_cn_from_sans: bool | None = None) -> IssuedCertificate

Issue a certificate and private key for a role (POST <mount>/issue/<role>).

A common name the role does not allow raises :class:ValidationError.

list_certificates

list_certificates() -> list[str]

Serials of all stored certificates; [] when there is none.

read_ca_chain

read_ca_chain() -> str

The CA chain as PEM text (GET <mount>/ca_chain, raw PEM).

read_certificate

read_certificate(serial: str) -> CertificateInfo

A certificate by serial; :class:NotFoundError when unknown.

revoke_certificate

revoke_certificate(serial: str) -> RevocationInfo

Revoke a certificate by serial (aa:bb:...); unknown serials raise :class:ValidationError.

sign_csr

sign_csr(role: str, csr: str, *, common_name: str | None = None, alt_names: Sequence[str] | None = None, ip_sans: Sequence[str] | None = None, uri_sans: Sequence[str] | None = None, ttl_s: Duration | None = None, format: Literal[pem, der, pem_bundle] | None = None, exclude_cn_from_sans: bool | None = None) -> SignedCertificate

Sign a PEM CSR for a role (POST <mount>/sign/<role>).

tidy

tidy(*, tidy_cert_store: bool = True, tidy_revoked_certs: bool = True, safety_buffer_s: Duration | None = None, wait: bool = True, timeout_s: Duration = 60.0, interval_s: Duration = 0.5) -> TidyStatus

Start a tidy run (POST <mount>/tidy, 202).

Unless wait=False, poll tidy-status until it is Finished, Error or Cancelled (:class:TimeoutError after timeout_s). Returns the last status.

tidy_status

tidy_status() -> TidyStatus

Current tidy progress (GET <mount>/tidy-status).

AsyncSecretCache

Bases: grow_hashicorp_vault._secrets.base.AsyncBaseSecretsProvider

Async :class:SecretCache; background refreshes run as asyncio tasks.

wait_refreshes

wait_refreshes() -> None

Wait for background refreshes currently running (useful in tests).

watch

watch(name: str, interval_s: float | timedelta, on_change: Callable, *, on_error: Callable | None = None, version: str | None = None, path: str | None = None) -> AsyncWatchHandle

Watches the underlying provider directly (bypasses the cache).

AsyncSecretsProvider

Bases: typing.Protocol

Asynchronous secrets interface (same methods, awaitable).

AsyncSys

Bases: grow_hashicorp_vault._api.AsyncModule

Async :class:Sys: async_client.sys.

capabilities

capabilities(token: str | Secret, paths: str | Sequence[str]) -> Capabilities

Another token's capabilities on each path (POST sys/capabilities).

The caller needs update on sys/capabilities; otherwise :class:PermissionDeniedError. paths is one path or a list.

capabilities_self

capabilities_self(paths: str | Sequence[str]) -> Capabilities

The client token's capabilities on each path (POST sys/capabilities-self).

paths is one path or a list. Returns a :class:Capabilities map from each requested path to its capabilities (create, read, update, patch, delete, list, sudo, root or deny)::

caps = client.sys.capabilities_self(["secret/data/app/db"])
if caps.allows("secret/data/app/db", "read"): ...

create_app_role

create_app_role(name: str, *, mount: str = 'approle', token_policies: Sequence[str] | None = None, token_ttl_s: Duration | None = None, token_max_ttl_s: Duration | None = None, secret_id_ttl_s: Duration | None = None, secret_id_num_uses: int | None = None, bind_secret_id: bool | None = None, token_type: str | None = None) -> None

Create or update an AppRole role (POST auth/<mount>/role/<name>).

delete_app_role

delete_app_role(name: str, *, mount: str = 'approle') -> None

Delete an AppRole role.

delete_policy

delete_policy(name: str) -> None

Delete an ACL policy.

disable_auth_method

disable_auth_method(path: str) -> None

Disable an auth method; its tokens are revoked.

disable_secrets_engine

disable_secrets_engine(path: str) -> None

Disable (unmount) a secrets engine; its data is deleted.

enable_auth_method

enable_auth_method(path: str, type: str, *, description: str | None = None, default_lease_ttl_s: Duration | None = None, max_lease_ttl_s: Duration | None = None, local: bool | None = None) -> None

Enable an auth method at path.

enable_secrets_engine

enable_secrets_engine(path: str, type: str, *, description: str | None = None, options: Mapping[str, str] | None = None, default_lease_ttl_s: Duration | None = None, max_lease_ttl_s: Duration | None = None, local: bool | None = None, seal_wrap: bool | None = None) -> None

Enable a secrets engine at path (e.g. type="kv", options={"version": "2"}).

A used path raises :class:ValidationError.

generate_secret_id

generate_secret_id(name: str, *, mount: str = 'approle', metadata: Mapping[str, str] | None = None, cidr_list: Sequence[str] | None = None, ttl_s: Duration | None = None, num_uses: int | None = None) -> SecretIdInfo

Generate a new secret id for an AppRole role.

health

health() -> HealthResponse

GET sys/health (unauthenticated); sealed, standby and uninitialised nodes are no error.

leader

leader() -> LeaderStatus

GET sys/leader (unauthenticated).

list_app_roles

list_app_roles(*, mount: str = 'approle') -> list[str]

AppRole role names; [] when there is none.

list_auth_methods

list_auth_methods() -> dict[str, MountInfo]

Auth methods by path ("approle/" → info).

list_mounts

list_mounts() -> dict[str, MountInfo]

Secrets engines by path ("secret/" → info).

list_policies

list_policies() -> list[str]

ACL policy names (includes default and root).

read_policy

read_policy(name: str) -> Policy

Read an ACL policy; :class:NotFoundError when missing.

read_role_id

read_role_id(name: str, *, mount: str = 'approle') -> str

The role id of an AppRole role; :class:NotFoundError for unknown roles.

seal_status

seal_status() -> SealStatus

GET sys/seal-status (unauthenticated).

version

version() -> str

Server version from sys/health (e.g. 2.2.2).

write_policy

write_policy(name: str, policy: str) -> None

Create or replace an ACL policy (PUT sys/policies/acl/<name>); invalid HCL raises :class:ValidationError.

AsyncTokenRenewer

Async :class:TokenRenewer (an asyncio task); see :meth:AsyncAuth.start_renewer.

expired property

expired

Whether on_expire fired.

expires_at property

expires_at

Expiry of the current token, None when it never expires or is unknown.

running property

running

Whether the renewer is active.

start

start(initial: LeaseState | None = None) -> None

Start renewing (TTL from lookup_self() when initial is not given).

stop

stop() -> None

Stop renewing (idempotent).

AsyncTransit

Bases: grow_hashicorp_vault._api.AsyncModule

Async :class:Transit: async_client.transit().

create_key

create_key(name: str, type: str = 'aes256-gcm96', *, exportable: bool | None = None, derived: bool | None = None, auto_rotate_period_s: Duration | None = None, allow_plaintext_backup: bool | None = None, key_size: int | None = None) -> TransitKey

Create a key (idempotent: an existing key is returned unchanged).

Types: aes128-gcm96, aes256-gcm96 (default), chacha20-poly1305, ed25519, ecdsa-p256/-p384/-p521, rsa-2048/-3072/-4096, hmac …

decrypt

decrypt(name: str, ciphertext: str, *, context: TransitInput | None = None, associated_data: TransitInput | None = None) -> bytes

Decrypt a vault:v<n>: ciphertext; returns the plaintext bytes.

decrypt_batch

decrypt_batch(name: str, items: Sequence[DecryptBatchItem]) -> list[DecryptBatchResult]

Decrypt many items in one request; see :meth:Transit.encrypt_batch for errors.

delete_key

delete_key(name: str) -> None

Delete a key (needs deletion_allowed=True, else :class:ValidationError).

encrypt

encrypt(name: str, plaintext: TransitInput, *, context: TransitInput | None = None, key_version: int | None = None, associated_data: TransitInput | None = None) -> Ciphertext

Encrypt plaintext (text is UTF-8 encoded).

encrypt_batch

encrypt_batch(name: str, items: Sequence[EncryptBatchItem]) -> list[EncryptBatchResult]

Encrypt many items in one request.

Results are in input order; a failed item has error set (the call itself fails only when the whole request fails).

generate_data_key

generate_data_key(name: str, *, plaintext: bool = True, bits: Literal[128, 256, 512] = 256, context: TransitInput | None = None) -> DataKey

Generate a data key encrypted with the transit key (plus its plaintext by default).

hash

hash(input: TransitInput, *, algorithm: str | None = None, format: Literal[hex, base64] | None = None) -> str

Hash of input (default sha2-256, hex).

hmac

hmac(name: str, input: TransitInput, *, algorithm: str | None = None, key_version: int | None = None) -> str

HMAC of input (vault:v<n>:<base64>).

list_keys

list_keys() -> list[str]

Key names (sorted); [] when there is none (no pagination on Vault OSS).

random_bytes

random_bytes(bytes: int, *, format: Literal[hex, base64] = 'base64') -> str

bytes random bytes from the server, encoded as base64 (default) or hex.

read_key

read_key(name: str) -> TransitKey

Read a key; :class:NotFoundError when missing.

rewrap

rewrap(name: str, ciphertext: str, *, context: TransitInput | None = None, key_version: int | None = None) -> Ciphertext

Re-encrypt a ciphertext with the latest (or given) key version without revealing it.

rotate_key

rotate_key(name: str) -> TransitKey

Add a new key version; returns the updated key.

sign

sign(name: str, input: TransitInput, *, hash_algorithm: str | None = None, signature_algorithm: Literal[pss, pkcs1v15] | None = None, prehashed: bool | None = None, key_version: int | None = None, context: TransitInput | None = None) -> Signature

Sign input with an asymmetric key (symmetric keys raise :class:ValidationError).

update_key_config

update_key_config(name: str, *, deletion_allowed: bool | None = None, min_decryption_version: int | None = None, min_encryption_version: int | None = None, exportable: bool | None = None, allow_plaintext_backup: bool | None = None, auto_rotate_period_s: Duration | None = None) -> TransitKey

Update key settings; returns the updated key.

verify

verify(name: str, input: TransitInput, *, signature: str | None = None, hmac: str | None = None, hash_algorithm: str | None = None, signature_algorithm: Literal[pss, pkcs1v15] | None = None, prehashed: bool | None = None, context: TransitInput | None = None) -> bool

Verify a signature or an hmac (exactly one); False when invalid.

AsyncVaultClient

Bases: grow_hashicorp_vault.client._ClientBase

Asynchronous Vault client (same modules and methods, awaitable); use async with or call :meth:aclose.

Cancel a call by cancelling its task: the SDK raises :class:CancelledError, which is also an :class:asyncio.CancelledError.

aclose

aclose() -> None

Stop renewers, managed leases and watchers (also of every :meth:with_namespace view), then close connections (idempotent; a view leaves the shared pool open).

close

close() -> None

Stop renewers, managed leases and watchers (also of every :meth:with_namespace view), then close connections (idempotent; a view leaves the shared pool open).

database

database(mount: str = 'database') -> AsyncDatabase

Database engine (default mount database).

from_env classmethod

from_env(env: Mapping[str, str] | None = None, **overrides: Any) -> AsyncVaultClient

Build a client from GROW_HASHICORP_VAULT_* and VAULT_* variables.

health

health() -> HealthStatus

See :meth:VaultClient.health.

kv

kv(mount: str | None = None) -> AsyncKvMount

See :meth:VaultClient.kv.

kv_v1

kv_v1(mount: str | None = None) -> AsyncKvV1

KV version 1 mount (no detection).

kv_v2

kv_v2(mount: str | None = None) -> AsyncKvV2

KV version 2 mount (no detection).

ping

ping() -> float

See :meth:VaultClient.ping.

pki

pki(mount: str = 'pki') -> AsyncPki

PKI engine (default mount pki).

request

request(method: Literal, path: str, *, params: Mapping[str, Any] | None = None, json: Any = None, headers: Mapping[str, str] | None = None, list: bool = False, wrap_ttl_s: float | timedelta | None = None, idempotent: bool | None = None) -> RawResponse

See :meth:VaultClient.request.

secrets

secrets(mount: str | None = None, *, path: str | None = None, value_field: str | None = None) -> AsyncVaultSecretsProvider

See :meth:VaultClient.secrets.

server_version

server_version() -> str

See :meth:VaultClient.server_version.

transit

transit(mount: str = 'transit') -> AsyncTransit

Transit engine (default mount transit).

with_namespace

with_namespace(namespace: str) -> AsyncVaultClient

See :meth:VaultClient.with_namespace (Vault Enterprise only; OSS ignores it).

AsyncVaultSecretsProvider

Bases: grow_hashicorp_vault._secrets.base.AsyncBaseSecretsProvider

Async :class:VaultSecretsProvider: async_client.secrets().

capabilities class-attribute

capabilities = frozenset({'delete', 'write', 'versions'})

Build an immutable unordered collection of unique elements.

path property

path

Base path inside the mount that names are relative to.

value_field property

value_field

Data field that holds the value.

full_path

full_path(name: str, path: str | None = None) -> str

The KV path of a secret: <path or provider path>/<name>.

get_all

get_all(path: str | None = None) -> dict[str, SecretValue]

Every secret directly under path (non-recursive), keyed by name.

set

set(name: str, value: Any, *, path: str | None = None, cas: int | None = None, tags: Mapping[str, str] | None = None, description: str | None = None) -> str

See :meth:VaultSecretsProvider.set.

AsyncWatchHandle

Async counterpart of :class:WatchHandle running as an asyncio task.

on_change and on_error may be plain or async callables.

stop

stop() -> None

Stop polling (idempotent).

wait

wait() -> None

Wait until the task has finished (after :meth:stop).

AsyncWrapping

Bases: grow_hashicorp_vault._api.AsyncModule

Async :class:Wrapping.

lookup_wrapping

lookup_wrapping(token: str | Secret) -> WrappingLookup

Properties of a wrapping token without using it (POST sys/wrapping/lookup).

unwrap

unwrap(token: str | Secret) -> UnwrapResult

Unwrap a token (POST sys/wrapping/unwrap authenticated with the token itself).

A used or invalid token raises :class:ValidationError; never retried.

wrap

wrap(data: Mapping[str, Any], ttl_s: Duration) -> WrapInfo

Wrap data in a single-use token valid for ttl_s (POST sys/wrapping/wrap).

Auth

Bases: grow_hashicorp_vault._api.SyncModule

Logins, token self-service and token renewal: client.auth.

active_renewers property

active_renewers

Number of active renewers.

create_token

create_token(*, policies: Sequence[str] | None = None, ttl_s: Duration | None = None, explicit_max_ttl_s: Duration | None = None, renewable: bool | None = None, display_name: str | None = None, meta: Mapping[str, str] | None = None, num_uses: int | None = None, no_parent: bool | None = None, no_default_policy: bool | None = None, period_s: Duration | None = None, role: str | None = None) -> AuthInfo

Create a child (or orphan, no_parent=True) token: POST auth/token/create.

login

login(method: AuthMethod, *, set_token: bool = True, auto_renew: bool | Mapping[str, Any] = False) -> AuthInfo

Log in with an auth method and (by default) use the new token for this client.

Failed logins raise :class:AuthenticationError. auto_renew=True (or a mapping of :meth:start_renewer keyword arguments) starts a :class:TokenRenewer that logs in again with the same method when the token can no longer be renewed.

lookup_self

lookup_self() -> TokenInfo

Properties of the client token: GET auth/token/lookup-self.

renew_self

renew_self(increment_s: Duration | None = None) -> AuthInfo

Renew the client token (POST auth/token/renew-self).

increment_s requests a TTL; the granted TTL is lease_duration_s (capped by the maximum TTL). Non-renewable tokens raise :class:ValidationError.

revoke_self

revoke_self() -> None

Revoke the client token (POST auth/token/revoke-self) and forget it.

start_renewer

start_renewer(**options: Any) -> TokenRenewer

Start a :class:TokenRenewer for the current token (TTL from lookup_self()).

Keyword arguments: reauth, increment_s, renew_fraction, min_delay_s, on_renew, on_error, on_expire. Stopped by client.close().

stop_renewers

stop_renewers() -> None

Stop every renewer started through this API (idempotent).

AuthInfo

Result of a login or token creation. The token and accessor are :class:Secret.

AuthMethod

Bases: abc.ABC

An auth method usable with client.auth.login(method).

Implement :meth:login_operation to add a method (use :func:login_post).

method class-attribute

method = ''

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

login_operation

login_operation() -> Op[AuthInfo]

The login as an SDK operation (a generator of requests).

secrets

secrets() -> list[str]

Credential values to redact from error messages.

AuthenticationError

Bases: grow_hashicorp_vault._core.errors.VaultError

Credentials missing or rejected (HTTP 401).

code class-attribute

code = <ErrorCode.AUTHENTICATION: 'AUTHENTICATION'>

Canonical error codes; the value is the wire form used by the conformance suite.

BaseConfig

Common, immutable client settings. Durations are float seconds (timedelta accepted).

Service configs subclass this (@dataclass(frozen=True, repr=False)), override url with the service default, add their own fields (Secret for credentials), extend :meth:_env_values and :meth:validate, and list vendor variables in ENV_VENDOR.

ENV_VENDOR class-attribute

ENV_VENDOR = {}

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

connect_timeout class-attribute

connect_timeout = 10.0

Convert a string or number to a floating-point number, if possible.

request_timeout class-attribute

request_timeout = 30.0

Convert a string or number to a floating-point number, if possible.

total_timeout class-attribute

total_timeout = 120.0

Convert a string or number to a floating-point number, if possible.

url class-attribute

url = ''

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

from_env classmethod

from_env(env: Mapping[str, str] | None = None, **overrides: Any) -> _C

Build from the environment, then validate.

Precedence: explicit keyword > GROW_HASHICORP_VAULT_<NAME> > vendor variables > default. env defaults to os.environ; pass a dict in tests.

known_secrets

known_secrets() -> list[str]

Revealed values of every :class:Secret field (used to redact error text).

validate

validate() -> _C

Check the common rules; raise :class:ConfigError. Returns self.

BaseSecretsProvider

Bases: abc.ABC

Implements :class:SecretsProvider on top of five primitives a service provides.

Primitives (opts are the option dataclasses):

  • _fetch_secret(name, GetOptions) -> SecretValue | None (None when missing)
  • _list_secrets(path) -> list[SecretMetadata] (secrets directly under path)
  • _put_secret(name, data: bytes, SetOptions) -> str (new version or "")
  • _remove_secret(name, DeleteOptions) -> None (raise :class:NotFoundError if missing)
  • _fetch_metadata(name, GetOptions) -> SecretMetadata | None

Watchers started with :meth:watch are stopped by :meth:close and, when owner is given (the client's registry), by client.close(). After :meth:close every call raises :class:CancelledError (": client is closed") before any primitive runs.

closed property

closed

True once :meth:close was called.

close

close() -> None

Stop every watcher started by this provider; later calls raise CANCELLED (idempotent).

delete

delete(name: str, *, path: str | None = None, versions: Sequence[str] | None = None, permanent: bool = False) -> None

Delete a secret; :class:NotFoundError when it does not exist.

ensure_open

ensure_open(op: str) -> None

Raise :class:CancelledError (": client is closed") after :meth:close.

Service methods that do not go through the base operations can call it first.

get

get(name: str, *, version: str | None = None, path: str | None = None) -> SecretValue | None

The secret, or None when it does not exist.

get_all

get_all(path: str | None = None) -> dict[str, SecretValue]

Every secret directly under path (non-recursive), keyed by name.

get_bool

get_bool(name: str, *, version: str | None = None, path: str | None = None) -> bool | None

true/false/1/0/yes/no/on/off, None when missing; else ValidationError.

get_json

get_json(name: str, *, version: str | None = None, path: str | None = None) -> Any

Decoded JSON, None when missing; :class:ValidationError when not JSON.

get_many

get_many(names: Sequence[str], *, version: str | None = None, path: str | None = None) -> dict[str, SecretValue]

Values in request order; missing names are omitted.

get_number

get_number(name: str, *, version: str | None = None, path: str | None = None) -> int | float | None

int or float, None when missing; :class:ValidationError otherwise.

list

list(prefix: str | None = None) -> builtins.list[SecretMetadata]

Metadata of the secrets under prefix, sorted by name.

load_env

load_env(source: str | Mapping[str, str], *, override: bool = False, prefix: str = '', environ: MutableMapping[str, str] | None = None) -> dict[str, str]

Export secrets to environment variables; returns {env_name: secret_name}.

source is a path (one variable per secret directly under it, named from the secret name relative to the path, upper-cased, non [A-Z0-9_] → _, plus prefix) or a mapping {env_name: secret_name} (a missing secret raises :class:NotFoundError before anything is set). Existing variables are kept unless override. environ defaults to :data:os.environ.

require

require(name: str, *, version: str | None = None, path: str | None = None) -> SecretValue

The secret; :class:NotFoundError when missing.

set

set(name: str, value: Any, *, path: str | None = None, cas: int | None = None, tags: Mapping[str, str] | None = None, description: str | None = None) -> str

Store value (str, bytes, or JSON-encoded object); returns the new version.

watch

watch(name: str, interval_s: float | timedelta, on_change: Callable, *, on_error: Callable | None = None, version: str | None = None, path: str | None = None) -> WatchHandle

Poll name every interval_s and call on_change(new, old) on change.

CacheStats

CacheStats(hits: 'int', misses: 'int', evictions: 'int', refreshes: 'int', size: 'int')

CancelToken

Thread-safe cancellation flag passed to sync calls as cancel=.

Cancelling interrupts an in-flight request (the call returns immediately with :class:CancelledError; the abandoned HTTP exchange finishes in the background) and any retry backoff sleep.

cancel

cancel() -> None

Request cancellation (idempotent).

on_cancel

on_cancel(callback: Callable[[], None]) -> Callable[[], None]

Run callback on cancellation (now if already cancelled); returns an unregister.

wait

wait(timeout: float | None = None) -> bool

Block until cancelled or timeout; return whether the token is cancelled.

CancelledError

Bases: grow_hashicorp_vault._core.errors.VaultError, asyncio.exceptions.CancelledError

The caller cancelled the operation (task cancel, :class:CancelToken, client close).

Also an :class:asyncio.CancelledError so asyncio keeps treating the task as cancelled.

code class-attribute

code = <ErrorCode.CANCELLED: 'CANCELLED'>

Canonical error codes; the value is the wire form used by the conformance suite.

Capabilities

Bases: builtins.dict

Capabilities per requested path ({"secret/data/app/db": ["read", "update"]}).

A plain dict with one helper, :meth:allows.

allows

allows(path: str, capability: str) -> bool

Whether path grants capability: root grants everything, deny and a path that was not requested grant nothing.

CertificateInfo

Result of :meth:Pki.read_certificate.

revoked property

revoked

Whether the certificate is revoked.

Ciphertext

Ciphertext vault:v<n>:<base64> and the key version that produced it.

ConfigError

Bases: grow_hashicorp_vault._core.errors.VaultError

Invalid or missing configuration.

code class-attribute

code = <ErrorCode.CONFIG: 'CONFIG'>

Canonical error codes; the value is the wire form used by the conformance suite.

ConflictError

Bases: grow_hashicorp_vault._core.errors.VaultError

Conflict or failed precondition (HTTP 409, 412, CAS mismatch).

code class-attribute

code = <ErrorCode.CONFLICT: 'CONFLICT'>

Canonical error codes; the value is the wire form used by the conformance suite.

ConnectionInfo

A connection as returned by :meth:Database.read_connection (never the password).

DataKey

A data key: ciphertext decrypts (with the transit key) to plaintext.

Database

Bases: grow_hashicorp_vault._api.SyncModule

Database engine on one mount: client.database(mount="database").

configure_connection

configure_connection(name: str, *, plugin_name: str, connection_url: str, username: str | None = None, password: str | Secret | None = None, allowed_roles: Sequence[str] | None = None, verify_connection: bool | None = None, extra: Mapping[str, Any] | None = None) -> None

Create or replace a connection (POST <mount>/config/<name>, verified by default).

connection_url uses {{username}}/{{password}} templates; extra holds plugin-specific fields sent as is (snake_case).

create_role

create_role(name: str, *, db_name: str, creation_statements: Sequence[str], revocation_statements: Sequence[str] | None = None, renew_statements: Sequence[str] | None = None, rollback_statements: Sequence[str] | None = None, default_ttl_s: Duration | None = None, max_ttl_s: Duration | None = None) -> None

Create or replace a dynamic role (POST <mount>/roles/<name>).

Statements use {{name}}, {{password}} and {{expiration}}.

delete_connection

delete_connection(name: str) -> None

Delete a connection.

delete_role

delete_role(name: str) -> None

Delete a role.

get_credentials

get_credentials(role: str) -> Lease[DatabaseCredentials]

Generate credentials for a role (GET <mount>/creds/<role>).

Keep them alive with client.leases.manage(lease, on_expire=...). Unknown roles raise :class:ValidationError. Never retried (every call creates new credentials).

read_connection

read_connection(name: str) -> ConnectionInfo

Read a connection (without its password); :class:NotFoundError when missing.

read_role

read_role(name: str) -> RoleInfo

Read a role; :class:NotFoundError when missing.

DatabaseCredentials

Dynamic database credentials (the password is a :class:Secret).

DecryptBatchItem

One item of :meth:Transit.decrypt_batch.

DecryptBatchResult

Result of one batch item; error is set when this item failed.

DeleteOptions

DeleteOptions(path: 'str | None' = None, versions: 'Sequence[str] | None' = None, permanent: 'bool' = False)

permanent class-attribute

permanent = False

Returns True when the argument is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

EncryptBatchItem

One item of :meth:Transit.encrypt_batch.

EncryptBatchResult

Result of one batch item; error is set when this item failed.

EnvReader

Reads GROW_<KEY_UPPER>_<NAME> and vendor variables from an injectable mapping.

Every getter returns None when no variable is set (empty strings count as unset). A present but invalid value raises :class:ConfigError that names the variable, never its value.

duration

duration(name: str, vendor_names: Iterable[str] = ()) -> builtins.float | None

Duration in seconds.

lookup

lookup(name: str, vendor_names: Iterable[str] = ()) -> tuple[str, str] | None

Return (variable_name, raw_value) for the first variable that is set.

ErrorCode

Bases: builtins.str, enum.Enum

Canonical error codes; the value is the wire form used by the conformance suite.

AUTHENTICATION class-attribute

AUTHENTICATION = <ErrorCode.AUTHENTICATION: 'AUTHENTICATION'>

Canonical error codes; the value is the wire form used by the conformance suite.

CANCELLED class-attribute

CANCELLED = <ErrorCode.CANCELLED: 'CANCELLED'>

Canonical error codes; the value is the wire form used by the conformance suite.

CONFIG class-attribute

CONFIG = <ErrorCode.CONFIG: 'CONFIG'>

Canonical error codes; the value is the wire form used by the conformance suite.

CONFLICT class-attribute

CONFLICT = <ErrorCode.CONFLICT: 'CONFLICT'>

Canonical error codes; the value is the wire form used by the conformance suite.

NOT_FOUND class-attribute

NOT_FOUND = <ErrorCode.NOT_FOUND: 'NOT_FOUND'>

Canonical error codes; the value is the wire form used by the conformance suite.

PERMISSION_DENIED class-attribute

PERMISSION_DENIED = <ErrorCode.PERMISSION_DENIED: 'PERMISSION_DENIED'>

Canonical error codes; the value is the wire form used by the conformance suite.

RATE_LIMITED class-attribute

RATE_LIMITED = <ErrorCode.RATE_LIMITED: 'RATE_LIMITED'>

Canonical error codes; the value is the wire form used by the conformance suite.

TIMEOUT class-attribute

TIMEOUT = <ErrorCode.TIMEOUT: 'TIMEOUT'>

Canonical error codes; the value is the wire form used by the conformance suite.

UNAVAILABLE class-attribute

UNAVAILABLE = <ErrorCode.UNAVAILABLE: 'UNAVAILABLE'>

Canonical error codes; the value is the wire form used by the conformance suite.

UNSUPPORTED class-attribute

UNSUPPORTED = <ErrorCode.UNSUPPORTED: 'UNSUPPORTED'>

Canonical error codes; the value is the wire form used by the conformance suite.

VALIDATION class-attribute

VALIDATION = <ErrorCode.VALIDATION: 'VALIDATION'>

Canonical error codes; the value is the wire form used by the conformance suite.

ErrorInfo

Passed to Hooks.on_error; error is the (redacted) SDK error.

GetOptions

GetOptions(version: 'str | None' = None, path: 'str | None' = None)

HealthResponse

Raw sys/health answer (sealed/standby/uninitialised nodes are no error).

HealthStatus

Result of health(); status is ok/degraded/unhealthy/unreachable or a vendor word.

Hooks

Optional callbacks invoked on every attempt. Exceptions raised by hooks are ignored.

HttpTransport

Synchronous transport (one per client).

Service options (all optional):

  • request_id_headers: vendor request id headers, checked before :data:REQUEST_ID_HEADERS.
  • retry_after_headers: headers read (in order) for the delay a 429/503 response asks for; default ("retry-after",), e.g. ("retry-after", "x-ratelimit-reset"). See :func:retry_after_from_headers.
  • error_mapper: mapper(error, response) returns a service-specific error for an HTTP error response (or None to keep the default). The mapped error is what Hooks.on_error, the retry planner (retry_after) and the caller see; whether a status is retried stays the SPEC rule. Exceptions raised by the mapper are logged and ignored.

Every call after :meth:close raises :class:CancelledError ("client is closed").

close

close() -> None

Close the connection pool and abort backoff sleeps (idempotent).

request

request(req: Request, *, cancel: CancelToken | None = None) -> Response

Send req with retries; return the response or raise the mapped error.

IssuedCertificate

Bases: grow_hashicorp_vault.pki.SignedCertificate

An issued certificate with its private key (a :class:Secret).

private_key_type class-attribute

private_key_type = ''

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

JwtAuth

Bases: grow_hashicorp_vault.auth.AuthMethod

JWT/OIDC login with a JWT: POST auth/<mount>/login {role, jwt}.

method class-attribute

method = 'jwt'

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

KubernetesAuth

Bases: grow_hashicorp_vault.auth.AuthMethod

Kubernetes login: POST auth/<mount>/login {role, jwt} with the service account token.

The token is read from jwt_path at login time unless jwt is given.

DEFAULT_JWT_PATH class-attribute

DEFAULT_JWT_PATH = '/var/run/secrets/kubernetes.io/serviceaccount/token'

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

method class-attribute

method = 'kubernetes'

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

KvMetadata

Metadata of a KV v2 secret (all versions).

KvMount

Bases: grow_hashicorp_vault._api.SyncModule, grow_hashicorp_vault.kv._KvBase

A KV mount whose version is detected on first use (or taken from config.kv_version); then delegates to the v1 or v2 behaviour. Version-only operations raise :class:UnsupportedError on v1 mounts.

delete

delete(path: str) -> None

Delete the secret (v2: soft-delete latest).

delete_metadata

delete_metadata(path: str) -> None

Delete all versions (KV v2 only).

delete_versions

delete_versions(path: str, versions: Sequence[int]) -> None

Soft-delete versions (KV v2 only).

destroy

destroy(path: str, versions: Sequence[int]) -> None

Destroy versions (KV v2 only).

list

list(path: str = '') -> list[str]

Keys directly under a folder (sub-folders end in /); [] when there is none.

Vault OSS has no list pagination: every key of the folder is returned.

patch

patch(path: str, data: Mapping[str, Any], *, cas: int | None = None) -> KvVersionMetadata

Merge keys into the latest version (RFC 7386: a None value removes the key).

read

read(path: str, *, version: int | None = None) -> KvSecret

Read the latest (or a given) version; :class:NotFoundError when missing, deleted or destroyed.

read_metadata

read_metadata(path: str) -> KvMetadata

Metadata of all versions (KV v2 only).

undelete

undelete(path: str, versions: Sequence[int]) -> None

Restore versions (KV v2 only).

version

version(path: str = '') -> KvVersion

The KV version of the mount (detected on first use).

write

write(path: str, data: Mapping[str, Any], *, cas: int | None = None) -> KvVersionMetadata | None

Write a new version (cas: the current version must equal it, 0 = create only).

A CAS mismatch raises :class:ConflictError.

write_metadata

write_metadata(path: str, *, max_versions: int | None = None, cas_required: bool | None = None, delete_version_after_s: Duration | None = None, custom_metadata: Mapping[str, str] | None = None) -> None

Update metadata settings (KV v2 only).

KvSecret

A KV secret: the key/value data and, on KV v2, the version metadata.

repr() hides the values.

KvV1

Bases: grow_hashicorp_vault._api.SyncModule, grow_hashicorp_vault.kv._KvBase

KV version 1 (unversioned) mount; version-only operations raise :class:UnsupportedError.

version class-attribute

version = 1

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.int(). For floating-point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral.

int('0b100', base=0) 4

delete

delete(path: str) -> None

Delete a secret (missing paths are not an error).

delete_metadata

delete_metadata(*args: Any, **kwargs: Any) -> Any

Not supported by KV version 1 (:class:UnsupportedError): deleteMetadata.

delete_versions

delete_versions(*args: Any, **kwargs: Any) -> Any

Not supported by KV version 1 (:class:UnsupportedError): deleteVersions.

destroy

destroy(*args: Any, **kwargs: Any) -> Any

Not supported by KV version 1 (:class:UnsupportedError): destroy.

list

list(path: str = '') -> list[str]

Keys directly under a folder (sub-folders end in /); [] when there is none.

patch

patch(*args: Any, **kwargs: Any) -> Any

Not supported by KV version 1 (:class:UnsupportedError): patch.

read

read(path: str, *, version: int | None = None) -> KvSecret

Read a secret; :class:NotFoundError when missing (version is v2 only).

read_metadata

read_metadata(*args: Any, **kwargs: Any) -> Any

Not supported by KV version 1 (:class:UnsupportedError): readMetadata.

undelete

undelete(*args: Any, **kwargs: Any) -> Any

Not supported by KV version 1 (:class:UnsupportedError): undelete.

write

write(path: str, data: Mapping[str, Any], *, cas: int | None = None) -> KvVersionMetadata | None

Write (replace) a secret; returns None on KV v1 (cas is v2 only).

write_metadata

write_metadata(*args: Any, **kwargs: Any) -> Any

Not supported by KV version 1 (:class:UnsupportedError): writeMetadata.

KvV2

Bases: grow_hashicorp_vault._api.SyncModule, grow_hashicorp_vault.kv._KvBase

KV version 2 (versioned) mount.

version class-attribute

version = 2

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.int(). For floating-point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral.

int('0b100', base=0) 4

delete

delete(path: str) -> None

Soft-delete the latest version (missing paths are not an error).

delete_metadata

delete_metadata(path: str) -> None

Delete the secret with all versions and metadata.

delete_versions

delete_versions(path: str, versions: Sequence[int]) -> None

Soft-delete the given versions.

destroy

destroy(path: str, versions: Sequence[int]) -> None

Permanently destroy versions.

list

list(path: str = '') -> list[str]

Keys directly under a folder (sub-folders end in /); [] when there is none.

Vault OSS has no list pagination: every key of the folder is returned.

patch

patch(path: str, data: Mapping[str, Any], *, cas: int | None = None) -> KvVersionMetadata

Merge keys into the latest version (RFC 7386: a None value removes the key).

read

read(path: str, *, version: int | None = None) -> KvSecret

Read the latest (or a given) version; :class:NotFoundError when missing, deleted or destroyed.

read_metadata

read_metadata(path: str) -> KvMetadata

Metadata of all versions; :class:NotFoundError when missing.

undelete

undelete(path: str, versions: Sequence[int]) -> None

Restore soft-deleted versions.

write

write(path: str, data: Mapping[str, Any], *, cas: int | None = None) -> KvVersionMetadata | None

Write a new version (cas: the current version must equal it, 0 = create only).

A CAS mismatch raises :class:ConflictError.

write_metadata

write_metadata(path: str, *, max_versions: int | None = None, cas_required: bool | None = None, delete_version_after_s: Duration | None = None, custom_metadata: Mapping[str, str] | None = None) -> None

Update the metadata settings of a secret.

KvVersionMetadata

Metadata of one KV v2 version.

LeaderStatus

sys/leader.

performance_standby class-attribute

performance_standby = False

Returns True when the argument is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

performance_standby_last_remote_wal class-attribute

performance_standby_last_remote_wal = 0

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.int(). For floating-point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral.

int('0b100', base=0) 4

Lease

Bases: typing.Generic

A lease on a dynamic secret (e.g. database credentials).

LeaseInfo

Result of :meth:LeaseManager.lookup.

LeaseManager

Bases: grow_hashicorp_vault._api.SyncModule

Lease operations and automatic renewal: client.leases.

active_leases property

active_leases

Number of managed leases.

lookup

lookup(lease_id: str) -> LeaseInfo

Lease details (PUT sys/leases/lookup); unknown leases raise :class:ValidationError.

manage

manage(lease: Lease[Any], *, increment_s: Duration | None = None, renew_fraction: float = 0.6666666666666666, min_delay_s: float = 0.5, on_renew: Callable[[LeaseRenewal], None] | None = None, on_error: Callable[[BaseException], None] | None = None, on_expire: Callable[[], None] | None = None, revoke_on_stop: bool = False, clock: Callable[[], float] | None = None, wait: Callable[[float], bool] | None = None, background: bool = True) -> ManagedLease

Keep a lease alive in a background thread.

Renews at 2/3 of its TTL until the maximum TTL is reached, then calls on_expire once when it expires. Stopped by the handle, :meth:stop_all or client.close().

renew

renew(lease_id: str, increment_s: Duration | None = None) -> LeaseRenewal

Renew a lease (PUT sys/leases/renew).

A TTL beyond the maximum is capped (see warnings); unknown or revoked leases raise :class:ValidationError.

revoke

revoke(lease_id: str) -> None

Revoke a lease now (PUT sys/leases/revoke).

revoke_prefix

revoke_prefix(prefix: str) -> None

Revoke every lease under a prefix (PUT sys/leases/revoke-prefix/<prefix>).

stop_all

stop_all() -> None

Stop every managed lease (revoking those with revoke_on_stop). Idempotent.

LeaseRenewal

Result of :meth:LeaseManager.renew.

LeaseState

Remaining lifetime of a token or lease.

LoggerLike

Bases: typing.Protocol

Structured logger interface accepted in configuration (SPEC Logger).

ManagedLease

Handle of a lease kept alive by :meth:LeaseManager.manage.

expired property

expired

Whether on_expire fired.

expires_at property

expires_at

Expiry of the current lease.

running property

running

Whether renewal is still active.

stop

stop() -> None

Stop renewing (and revoke when revoke_on_stop). Idempotent.

MountInfo

A secrets engine or auth method mount.

NotFoundError

Bases: grow_hashicorp_vault._core.errors.VaultError

Missing record (HTTP 404).

code class-attribute

code = <ErrorCode.NOT_FOUND: 'NOT_FOUND'>

Canonical error codes; the value is the wire form used by the conformance suite.

PermissionDeniedError

Bases: grow_hashicorp_vault._core.errors.VaultError

Authenticated but not allowed (HTTP 403).

code class-attribute

code = <ErrorCode.PERMISSION_DENIED: 'PERMISSION_DENIED'>

Canonical error codes; the value is the wire form used by the conformance suite.

Pki

Bases: grow_hashicorp_vault._api.SyncModule

PKI engine on one mount: client.pki(mount="pki").

issue_certificate

issue_certificate(role: str, common_name: str, *, alt_names: Sequence[str] | None = None, ip_sans: Sequence[str] | None = None, uri_sans: Sequence[str] | None = None, ttl_s: Duration | None = None, format: Literal['pem', 'der', 'pem_bundle'] | None = None, private_key_format: Literal['der', 'pkcs8'] | None = None, exclude_cn_from_sans: bool | None = None) -> IssuedCertificate

Issue a certificate and private key for a role (POST <mount>/issue/<role>).

A common name the role does not allow raises :class:ValidationError.

list_certificates

list_certificates() -> list[str]

Serials of all stored certificates; [] when there is none.

read_ca_chain

read_ca_chain() -> str

The CA chain as PEM text (GET <mount>/ca_chain, raw PEM).

read_certificate

read_certificate(serial: str) -> CertificateInfo

A certificate by serial; :class:NotFoundError when unknown.

revoke_certificate

revoke_certificate(serial: str) -> RevocationInfo

Revoke a certificate by serial (aa:bb:...); unknown serials raise :class:ValidationError.

sign_csr

sign_csr(role: str, csr: str, *, common_name: str | None = None, alt_names: Sequence[str] | None = None, ip_sans: Sequence[str] | None = None, uri_sans: Sequence[str] | None = None, ttl_s: Duration | None = None, format: Literal['pem', 'der', 'pem_bundle'] | None = None, exclude_cn_from_sans: bool | None = None) -> SignedCertificate

Sign a PEM CSR for a role (POST <mount>/sign/<role>).

tidy

tidy(*, tidy_cert_store: bool = True, tidy_revoked_certs: bool = True, safety_buffer_s: Duration | None = None, wait: bool = True, timeout_s: Duration = 60.0, interval_s: Duration = 0.5) -> TidyStatus

Start a tidy run (POST <mount>/tidy, 202).

Unless wait=False, poll tidy-status until it is Finished, Error or Cancelled (:class:TimeoutError after timeout_s). Returns the last status.

tidy_status

tidy_status() -> TidyStatus

Current tidy progress (GET <mount>/tidy-status).

Policy

An ACL policy.

RateLimitError

Bases: grow_hashicorp_vault._core.errors.VaultError

Too many requests (HTTP 429); retry_after holds the requested delay when known.

code class-attribute

code = <ErrorCode.RATE_LIMITED: 'RATE_LIMITED'>

Canonical error codes; the value is the wire form used by the conformance suite.

default_retryable class-attribute

default_retryable = True

Returns True when the argument is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

RawResponse

Result of :meth:VaultClient.request: the decoded Vault envelope.

Request

One logical API call (possibly several attempts).

path is joined to the base URL ({name} style values must already be encoded; use :func:urllib.parse.quote); an absolute http:///https:// URL is used as is (for pagination links the service returns; the default headers, config.headers included, are sent there too, so only pass URLs of the same service). json is encoded when not None; content sends raw bytes. idempotent overrides the method rule; an idempotency_key sends the Idempotency-Key header and marks the request idempotent. raise_for_status=False returns error responses instead of raising (retries still apply). Statuses in allow_status are expected answers (a 404 that carries data, a health endpoint's 503): the response is returned at once, like a success, without retries or on_error.

allow_status class-attribute

allow_status = ()

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

operation class-attribute

operation = ''

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

raise_for_status class-attribute

raise_for_status = True

Returns True when the argument is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

RequestInfo

Passed to Hooks.on_request; url and headers are redacted.

ResourceRegistry

Holds :class:Stoppable objects; :meth:stop_all stops each once, ignoring errors.

register

register(item: Stoppable) -> None

Track item; when the registry is already closed the item is stopped now.

Response

A completed HTTP response (body fully read).

attempts class-attribute

attempts = 1

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.int(). For floating-point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral.

int('0b100', base=0) 4

operation class-attribute

operation = ''

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

json

json() -> Any

Decode the body as JSON; :class:ValidationError when it is not valid JSON.

ResponseInfo

Passed to Hooks.on_response; headers are the redacted response headers (rate limit headers and the like stay readable).

RetryPolicy

Retry settings. Durations are seconds (datetime.timedelta is accepted).

Backoff for retry n (0-based) is full jitter: random(0, min(max_backoff, initial_backoff * multiplier ** n)).

random returns a float in [0, 1); inject it in tests for deterministic sleeps.

initial_backoff class-attribute

initial_backoff = 0.1

Convert a string or number to a floating-point number, if possible.

max_attempts property

max_attempts

Total attempts including the first one.

max_backoff class-attribute

max_backoff = 10.0

Convert a string or number to a floating-point number, if possible.

max_retries class-attribute

max_retries = 3

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.int(). For floating-point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral.

int('0b100', base=0) 4

max_retry_after class-attribute

max_retry_after = 60.0

Convert a string or number to a floating-point number, if possible.

multiplier class-attribute

multiplier = 2.0

Convert a string or number to a floating-point number, if possible.

backoff

backoff(retry: int) -> float

Full-jitter sleep in seconds before retry retry (0-based).

backoff_cap

backoff_cap(retry: int) -> float

Upper bound of the jittered sleep before retry retry (0-based).

random builtin

random()

random() -> x in the interval [0, 1).

RevocationInfo

Result of :meth:Pki.revoke_certificate.

RoleInfo

A role as returned by :meth:Database.read_role.

SealStatus

sys/seal-status.

Secret

Wraps a credential so it never shows up in str/repr/logs.

s = Secret("hunter2") str(s), s.reveal() ('[REDACTED]', 'hunter2')

reveal

reveal() -> str

Return the wrapped value.

SecretCache

Bases: grow_hashicorp_vault._secrets.base.BaseSecretsProvider

Caches reads of a :class:SecretsProvider; writes pass through and invalidate.

  • Entries live ttl_s; negative results (missing secrets) are cached too.
  • Refresh-ahead: a hit after ttl_s * refresh_ahead_factor starts one background refresh.
  • Stale-while-revalidate: up to ttl_s + stale_while_revalidate_s the stale value is returned while one refresh runs.
  • LRU eviction beyond max_entries. clock (monotonic seconds) is injectable; spawn runs background refreshes (default: a daemon thread).
  • :meth:close makes later calls raise :class:CancelledError ("client is closed"); it does not close the wrapped provider.

invalidate

invalidate(name: str) -> None

Drop every cached entry for name.

watch

watch(name: str, interval_s: float | timedelta, on_change: Callable, *, on_error: Callable | None = None, version: str | None = None, path: str | None = None) -> WatchHandle

Watches the underlying provider directly (bypasses the cache).

SecretIdInfo

A generated AppRole secret id (:class:Secret values).

SecretMetadata

Names and metadata of a secret (never its value).

get(meta.name, path=meta.path) fetches the secret the metadata describes.

SecretValue

Redacting wrapper around a secret's bytes.

str()/repr() print SecretValue([REDACTED]); use :meth:reveal, :meth:reveal_bytes or :meth:json to read the value.

fingerprint

fingerprint() -> str

SHA-256 hex digest of the value (used by watch when there is no version).

json

json() -> Any

The value decoded as JSON; :class:ValidationError when it is not JSON.

reveal

reveal() -> str

The value as UTF-8 text; :class:ValidationError for non-UTF-8 binary data.

reveal_bytes

reveal_bytes() -> bytes

The raw bytes.

SecretsProvider

Bases: typing.Protocol

Synchronous secrets interface implemented by every secrets service package.

ServiceError

Bases: builtins.Exception

Base class of every error raised by this SDK.

Attributes:

Name Type Description
code

canonical :class:ErrorCode.

message

human readable text; never contains credentials or raw response bodies.

http_status

HTTP status when the error came from a response.

request_id

vendor request id header when present.

retryable

whether retrying the same call may succeed.

retry_after

server requested delay in seconds (rate limiting / unavailable).

cause property

cause

The underlying error, if any.

code class-attribute

code = <ErrorCode.UNAVAILABLE: 'UNAVAILABLE'>

Canonical error codes; the value is the wire form used by the conformance suite.

default_retryable class-attribute

default_retryable = False

Returns True when the argument is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

SetOptions

SetOptions(path: 'str | None' = None, cas: 'int | None' = None, tags: 'Mapping[str, str] | None' = None, description: 'str | None' = None)

Signature

A signature vault:v<n>:<base64>.

SignedCertificate

A certificate issued or signed by the PKI engine.

Stoppable

Bases: typing.Protocol

Sys

Bases: grow_hashicorp_vault._api.SyncModule

System backend: client.sys. Most write calls need a privileged (root/sudo) token.

capabilities

capabilities(token: str | Secret, paths: str | Sequence[str]) -> Capabilities

Another token's capabilities on each path (POST sys/capabilities).

The caller needs update on sys/capabilities; otherwise :class:PermissionDeniedError. paths is one path or a list.

capabilities_self

capabilities_self(paths: str | Sequence[str]) -> Capabilities

The client token's capabilities on each path (POST sys/capabilities-self).

paths is one path or a list. Returns a :class:Capabilities map from each requested path to its capabilities (create, read, update, patch, delete, list, sudo, root or deny)::

caps = client.sys.capabilities_self(["secret/data/app/db"])
if caps.allows("secret/data/app/db", "read"): ...

create_app_role

create_app_role(name: str, *, mount: str = 'approle', token_policies: Sequence[str] | None = None, token_ttl_s: Duration | None = None, token_max_ttl_s: Duration | None = None, secret_id_ttl_s: Duration | None = None, secret_id_num_uses: int | None = None, bind_secret_id: bool | None = None, token_type: str | None = None) -> None

Create or update an AppRole role (POST auth/<mount>/role/<name>).

delete_app_role

delete_app_role(name: str, *, mount: str = 'approle') -> None

Delete an AppRole role.

delete_policy

delete_policy(name: str) -> None

Delete an ACL policy.

disable_auth_method

disable_auth_method(path: str) -> None

Disable an auth method; its tokens are revoked.

disable_secrets_engine

disable_secrets_engine(path: str) -> None

Disable (unmount) a secrets engine; its data is deleted.

enable_auth_method

enable_auth_method(path: str, type: str, *, description: str | None = None, default_lease_ttl_s: Duration | None = None, max_lease_ttl_s: Duration | None = None, local: bool | None = None) -> None

Enable an auth method at path.

enable_secrets_engine

enable_secrets_engine(path: str, type: str, *, description: str | None = None, options: Mapping[str, str] | None = None, default_lease_ttl_s: Duration | None = None, max_lease_ttl_s: Duration | None = None, local: bool | None = None, seal_wrap: bool | None = None) -> None

Enable a secrets engine at path (e.g. type="kv", options={"version": "2"}).

A used path raises :class:ValidationError.

generate_secret_id

generate_secret_id(name: str, *, mount: str = 'approle', metadata: Mapping[str, str] | None = None, cidr_list: Sequence[str] | None = None, ttl_s: Duration | None = None, num_uses: int | None = None) -> SecretIdInfo

Generate a new secret id for an AppRole role.

health

health() -> HealthResponse

GET sys/health (unauthenticated); sealed, standby and uninitialised nodes are no error.

leader

leader() -> LeaderStatus

GET sys/leader (unauthenticated).

list_app_roles

list_app_roles(*, mount: str = 'approle') -> list[str]

AppRole role names; [] when there is none.

list_auth_methods

list_auth_methods() -> dict[str, MountInfo]

Auth methods by path ("approle/" → info).

list_mounts

list_mounts() -> dict[str, MountInfo]

Secrets engines by path ("secret/" → info).

list_policies

list_policies() -> list[str]

ACL policy names (includes default and root).

read_policy

read_policy(name: str) -> Policy

Read an ACL policy; :class:NotFoundError when missing.

read_role_id

read_role_id(name: str, *, mount: str = 'approle') -> str

The role id of an AppRole role; :class:NotFoundError for unknown roles.

seal_status

seal_status() -> SealStatus

GET sys/seal-status (unauthenticated).

version

version() -> str

Server version from sys/health (e.g. 2.2.2).

write_policy

write_policy(name: str, policy: str) -> None

Create or replace an ACL policy (PUT sys/policies/acl/<name>); invalid HCL raises :class:ValidationError.

TidyStatus

Tidy progress from <mount>/tidy-status.

TimeoutError

Bases: grow_hashicorp_vault._core.errors.VaultError

A connect, request or total deadline was exceeded (also HTTP 408, 504).

code class-attribute

code = <ErrorCode.TIMEOUT: 'TIMEOUT'>

Canonical error codes; the value is the wire form used by the conformance suite.

default_retryable class-attribute

default_retryable = True

Returns True when the argument is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

TlsConfig

TLS settings. insecure_skip_verify is for tests only and logs a warning once.

insecure_skip_verify class-attribute

insecure_skip_verify = False

Returns True when the argument is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

TokenAuth

Bases: grow_hashicorp_vault.auth.AuthMethod

Uses an existing token; login checks it with lookup-self.

method class-attribute

method = 'token'

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

TokenInfo

Token properties from :meth:Auth.lookup_self.

TokenRenewal

One renewal or re-login seen by a :class:TokenRenewer on_renew callback.

TokenRenewer

Renews the client token at 2/3 of its TTL (renew-self).

When the token cannot be renewed any more it logs in again with reauth or calls on_expire once at expiry. Stopped by :meth:stop or client.close(). Create it with :meth:Auth.start_renewer (or login(..., auto_renew=True)).

expired property

expired

Whether on_expire fired.

expires_at property

expires_at

Expiry of the current token, None when it never expires or is unknown.

running property

running

Whether the renewer is active.

start

start(initial: LeaseState | None = None, *, background: bool = True) -> None

Start renewing; without initial the TTL is read with lookup_self().

A token without TTL (e.g. root) needs no renewal; the renewer then stays idle.

stop

stop() -> None

Stop renewing (idempotent).

Transit

Bases: grow_hashicorp_vault._api.SyncModule

Transit engine on one mount: client.transit(mount="transit").

create_key

create_key(name: str, type: str = 'aes256-gcm96', *, exportable: bool | None = None, derived: bool | None = None, auto_rotate_period_s: Duration | None = None, allow_plaintext_backup: bool | None = None, key_size: int | None = None) -> TransitKey

Create a key (idempotent: an existing key is returned unchanged).

Types: aes128-gcm96, aes256-gcm96 (default), chacha20-poly1305, ed25519, ecdsa-p256/-p384/-p521, rsa-2048/-3072/-4096, hmac …

decrypt

decrypt(name: str, ciphertext: str, *, context: TransitInput | None = None, associated_data: TransitInput | None = None) -> bytes

Decrypt a vault:v<n>: ciphertext; returns the plaintext bytes.

decrypt_batch

decrypt_batch(name: str, items: Sequence[DecryptBatchItem]) -> list[DecryptBatchResult]

Decrypt many items in one request; see :meth:Transit.encrypt_batch for errors.

delete_key

delete_key(name: str) -> None

Delete a key (needs deletion_allowed=True, else :class:ValidationError).

encrypt

encrypt(name: str, plaintext: TransitInput, *, context: TransitInput | None = None, key_version: int | None = None, associated_data: TransitInput | None = None) -> Ciphertext

Encrypt plaintext (text is UTF-8 encoded).

encrypt_batch

encrypt_batch(name: str, items: Sequence[EncryptBatchItem]) -> list[EncryptBatchResult]

Encrypt many items in one request.

Results are in input order; a failed item has error set (the call itself fails only when the whole request fails).

generate_data_key

generate_data_key(name: str, *, plaintext: bool = True, bits: Literal[128, 256, 512] = 256, context: TransitInput | None = None) -> DataKey

Generate a data key encrypted with the transit key (plus its plaintext by default).

hash

hash(input: TransitInput, *, algorithm: str | None = None, format: Literal['hex', 'base64'] | None = None) -> str

Hash of input (default sha2-256, hex).

hmac

hmac(name: str, input: TransitInput, *, algorithm: str | None = None, key_version: int | None = None) -> str

HMAC of input (vault:v<n>:<base64>).

list_keys

list_keys() -> list[str]

Key names (sorted); [] when there is none (no pagination on Vault OSS).

random_bytes

random_bytes(bytes: int, *, format: Literal['hex', 'base64'] = 'base64') -> str

bytes random bytes from the server, encoded as base64 (default) or hex.

read_key

read_key(name: str) -> TransitKey

Read a key; :class:NotFoundError when missing.

rewrap

rewrap(name: str, ciphertext: str, *, context: TransitInput | None = None, key_version: int | None = None) -> Ciphertext

Re-encrypt a ciphertext with the latest (or given) key version without revealing it.

rotate_key

rotate_key(name: str) -> TransitKey

Add a new key version; returns the updated key.

sign

sign(name: str, input: TransitInput, *, hash_algorithm: str | None = None, signature_algorithm: Literal['pss', 'pkcs1v15'] | None = None, prehashed: bool | None = None, key_version: int | None = None, context: TransitInput | None = None) -> Signature

Sign input with an asymmetric key (symmetric keys raise :class:ValidationError).

update_key_config

update_key_config(name: str, *, deletion_allowed: bool | None = None, min_decryption_version: int | None = None, min_encryption_version: int | None = None, exportable: bool | None = None, allow_plaintext_backup: bool | None = None, auto_rotate_period_s: Duration | None = None) -> TransitKey

Update key settings; returns the updated key.

verify

verify(name: str, input: TransitInput, *, signature: str | None = None, hmac: str | None = None, hash_algorithm: str | None = None, signature_algorithm: Literal['pss', 'pkcs1v15'] | None = None, prehashed: bool | None = None, context: TransitInput | None = None) -> bool

Verify a signature or an hmac (exactly one); False when invalid.

TransitKey

A transit key.

UnavailableError

Bases: grow_hashicorp_vault._core.errors.VaultError

Network error or server unavailable (HTTP 500, 502, 503).

code class-attribute

code = <ErrorCode.UNAVAILABLE: 'UNAVAILABLE'>

Canonical error codes; the value is the wire form used by the conformance suite.

default_retryable class-attribute

default_retryable = True

Returns True when the argument is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

UnsupportedError

Bases: grow_hashicorp_vault._core.errors.VaultError

The service or deployment does not offer this capability (HTTP 501, missing API).

code class-attribute

code = <ErrorCode.UNSUPPORTED: 'UNSUPPORTED'>

Canonical error codes; the value is the wire form used by the conformance suite.

UnwrapResult

Result of :meth:Wrapping.unwrap: the original response (repr hides data).

UserpassAuth

Bases: grow_hashicorp_vault.auth.AuthMethod

Username/password login: POST auth/<mount>/login/<username> {password}.

method class-attribute

method = 'userpass'

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

ValidationError

Bases: grow_hashicorp_vault._core.errors.VaultError

Bad input (HTTP 400, 413, 422, other 4xx, client-side validation).

code class-attribute

code = <ErrorCode.VALIDATION: 'VALIDATION'>

Canonical error codes; the value is the wire form used by the conformance suite.

VaultClient

Bases: grow_hashicorp_vault.client._ClientBase

Synchronous Vault client. Thread-safe; use as a context manager or call :meth:close.

Service modules: :attr:auth, :attr:sys, :attr:wrapping, :attr:leases, :meth:kv, :meth:kv_v1, :meth:kv_v2, :meth:transit, :meth:database, :meth:pki and :meth:secrets (the SecretsProvider). Cancel calls from another thread with with client.cancellable(token): ... or the cancel= argument of the core methods.

cancellable

cancellable(token: CancelToken) -> Iterator[CancelToken]

Apply token to every call made by this thread inside the with block.

close

close() -> None

Stop token renewers, managed leases and secret watchers (also of every :meth:with_namespace view), then release connections (idempotent). Closing a view leaves the shared connection pool open.

database

database(mount: str = 'database') -> Database

Database engine (default mount database).

from_env classmethod

from_env(env: Mapping[str, str] | None = None, **overrides: Any) -> VaultClient

Build a client from GROW_HASHICORP_VAULT_* and VAULT_* variables.

health

health(*, cancel: CancelToken | None = None) -> HealthStatus

Unauthenticated health (GET /v1/sys/health); never raises for an unhealthy or unreachable server.

healthy is true only for an active, unsealed node; status is active, standby, perfstandby, sealed or uninitialized (unreachable on any error). details holds version, initialized, sealed, standby and clusterName (when set); on errors error (and httpStatus). Raises only :class:CancelledError and :class:ConfigError.

kv

kv(mount: str | None = None) -> KvMount

KV mount with auto-detected version (default config.kv_mount); cached per mount.

kv_v1

kv_v1(mount: str | None = None) -> KvV1

KV version 1 mount (no detection).

kv_v2

kv_v2(mount: str | None = None) -> KvV2

KV version 2 mount (no detection).

ping

ping(*, cancel: CancelToken | None = None) -> float

Authenticated round trip (GET auth/token/lookup-self); latency in ms.

A missing, invalid or revoked token raises :class:AuthenticationError.

pki

pki(mount: str = 'pki') -> Pki

PKI engine (default mount pki).

request

request(method: Literal, path: str, *, params: Mapping[str, Any] | None = None, json: Any = None, headers: Mapping[str, str] | None = None, list: bool = False, wrap_ttl_s: float | timedelta | None = None, idempotent: bool | None = None) -> RawResponse

Call any Vault API path (/v1/<path>) with the client token, namespace, retries and error mapping (for endpoints this SDK has no method for).

secrets

secrets(mount: str | None = None, *, path: str | None = None, value_field: str | None = None) -> VaultSecretsProvider

:class:SecretsProvider over a KV mount (default config.kv_mount) and base path (default config.secrets_path); close() stops its watchers.

server_version

server_version(*, cancel: CancelToken | None = None) -> str

Server version from sys/health (e.g. 2.2.2).

transit

transit(mount: str = 'transit') -> Transit

Transit engine (default mount transit).

with_namespace

with_namespace(namespace: str) -> VaultClient

A view of this client whose requests carry X-Vault-Namespace: <namespace>.

"" selects the root namespace (no header); surrounding slashes are removed. The view shares the connection pool and starts with this client's current token; logins, token changes, KV version detection, renewers and watchers of the view do not affect this client, which stays unchanged. Closing the view stops its own background work; closing this client also closes every view.

Vault Enterprise only. Vault OSS silently ignores the header and serves the root namespace, so on OSS a view reads and writes the root namespace and a wrong namespace is not detected.

team = client.with_namespace("team-a") # doctest: +SKIP team.kv().read("app/db") # doctest: +SKIP

VaultConfig

Bases: grow_hashicorp_vault._core.config.BaseConfig

Immutable settings for :class:~grow_hashicorp_vault.VaultClient.

Common fields (url, timeouts, retry, tls, proxy, headers, user_agent_suffix, hooks, logger) come from :class:BaseConfig. Durations are float seconds; datetime.timedelta is accepted. token accepts a str and is stored as a :class:Secret; repr() never shows it.

Service fields:

  • token — client token sent as X-Vault-Token. Leave it unset when the client logs in with an auth method (client.auth.login(...)).
  • namespace — sent as X-Vault-Namespace (None/"" = root namespace). Namespaces are a Vault Enterprise feature: Vault OSS ignores the header and serves the root namespace, so a wrong value is not detected there. See VaultClient.with_namespace.
  • kv_mount — default KV mount of client.kv() / client.secrets() ("secret").
  • kv_version — 1 or 2 to skip KV version auto-detection (sys/internal/ui/mounts) for tokens that cannot read it; None = auto-detect.
  • secrets_path — base path inside the KV mount of client.secrets() ("" = root).
  • value_field — KV data field that holds a client.secrets() value ("value").

Environment (from_env): GROW_HASHICORP_VAULT_<NAME> first, then the vendor variables of :data:VENDOR_ENV (VAULT_*). Names: URL, TOKEN, NAMESPACE, CONNECT_TIMEOUT, REQUEST_TIMEOUT, TOTAL_TIMEOUT, MAX_RETRIES, CA_CERT, CLIENT_CERT, CLIENT_KEY, INSECURE_SKIP_VERIFY, PROXY, KV_MOUNT, KV_VERSION (1, 2; 0 = auto-detect) and SECRETS_PATH.

ENV_VENDOR class-attribute

ENV_VENDOR = {'URL': ('VAULT_ADDR',), 'TOKEN': ('VAULT_TOKEN',), 'NAMESPACE': ('VAULT_NAMESPACE',), 'CA_CERT': ('VAULT_CACERT',), 'CLIENT_CERT': ('VAULT_CLIENT_CERT',), 'CLIENT_KEY': ('VAULT_CLIENT_KEY',), 'INSECURE_SKIP_VERIFY': ('VAULT_SKIP_VERIFY',)}

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

kv_mount class-attribute

kv_mount = 'secret'

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

secrets_path class-attribute

secrets_path = ''

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

url class-attribute

url = 'http://127.0.0.1:8200'

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

value_field class-attribute

value_field = 'value'

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

validate

validate() -> _C

Common checks plus service rules; raises :class:ConfigError.

VaultError

Bases: builtins.Exception

Base class of every error raised by this SDK.

Attributes:

Name Type Description
code

canonical :class:ErrorCode.

message

human readable text; never contains credentials or raw response bodies.

http_status

HTTP status when the error came from a response.

request_id

vendor request id header when present.

retryable

whether retrying the same call may succeed.

retry_after

server requested delay in seconds (rate limiting / unavailable).

cause property

cause

The underlying error, if any.

code class-attribute

code = <ErrorCode.UNAVAILABLE: 'UNAVAILABLE'>

Canonical error codes; the value is the wire form used by the conformance suite.

default_retryable class-attribute

default_retryable = False

Returns True when the argument is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

VaultSecretsProvider

Bases: grow_hashicorp_vault._secrets.base.BaseSecretsProvider

:class:SecretsProvider over an Vault KV mount (v1 or v2, auto-detected).

Create it with client.secrets(mount=None, path="", value_field="value").

  • get(name) reads <path>/<name>; KV v2 versions are the SecretValue.version.
  • set returns the new KV v2 version ("" on KV v1); cas and tags (custom metadata) need KV v2. str is stored as is, bytes as base64 (with encoding: base64), other values JSON-encoded.
  • delete soft-deletes the latest version (KV v2); versions deletes those versions, permanent=True removes all versions and metadata. Missing → :class:NotFoundError.
  • list(prefix) lists one folder level (sub-folders skipped); on KV v2 each entry carries its metadata and secrets whose current version is deleted are skipped.

capabilities class-attribute

capabilities = frozenset({'delete', 'write', 'versions'})

Build an immutable unordered collection of unique elements.

path property

path

Base path inside the mount that names are relative to.

value_field property

value_field

Data field that holds the value.

full_path

full_path(name: str, path: str | None = None) -> str

The KV path of a secret: <path or provider path>/<name>.

get_all

get_all(path: str | None = None) -> dict[str, SecretValue]

Every secret directly under path (non-recursive), keyed by name.

set

set(name: str, value: Any, *, path: str | None = None, cas: int | None = None, tags: Mapping[str, str] | None = None, description: str | None = None) -> str

Store value (str, bytes → base64, other → JSON); returns the version.

WatchHandle

Polls fetch every interval_s in a daemon thread and reports changes.

The first successful fetch is the baseline; later fetches whose version (or SHA-256 when unversioned) differ call on_change(new, old), including deletion (new is None). Errors (from fetching or from on_change) go to on_error and polling continues. A :class:CancelledError from fetching (the provider or client was closed) ends the watcher quietly (:attr:stopped becomes true), like the async watcher.

join

join(timeout: float | None = None) -> None

Wait for the watcher thread to finish (after :meth:stop).

stop

stop() -> None

Stop polling (idempotent, does not wait for an in-flight fetch).

WrapInfo

A wrapping token (a :class:Secret) and its properties.

Wrapping

Bases: grow_hashicorp_vault._api.SyncModule

Response wrapping: client.wrapping.

lookup_wrapping

lookup_wrapping(token: str | Secret) -> WrappingLookup

Properties of a wrapping token without using it (POST sys/wrapping/lookup).

unwrap

unwrap(token: str | Secret) -> UnwrapResult

Unwrap a token (POST sys/wrapping/unwrap authenticated with the token itself).

A used or invalid token raises :class:ValidationError; never retried.

wrap

wrap(data: Mapping[str, Any], ttl_s: Duration) -> WrapInfo

Wrap data in a single-use token valid for ttl_s (POST sys/wrapping/wrap).

WrappingLookup

Result of :meth:Wrapping.lookup_wrapping.

apoll_until async

apoll_until(fn: Callable[[], Awaitable[T | None]], *, timeout_s: float = 30.0, interval_s: float = 1.0, predicate: Callable[[T], bool] | None = None, operation: str = 'poll', clock: Callable[[], float] = monotonic) -> T

Async :func:poll_until; fn is an async callable.

env_var_name

env_var_name(name: str, path: str | None, prefix: str) -> str

Variable name for secret name listed under path.

The name relative to path is upper-cased and every character outside [A-Z0-9_] becomes _; prefix is prepended.

error_for_code

error_for_code(code: ErrorCode | str) -> type[VaultError]

Return the error class for a code (ErrorCode member or wire value).

error_from_status

error_from_status(status: int, operation: str, *, content: bytes = b'', headers: Headers | None = None, known_secrets: list[str] | None = None, retry_after: float | None = None, request_id_headers: Sequence[str] = ()) -> ServiceError

Map an HTTP error status to the SPEC 2.1 error with a redacted, truncated message.

request_id_headers are checked before the default :data:REQUEST_ID_HEADERS.

get_logger

get_logger() -> logging.Logger

The package logger (LOGGER_NAME), silent by default (NullHandler).

new_idempotency_key

new_idempotency_key() -> str

A random key for the Idempotency-Key header.

parse_bool

parse_bool(text: str) -> bool

Parse true/false/1/0/yes/no/on/off (case-insensitive); raise :class:ValueError.

parse_duration

parse_duration(text: str) -> float

Parse a duration into seconds.

Accepts integer milliseconds ("1500" → 1.5) or Go-style units ("500ms", "10s", "2m", "1h", "1m30s"). Raises :class:ValueError for anything else.

parse_retry_after

parse_retry_after(value: str | None, *, now: Callable[[], float] = time) -> float | None

Parse Retry-After as delta seconds or an HTTP-date; return seconds (>= 0) or None.

poll_until

poll_until(fn: Callable[[], T | None], *, timeout_s: float = 30.0, interval_s: float = 1.0, predicate: Callable[[T], bool] | None = None, operation: str = 'poll', sleep: Callable[[float], None] = sleep, clock: Callable[[], float] = monotonic) -> T

Call fn every interval_s until it returns a ready value; return that value.

A value is ready when it is not None and predicate(value) is true (without a predicate: not an empty container). Retryable SDK errors raised by fn are remembered and polling continues; other errors propagate. Raises :class:TimeoutError after timeout_s.

redact_fields

redact_fields(value: Any, extra_keys: Iterable[str] = ()) -> Any

Recursively redact values whose key looks sensitive in nested mappings and lists.

redact_headers

redact_headers(headers: Mapping[str, str] | Iterable[tuple[str, str]]) -> dict[str, str]

Copy of headers with sensitive values replaced by [REDACTED].

redact_text

redact_text(text: str, known_secrets: Iterable[str | Secret | None] = ()) -> str

Replace every known secret value (length >= 4) in text with [REDACTED].

redact_url

redact_url(url: str) -> str

Redact user info and every query value (all values, not only sensitive ones).

Query names are kept so the URL stays useful in logs.

retry_after_from_headers

retry_after_from_headers(headers: Headers | Mapping[str, str], names: Sequence[str] = ('retry-after',), *, now: Callable[[], float] = time) -> float | None

Server requested delay in seconds from the first of names that parses.

Retry-After is delta seconds or an HTTP-date. Other headers (X-RateLimit-Reset, RateLimit-Reset …) may be delta seconds or a Unix timestamp in seconds or milliseconds; timestamps are turned into the remaining delay.

to_seconds

to_seconds(value: float | timedelta) -> float

Normalise a duration given as float seconds or :class:datetime.timedelta.

truncate

truncate(text: str, limit: int = 300) -> str

Truncate text to limit characters (adds an ellipsis when cut).

user_agent

user_agent(suffix: str | None = None) -> str

grow-codes-<key>/<version> (python) plus <suffix> when given.