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
¶
The AWS caching-client defaults: {"ttl_s": 3600.0, "max_entries": 1024}.
get_secret_binary
async
¶
See :meth:AwsSecretCache.get_secret_binary.
get_secret_string
async
¶
See :meth:AwsSecretCache.get_secret_string.
get_secret_value
async
¶
See :meth:AwsSecretCache.get_secret_value.
refresh_now
async
¶
See :meth:AwsSecretCache.refresh_now.
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.
aclose
async
¶
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
¶
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
¶
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
¶
See :meth:AwsSecretsManagerClient.describe_secret.
from_env
classmethod
¶
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
¶
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.
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()).
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
¶
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 ¶
An async version-stage aware cache (see :class:AsyncAwsSecretCache).
secrets ¶
The async :class:SecretsProvider view of this client.
server_version
async
¶
Always raises :class:UnsupportedError (AWS exposes no server version).
tag_resource
async
¶
See :meth:AwsSecretsManagerClient.tag_resource.
untag_resource
async
¶
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
¶
Wraps an existing (entered) aiobotocore client; :meth:aclose leaves it open.
AsyncAwsSecretsManagerSecretsProvider ¶
Bases: AsyncBaseSecretsProvider
Async :class:AwsSecretsManagerSecretsProvider (async_client.secrets()).
AsyncBaseSecretsProvider ¶
Bases: ABC
Async counterpart of :class:BaseSecretsProvider (async primitives).
After :meth:aclose every call raises :class:CancelledError ("client is closed").
aclose
async
¶
Stop every watcher started by this provider; later calls raise CANCELLED (idempotent).
ensure_open ¶
Raise :class:CancelledError ("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").
AsyncPaginator ¶
AsyncSecretCache ¶
Bases: AsyncBaseSecretsProvider
Async :class:SecretCache; background refreshes run as asyncio tasks.
wait_refreshes
async
¶
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 ¶
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
¶
The AWS caching-client defaults: {"ttl_s": 3600.0, "max_entries": 1024}.
get_secret_binary ¶
The value as bytes.
get_secret_string ¶
The value as text (SecretString, or UTF-8 of the binary).
get_secret_value ¶
The cached value of secret_id at the stage (default: the cache's stage).
refresh_now ¶
Forces a refresh check now (and a fetch when the stage moved); returns the value.
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.
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 ¶
Turns rotation off and cancels a rotation in progress (CancelRotateSecret).
close ¶
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 ¶
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 ¶
Metadata of a secret (DescribeSecret), never the value.
from_env
classmethod
¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
A version-stage aware cache with the AWS caching-client semantics (TTL 1 h, 1024
entries); options are those of :class:AwsSecretCache.
secrets ¶
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 ¶
Always raises :class:UnsupportedError: AWS exposes no server version (the API
contract date is the constant API_VERSION).
tag_resource ¶
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
¶
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
¶
The override, or the public endpoint of region (us-east-1 when unset).
endpoint
property
¶
The endpoint override passed to the AWS SDK (None = the SDK resolves it).
from_env
classmethod
¶
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 ¶
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=...)readsVersionId = version(stage labels: useclient.get_secret_value).setstores UTF-8 text asSecretStringand other bytes asSecretBinary; it creates the secret when missing (withdescription/tags) and returns the new VersionId.casis not supported (:class:ValidationError).deleteschedules deletion with the recovery window (default 30 days);permanent=Truedeletes 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 underpath(non-recursive).get_many/get_alluseBatchGetSecretValuein chunks of 20.
get_all ¶
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.
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 underpath)_put_secret(name, data: bytes, SetOptions) -> str(new version or"")_remove_secret(name, DeleteOptions) -> None(raise :class:NotFoundErrorif 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 ("
close ¶
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 ¶
Raise :class:CancelledError ("close.
Service methods that do not go through the base operations can call it first.
get ¶
The secret, or None when it does not exist.
get_all ¶
Every secret directly under path (non-recursive), keyed by name.
get_bool ¶
true/false/1/0/yes/no/on/off, None when missing; else ValidationError.
get_json ¶
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 ¶
int or float, None when missing; :class:ValidationError otherwise.
list ¶
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 ¶
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.
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
¶
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.
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 (orNoneto keep the default). The mapped error is whatHooks.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").
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.
PermissionDeniedError ¶
Bases: AwsSecretsManagerError
Authenticated but not allowed (HTTP 403).
PolicyValidationError
dataclass
¶
One problem found by validate_resource_policy.
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 ¶
Track item; when the registry is already closed the item is stopped now.
Response
dataclass
¶
A completed HTTP response (body fully read).
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.
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')
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_factorstarts one background refresh. - Stale-while-revalidate: up to
ttl_s + stale_while_revalidate_sthe stale value is returned while one refresh runs. - LRU eviction beyond
max_entries.clock(monotonic seconds) is injectable;spawnruns background refreshes (default: a daemon thread). - :meth:
closemakes later calls raise :class:CancelledError("client is closed"); it does not close the wrapped provider.
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.
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 ¶
SHA-256 hex digest of the value (used by watch when there is no version).
SecretVersion
dataclass
¶
One version of a secret (ListSecretVersionIds).
SecretWriteResult
dataclass
¶
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.
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 ¶
The AWS error code behind an SDK error (or a botocore ClientError), if known.
code_for_status ¶
SPEC 2.1 status mapping (used only when the AWS error code is unknown).
env_var_name ¶
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 ¶
The error code of an XML (<Code>) error body, None when there is none.
error_for_code ¶
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 ¶
path/name when a path is given, otherwise name.
get_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.
parse_bool ¶
Parse true/false/1/0/yes/no/on/off (case-insensitive); raise :class:ValueError.
parse_duration ¶
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 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 ¶
Recursively redact values whose key looks sensitive in nested mappings and lists.
redact_headers ¶
Copy of headers with sensitive values replaced by [REDACTED].
redact_text ¶
Replace every known secret value (length >= 4) in text with [REDACTED].
redact_url ¶
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 ¶
A :class:SecretDescription as SPEC :class:SecretMetadata.
to_seconds ¶
Normalise a duration given as float seconds or :class:datetime.timedelta.
truncate ¶
Truncate text to limit characters (adds an ellipsis when cut).
user_agent ¶
grow-codes-<key>/<version> (python) plus <suffix> when given.