Source code for ds_common_placeholder_py_lib.secret_store

"""
**File:** ``secret_store.py``
**Region:** ``ds-common-placeholder-py-lib``

Description
-----------
Reads secrets from ds-vault (``ds-vault-py-sdk``) for ``get_secret``. The
package talks to the vault itself; there is nothing for a service to wire.
Tests and examples replace the vault with
:func:`ds_common_placeholder_py_lib.testing.fake_vault`.

Configuration is the same as the dispatchers': ``VAULT_DATABASE_URL`` for the
vault's Postgres table, and the usual AWS credentials for KMS. One client is
created per process on first use; nothing is read at import time.

The client keeps nothing between reads: the SDK's plaintext, decrypted data
key, record, and SSM parameter caches are all disabled, so a resolved secret lives only in
the execution that resolved it (contract §10) and a rotated secret is picked
up on the next read. The cost is one vault query and one KMS decrypt per
secret read. The SDK's caches are not thread-safe, so reads
are serialised.

The SDK does not check which tenant a key belongs to; ``get_secret`` does
that before calling :func:`read_secret` (contract §7).
"""

from __future__ import annotations

import os
import threading
from contextvars import ContextVar
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from collections.abc import Callable

VAULT_DSN_ENV = "VAULT_DATABASE_URL"

_lock = threading.Lock()
_client: Any = None
# Replaces ds-vault while ds_common_placeholder_py_lib.testing.fake_vault is
# active, in that thread or async task only.
_fake: ContextVar[Callable[[str], bytes | str | None] | None] = ContextVar("fake_vault", default=None)


[docs] def read_secret(key: str) -> bytes | str | None: """Read one vault value. Args: key: A vault path, already checked against the run's tenant. Returns: The stored bytes, or ``None`` if the vault has no such key. Raises: RuntimeError: If ``VAULT_DATABASE_URL`` is not set. Exception: Whatever the SDK raises for connection or decryption failures. ``get_secret`` turns it into ``secret_unavailable``. """ fake = _fake.get() if fake is not None: return fake(key) from vault import SecretNotFound # noqa: PLC0415 client = _vault_client() with _lock: try: value: bytes = client.get_secret(key=key) except SecretNotFound: return None return value
def _vault_client() -> Any: global _client # noqa: PLW0603 with _lock: if _client is None: dsn = os.environ.get(VAULT_DSN_ENV) if not dsn: raise RuntimeError(f"{VAULT_DSN_ENV} is not set") from vault import DSVaultClient # noqa: PLC0415 from vault.providers.kms import KMSProvider # noqa: PLC0415 from vault.providers.ssm import SSMProvider # noqa: PLC0415 from vault.repositories.postgres import PostgresSecretRepository # noqa: PLC0415 # maxsize=0: the caches drop every entry as soon as it is stored. _client = DSVaultClient( repository=PostgresSecretRepository(dsn=dsn, cache_maxsize=0), kms_provider=KMSProvider(cache_maxsize=0), ssm_provider=SSMProvider(cache_maxsize=0), plaintext_cache_maxsize=0, ) return _client