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 AWS Secrets Manager (boto3 / aioboto3).

from grow_aws_secrets_manager import AwsSecretsManagerClient with AwsSecretsManagerClient.from_env() as client: # doctest: +SKIP ... client.get_secret_value("app/db").value.reveal()

Not affiliated with or endorsed by Amazon Web Services. Amazon Web Services, AWS and AWS Secrets Manager are trademarks of Amazon.com, Inc. or its affiliates.

AsyncAwsSecretCache

Async :class:AwsSecretCache in front of an :class:AsyncAwsSecretsManagerClient.

aws_defaults staticmethod

aws_defaults() -> dict[str, Any]

The AWS caching-client defaults: {"ttl_s": 3600.0, "max_entries": 1024}.

clear

clear() -> None

Drops every entry.

get_secret_binary async

get_secret_binary(secret_id: str, *, version_stage: str | None = None) -> bytes

See :meth:AwsSecretCache.get_secret_binary.

get_secret_string async

get_secret_string(secret_id: str, *, version_stage: str | None = None) -> str

See :meth:AwsSecretCache.get_secret_string.

get_secret_value async

get_secret_value(secret_id: str, *, version_stage: str | None = None) -> AwsSecretValue

See :meth:AwsSecretCache.get_secret_value.

invalidate

invalidate(secret_id: str) -> None

Drops every cached stage of secret_id.

refresh_now async

refresh_now(secret_id: str, *, version_stage: str | None = None) -> AwsSecretValue

See :meth:AwsSecretCache.refresh_now.

stats

stats() -> AwsSecretCacheStats

Counters and the current size.

AsyncAwsSecretsManagerClient

Bases: _Base

Asynchronous AWS Secrets Manager client on aioboto3 (extra async), with the same methods as :class:AwsSecretsManagerClient. Use async with or call :meth:aclose.

Cancel a call by cancelling its task: the SDK raises :class:CancelledError (also an :class:asyncio.CancelledError). A caller-supplied sdk_client must be an entered aiobotocore secretsmanager client; credentials must be aiobotocore credentials.

sdk property

sdk: Any

The underlying aiobotocore client (None until the first call builds it).

aclose async

aclose() -> None

Stops watchers and closes the aiobotocore clients this instance built. Idempotent.

batch_get_secret_value async

batch_get_secret_value(secret_ids: Sequence[str] | None = None, *, filters: Sequence[SecretFilter] | None = None, max_results: int | None = None) -> BatchGetResult

See :meth:AwsSecretsManagerClient.batch_get_secret_value.

cancel_rotate_secret async

cancel_rotate_secret(secret_id: str) -> SecretWriteResult

See :meth:AwsSecretsManagerClient.cancel_rotate_secret.

create_secret async

create_secret(name: str, value: Any = None, *, description: str | None = None, kms_key_id: str | None = None, tags: Mapping[str, str] | None = None, client_request_token: str | None = None, add_replica_regions: Sequence[ReplicaRegion] | None = None, force_overwrite_replica_secret: bool | None = None) -> SecretWriteResult

See :meth:AwsSecretsManagerClient.create_secret.

delete_resource_policy async

delete_resource_policy(secret_id: str) -> SecretRef

See :meth:AwsSecretsManagerClient.delete_resource_policy.

delete_secret async

delete_secret(secret_id: str, *, recovery_window_days: int | None = None, force_delete_without_recovery: bool | None = None) -> DeleteSecretResult

See :meth:AwsSecretsManagerClient.delete_secret.

describe_secret async

describe_secret(secret_id: str) -> SecretDescription

See :meth:AwsSecretsManagerClient.describe_secret.

from_env classmethod

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

A client from GROW_AWS_SECRETS_MANAGER_* and the standard AWS variables.

get_json_field async

get_json_field(secret_id: str, field: str, *, version_id: str | None = None, version_stage: str | None = None) -> Any

See :meth:AwsSecretsManagerClient.get_json_field.

get_random_password async

get_random_password(*, length: int = 32, exclude_characters: str | None = None, exclude_numbers: bool | None = None, exclude_punctuation: bool | None = None, exclude_uppercase: bool | None = None, exclude_lowercase: bool | None = None, include_space: bool | None = None, require_each_included_type: bool | None = None) -> Secret

