text stringlengths 0 1.47k |
|---|
if parent == base or base not in parent.parents: |
break |
try: |
parent.rmdir() |
except OSError: |
break |
await asyncio.to_thread(_do) |
async def list(self, kb: str, prefix: str, limit: int = 20, cursor: str | None = None) -> dict: |
# Walk only the subtree the prefix names: everything before its last "/" is a directory |
# under the store, the rest a name prefix inside it. Walking the whole store cost every |
# blob on every call, and a paged listing repeated the walk per page: with 15k blobs on a |
# self-hosted volume one turns read took 55 s and the gateway sat at 150% CPU (2026-09-06). |
def _do(): |
base = (self._root / kb).resolve() |
dir_part, _, _ = prefix.rpartition("/") |
top = (base / dir_part).resolve() if dir_part else base |
if not str(top).startswith(str(base)) or not top.is_dir(): # escape or nothing there |
return {"items": [], "cursor": None} |
root_len = len(str(base)) + 1 |
keys: list[str] = [] |
for root, _dirs, files in os.walk(top): |
rel = root[root_len:].replace(os.sep, "/") if len(root) > root_len else "" |
for name in files: |
if name.endswith(".tmp"): |
continue |
key = f"{rel}/{name}" if rel else name |
if key.startswith(prefix) and (not cursor or key > cursor): |
keys.append(key) |
keys.sort() |
page = keys[:limit] |
nxt = page[-1] if len(keys) > limit else None |
return {"items": [{"file_id": k} for k in page], "cursor": nxt} |
return await asyncio.to_thread(_do) |
async def probe(self) -> None: |
def _do(): |
self._root.mkdir(parents=True, exist_ok=True) |
if not os.access(self._root, os.W_OK): |
raise RuntimeError(f"blob root not writable: {self._root}") |
await asyncio.to_thread(_do) |
# ── local: env/file secrets ("bring your own provider keys") ────────────────────── |
class SecretsNotConfigured(RuntimeError): |
"""Raised when a secret must be written but there is nowhere safe to write it. |
Deliberately an error rather than a fallback. A provider key injected read-only through the |
environment is one risk; a customer's production database connection string written to a file |
in plaintext is another entirely, and the difference is not something to decide silently on |
the operator's behalf.""" |
class FileSecretStore: |
"""Reads HR_SECRET_{TENANT}_{NAME} from the environment first (read-only injection — the |
open-repo way to supply provider credentials without any vault), then falls back to files |
under {root}/{tenant}/{name}. |
Files are ENCRYPTED when HR_SECRET_KEY is set: AES-256-GCM under a key derived from it, with |
a random nonce per write, stored as `hrenc1:<b64 nonce||ciphertext>`. Reads accept both forms, |
so a store written before this existed keeps working and re-encrypts on its next write. |
Without HR_SECRET_KEY, `put(..., require_encryption=True)` REFUSES. That is the whole point: |
the caller that stores a database credential says so, and on an instance with no key it gets |
an error telling the operator what to set, instead of a plaintext file nobody knew about.""" |
_MAGIC = "hrenc1:" |
def __init__(self, root: str): |
self._root = Path(root) |
self._key = self._derive(os.environ.get("HR_SECRET_KEY", "")) |
@property |
def encrypts(self) -> bool: |
return self._key is not None |
@staticmethod |
def _derive(passphrase: str) -> bytes | None: |
"""A 32-byte key from the operator's passphrase. Scrypt with a fixed salt: the salt's job |
is to stop cross-deployment rainbow tables, and there is nowhere to keep a random one that |
would not sit beside the ciphertext anyway.""" |
if not passphrase: |
return None |
return hashlib.scrypt(passphrase.encode(), salt=b"harnessrouter.secret.v1", |
n=2 ** 14, r=8, p=1, dklen=32) |
def _seal(self, value: str) -> str: |
from cryptography.hazmat.primitives.ciphers.aead import AESGCM |
nonce = secrets_mod.token_bytes(12) |
blob = nonce + AESGCM(self._key).encrypt(nonce, value.encode(), None) |
return self._MAGIC + base64.b64encode(blob).decode() |
def _open(self, raw: str) -> str: |
if not raw.startswith(self._MAGIC): |
return raw # written before encryption existed |
if self._key is None: |
raise SecretsNotConfigured( |
"This secret is encrypted but HR_SECRET_KEY is not set. Set it to the passphrase " |
"used when the secret was stored.") |
from cryptography.hazmat.primitives.ciphers.aead import AESGCM |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.