Source code for ds_common_placeholder_py_lib.functions.secrets

"""
**File:** ``functions/secrets.py``
**Region:** ``ds-common-placeholder-py-lib``

Description
-----------
``get_secret`` (contract §7): tenant-scoped vault keys, base64 handling, and
recording each value so :meth:`Context.scrub <ds_common_placeholder_py_lib.context.Context.scrub>`
can remove it.
"""

from __future__ import annotations

import base64
import binascii
from typing import TYPE_CHECKING, Any

from ..errors import ErrorCode, PlaceholderError
from ..secret_store import read_secret

if TYPE_CHECKING:
    from ..context import Context

_VAULT_PREFIX = ("", "ds", "vault")


[docs] def key_tenant(key: object) -> str | None: """The tenant segment of a vault key ``/ds/vault/<store>/<tenant>/…``. Only the tenant is read; the rest of the key's format is the definition author's (and the frontend's) concern. Returns ``None`` when the key has no tenant segment, so it cannot be shown to belong to any tenant. """ if not isinstance(key, str): return None parts = key.split("/") if len(parts) < 5 or tuple(parts[:3]) != _VAULT_PREFIX or not parts[4]: return None return parts[4]
[docs] def get_secret(ctx: Context, args: list[Any]) -> str: """Read a vault value of the run's tenant from ds-vault. Raises: PlaceholderError: ``secret_scope`` if the key's tenant segment is not the context's tenant (checked before the vault is read), ``secret_missing`` if the vault has no such key, ``secret_unavailable`` if the vault cannot be read (configuration, connection, or KMS), ``type`` if the value is not UTF-8. """ key = args[0] if key_tenant(key) != ctx.tenant_id: raise PlaceholderError(ErrorCode.SECRET_SCOPE, "key does not belong to the run's tenant") try: raw = read_secret(key) except Exception as exc: # Driver and KMS errors can quote the DSN or key material: keep no chain. raise PlaceholderError(ErrorCode.SECRET_UNAVAILABLE, f"vault read failed ({type(exc).__name__})") from None if raw is None: raise PlaceholderError(ErrorCode.SECRET_MISSING, "secret not found") if isinstance(raw, bytes): try: raw = raw.decode("utf-8") except UnicodeDecodeError: raise PlaceholderError(ErrorCode.TYPE, "secret is not valid UTF-8") from None ctx._record_secret(raw) value = _try_base64(raw) ctx._record_secret(value) return value
[docs] def secret(ctx: Context, args: list[Any]) -> str: """A secret already read upstream (``resolve(strict=False)`` writes each one as ``@{secret, '…'}``): return it and record it, so :meth:`Context.scrub` and the SQL check know it.""" value: str = args[0] ctx._record_secret(value) return value
def _try_base64(value: str) -> str: try: return base64.b64decode(value, validate=True).decode("utf-8") except (binascii.Error, ValueError): return value