See :meth:AwsSecretsManagerClient.get_random_password.

get_resource_policy async

get_resource_policy(secret_id: str) -> ResourcePolicyResult

See :meth:AwsSecretsManagerClient.get_resource_policy.

get_secret_value async

get_secret_value(secret_id: str, *, version_id: str | None = None, version_stage: str | None = None) -> AwsSecretValue

See :meth:AwsSecretsManagerClient.get_secret_value.

health async

health() -> HealthStatus

See :meth:AwsSecretsManagerClient.health.

list_secret_version_ids

list_secret_version_ids(secret_id: str, *, include_deprecated: bool | None = None, max_results: int | None = None) -> AsyncPaginator[SecretVersion]

See :meth:AwsSecretsManagerClient.list_secret_version_ids.

list_secrets

list_secrets(*, filters: Sequence[SecretFilter] | None = None, include_planned_deletion: bool | None = None, sort_order: SortOrder | None = None, max_results: int | None = None) -> AsyncPaginator[SecretDescription]

See :meth:AwsSecretsManagerClient.list_secrets (async for / to_list()).

ping async

ping() -> float

See :meth:AwsSecretsManagerClient.ping.

put_resource_policy async

put_resource_policy(secret_id: str, policy: str | Mapping[str, Any], *, block_public_policy: bool | None = None) -> SecretRef

See :meth:AwsSecretsManagerClient.put_resource_policy.

put_secret_value async

put_secret_value(secret_id: str, value: Any, *, version_stages: Sequence[str] | None = None, client_request_token: str | None = None) -> PutSecretValueResult

See :meth:AwsSecretsManagerClient.put_secret_value.

restore_secret async

restore_secret(secret_id: str) -> SecretRef

See :meth:AwsSecretsManagerClient.restore_secret.

rotate_secret async

rotate_secret(secret_id: str, *, lambda_arn: str | None = None, rules: RotationRules | None = None, rotate_immediately: bool | None = None, client_request_token: str | None = None) -> SecretWriteResult

See :meth:AwsSecretsManagerClient.rotate_secret.

secret_cache

secret_cache(**options: Any) -> AsyncAwsSecretCache

An async version-stage aware cache (see :class:AsyncAwsSecretCache).

secrets

secrets(*, recovery_window_days: int | None = None) -> AsyncAwsSecretsManagerSecretsProvider

The async :class:SecretsProvider view of this client.

server_version async

server_version() -> str

Always raises :class:UnsupportedError (AWS exposes no server version).

tag_resource async

tag_resource(secret_id: str, tags: Mapping[str, str]) -> None

See :meth:AwsSecretsManagerClient.tag_resource.

untag_resource async

untag_resource(secret_id: str, tag_keys: Sequence[str]) -> None

See :meth:AwsSecretsManagerClient.untag_resource.

update_secret async

update_secret(secret_id: str, *, value: Any = None, description: str | None = None, kms_key_id: str | None = None, client_request_token: str | None = None) -> SecretWriteResult

See :meth:AwsSecretsManagerClient.update_secret.

update_secret_version_stage async

update_secret_version_stage(secret_id: str, version_stage: str, *, move_to_version_id: str | None = None, remove_from_version_id: str | None = None) -> SecretRef

See :meth:AwsSecretsManagerClient.update_secret_version_stage.

validate_resource_policy async

validate_resource_policy(policy: str | Mapping[str, Any], *, secret_id: str | None = None) -> ValidateResourcePolicyResult

See :meth:AwsSecretsManagerClient.validate_resource_policy.

with_sdk_client classmethod

with_sdk_client(sdk_client: Any, **options: Any) -> AsyncAwsSecretsManagerClient

Wraps an existing (entered) aiobotocore client; :meth:aclose leaves it open.

AsyncAwsSecretsManagerSecretsProvider

Bases: AsyncBaseSecretsProvider

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

client property

client: AsyncAwsSecretsManagerClient

The client this provider uses.

get_all async

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

See :meth:AwsSecretsManagerSecretsProvider.get_all.

get_many async

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

See :meth:AwsSecretsManagerSecretsProvider.get_many.

AsyncBaseSecretsProvider

