Skip to content

The agent that grows with you

fix(dashboard-auth): clock-skew leeway for JWT verification; classify not-yet-valid tokens as validation failures

Austin Pickettc5cb0f597b7c
diff --git a/plugins/dashboard_auth/_shared.py b/plugins/dashboard_auth/_shared.py
index 8d17d0b4a0b..526321bc62e 100644
--- a/plugins/dashboard_auth/_shared.py
+++ b/plugins/dashboard_auth/_shared.py
@@ -10,6 +10,7 @@ from __future__ import annotations
import base64
import hashlib
import logging
+import math
import os
import secrets
import urllib.parse
@@ -26,6 +27,12 @@ JWKS_CACHE_SECONDS = 300
TOKEN_ENDPOINT_TIMEOUT_SEC = 10.0
JSON_HEADERS = {"Accept": "application/json"}
+# Clock-skew leeway (seconds) for JWT time-claim verification (RFC 7519 §4.1.4-4.1.6
+# allow "some small leeway, usually no more than a few minutes"). Applied symmetrically
+# to exp/nbf/iat by PyJWT; 60s absorbs the sub-second NTP jitter / unsynced-container
+# drift seen in the field (#47815) without meaningfully extending token lifetime.
+DEFAULT_TOKEN_LEEWAY_SECONDS = 60.0
+
# ---- Config / env resolution ----
@@ -49,6 +56,29 @@ def resolve_env_or_cfg(env_name: str, cfg_value: Any) -> str:
return os.environ.get(env_name, "").strip() or str(cfg_value or "").strip()
+def parse_leeway(raw: Any) -> float:
+ """Seconds of clock-skew tolerance for JWT time claims, fail-closed.
+
+ Unset → :data:`DEFAULT_TOKEN_LEEWAY_SECONDS` (60s — the zero-leeway default
+ made any issuer-ahead clock skew fail, #47815). An explicit value must be a
+ finite, non-negative number: unparseable / negative / NaN / inf fall back to
+ ``0.0`` so a typo can only ever *lose* tolerance, never widen the window.
+ ``0`` is honoured (strict pre-fix behaviour for operators who want it).
+ """
+ if raw is None:
+ return DEFAULT_TOKEN_LEEWAY_SECONDS
+ text = str(raw).strip()
+ if not text:
+ return DEFAULT_TOKEN_LEEWAY_SECONDS
+ try:
+ value = float(text)
+ except ValueError:
+ return 0.0
+ if not math.isfinite(value) or value < 0:
+ return 0.0
+ return value
+
+
# ---- register() bookkeeping ----
class SkipRegistration(Exception):
@@ -190,31 +220,41 @@ def make_jwks_client(jwks_url: str) -> Any:
def verify_jwt(
- token: str, jwks_client: Any, *, algorithms: list[str], audience: str, issuer: str, label: str) -> Dict[str, Any]:
+ token: str, jwks_client: Any, *, algorithms: list[str], audience: str, issuer: str, label: str,
+ leeway: float = DEFAULT_TOKEN_LEEWAY_SECONDS,
+) -> Dict[str, Any]:
"""Verify ``token`` against ``jwks_client`` with pinned ``aud``/``iss``.
+ ``leeway`` is seconds of clock-skew tolerance on the time claims (default
+ 60 — the previous zero-leeway made any issuer-ahead skew fail login, #47815).
+
Unreachable JWKS → ``ProviderError`` (503); a bearer that is not one of our JWTs
(opaque peer key, foreign kid) → ``InvalidCodeError`` (None / next provider); folding
- both into 503 broke peer-key bearers. Expiry raises ``InvalidCodeError`` (verify_session
- maps it to None); any other claim failure raises ``ProviderError`` with the unverified
- iss/aud appended so operators can spot config drift.
+ both into 503 broke peer-key bearers. Expiry and not-yet-valid (``iat``/``nbf`` in
+ the future beyond the leeway — a *token* failure, not a transport failure) raise
+ ``InvalidCodeError`` (verify_session maps it to None); any other claim failure raises
+ ``ProviderError`` with the unverified iss/aud appended so operators can spot config
+ drift.
"""
import jwt # lazy — keeps startup fast for the ungated path
try:
signing_key = jwks_client.get_signing_key_from_jwt(token)
except Exception as exc:
- # Unreachable JWKS -> ProviderError (503); a bearer that is not one of our JWTs (opaque peer key,
- # foreign kid) -> InvalidCodeError (None / next provider). Folding both into 503 produced #94558.
# Unreachable JWKS -> ProviderError (503); a bearer that is not one of our JWTs (opaque peer key,
# foreign kid) -> InvalidCodeError (None / next provider). Folding both into 503 produced #94558.
raise classify_jwks_lookup_error(exc) from exc
try:
return jwt.decode(
- token, signing_key.key, algorithms=algorithms, audience=audience, issuer=issuer,
+ token, signing_key.key, algorithms=algorithms, audience=audience, issuer=issuer, leeway=leeway,
options={"require": ["exp", "iat", "aud", "iss", "sub"]})
except jwt.ExpiredSignatureError as exc:
raise InvalidCodeError(f"{label} expired: {exc}") from exc
+ except jwt.ImmatureSignatureError as exc:
+ # iat/nbf ahead of now beyond the leeway = clock skew or a bad token — the
+ # provider is *reachable*, so this must NOT surface as ProviderError/503
+ # (which discarded rotated refresh tokens and forced re-login, #47815).
+ raise InvalidCodeError(f"{label} not yet valid: {exc}") from exc
except jwt.InvalidTokenError as exc:
# Decoding without verification is safe here: verification already failed and
# these values are surfaced for diagnostics only, never trusted.
diff --git a/plugins/dashboard_auth/nous/__init__.py b/plugins/dashboard_auth/nous/__init__.py
index 3f56be7794f..ee1713c7c71 100644
--- a/plugins/dashboard_auth/nous/__init__.py
+++ b/plugins/dashboard_auth/nous/__init__.py
@@ -15,10 +15,12 @@ from typing import Any, Dict, Optional
from hermes_cli.dashboard_auth import LoginStart, ProviderError, Session
from plugins.dashboard_auth._shared import (
+ DEFAULT_TOKEN_LEEWAY_SECONDS,
JwtOAuthProvider,
SkipRegistration,
exchange_token,
load_config_section,
+ parse_leeway,
pkce_login_start,
refresh_token_from,
register_provider,
@@ -43,13 +45,16 @@ class NousDashboardAuthProvider(JwtOAuthProvider):
name = "nous"
display_name = "Nous Research"
- def __init__(self, *, client_id: str, portal_url: str) -> None:
+ def __init__(self, *, client_id: str, portal_url: str, token_leeway: float = DEFAULT_TOKEN_LEEWAY_SECONDS) -> None:
# Defense-in-depth: register() filters too, but a malformed id must never construct a provider.
if not client_id.startswith("agent:"):
raise ValueError(f"client_id must match contract shape 'agent:{{instance_id}}', got {client_id!r}")
self._client_id = client_id
self._agent_instance_id = client_id[len("agent:") :]
self._portal_url = portal_url.rstrip("/")
+ # Clock-skew tolerance (seconds) for the access token's exp/nbf/iat claims;
+ # the default absorbs Portal/host clock skew (#47815), 0 restores strict mode.
+ self._token_leeway = parse_leeway(token_leeway)
self._jwks_url = f"{self._portal_url}/.well-known/jwks.json"
self._authorize_url = f"{self._portal_url}/oauth/authorize"
self._token_url = f"{self._portal_url}/api/oauth/token"
@@ -93,7 +98,7 @@ class NousDashboardAuthProvider(JwtOAuthProvider):
claims = verify_jwt(
access_token, self._get_jwks_client(), algorithms=["RS256"],
audience=self._client_id, # contract C2: bare client_id
- issuer=self._portal_url, label="access token")
+ issuer=self._portal_url, label="access token", leeway=self._token_leeway)
# Contract C9: agent_instance_id is "should" not "must" — tolerated when absent
# (the aud check already binds the token to this instance).
token_instance_id = claims.get("agent_instance_id")
@@ -142,7 +147,9 @@ def _settings() -> dict:
f"shape 'agent:{{instance_id}}'. The Nous Portal provisions this value at deploy "
f"time; check your Fly app's secrets or override with the value from the Portal admin UI.",
level="warning")
- return {"client_id": client_id, "portal_url": portal_url}
+ return {"client_id": client_id, "portal_url": portal_url,
+ # Clock-skew tolerance for access-token exp/nbf/iat (config.yaml only; default 60s, 0 = strict).
+ "token_leeway": parse_leeway(section.get("token_leeway"))}
def register(ctx) -> None:
@@ -152,4 +159,5 @@ def register(ctx) -> None:
kwargs, LAST_SKIP_REASON = register_provider(ctx, logger, _TAG, NousDashboardAuthProvider, _settings)
if kwargs is not None:
logger.info(
- "dashboard-auth-nous: registered provider (client_id=%s, portal=%s)", kwargs["client_id"], kwargs["portal_url"])
+ "dashboard-auth-nous: registered provider (client_id=%s, portal=%s, token_leeway=%ss)",
+ kwargs["client_id"], kwargs["portal_url"], kwargs["token_leeway"])
diff --git a/plugins/dashboard_auth/self_hosted/__init__.py b/plugins/dashboard_auth/self_hosted/__init__.py
index 5347f948a84..f056b973a7f 100644
--- a/plugins/dashboard_auth/self_hosted/__init__.py
+++ b/plugins/dashboard_auth/self_hosted/__init__.py
@@ -5,7 +5,9 @@ endpoints from ``{issuer}/.well-known/openid-configuration``, builds the PKCE (S
URL, exchanges the code, and verifies the **ID token** (the access token is opaque per spec)
against the discovered ``jwks_uri`` with ``iss``/``aud`` pinned. Public and confidential
(``client_secret`` layered on top of PKCE, never replacing it) clients both work. Config:
-``dashboard.oauth.self_hosted.{issuer,client_id,scopes,client_secret}`` or ``HERMES_DASHBOARD_OIDC_*``.
+``dashboard.oauth.self_hosted.{issuer,client_id,scopes,client_secret,id_token_leeway}`` or
+``HERMES_DASHBOARD_OIDC_*`` (leeway is config.yaml-only; default 60s of clock-skew tolerance
+for the ID token's time claims, ``0`` restores strict verification).
"""
from __future__ import annotations
@@ -21,6 +23,7 @@ import httpx
from hermes_cli.dashboard_auth import LoginStart, ProviderError, Session
from plugins.dashboard_auth._shared import (
+ DEFAULT_TOKEN_LEEWAY_SECONDS,
JSON_HEADERS,
TOKEN_ENDPOINT_TIMEOUT_SEC as _TOKEN_ENDPOINT_TIMEOUT_SEC,
JwtOAuthProvider,
@@ -28,6 +31,7 @@ from plugins.dashboard_auth._shared import (
exchange_token,
load_config_section,
parse_json_body,
+ parse_leeway,
pkce_login_start,
refresh_token_from,
register_provider,
@@ -79,7 +83,14 @@ class SelfHostedOIDCProvider(JwtOAuthProvider):
name = "self-hosted"
display_name = "Self-Hosted OIDC"
- def __init__(self, *, issuer: str, client_id: str, scopes: str = _DEFAULT_SCOPES, client_secret: str = "") -> None:
+ # Class-level default so partially-constructed instances (object.__new__ in
+ # tests) still verify with the standard clock-skew leeway.
+ _id_token_leeway: float = DEFAULT_TOKEN_LEEWAY_SECONDS
+
+ def __init__(
+ self, *, issuer: str, client_id: str, scopes: str = _DEFAULT_SCOPES, client_secret: str = "",
+ id_token_leeway: float = DEFAULT_TOKEN_LEEWAY_SECONDS,
+ ) -> None:
if not issuer:
raise ValueError("issuer is required")
if not client_id:
@@ -90,6 +101,9 @@ class SelfHostedOIDCProvider(JwtOAuthProvider):
_require_https_or_loopback(self._issuer, field="issuer")
self._client_id = client_id
self._scopes = scopes.strip() or _DEFAULT_SCOPES
+ # Clock-skew tolerance (seconds) for the ID token's exp/nbf/iat claims;
+ # the default absorbs unsynced-IDP skew (#47815), 0 restores strict mode.
+ self._id_token_leeway = parse_leeway(id_token_leeway)
# Empty/whitespace secret ⇒ public client, so a provisioned-but-blank secret
# can't flip us into a broken confidential mode.
self._client_secret = (client_secret or "").strip()
@@ -251,7 +265,7 @@ class SelfHostedOIDCProvider(JwtOAuthProvider):
issuer = self._get_discovery()["issuer"]
return verify_jwt(
id_token, self._get_jwks_client(), algorithms=list(_ALLOWED_ID_TOKEN_ALGS),
- audience=self._client_id, issuer=issuer, label="ID token")
+ audience=self._client_id, issuer=issuer, label="ID token", leeway=self._id_token_leeway)
_claims_for = _verify_id_token
@@ -299,7 +313,9 @@ def _settings() -> dict:
"issuer": issuer, "client_id": client_id,
"scopes": setting("HERMES_DASHBOARD_OIDC_SCOPES", "scopes") or _DEFAULT_SCOPES,
# Credential: canonical home is the env var / ~/.hermes/.env. Empty ⇒ public client.
- "client_secret": setting("HERMES_DASHBOARD_OIDC_CLIENT_SECRET", "client_secret")}
+ "client_secret": setting("HERMES_DASHBOARD_OIDC_CLIENT_SECRET", "client_secret"),
+ # Clock-skew tolerance for ID-token exp/nbf/iat (config.yaml only; default 60s, 0 = strict).
+ "id_token_leeway": parse_leeway(oidc_cfg.get("id_token_leeway"))}
def register(ctx) -> None:
@@ -309,5 +325,6 @@ def register(ctx) -> None:
kw, LAST_SKIP_REASON = register_provider(ctx, logger, _TAG, SelfHostedOIDCProvider, _settings)
if kw is not None:
logger.info(
- "dashboard-auth-self-hosted: registered provider (issuer=%s, client_id=%s, scopes=%r, confidential=%s)",
- kw["issuer"], kw["client_id"], kw["scopes"], bool(kw["client_secret"])) # never log the secret itself
+ "dashboard-auth-self-hosted: registered provider "
+ "(issuer=%s, client_id=%s, scopes=%r, confidential=%s, id_token_leeway=%ss)",
+ kw["issuer"], kw["client_id"], kw["scopes"], bool(kw["client_secret"]), kw["id_token_leeway"]) # never log the secret itself
diff --git a/tests/plugins/dashboard_auth/test_jwt_clock_skew_leeway.py b/tests/plugins/dashboard_auth/test_jwt_clock_skew_leeway.py
new file mode 100644
index 00000000000..ba2da4bf018
--- /dev/null
+++ b/tests/plugins/dashboard_auth/test_jwt_clock_skew_leeway.py
@@ -0,0 +1,266 @@
+"""Clock-skew leeway for dashboard-auth JWT verification (#47815).
+
+PyJWT's default ``leeway=0`` while ``iat`` is required means any host whose clock
+lags the issuer's — different VM/container, NTP jitter — fails verification with
+``ImmatureSignatureError``. Invariants covered here, one per acceptance case:
+
+1. A future-``iat`` token (clock skew) verifies with the default leeway — for the
+ shared ``verify_jwt``, the self-hosted OIDC provider and the Nous provider.
+2. ``ImmatureSignatureError`` beyond the leeway is a *validation* failure
+ (``InvalidCodeError`` → ``verify_session`` returns ``None`` → the middleware
+ retries/refreshes), NOT a ``ProviderError`` (which surfaces as 503
+ "provider unreachable" and historically discarded rotated refresh tokens).
+3. The leeway is configurable via config.yaml for both providers, and a typo
+ (unparseable / negative / non-finite) fails closed to 0 — it can never widen
+ the window.
+
+All HTTP and JWKS are stubbed; nothing here talks to a real IdP or Portal.
+"""
+
+from __future__ import annotations
+
+import math
+import time
+from typing import Any, Dict
+from unittest.mock import MagicMock
+
+import jwt as pyjwt
+import pytest
+from cryptography.hazmat.primitives import serialization
+from cryptography.hazmat.primitives.asymmetric import rsa
+
+import plugins.dashboard_auth._shared as shared
+import plugins.dashboard_auth.nous as nous_plugin
+import plugins.dashboard_auth.self_hosted as oidc_plugin
+from hermes_cli.dashboard_auth import InvalidCodeError, ProviderError
+
+_ISSUER = "https://auth.example.com/application/o/hermes"
+_CLIENT_ID = "hermes-dashboard"
+_PORTAL = "https://portal.example.com"
+_DISCOVERY_DOC = {
+ "issuer": _ISSUER,
+ "authorization_endpoint": f"{_ISSUER}/authorize",
+ "token_endpoint": f"{_ISSUER}/token",
+ "jwks_uri": f"{_ISSUER}/jwks",
+}
+
+
[email protected](scope="module")
+def rsa_keypair() -> Dict[str, Any]:
+ key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ private_pem = key.private_bytes(
+ encoding=serialization.Encoding.PEM,
+ format=serialization.PrivateFormat.PKCS8,
+ encryption_algorithm=serialization.NoEncryption(),
+ ).decode()
+ public_key = serialization.load_pem_private_key(
+ private_pem.encode(), password=None
+ ).public_key()
+ return {"private_pem": private_pem, "public_key": public_key, "kid": "test-key-1"}
+
+
+def _fake_jwks_client(rsa_keypair) -> MagicMock:
+ fake_key = MagicMock()
+ fake_key.key = rsa_keypair["public_key"]
+ client = MagicMock()
+ client.get_signing_key_from_jwt.return_value = fake_key
+ return client
+
+
+def _mint_token(
+ rsa_keypair: Dict[str, Any],
+ *,
+ iss: str,
+ aud: str,
+ iat_offset: int = 0,
+ ttl_seconds: int = 900,
+) -> str:
+ """A minimal signed JWT whose ``iat`` is ``iat_offset`` seconds in the future."""
+ now = int(time.time())
+ claims = {"iss": iss, "aud": aud, "sub": "usr_abc", "iat": now + iat_offset, "exp": now + ttl_seconds}
+ return pyjwt.encode(claims, rsa_keypair["private_pem"], algorithm="RS256", headers={"kid": rsa_keypair["kid"]})
+
+
+def _self_hosted_provider(rsa_keypair, *, leeway: float | None = None) -> Any:
+ kwargs: Dict[str, Any] = {"issuer": _ISSUER, "client_id": _CLIENT_ID}
+ if leeway is not None:
+ kwargs["id_token_leeway"] = leeway
+ p = oidc_plugin.SelfHostedOIDCProvider(**kwargs)
+ p._discovery = dict(_DISCOVERY_DOC)
+ p._discovery_fetched_at = time.time()
+ p._jwks_client = _fake_jwks_client(rsa_keypair)
+ return p
+
+
+def _nous_provider(rsa_keypair, *, leeway: float | None = None) -> Any:
+ kwargs: Dict[str, Any] = {"client_id": "agent:inst123", "portal_url": _PORTAL}
+ if leeway is not None:
+ kwargs["token_leeway"] = leeway
+ p = nous_plugin.NousDashboardAuthProvider(**kwargs)
+ p._jwks_client = _fake_jwks_client(rsa_keypair)
+ return p
+
+
+# ---------------------------------------------------------------------------
+# 1. Future-iat tokens verify with the default leeway (clock skew tolerated)
+# ---------------------------------------------------------------------------
+
+
+class TestDefaultLeewayAbsorbsClockSkew:
+ """A token whose iat is seconds ahead of the verifier (issuer clock skew)
+ is the normal case for hosts without tight time-sync — RFC 7519 §4.1.4-4.1.6
+ allow "some small leeway, usually no more than a few minutes"."""
+
+ SKEW = 30 # seconds of issuer-ahead skew, well inside the 60s default
+
+ def test_shared_verify_jwt(self, rsa_keypair):
+ token = _mint_token(rsa_keypair, iss=_ISSUER, aud=_CLIENT_ID, iat_offset=self.SKEW)
+ claims = shared.verify_jwt(
+ token, _fake_jwks_client(rsa_keypair), algorithms=["RS256"],
+ audience=_CLIENT_ID, issuer=_ISSUER, label="ID token")
+ assert claims["sub"] == "usr_abc"
+
+ def test_self_hosted_verify_session(self, rsa_keypair):
+ provider = _self_hosted_provider(rsa_keypair)
+ token = _mint_token(rsa_keypair, iss=_ISSUER, aud=_CLIENT_ID, iat_offset=self.SKEW)
+ session = provider.verify_session(access_token=token)
+ assert session is not None
+ assert session.user_id == "usr_abc"
+
+ def test_nous_verify_session(self, rsa_keypair):
+ provider = _nous_provider(rsa_keypair)
+ token = _mint_token(rsa_keypair, iss=_PORTAL, aud="agent:inst123", iat_offset=self.SKEW)
+ session = provider.verify_session(access_token=token)
+ assert session is not None
+ assert session.user_id == "usr_abc"
+
+
+# ---------------------------------------------------------------------------
+# 2. ImmatureSignatureError beyond the leeway is a validation failure, not 503
+# ---------------------------------------------------------------------------
+
+
+class TestImmatureSignatureClassification:
+ """Skew larger than the leeway still fails — but as a *token* failure
+ (InvalidCodeError → verify_session returns None → middleware refreshes /
+ 401s), never as ProviderError ("provider unreachable" / 503), which used to
+ discard already-rotated refresh tokens."""
+
+ HUGE_SKEW = 3600 # an hour ahead: far beyond any sane leeway
+
+ def test_shared_verify_jwt_raises_invalid_code(self, rsa_keypair):
+ token = _mint_token(rsa_keypair, iss=_ISSUER, aud=_CLIENT_ID, iat_offset=self.HUGE_SKEW)
+ with pytest.raises(InvalidCodeError, match="not yet valid"):
+ shared.verify_jwt(
+ token, _fake_jwks_client(rsa_keypair), algorithms=["RS256"],
+ audience=_CLIENT_ID, issuer=_ISSUER, label="ID token")
+
+ def test_self_hosted_verify_session_returns_none(self, rsa_keypair):
+ provider = _self_hosted_provider(rsa_keypair)
+ token = _mint_token(rsa_keypair, iss=_ISSUER, aud=_CLIENT_ID, iat_offset=self.HUGE_SKEW)
+ assert provider.verify_session(access_token=token) is None
+
+ def test_nous_verify_session_returns_none(self, rsa_keypair):
+ provider = _nous_provider(rsa_keypair)
+ token = _mint_token(rsa_keypair, iss=_PORTAL, aud="agent:inst123", iat_offset=self.HUGE_SKEW)
+ assert provider.verify_session(access_token=token) is None
+
+
+# ---------------------------------------------------------------------------
+# 3. parse_leeway fails closed
+# ---------------------------------------------------------------------------
+
+
+class TestParseLeeway:
+ def test_empty_uses_default(self):
+ assert shared.parse_leeway(None) == shared.DEFAULT_TOKEN_LEEWAY_SECONDS
+ assert shared.parse_leeway("") == shared.DEFAULT_TOKEN_LEEWAY_SECONDS
+
+ @pytest.mark.parametrize("bad", ["not-a-number", "-5", "nan", "inf", "-inf", float("nan"), float("inf")])
+ def test_invalid_fails_closed_to_zero(self, bad):
+ assert shared.parse_leeway(bad) == 0.0
+
+ def test_valid_values(self):
+ assert shared.parse_leeway("0") == 0.0
+ assert shared.parse_leeway(30) == 30.0
+ assert shared.parse_leeway("120.5") == 120.5
+
+ def test_explicit_zero_is_respected(self):
+ # leeway=0 keeps the strict pre-fix behaviour for operators who want it
+ assert shared.parse_leeway(0) == 0.0
+
+ def test_finite_check(self):
+ assert not math.isinf(shared.parse_leeway("60"))
+
+
+# ---------------------------------------------------------------------------
+# 4. Config plumbing (config.yaml only — no new env vars)
+# ---------------------------------------------------------------------------
+
+
+def _patch_oauth_config(monkeypatch, oauth_block):
+ cfg = {} if oauth_block is None else {"dashboard": {"oauth": oauth_block}}
+ monkeypatch.setattr("hermes_cli.config.load_config", lambda: cfg)
+
+
+class TestSelfHostedConfig:
+ @pytest.fixture(autouse=True)
+ def clear_env(self, monkeypatch):
+ for var in ("HERMES_DASHBOARD_OIDC_ISSUER", "HERMES_DASHBOARD_OIDC_CLIENT_ID"):
+ monkeypatch.delenv(var, raising=False)
+
+ def test_leeway_from_config_yaml(self, monkeypatch, rsa_keypair):
+ _patch_oauth_config(monkeypatch, {"self_hosted": {
+ "issuer": _ISSUER, "client_id": _CLIENT_ID, "id_token_leeway": 300}})
+ ctx = MagicMock()
+ oidc_plugin.register(ctx)
+ registered = ctx.register_dashboard_auth_provider.call_args.args[0]
+ assert registered._id_token_leeway == 300.0
+
+ def test_unset_leeway_uses_default(self, monkeypatch):
+ _patch_oauth_config(monkeypatch, {"self_hosted": {"issuer": _ISSUER, "client_id": _CLIENT_ID}})
+ ctx = MagicMock()
+ oidc_plugin.register(ctx)
+ registered = ctx.register_dashboard_auth_provider.call_args.args[0]
+ assert registered._id_token_leeway == shared.DEFAULT_TOKEN_LEEWAY_SECONDS
+
+ def test_invalid_config_leeway_fails_closed(self, monkeypatch, rsa_keypair):
+ _patch_oauth_config(monkeypatch, {"self_hosted": {
+ "issuer": _ISSUER, "client_id": _CLIENT_ID, "id_token_leeway": "garbage"}})
+ ctx = MagicMock()
+ oidc_plugin.register(ctx)
+ registered = ctx.register_dashboard_auth_provider.call_args.args[0]
+ assert registered._id_token_leeway == 0.0
+
+ def test_explicit_leeway_bounds_tolerance(self, rsa_keypair):
+ # leeway=0: a clearly-future iat is rejected (strict mode still available)
+ provider = _self_hosted_provider(rsa_keypair, leeway=0)
+ token = _mint_token(rsa_keypair, iss=_ISSUER, aud=_CLIENT_ID, iat_offset=60)
+ assert provider.verify_session(access_token=token) is None
+
+
+class TestNousConfig:
+ @pytest.fixture(autouse=True)
+ def clear_env(self, monkeypatch):
+ monkeypatch.delenv("HERMES_DASHBOARD_OAUTH_CLIENT_ID", raising=False)
+
+ def test_leeway_from_config_yaml(self, monkeypatch):
+ _patch_oauth_config(monkeypatch, {"client_id": "agent:inst123", "token_leeway": 120})
+ ctx = MagicMock()
+ nous_plugin.register(ctx)
+ registered = ctx.register_dashboard_auth_provider.call_args.args[0]
+ assert registered._token_leeway == 120.0
+
+ def test_unset_leeway_uses_default(self, monkeypatch):
+ _patch_oauth_config(monkeypatch, {"client_id": "agent:inst123"})
+ ctx = MagicMock()
+ nous_plugin.register(ctx)
+ registered = ctx.register_dashboard_auth_provider.call_args.args[0]
+ assert registered._token_leeway == shared.DEFAULT_TOKEN_LEEWAY_SECONDS
+
+ def test_invalid_config_leeway_fails_closed(self, monkeypatch):
+ _patch_oauth_config(monkeypatch, {"client_id": "agent:inst123", "token_leeway": -3})
+ ctx = MagicMock()
+ nous_plugin.register(ctx)
+ registered = ctx.register_dashboard_auth_provider.call_args.args[0]
+ assert registered._token_leeway == 0.0
diff --git a/tests/plugins/dashboard_auth/test_nous_provider.py b/tests/plugins/dashboard_auth/test_nous_provider.py
index d9cd1193e82..6cdbf17f842 100644
--- a/tests/plugins/dashboard_auth/test_nous_provider.py
+++ b/tests/plugins/dashboard_auth/test_nous_provider.py
@@ -437,7 +437,9 @@ class TestVerifySession:
return p
def test_expired_token_returns_none(self, provider, rsa_keypair):
- token = _mint_token(rsa_keypair, ttl_seconds=-1)
+ # Well past the 60s default leeway — a just-expired token is accepted
+ # within the clock-skew window (RFC 7519 §4.1.4), a long-dead one is not.
+ token = _mint_token(rsa_keypair, ttl_seconds=-600)
assert provider.verify_session(access_token=token) is None
def test_wrong_audience_raises_provider_error(self, provider, rsa_keypair):
diff --git a/tests/plugins/dashboard_auth/test_self_hosted_provider.py b/tests/plugins/dashboard_auth/test_self_hosted_provider.py
index 7b451ec17d7..713d11c896f 100644
--- a/tests/plugins/dashboard_auth/test_self_hosted_provider.py
+++ b/tests/plugins/dashboard_auth/test_self_hosted_provider.py
@@ -681,7 +681,9 @@ class TestVerifySession:
def test_expired_returns_none(self, provider, rsa_keypair):
- token = _mint_id_token(rsa_keypair, ttl_seconds=-1)
+ # Well past the 60s default leeway — a just-expired token is accepted
+ # within the clock-skew window (RFC 7519 §4.1.4), a long-dead one is not.
+ token = _mint_id_token(rsa_keypair, ttl_seconds=-600)
assert provider.verify_session(access_token=token) is None
def test_wrong_audience_raises(self, provider, rsa_keypair):
diff --git a/website/docs/user-guide/features/web-dashboard.md b/website/docs/user-guide/features/web-dashboard.md
index 99727e86e29..580b8a55f61 100644
--- a/website/docs/user-guide/features/web-dashboard.md
+++ b/website/docs/user-guide/features/web-dashboard.md
@@ -690,6 +690,7 @@ The plugin reads from two surfaces, with the environment variable winning when s
dashboard:
oauth:
client_id: agent:01HXYZ… # required to engage the gate
+ token_leeway: 60 # optional; seconds of clock-skew tolerance
```
**Environment variables** — operator overrides:
@@ -702,6 +703,8 @@ Per the Hermes Agent convention (`~/.hermes/.env` is for API keys / secrets only
Empty environment values are treated as unset, so a provisioned-but-not-populated platform secret can't accidentally shadow a valid `config.yaml` entry.
+`dashboard.oauth.token_leeway` (config.yaml only) is the clock-skew tolerance — in seconds — applied to the Portal access token's `exp`/`nbf`/`iat` claims during JWT verification. The default is `60` (RFC 7519 §4.1.4-4.1.6), so a host whose clock lags the Portal's doesn't fail login; `0` restores strict verification, and an invalid value (unparseable / negative / non-finite) fails closed to `0`. The self-hosted OIDC provider has the equivalent `dashboard.oauth.self_hosted.id_token_leeway` knob.
+
If neither source provides a client_id, the plugin reports the specific reason and the dashboard's fail-closed bind error tells you exactly what to fix:
```
@@ -854,6 +857,7 @@ dashboard:
issuer: https://auth.example.com/application/o/hermes/ # required
client_id: hermes-dashboard # required
scopes: "openid profile email" # optional (this is the default)
+ id_token_leeway: 60 # optional; seconds of clock-skew tolerance
```
**Environment variables** — operator overrides (env wins over `config.yaml` when set non-empty; an empty value is treated as unset):
@@ -868,7 +872,7 @@ In your IDP, register a **public** application/client with the authorization-cod
#### What it verifies
-The provider verifies the OpenID Connect **ID token** (RS256/ES256) against the discovered `jwks_uri`, with the `iss` and `aud` claims pinned to your configured `issuer` and `client_id`. Standard OIDC claims map onto the dashboard session:
+The provider verifies the OpenID Connect **ID token** (RS256/ES256) against the discovered `jwks_uri`, with the `iss` and `aud` claims pinned to your configured `issuer` and `client_id`. The time claims (`exp`/`nbf`/`iat`) are verified with a 60-second clock-skew leeway (RFC 7519 §4.1.4-4.1.6), so a dashboard host whose clock lags the IDP's doesn't fail login; tune it with `dashboard.oauth.self_hosted.id_token_leeway` in `config.yaml` (any value below `60` tightens it, `0` restores strict verification, and an invalid value fails closed to `0`). Standard OIDC claims map onto the dashboard session:
| Session field | Claim(s) |
|---------------|----------|