Skip to content

The agent that grows with you

fix(website-policy): make cache-hit check explicit

Kanan071959cabb32
diff --git a/tests/tools/test_website_policy_cache_scope.py b/tests/tools/test_website_policy_cache_scope.py
new file mode 100644
index 00000000000..e9b7769126a
--- /dev/null
+++ b/tests/tools/test_website_policy_cache_scope.py
@@ -0,0 +1,82 @@
+"""Regression tests for website-policy cache scope and TTL."""
+
+from __future__ import annotations
+
+from contextlib import contextmanager
+from pathlib import Path
+
+import pytest
+import yaml
+
+import tools.website_policy as website_policy
+from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+
+
+@contextmanager
+def _profile(home: Path):
+ token = set_hermes_home_override(home)
+ try:
+ yield
+ finally:
+ reset_hermes_home_override(token)
+
+
+def _write_policy(home: Path, *, enabled: bool, domains: list[str] | None = None) -> None:
+ home.mkdir(parents=True, exist_ok=True)
+ (home / "config.yaml").write_text(
+ yaml.safe_dump(
+ {
+ "security": {
+ "website_blocklist": {
+ "enabled": enabled,
+ "domains": domains or [],
+ }
+ }
+ },
+ sort_keys=False,
+ ),
+ encoding="utf-8",
+ )
+
+
[email protected](autouse=True)
+def _reset_website_policy_cache():
+ website_policy._cached_policy = None
+ website_policy._cached_policy_path = None
+ website_policy._cached_policy_time = 0.0
+ yield
+ website_policy._cached_policy = None
+ website_policy._cached_policy_path = None
+ website_policy._cached_policy_time = 0.0
+
+
+def test_disabled_fast_path_does_not_cross_profile_boundary(tmp_path):
+ first = tmp_path / "first"
+ second = tmp_path / "second"
+ _write_policy(first, enabled=False)
+ _write_policy(second, enabled=True, domains=["blocked.test"])
+
+ with _profile(first):
+ assert website_policy.check_website_access("https://blocked.test") is None
+
+ with _profile(second):
+ result = website_policy.check_website_access("https://blocked.test")
+
+ assert result is not None
+ assert result["rule"] == "blocked.test"
+
+
+def test_disabled_fast_path_respects_cache_ttl(tmp_path):
+ home = tmp_path / "profile"
+ _write_policy(home, enabled=False)
+
+ with _profile(home):
+ assert website_policy.check_website_access("https://blocked.test") is None
+
+ _write_policy(home, enabled=True, domains=["blocked.test"])
+ website_policy._cached_policy_time -= website_policy._CACHE_TTL_SECONDS + 1
+
+ result = website_policy.check_website_access("https://blocked.test")
+
+ assert result is not None
+ assert result["rule"] == "blocked.test"
diff --git a/tools/website_policy.py b/tools/website_policy.py
index e629e3fa56e..f0c3acd657b 100644
--- a/tools/website_policy.py
+++ b/tools/website_policy.py
@@ -30,6 +30,18 @@ _cached_policy_path: Optional[str] = None
_cached_policy_time: float = 0.0
+def _fresh_cached_policy(resolved_path: str, now: float) -> Optional[Dict[str, Any]]:
+ """Return the cached policy only when it belongs to this config path and is still within TTL."""
+ with _cache_lock:
+ if (
+ _cached_policy is not None
+ and _cached_policy_path == resolved_path
+ and (now - _cached_policy_time) < _CACHE_TTL_SECONDS
+ ):
+ return _cached_policy
+ return None
+
+
class WebsitePolicyError(Exception):
"""Raised when a website policy file is malformed."""
@@ -105,10 +117,9 @@ def load_website_blocklist(config_path: Optional[Path] = None) -> dict[str, Any]
resolved_path = str(config_path or default_path)
now = time.monotonic()
if config_path is None:
- with _cache_lock:
- fresh = _cached_policy_path == resolved_path and (now - _cached_policy_time) < _CACHE_TTL_SECONDS
- if _cached_policy is not None and fresh:
- return _cached_policy
+ cached = _fresh_cached_policy(resolved_path, now)
+ if cached is not None:
+ return cached
config_path = config_path or default_path
policy = _load_policy_config(config_path)
domains = map(_normalize_rule, _require_type(policy, "domains", list, []))
@@ -154,11 +165,12 @@ def check_website_access(url: str, config_path: Optional[Path] = None) -> Option
Fails open on policy errors (warn + ``None``) so a config typo can't break all web tools — except with
an explicit ``config_path`` (tests), where errors propagate.
"""
- # Fast path: cached policy disabled/empty → no YAML read, no host extraction.
+ # Fast path: only a fresh disabled policy for THIS profile may skip loading/host parsing.
if config_path is None:
- with _cache_lock:
- if _cached_policy is not None and not _cached_policy.get("enabled"):
- return None
+ default_path = get_hermes_home() / "config.yaml"
+ cached = _fresh_cached_policy(str(default_path), time.monotonic())
+ if cached is not None and not cached.get("enabled"):
+ return None
host = _extract_host_from_urlish(url)
if not host:
return None