Bases: ABC

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

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

closed property

closed: bool

True once :meth:aclose was called.

aclose async

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 async

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: OnChange, *, on_error: OnError | None = None, version: str | None = None, path: str | None = None) -> AsyncWatchHandle

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

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 async

aclose() -> None

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

request async

request(req: Request) -> Response

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

AsyncPaginator

Bases: Generic[T]

Async :class:Paginator: async for item in client.list_secrets() or await client.list_secrets().to_list().

pages async

pages() -> AsyncIterator[list[T]]

Yields one list per page.

to_list async

to_list() -> list[T]

Every item of every page.

AsyncSecretCache

Bases: AsyncBaseSecretsProvider

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

wait_refreshes async

wait_refreshes() -> None

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

watch

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

Watches the underlying provider directly (bypasses the cache).

AsyncSecretCacheSource

Bases: Protocol

The client operations :class:AsyncAwsSecretCache needs.

AsyncSecretsProvider

Bases: Protocol

Asynchronous secrets interface (same methods, awaitable).

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 async

wait() -> None

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

AuthenticationError

Bases: AwsSecretsManagerError

Credentials missing or rejected (HTTP 401).

AwsSecretCache

Version-stage aware cache in front of an :class:AwsSecretsManagerClient (client.secret_cache()). Thread-safe.

Options: ttl_s (refresh interval, default 3600), max_entries (LRU capacity, default 1024), version_stage (default AWSCURRENT), clock (monotonic seconds) and on_refresh_error (called when a refresh fails and the cached value is served instead).

aws_defaults staticmethod

aws_defaults() -> dict[str, Any]

The AWS caching-client defaults: {"ttl_s": 3600.0, "max_entries": 1024}.

clear

clear() -> None

Drops every entry.

get_secret_binary

get_secret_binary(secret_id: str, *, version_stage: str | None = None) -> bytes

The value as bytes.

get_secret_string

get_secret_string(secret_id: str, *, version_stage: str | None = None) -> str

The value as text (SecretString, or UTF-8 of the binary).

get_secret_value

get_secret_value(secret_id: str, *, version_stage: str | None = None) -> AwsSecretValue

