Skip to content

The agent that grows with you

fix(models): key the pricing cache per credential, not per auth state

Mariano Nicolinie89f0087b477
diff --git a/hermes_cli/models.py b/hermes_cli/models.py
index e2bd3a66825..c5a3d1e5d0a 100644
--- a/hermes_cli/models.py
+++ b/hermes_cli/models.py
@@ -2256,23 +2256,39 @@ def _cache_catalog(
# NUL cannot appear in a URL, so this cannot collide with a real base URL.
-_PRICING_AUTH_KEY_SUFFIX = "\x00auth"
+_PRICING_AUTH_KEY_PREFIX = "\x00auth:"
+
+
+def _pricing_auth_fingerprint(api_key: str | None) -> str:
+ """Key suffix identifying the credential a catalog was read with.
+
+ A governed endpoint answers each token with the catalog its org may reach,
+ so two credentials cannot share an entry. blake2b for cache-key
+ fingerprinting only, same rationale as :func:`_custom_endpoint_fingerprint`.
+ """
+ if not api_key:
+ return ""
+ import hashlib
+
+ digest = hashlib.blake2b(api_key.encode("utf-8", errors="replace"), digest_size=8)
+ return _PRICING_AUTH_KEY_PREFIX + digest.hexdigest()
def peek_cached_pricing(base_url: str) -> dict[str, dict[str, Any]]:
"""Pricing already cached for *base_url*, or ``{}``. Never fetches.
Accepts a ``/v1``-suffixed URL as well as the pre-``/v1`` root the fetchers
- key on, and prefers the authenticated catalog.
+ key on, and prefers an authenticated catalog. Scans rather than rebuilding a
+ key, because callers hold a base URL but no credential.
"""
root = (base_url or "").rstrip("/")
if root.endswith("/v1"):
root = root[:-3].rstrip("/")
- for key in (root + _PRICING_AUTH_KEY_SUFFIX, root):
- cached = _pricing_cache.get(key)
- if cached:
+ authed_prefix = root + _PRICING_AUTH_KEY_PREFIX
+ for key, cached in _pricing_cache.items():
+ if cached and key.startswith(authed_prefix):
return cached
- return {}
+ return _pricing_cache.get(root) or {}
def _format_price_per_mtok(per_token_str: str) -> str:
@@ -2411,8 +2427,8 @@ def fetch_models_with_pricing(
) -> dict[str, dict[str, Any]]:
"""Fetch ``/v1/models`` and return ``{model_id: {prompt, completion, ...}}``.
- Results are cached per *base_url* and per auth state, so repeated calls
- are free and an authenticated read never answers an anonymous one.
+ Results are cached per *base_url* and per credential, so repeated calls are
+ free and one caller's catalog never answers another's read.
Works with any OpenRouter-compatible endpoint (OpenRouter, Nous Portal).
When *include_sale_original* is true (Nous Portal only) and the gateway
@@ -2424,11 +2440,7 @@ def fetch_models_with_pricing(
``original``.
"""
url_root = (base_url or "").rstrip("/")
- # A governed endpoint answers an authenticated read with a policy-filtered
- # catalog and an anonymous one with the full catalog, so the two cannot
- # share an entry. Only whether a key was supplied participates, never its
- # value.
- cache_key = url_root + _PRICING_AUTH_KEY_SUFFIX if api_key else url_root
+ cache_key = url_root + _pricing_auth_fingerprint(api_key)
if not force_refresh:
cached = _cached_catalog(cache_key)
if cached is not None:
diff --git a/tests/hermes_cli/test_nous_policy_filter.py b/tests/hermes_cli/test_nous_policy_filter.py
index 35a0de704e8..2de05979643 100644
--- a/tests/hermes_cli/test_nous_policy_filter.py
+++ b/tests/hermes_cli/test_nous_policy_filter.py
@@ -13,7 +13,11 @@ import pytest
import hermes_cli.models as models_mod
import hermes_cli.nous_account as account_mod
-from hermes_cli.models import nous_policy_allowed_ids, restrict_to_nous_policy
+from hermes_cli.models import (
+ _NOUS_POLICY_APPEND_MAX,
+ nous_policy_allowed_ids,
+ restrict_to_nous_policy,
+)
from hermes_cli.nous_account import nous_policy_present
@@ -191,43 +195,21 @@ class TestAllowlistOutsideTheCuratedList:
)
assert kept == ["z/curated", "a/curated"]
- def test_jurisdiction_policy_never_grows_the_list(self):
- """A region filter can slip under the size cap, so the cap alone is not
- enough of a guard."""
- curated = ["vendor/one", "vendor/two", "vendor/three"]
- reachable = {"vendor/one", "vendor/two"} | {f"cn/model-{i}" for i in range(20)}
- assert restrict_to_nous_policy(curated, reachable, rescue_empty=True) == [
- "vendor/one",
- "vendor/two",
- ]
-
- def test_does_not_append_a_free_sibling_already_covered(self):
- assert restrict_to_nous_policy(
- ["vendor/m:free"], {"vendor/m"}, rescue_empty=True
- ) == ["vendor/m:free"]
-
- def test_a_provider_only_policy_does_not_bury_the_curated_order(self):
- curated = ["vendor/one", "vendor/two"]
- catalog = {f"vendor/model-{i}" for i in range(300)} | set(curated)
- assert restrict_to_nous_policy(curated, catalog, rescue_empty=True) == curated
+ def test_does_not_rescue_a_catalog_sized_allowed_set(self):
+ """Past the cap the set reads as a whole catalog, and dumping it would
+ bury the curated order the pickers show on purpose."""
+ oversized = {f"cn/model-{i}" for i in range(_NOUS_POLICY_APPEND_MAX + 1)}
+ assert restrict_to_nous_policy(["vendor/one"], oversized, rescue_empty=True) == []
class TestRescueIsOptIn:
"""The rescue is meaningful only for the list a user picks from."""
- def test_no_rescue_by_default(self):
- assert restrict_to_nous_policy([], {"a/one", "b/two"}) == []
-
def test_rescue_only_when_asked(self):
- assert restrict_to_nous_policy(
- [], {"a/one"}, rescue_empty=True
- ) == ["a/one"]
+ assert restrict_to_nous_policy([], {"a/one"}, rescue_empty=True) == ["a/one"]
def test_an_already_empty_unavailable_list_is_never_filled(self):
"""A paid tier has no gated models, so this list is legitimately
empty — not a filter result to rescue."""
reachable = {f"cn/model-{i}" for i in range(42)}
assert restrict_to_nous_policy([], reachable) == []
-
- def test_rescue_does_not_resurrect_a_fully_blocked_list(self):
- assert restrict_to_nous_policy(["x/blocked"], {"y/allowed"}) == []
diff --git a/tests/hermes_cli/test_pricing_cache_auth_key.py b/tests/hermes_cli/test_pricing_cache_auth_key.py
index d67c8d6e3a0..df3946ac390 100644
--- a/tests/hermes_cli/test_pricing_cache_auth_key.py
+++ b/tests/hermes_cli/test_pricing_cache_auth_key.py
@@ -1,8 +1,7 @@
-"""``_pricing_cache`` keys on auth state, not just the base URL.
+"""``_pricing_cache`` keys on the credential, not just the base URL.
-Nous ``/v1/models`` answers an authenticated read with a policy-filtered
-catalog and an anonymous one with the full catalog, so the two must not share
-a cache entry.
+Nous ``/v1/models`` answers each caller with the catalog their org may reach,
+so an anonymous read, and two different tokens, must not share a cache entry.
"""
from __future__ import annotations
@@ -57,23 +56,57 @@ def catalog(monkeypatch):
return requests
-def test_authenticated_read_is_not_answered_by_an_anonymous_one(catalog):
- anon = fetch_models_with_pricing(api_key="", base_url=BASE)
- authed = fetch_models_with_pricing(api_key="sk-test", base_url=BASE)
+def per_org_catalog(monkeypatch):
+ """Serve each token the catalog its own org may reach."""
+ requests: list[str | None] = []
- assert sorted(anon) == sorted(_FULL)
- assert sorted(authed) == sorted(_FILTERED)
- assert len(catalog) == 2, "the authenticated read must reach the network"
- assert catalog[0] is None and catalog[1] == "Bearer sk-test"
+ def _fake_urlopen(req, timeout=8.0):
+ auth = req.get_header("Authorization")
+ requests.append(auth)
+ org = "a" if auth == "Bearer tok-a" else "b"
+ payload = {
+ "data": [
+ {
+ "id": f"org-{org}/only",
+ "pricing": {"prompt": "0.000002", "completion": "0.00001"},
+ }
+ ]
+ }
+ resp = MagicMock()
+ resp.read.return_value = json.dumps(payload).encode()
+ resp.__enter__ = lambda self: self
+ resp.__exit__ = lambda *a: False
+ return resp
+
+ monkeypatch.setattr(models_mod, "_urlopen_model_catalog_request", _fake_urlopen)
+ return requests
-def test_anonymous_read_is_not_answered_by_an_authenticated_one(catalog):
- authed = fetch_models_with_pricing(api_key="sk-test", base_url=BASE)
+def test_one_token_does_not_receive_another_tokens_catalog(per_org_catalog):
+ """Two orgs in one process — a long-lived gateway or desktop backend after
+ a profile switch or re-login."""
+ a = fetch_models_with_pricing(api_key="tok-a", base_url=BASE)
+ b = fetch_models_with_pricing(api_key="tok-b", base_url=BASE)
+
+ assert list(a) == ["org-a/only"]
+ assert list(b) == ["org-b/only"], "token B was handed token A's catalog"
+ assert len(per_org_catalog) == 2, "token B must reach the network"
+
+
+def test_credential_value_does_not_appear_in_the_cache_key():
+ """Guards against keying on the raw token."""
+ assert "sk-super-secret" not in models_mod._pricing_auth_fingerprint("sk-super-secret")
+
+
+def test_anonymous_and_authenticated_reads_are_separate(catalog):
+ """Also pins the header: anonymous must send none."""
anon = fetch_models_with_pricing(api_key="", base_url=BASE)
+ authed = fetch_models_with_pricing(api_key="sk-test", base_url=BASE)
- assert sorted(authed) == sorted(_FILTERED)
assert sorted(anon) == sorted(_FULL)
- assert len(catalog) == 2
+ assert sorted(authed) == sorted(_FILTERED)
+ assert catalog == [None, "Bearer sk-test"]
@pytest.mark.parametrize("api_key", ["sk-test", ""])