verify.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. """Inbound cron-fire token verification for Chronos.
  2. NAS POSTs ``/api/cron/fire`` with a short-lived NAS-minted JWT, verified via PyJWT (never
  3. hand-rolled) before any job runs. ``get_fire_verifier`` is the pluggable seam so an alternative
  4. auth mode (direct per-job cron-key) can swap in without a handler change.
  5. """
  6. from __future__ import annotations
  7. import logging
  8. import threading
  9. from typing import Any, Callable, Dict, Optional
  10. logger = logging.getLogger("cron.chronos.verify")
  11. # Purpose claim scoping a token to the fire endpoint (a general agent JWT must not replay here).
  12. _FIRE_PURPOSE = "cron_fire"
  13. # Process-wide PyJWKClient cache keyed by JWKS URL: PyJWKClient caches keys on the INSTANCE, so a
  14. # fresh client per fire re-fetched JWKS every time (portal rate-limits 403->401; relay 504s).
  15. _JWK_CLIENTS: dict[str, Any] = {}
  16. _JWK_CLIENTS_LOCK = threading.Lock()
  17. def _get_jwk_client(jwks_url: str) -> Any:
  18. """Return the process-cached PyJWKClient for ``jwks_url`` (double-checked lock)."""
  19. client = _JWK_CLIENTS.get(jwks_url)
  20. if client is not None:
  21. return client
  22. with _JWK_CLIENTS_LOCK:
  23. client = _JWK_CLIENTS.get(jwks_url)
  24. if client is None:
  25. from jwt import PyJWKClient
  26. # Explicit Accept + User-Agent: the portal WAF 403s the default urllib fingerprint.
  27. client = PyJWKClient(
  28. jwks_url, headers={"Accept": "application/json", "User-Agent": "HermesAgent/1.0"})
  29. _JWK_CLIENTS[jwks_url] = client
  30. return client
  31. def verify_nas_fire_token(*, token: str, expected_audience: str, jwks_or_key: Optional[str] = None,
  32. issuer: Optional[str] = None, leeway_seconds: int = 30) -> Optional[dict[str, Any]]:
  33. """Verify a NAS-minted cron-fire JWT; return decoded claims or None (never raises, so the
  34. handler answers 401 without leaking which check failed). Checks asymmetric signature (JWKS
  35. URL or inline PEM; symmetric rejected), ``aud``, ``exp``/``nbf`` with leeway, ``iss`` when
  36. configured, and ``purpose == "cron_fire"``."""
  37. if not token or not expected_audience:
  38. return None
  39. if not jwks_or_key: # never fall back to unsigned decode on a security boundary
  40. logger.warning("cron fire: no JWKS/key configured; refusing token")
  41. return None
  42. try:
  43. import jwt
  44. if jwks_or_key.startswith(("http://", "https://")):
  45. signing_key = _get_jwk_client(jwks_or_key).get_signing_key_from_jwt(token).key
  46. else:
  47. signing_key = jwks_or_key # inline PEM public key (test / pinned-key deployments)
  48. decode_kwargs: dict[str, Any] = dict(
  49. algorithms=["RS256", "RS384", "RS512", "ES256", "ES384"], audience=expected_audience,
  50. leeway=leeway_seconds, options={"require": ["exp", "aud"]})
  51. if issuer:
  52. decode_kwargs["issuer"] = issuer
  53. claims = jwt.decode(token, signing_key, **decode_kwargs)
  54. except Exception as e:
  55. logger.warning("cron fire: token verification failed: %s", e)
  56. return None
  57. if claims.get("purpose") != _FIRE_PURPOSE:
  58. logger.warning("cron fire: token missing/!=%s purpose claim", _FIRE_PURPOSE)
  59. return None
  60. return claims
  61. def get_fire_verifier() -> Callable[..., Optional[dict[str, Any]]]:
  62. """Return the active inbound-fire verifier (default: the NAS-JWT verifier)."""
  63. return verify_nas_fire_token