The cached value of secret_id at the stage (default: the cache's stage).

invalidate

invalidate(secret_id: str) -> None

Drops every cached stage of secret_id.

refresh_now

refresh_now(secret_id: str, *, version_stage: str | None = None) -> AwsSecretValue

Forces a refresh check now (and a fetch when the stage moved); returns the value.

stats

stats() -> AwsSecretCacheStats

Counters and the current size.

AwsSecretCacheStats dataclass

Counters of :meth:AwsSecretCache.stats.

AwsSecretValue dataclass

A secret value read from AWS (GetSecretValue, BatchGetSecretValue).

value.version is the version id; binary is true when the secret stores SecretBinary (false for SecretString). repr() never shows the value.

AwsSecretsManagerClient

Bases: _Base

Synchronous AWS Secrets Manager client on boto3. Thread-safe; use it as a context manager or call :meth:close.

Every I/O method accepts cancel= (a :class:CancelToken): cancelling returns :class:CancelledError at once (the abandoned AWS call finishes in the background). The whole call, retries included, is bounded by config.total_timeout (:class:TimeoutError).

Errors are mapped by AWS error code: NotFoundError (ResourceNotFoundException), ConflictError (ResourceExistsException, InvalidRequestException e.g. scheduled for deletion), ValidationError, PermissionDeniedError, AuthenticationError, RateLimitError, UnavailableError, TimeoutError.

sdk property

sdk: Any

The underlying boto3 client (escape hatch for operations not wrapped here).

batch_get_secret_value

batch_get_secret_value(secret_ids: Sequence[str] | None = None, *, filters: Sequence[SecretFilter] | None = None, max_results: int | None = None, cancel: CancelToken | None = None) -> BatchGetResult

Reads many secrets at once (BatchGetSecretValue).

Give secret_ids (lists longer than 20 are split; values come back in request order) or filters (every page is read; max_results is the page size, 1-20). Per-secret failures are returned in errors; the call itself succeeds.

cancel_rotate_secret

cancel_rotate_secret(secret_id: str, *, cancel: CancelToken | None = None) -> SecretWriteResult

Turns rotation off and cancels a rotation in progress (CancelRotateSecret).

close

close() -> None

Stops the watchers of the providers from :meth:secrets and closes the boto3 client this instance built (never a caller-supplied one). Idempotent.

create_secret

create_secret(name: str, value: Any = None, *, description: str | None = None, kms_key_id: str | None = None, tags: Mapping[str, str] | None = None, client_request_token: str | None = None, add_replica_regions: Sequence[ReplicaRegion] | None = None, force_overwrite_replica_secret: bool | None = None, cancel: CancelToken | None = None) -> SecretWriteResult

Creates a secret (CreateSecret).

value: str → SecretString, bytes → SecretBinary, other objects → JSON SecretString, None → a secret without a version. :class:ConflictError when the name exists (or is scheduled for deletion).

delete_resource_policy

delete_resource_policy(secret_id: str, *, cancel: CancelToken | None = None) -> SecretRef

Removes the resource policy (DeleteResourcePolicy).

delete_secret

delete_secret(secret_id: str, *, recovery_window_days: int | None = None, force_delete_without_recovery: bool | None = None, cancel: CancelToken | None = None) -> DeleteSecretResult

Schedules deletion (DeleteSecret) after recovery_window_days (7-30, AWS default 30) or deletes at once with force_delete_without_recovery. Both together → :class:ValidationError. AWS answers success for a forced delete of a missing secret.

describe_secret

describe_secret(secret_id: str, *, cancel: CancelToken | None = None) -> SecretDescription

Metadata of a secret (DescribeSecret), never the value.

from_env classmethod

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

A client from GROW_AWS_SECRETS_MANAGER_* and the standard AWS variables.

get_json_field

get_json_field(secret_id: str, field: str, *, version_id: str | None = None, version_stage: str | None = None, cancel: CancelToken | None = None) -> Any

One field of a JSON secret: an exact key first, otherwise a dot path ("db.host").

None when the field is absent; :class:ValidationError when the value is binary or not a JSON object; :class:NotFoundError when the secret is missing.

get_random_password

get_random_password(*, length: int = 32, exclude_characters: str | None = None, exclude_numbers: bool | None = None, exclude_punctuation: bool | None = None, exclude_uppercase: bool | None = None, exclude_lowercase: bool | None = None, include_space: bool | None = None, require_each_included_type: bool | None = None, cancel: CancelToken | None = None) -> Secret

Generates a random password (GetRandomPassword, length 1-4096, default 32), returned as a redacting :class:Secret.

get_resource_policy

get_resource_policy(secret_id: str, *, cancel: CancelToken | None = None) -> ResourcePolicyResult

Reads the resource policy (GetResourcePolicy); resource_policy is None when the secret has none, policy is the parsed object.

get_secret_value

get_secret_value(secret_id: str, *, version_id: str | None = None, version_stage: str | None = None, cancel: CancelToken | None = None) -> AwsSecretValue

Reads a secret value (GetSecretValue), by default the AWSCURRENT version.

secret_id is a name or ARN. :class:NotFoundError when the secret, version or stage does not exist; :class:ConflictError when the secret is scheduled for deletion.

health

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

Liveness: a signed ListSecrets {MaxResults: 1}, no retries, ≤ 5 s timeouts.

ok when AWS answers (also when the credentials are rejected: details["auth"] == "failed"), degraded when throttled, unhealthy on HTTP 5xx, unreachable on network errors and timeouts. Raises only :class:CancelledError (also on a closed client) and :class:ConfigError.

list_secret_version_ids

list_secret_version_ids(secret_id: str, *, include_deprecated: bool | None = None, max_results: int | None = None, cancel: CancelToken | None = None) -> Paginator[SecretVersion]

Lists the versions of a secret (ListSecretVersionIds) lazily across all pages.

list_secrets

list_secrets(*, filters: Sequence[SecretFilter] | None = None, include_planned_deletion: bool | None = None, sort_order: SortOrder | None = None, max_results: int | None = None, cancel: CancelToken | None = None) -> Paginator[SecretDescription]

Lists secrets (ListSecrets) lazily across all pages: for s in client.list_secrets() or client.list_secrets().to_list().

ping

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

Authenticated round trip (ListSecrets {MaxResults: 1}); latency in milliseconds.

:class:AuthenticationError for unknown keys or bad signatures, :class:PermissionDeniedError when secretsmanager:ListSecrets is not allowed.

put_resource_policy

put_resource_policy(secret_id: str, policy: str | Mapping[str, Any], *, block_public_policy: bool | None = None, cancel: CancelToken | None = None) -> SecretRef

Attaches a resource policy (PutResourcePolicy); mappings are JSON-encoded.

put_secret_value

put_secret_value(secret_id: str, value: Any, *, version_stages: Sequence[str] | None = None, client_request_token: str | None = None, cancel: CancelToken | None = None) -> PutSecretValueResult

Stores a new version (PutSecretValue). By default it becomes AWSCURRENT (the old one becomes AWSPREVIOUS); with version_stages only those labels move.

restore_secret

restore_secret(secret_id: str, *, cancel: CancelToken | None = None) -> SecretRef

Cancels a scheduled deletion (RestoreSecret); a no-op for a live secret.

rotate_secret

rotate_secret(secret_id: str, *, lambda_arn: str | None = None, rules: RotationRules | None = None, rotate_immediately: bool | None = None, client_request_token: str | None = None, cancel: CancelToken | None = None) -> SecretWriteResult

Configures and/or starts rotation (RotateSecret). Without lambda_arn the secret's managed or existing rotation function is used.

secret_cache

secret_cache(**options: Any) -> AwsSecretCache

A version-stage aware cache with the AWS caching-client semantics (TTL 1 h, 1024 entries); options are those of :class:AwsSecretCache.

secrets

secrets(*, recovery_window_days: int | None = None) -> AwsSecretsManagerSecretsProvider

The :class:SecretsProvider view (SPEC section 3) of this client; close() stops its watchers. recovery_window_days defaults to config.recovery_window_days.

server_version

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

Always raises :class:UnsupportedError: AWS exposes no server version (the API contract date is the constant API_VERSION).

tag_resource

tag_resource(secret_id: str, tags: Mapping[str, str], *, cancel: CancelToken | None = None) -> None

Adds or replaces tags (TagResource).

untag_resource

untag_resource(secret_id: str, tag_keys: Sequence[str], *, cancel: CancelToken | None = None) -> None

Removes tags by key (UntagResource).

update_secret

update_secret(secret_id: str, *, value: Any = None, description: str | None = None, kms_key_id: str | None = None, client_request_token: str | None = None, cancel: CancelToken | None = None) -> SecretWriteResult

Updates description, KMS key and/or value (UpdateSecret); a new version is created only when value is given.

update_secret_version_stage

update_secret_version_stage(secret_id: str, version_stage: str, *, move_to_version_id: str | None = None, remove_from_version_id: str | None = None, cancel: CancelToken | None = None) -> SecretRef

Moves a stage label between versions (UpdateSecretVersionStage). Moving AWSCURRENT needs remove_from_version_id = the current version.

validate_resource_policy

validate_resource_policy(policy: str | Mapping[str, Any], *, secret_id: str | None = None, cancel: CancelToken | None = None) -> ValidateResourcePolicyResult

Checks a policy with IAM Access Analyzer (ValidateResourcePolicy). Emulators that lack the operation (Moto 5.2.4) raise :class:UnsupportedError.

with_sdk_client classmethod

with_sdk_client(sdk_client: Any, **options: Any) -> AwsSecretsManagerClient

Wraps an existing boto3 secretsmanager client; :meth:close leaves it open.

AwsSecretsManagerConfig dataclass

Bases: BaseConfig

Immutable settings for :class:~grow_aws_secrets_manager.AwsSecretsManagerClient.

Common fields (url, timeouts, retry, tls, proxy, headers, user_agent_suffix, hooks, logger) come from :class:BaseConfig; durations are float seconds (datetime.timedelta accepted). url is the endpoint override: empty (the default) lets the AWS SDK resolve https://secretsmanager.<region>.amazonaws.com.

AWS fields: region, access_key_id, secret_access_key and session_token (stored as :class:Secret), profile, credentials (a botocore credentials object used instead of the key fields), role_arn / role_session_name / external_id / role_duration_s (assume a role with STS on top of the base credentials), recovery_window_days (7-30, default 30) and sdk_client (an existing boto3 / aioboto3 Secrets Manager client; mutually exclusive with the credential, region and endpoint fields). repr() never shows a credential.

Environment (from_env), explicit value > GROW_AWS_SECRETS_MANAGER_<NAME> > AWS variable > default: URL (> AWS_ENDPOINT_URL_SECRETS_MANAGER > AWS_ENDPOINT_URL), REGION (> AWS_REGION > AWS_DEFAULT_REGION), ACCESS_KEY_ID / SECRET_ACCESS_KEY / SESSION_TOKEN (taken as one set from either the GROW_* or the AWS_* variables, never mixed), PROFILE (> AWS_PROFILE), ROLE_ARN, ROLE_SESSION_NAME, EXTERNAL_ID, RECOVERY_WINDOW_DAYS and the common CONNECT_TIMEOUT, REQUEST_TIMEOUT, TOTAL_TIMEOUT, MAX_RETRIES, CA_CERT, CLIENT_CERT, CLIENT_KEY, INSECURE_SKIP_VERIFY, PROXY. Credentials left unset use the AWS SDK default chain (environment, shared config / SSO, web identity, container, instance metadata).

effective_url property

effective_url: str

The override, or the public endpoint of region (us-east-1 when unset).

endpoint property

endpoint: str | None

The endpoint override passed to the AWS SDK (None = the SDK resolves it).

from_env classmethod

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

Build from the environment, then validate.

Precedence: explicit keyword > GROW_AWS_SECRETS_MANAGER_<NAME> > AWS variables > default. An explicit sdk_client or credentials replaces the credentials found in the environment (an sdk_client also drops the environment's region, endpoint, profile and role). env defaults to os.environ; pass a dict in tests.

validate

validate() -> _C

Common checks plus the AWS rules; raises :class:ConfigError. Returns self.

AwsSecretsManagerSecretsProvider

Bases: BaseSecretsProvider

:class:SecretsProvider over AWS Secrets Manager (client.secrets()).

Capabilities: write, versions, delete.

  • get(name, version=...) reads VersionId = version (stage labels: use client.get_secret_value).
  • set stores UTF-8 text as SecretString and other bytes as SecretBinary; it creates the secret when missing (with description / tags) and returns the new VersionId. cas is not supported (:class:ValidationError).
  • delete schedules deletion with the recovery window (default 30 days); permanent=True deletes at once. A name scheduled for deletion cannot be written again until it is restored or purged (:class:ConflictError).
  • list(prefix) matches names by string prefix (recursive); get_all(path) returns the secrets directly under path (non-recursive). get_many / get_all use BatchGetSecretValue in chunks of 20.

client property

client: AwsSecretsManagerClient

The client this provider uses.

get_all

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

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

get_many

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

Present secrets in request order (BatchGetSecretValue in chunks of 20; per-name reads when a version is requested).

BaseConfig dataclass

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.

from_env classmethod

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

Build from the environment, then validate.

Precedence: explicit keyword > GROW_AWS_SECRETS_MANAGER_<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

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: bool

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: OnChange, *, on_error: OnError | None = None, version: str | None = None, path: str | None = None) -> WatchHandle

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

BatchGetError dataclass

A per-secret failure of batch_get_secret_value (the call itself succeeded).

BatchGetResult dataclass

Result of batch_get_secret_value: values (request order for ids) and failures.

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: AwsSecretsManagerError, 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.

ConfigError

Bases: AwsSecretsManagerError

Invalid or missing configuration.

ConflictError

Bases: AwsSecretsManagerError

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

DeleteSecretResult dataclass

Bases: SecretRef

Result of delete_secret; deletion_date is when the secret will be (was) purged.

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: str, Enum

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

ErrorInfo dataclass

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

HealthStatus dataclass

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

Hooks dataclass

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.

LoggerLike

Bases: Protocol

Structured logger interface accepted in configuration (SPEC Logger).

NotFoundError

Bases: AwsSecretsManagerError

Missing record (HTTP 404).

Paginator

Bases: Generic[T]

Lazily walks every page of an AWS list operation.

Iterate it (for item in client.list_secrets()), walk :meth:pages, or collect everything with :meth:to_list. Every iteration starts again from the first page.

pages

pages() -> Iterator[list[T]]

Yields one list per page.

to_list

to_list() -> list[T]

Every item of every page.

PermissionDeniedError

Bases: AwsSecretsManagerError

Authenticated but not allowed (HTTP 403).

PolicyValidationError dataclass

One problem found by validate_resource_policy.

PutSecretValueResult dataclass

Bases: SecretRef

Result of put_secret_value.

RateLimitError

Bases: AwsSecretsManagerError

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

ReplicaRegion dataclass

A replica region for create_secret.

ReplicationStatus dataclass

Replication status of one replica region.

Request dataclass

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.

RequestInfo dataclass

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

ResourcePolicyResult dataclass

Bases: SecretRef

Result of get_resource_policy.

resource_policy is the policy JSON text (None without a policy); policy is the parsed object (None when absent or not a JSON object).

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 dataclass

A completed HTTP response (body fully read).

json

json() -> Any

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

ResponseInfo dataclass

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

RetryPolicy dataclass

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.

max_attempts property

max_attempts: int

Total attempts including the first one.

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).

