"""Signed links to what the Orchestration engine keeps (ADR-0004). A link is a path with `exp` and `sig` in its query: `sig` is an HMAC of the path and `exp` under the engine's secret. `exp` 0 never expires. """ from __future__ import annotations import hashlib import hmac import time from collections.abc import Callable from urllib.parse import urlencode class Signer: def __init__( self, secret: str, ttl_seconds: int, now: Callable[[], float] = time.time, ) -> None: self._secret = secret.encode() self._ttl = ttl_seconds self._now = now def _signature(self, path: str, exp: int) -> str: return hmac.new( self._secret, f"{path}\n{exp}".encode(), hashlib.sha256 ).hexdigest() def sign(self, path: str) -> dict[str, str]: """The query that makes `path` readable.""" exp = int(self._now()) + self._ttl if self._ttl > 0 else 0 return {"exp": str(exp), "sig": self._signature(path, exp)} def verify(self, path: str, exp: str | None = None, sig: str | None = None) -> bool: if not exp or not sig or not exp.isdigit(): return False expires = int(exp) if expires and expires < self._now(): return False return hmac.compare_digest(sig, self._signature(path, expires)) def link(self, base_url: str, path: str) -> str: """`path` under `base_url`, signed.""" return f"{base_url.rstrip('/')}{path}?{urlencode(self.sign(path))}"