"""Secret resolution for channel credentials (the gateway's ``CredentialProvider`` pattern). ``channel_accounts`` rows hold only a *reference* (``secret_ref``, e.g. ``"acme-whatsapp-token"``), never a secret. The delivery worker and inbox poller resolve the reference at the moment they call the provider; the value lives only in that call's headers. It is never stored in a tenant table, written to a tool result, or shown to a model. ``EnvSecretStore`` reads ``WP_SECRET_`` (upper-cased, non-alphanumerics -> ``_``); a deployment swaps in a vault-backed store with the same one-method protocol. """ from __future__ import annotations import os import re import uuid from collections.abc import Mapping from typing import Protocol _NON_ALNUM = re.compile(r"[^A-Za-z0-9]+") MAX_REF = 120 class SecretNotFound(LookupError): pass class SecretStore(Protocol): def get(self, ref: str) -> str | None: ... def env_name(ref: str) -> str: return "WP_SECRET_" + _NON_ALNUM.sub("_", ref).strip("_").upper() def valid_ref(ref: str) -> bool: return 0 < len(ref) <= MAX_REF and bool(re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:/-]*", ref)) class EnvSecretStore: def __init__(self, environ: Mapping[str, str] | None = None) -> None: self._env = environ if environ is not None else os.environ def get(self, ref: str) -> str | None: if not valid_ref(ref): return None value = self._env.get(env_name(ref)) return value or None class StaticSecretStore: """In-memory store (tests, single-tenant demos).""" def __init__(self, values: Mapping[str, str]) -> None: self._values = dict(values) def get(self, ref: str) -> str | None: return self._values.get(ref) class ChannelCredentials: """Resolves an account's ``secret_ref`` (the CredentialProvider of the channel layer).""" def __init__(self, store: SecretStore | None = None) -> None: self.store: SecretStore = store or EnvSecretStore() def resolve(self, tenant_id: uuid.UUID, ref: str | None) -> str: if not ref: raise SecretNotFound(f"tenant {tenant_id}: channel account has no secret_ref") value = self.store.get(ref) if not value: raise SecretNotFound(f"tenant {tenant_id}: secret {ref!r} is not set") return value