RotationRules dataclass

Rotation schedule: every N days, or a rate(…) / cron(…) expression.

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: 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: OnChange, *, on_error: OnError | None = None, version: str | None = None, path: str | None = None) -> WatchHandle

Watches the underlying provider directly (bypasses the cache).

SecretCacheSource

Bases: Protocol

The client operations :class:AwsSecretCache needs.

SecretDescription dataclass

Secret metadata (DescribeSecret, ListSecrets entries). Never contains the value.

pending_deletion property

pending_deletion: bool

True when the secret is scheduled for deletion.

version_id_for_stage

version_id_for_stage(stage: str = AWSCURRENT) -> str | None

The version id that carries stage (None when no version has it).

SecretFilter dataclass

A ListSecrets / BatchGetSecretValue filter. A value prefixed ! negates it.

SecretMetadata dataclass

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

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

SecretRef dataclass

ARN and name of a secret.

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.

SecretVersion dataclass

One version of a secret (ListSecretVersionIds).

SecretWriteResult dataclass

Bases: SecretRef

Result of writes that may create a version (version_id is None when none was).

SecretsProvider

Bases: Protocol

Synchronous secrets interface implemented by every secrets service package.

TimeoutError

Bases: AwsSecretsManagerError

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

TlsConfig dataclass

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

UnavailableError

Bases: AwsSecretsManagerError

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

UnsupportedError

Bases: AwsSecretsManagerError

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

ValidateResourcePolicyResult dataclass

Result of validate_resource_policy.

ValidationError

Bases: AwsSecretsManagerError

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

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).

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] = time.monotonic) -> T

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

aws_error_code

aws_error_code(err: BaseException) -> str | None

The AWS error code behind an SDK error (or a botocore ClientError), if known.

code_for_status

code_for_status(status: int) -> ErrorCode

SPEC 2.1 status mapping (used only when the AWS error code is unknown).

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_code_from_body

error_code_from_body(text: str) -> str | None

The error code of an XML (<Code>) error body, None when there is none.

error_for_code

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

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.

full_name

full_name(name: str, path: str | None) -> str

path/name when a path is given, otherwise name.

get_logger

get_logger() -> logging.Logger

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

map_aws_error

map_aws_error(exc: BaseException, operation: str, *, known_secrets: Iterable[str | Secret | None] = (), unsupported_on_html_500: bool = False) -> AwsSecretsManagerError

Converts anything boto3 / aiobotocore raises into an SDK error.

The message is "<operation>: <AwsCode>: <redacted vendor text> (HTTP <status>)"; the AWS code is kept on the error (:func:aws_error_code). unsupported_on_html_500 marks an operation some emulators lack: a non-JSON HTTP 500 then maps to UNSUPPORTED.

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.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] = time.sleep, clock: Callable[[], float] = time.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_HEADERS, *, now: Callable[[], float] = time.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_metadata

to_metadata(d: SecretDescription) -> SecretMetadata

A :class:SecretDescription as SPEC :class:SecretMetadata.

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.