mirror of
https://github.com/NousResearch/hermes-agent.git
synced 2026-11-17 04:11:35 +00:00
# Conflicts: # apps/desktop/e2e/archived-hidden-session-recoverable.spec.ts # apps/desktop/e2e/bot-chat-message-agent-friendly-name.spec.ts # apps/desktop/e2e/bot-mailbox-unreadable-ticket.spec.ts # apps/desktop/e2e/bot-mode-roster-localized.spec.ts # apps/desktop/e2e/bot-mode-row-click-mirrors-registry.spec.ts # apps/desktop/e2e/bot-mode-tab-shows-bot-name.spec.ts # apps/desktop/e2e/bot-roster-group-row-organisation.spec.ts # apps/desktop/e2e/bot-roster-ignores-infra-dirs.spec.ts # apps/desktop/e2e/bot-roster-timestamp-meta.spec.ts # apps/desktop/e2e/bot-roster-user-sections.spec.ts # apps/desktop/e2e/bot-routines-pane-narrow.spec.ts # apps/desktop/e2e/bot-row-open-recent-session.spec.ts # apps/desktop/e2e/bot-tile-ignores-ambient-composer-model.spec.ts # apps/desktop/e2e/group-composer-auto-grow.spec.ts # apps/desktop/e2e/group-create-gate-remote-roster.spec.ts # apps/desktop/e2e/group-prompt-renamed-primary-handle.spec.ts # apps/desktop/e2e/hosted-room-backend-continuity.spec.ts # apps/desktop/e2e/hosted-room-legacy-store-migration.spec.ts # apps/desktop/e2e/settings-scope-chips-bot-title.spec.ts # apps/desktop/e2e/worktree-branch-status.spec.ts # apps/desktop/electron/backend-probes.test.ts # apps/desktop/electron/connection-apply.test.ts # apps/desktop/electron/desktop-electron-pin.test.ts # apps/desktop/electron/desktop-uninstall.test.ts # apps/desktop/electron/gateway-file-download-transport.test.ts # apps/desktop/electron/gateway-stop-before-update.test.ts # apps/desktop/electron/github-api-auth.test.ts # apps/desktop/electron/registry-primary-profile-scope.test.ts # apps/desktop/electron/update-api-check.test.ts # apps/desktop/electron/update-handoff-marker.test.ts # apps/desktop/electron/venv-blocker-scan.test.ts # apps/desktop/scripts/after-extract.test.mjs # apps/desktop/scripts/local-pack-publish.test.mjs # apps/desktop/scripts/tasks-scroll.test.mjs # apps/desktop/src/app/settings/model-settings.test.tsx # apps/desktop/src/app/updates-overlay.blockers.test.tsx # apps/desktop/src/components/desktop-install-overlay.test.tsx # apps/desktop/src/lib/update-copy.test.ts # scripts/ci/check_os_marker_fakes.py # tests-js/desktop-mac-usage-descriptions.test.ts # tests-js/node-engine-alignment.test.ts # tests/agent/lsp/test_install_and_lint_fixes.py # tests/agent/test_command_token_source.py # tests/agent/test_compression_boundary_hook.py # tests/agent/test_create_openai_client_ssl_verify.py # tests/agent/test_custom_provider_ca_probes.py # tests/agent/test_endpoint_blackhole.py # tests/agent/test_estimator_parity.py # tests/agent/test_in_place_compaction.py # tests/agent/test_moa_loop_mode.py # tests/agent/test_model_metadata.py # tests/agent/test_skill_session_platform_gate.py # tests/agent/test_skill_utils.py # tests/agent/test_ssl_ca_guard.py # tests/computer_use/test_doctor.py # tests/cron/test_codex_execution_paths.py # tests/cron/test_cron_bot_chat_delivery.py # tests/cron/test_cron_script.py # tests/cron/test_media_delivery_parity.py # tests/cron/test_misfire_catchup.py # tests/cron/test_parallel_pool.py # tests/cron/test_recurring_eagain_redispatch.py # tests/gateway/test_choice_picker.py # tests/gateway/test_control_socket_windows_live.py # tests/gateway/test_dingtalk.py # tests/gateway/test_feishu.py # tests/gateway/test_feishu_onboard.py # tests/gateway/test_gateway_shutdown.py # tests/gateway/test_matrix.py # tests/gateway/test_model_command_custom_providers.py # tests/gateway/test_reasoning_command.py # tests/gateway/test_runtime_footer.py # tests/gateway/test_session.py # tests/gateway/test_session_hygiene.py # tests/gateway/test_status.py # tests/gateway/test_teams.py # tests/gateway/test_turn_lease.py # tests/gateway/test_whatsapp_connect.py # tests/hermes_cli/test_approvals_command.py # tests/hermes_cli/test_auth_store_lock_concurrent.py # tests/hermes_cli/test_backup.py # tests/hermes_cli/test_banner_git_state.py # tests/hermes_cli/test_certifi_repair.py # tests/hermes_cli/test_cmd_update.py # tests/hermes_cli/test_compat_manifest_targets.py # tests/hermes_cli/test_computer_use_cli.py # tests/hermes_cli/test_cpr_local_leak.py # tests/hermes_cli/test_dashboard_auth_gate.py # tests/hermes_cli/test_dashboard_procs_kill_grace.py # tests/hermes_cli/test_desktop_lifecycle_windows_live.py # tests/hermes_cli/test_doctor.py # tests/hermes_cli/test_doctor_command_install.py # tests/hermes_cli/test_fleet_config_migration_windows_live.py # tests/hermes_cli/test_gateway.py # tests/hermes_cli/test_gateway_platform_gating.py # tests/hermes_cli/test_gateway_restart_loop.py # tests/hermes_cli/test_gateway_task_probe.py # tests/hermes_cli/test_gateway_wsl.py # tests/hermes_cli/test_gui_command.py # tests/hermes_cli/test_install_cua_driver.py # tests/hermes_cli/test_kanban_db.py # tests/hermes_cli/test_lazy_command_exports.py # tests/hermes_cli/test_lazy_refresh_venv_repair.py # tests/hermes_cli/test_linux_desktop_entry.py # tests/hermes_cli/test_local_runtime.py # tests/hermes_cli/test_local_runtime_updates.py # tests/hermes_cli/test_managed_uv.py # tests/hermes_cli/test_mcp_reload_confirm_gate.py # tests/hermes_cli/test_nous_subscription.py # tests/hermes_cli/test_npm_engine.py # tests/hermes_cli/test_personality_none.py # tests/hermes_cli/test_pet_toggle.py # tests/hermes_cli/test_plan_reconciliation_windows_live.py # tests/hermes_cli/test_plugin_event_bus.py # tests/hermes_cli/test_plugin_manifest_v2.py # tests/hermes_cli/test_plugin_packs.py # tests/hermes_cli/test_plugins_cmd.py # tests/hermes_cli/test_plugins_cmd_enable_disable_nested.py # tests/hermes_cli/test_process_identity.py # tests/hermes_cli/test_profiles.py # tests/hermes_cli/test_profiles_sidebar_cache.py # tests/hermes_cli/test_pty_bridge.py # tests/hermes_cli/test_resolve_turn_limit.py # tests/hermes_cli/test_serve_runtime_inventory.py # tests/hermes_cli/test_session_vacuum_config.py # tests/hermes_cli/test_set_config_value.py # tests/hermes_cli/test_signal_handler_kanban_worker.py # tests/hermes_cli/test_slash_confirm_windows.py # tests/hermes_cli/test_stale_pid_guard.py # tests/hermes_cli/test_startup_fast_guards.py # tests/hermes_cli/test_status.py # tests/hermes_cli/test_telegram_managed_bot.py # tests/hermes_cli/test_tools_config.py # tests/hermes_cli/test_update_apply_shallow_count.py # tests/hermes_cli/test_update_autostash.py # tests/hermes_cli/test_update_concurrent_quarantine.py # tests/hermes_cli/test_update_fetch_failure_classifier.py # tests/hermes_cli/test_update_fleet_probe_resume_token.py # tests/hermes_cli/test_update_handoff_backend_reap.py # tests/hermes_cli/test_update_handoff_desktop_rebuild.py # tests/hermes_cli/test_update_head_moved_gate.py # tests/hermes_cli/test_update_host_obligation.py # tests/hermes_cli/test_update_import_guard.py # tests/hermes_cli/test_update_interrupted_recovery.py # tests/hermes_cli/test_update_inventory.py # tests/hermes_cli/test_update_launchd_unloaded_gateway.py # tests/hermes_cli/test_update_missing_configured_deps.py # tests/hermes_cli/test_update_modified_notice.py # tests/hermes_cli/test_update_multiplex_migration_hook.py # tests/hermes_cli/test_update_no_gateway_restart.py # tests/hermes_cli/test_update_orphan_backend_reap.py # tests/hermes_cli/test_update_parked_branch_guard.py # tests/hermes_cli/test_update_post_pull_syntax_guard.py # tests/hermes_cli/test_update_receipt.py # tests/hermes_cli/test_update_self_lock.py # tests/hermes_cli/test_update_shim_fail_closed.py # tests/hermes_cli/test_update_shim_self_lock.py # tests/hermes_cli/test_update_sqlite_remediation.py # tests/hermes_cli/test_update_stale_dashboard.py # tests/hermes_cli/test_update_stale_virtualenv.py # tests/hermes_cli/test_update_venv_health.py # tests/hermes_cli/test_update_venv_ownership_preflight.py # tests/hermes_cli/test_update_wedged_gateway.py # tests/hermes_cli/test_update_yes_flag.py # tests/hermes_cli/test_update_zip_two_phase.py # tests/hermes_cli/test_urllib_security.py # tests/hermes_cli/test_ux_messages_auth_config.py # tests/hermes_cli/test_ux_messages_startup.py # tests/hermes_cli/test_venv_holder_classifier.py # tests/hermes_cli/test_verify_console_scripts.py # tests/hermes_cli/test_verify_core_dependencies.py # tests/hermes_cli/test_web_server.py # tests/hermes_cli/test_web_server_console_ws.py # tests/hermes_cli/test_web_server_ws_ping.py # tests/hermes_cli/test_web_ui_build.py # tests/hermes_state/test_fts_rebuild_admission.py # tests/hermes_state/test_hermes_state.py # tests/plugins/memory/test_memory_lazy_install.py # tests/plugins/test_google_meet_plugin.py # tests/plugins/test_langfuse_plugin.py # tests/plugins/test_security_guidance_plugin.py # tests/plugins/test_transform_llm_output_hook.py # tests/scripts/desktop_update/test_desktop_update_windows_gateway_flag.py # tests/scripts/desktop_update/test_desktop_update_windows_python_handoff.py # tests/scripts/desktop_update/test_desktop_update_windows_timestamp.py # tests/scripts/install/test_install_clone_throttle_fallback.py # tests/scripts/install/test_install_lockfile_churn.py # tests/scripts/install/test_install_no_initial_commit.py # tests/scripts/install/test_install_sh_browser_install.py # tests/scripts/install/test_install_sh_node_prerelease.py # tests/scripts/install/test_install_sh_symlink_stomp.py # tests/scripts/install/test_install_sh_uv_lock_config.py # tests/scripts/install/test_install_unmerged_index.py # tests/scripts/test_contributor_map.py # tests/scripts/test_run_tests_parallel.py # tests/skills/test_competitor_news_monitor_skill.py # tests/skills/test_document_to_action_items_skill.py # tests/skills/test_google_workspace_setup.py # tests/skills/test_google_workspace_setup_deps.py # tests/skills/test_grounded_citations_skill.py # tests/skills/test_ip_as_logo_skill.py # tests/skills/test_live_dashboard_skill.py # tests/skills/test_mcp_oauth_remote_gateway_skill.py # tests/skills/test_office_document_skills.py # tests/skills/test_openclaw_migration.py # tests/skills/test_product_price_monitor_skill.py # tests/skills/test_scrollcraft_skill.py # tests/skills/test_setup_wizard_generator_skill.py # tests/skills/test_weekly_review_planning_skill.py # tests/test_engines_satisfiable.py # tests/test_fast_safe_load.py # tests/test_hermes_bootstrap.py # tests/test_hermes_constants.py # tests/test_hermes_logging.py # tests/test_managed_runtime_resolution.py # tests/test_model_tools_async_bridge.py # tests/test_packaging_build_guard.py # tests/test_packaging_metadata.py # tests/test_yaml_indent_consistency.py # tests/tools/test_approval_timeout_overflow.py # tests/tools/test_base_environment.py # tests/tools/test_bot_mode_dm.py # tests/tools/test_browser_chromium_check.py # tests/tools/test_browser_hardening.py # tests/tools/test_browser_homebrew_paths.py # tests/tools/test_browser_npx_warmup.py # tests/tools/test_browser_orphan_reaper.py # tests/tools/test_browser_real_profile.py # tests/tools/test_browser_use_cli.py # tests/tools/test_clipboard.py # tests/tools/test_code_execution.py # tests/tools/test_code_execution_modes.py # tests/tools/test_code_execution_windows_env.py # tests/tools/test_computer_use.py # tests/tools/test_delegate_liveness_timeout.py # tests/tools/test_execute_code_approval_cluster.py # tests/tools/test_execution_flag_detection.py # tests/tools/test_fal_common.py # tests/tools/test_file_operations.py # tests/tools/test_file_tools.py # tests/tools/test_file_tools_cwd_resolution.py # tests/tools/test_file_tools_live.py # tests/tools/test_lazy_deps.py # tests/tools/test_lazy_deps_durable_target.py # tests/tools/test_lazy_deps_managed.py # tests/tools/test_local_env_blocklist.py # tests/tools/test_local_tempdir.py # tests/tools/test_macos_protected_search.py # tests/tools/test_mcp_npx_cached_bin.py # tests/tools/test_oneshot_completion_linger.py # tests/tools/test_process_registry.py # tests/tools/test_read_file_schema_gating.py # tests/tools/test_skill_improvements.py # tests/tools/test_skills_sync.py # tests/tools/test_termux_api_detection.py # tests/tools/test_tirith_security.py # tests/tools/test_transcription_tools.py # tests/tools/test_tts_streaming.py # tests/tools/test_wake_word.py # tests/tui_gateway/test_compute_host_borrowed_lease.py # tests/tui_gateway/test_compute_host_turn_protocol.py # tests/tui_gateway/test_isolated_orphan_activity.py # tests/tui_gateway/test_protocol.py # tests/tui_gateway/test_slash_worker_profile_home.py # tests/tui_gateway/test_subprocess_encoding.py # tests/tui_gateway/test_tui_gateway_server.py # ui-tui/src/__tests__/terminalParity.test.ts # ui-tui/src/__tests__/termuxComposerLayout.test.ts # ui-tui/src/__tests__/textInputFastEcho.test.ts
487 lines
19 KiB
Python
487 lines
19 KiB
Python
"""Tests for cold-load token expiry tracking in MCP OAuth.
|
|
|
|
PR #11383's consolidation fixed external-refresh reloading (mtime disk-watch)
|
|
and 401 dedup, but left two underlying latent bugs in place:
|
|
|
|
1. ``HermesTokenStorage.set_tokens`` persisted only relative ``expires_in``,
|
|
which is meaningless after a process restart.
|
|
2. The MCP SDK's ``OAuthContext._initialize`` loads ``current_tokens`` from
|
|
storage but does NOT call ``update_token_expiry``, so
|
|
``token_expiry_time`` stays None. ``is_token_valid()`` then returns True
|
|
for any loaded token regardless of actual age, and the SDK's preemptive
|
|
refresh branch at ``oauth2.py:491`` is never taken.
|
|
|
|
Consequence: a token that expired while the process was down ships to the
|
|
server with a stale Bearer header. The server's response is provider-specific
|
|
— some return HTTP 401 (caught by the consolidation's 401 handler, which
|
|
surfaces a ``needs_reauth`` error), others return HTTP 200 with an
|
|
application-level auth failure in the body (e.g. BetterStack's "No teams
|
|
found. Please check your authentication."), which the consolidation cannot
|
|
detect.
|
|
|
|
These tests pin the contract for Fix A:
|
|
- ``set_tokens`` persists an absolute ``expires_at`` wall-clock timestamp.
|
|
- ``get_tokens`` reconstructs ``expires_in`` from ``expires_at - now`` so
|
|
the SDK's ``update_token_expiry`` computes the correct absolute expiry.
|
|
- ``HermesMCPOAuthProvider._initialize`` seeds ``context.token_expiry_time``
|
|
after loading, so ``is_token_valid()`` reports True only for tokens that
|
|
are actually still valid, and the SDK's preemptive refresh fires for
|
|
expired tokens with a live refresh_token.
|
|
|
|
Reference: Claude Code solves this via an ``OAuthTokens.expiresAt`` absolute
|
|
timestamp persisted alongside the access_token (``auth.ts:~180``).
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import json
|
|
import time
|
|
|
|
import pytest
|
|
|
|
pytest.importorskip("mcp.client.auth.oauth2", reason="MCP SDK 1.26.0+ required")
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# HermesTokenStorage — absolute expiry persistence
|
|
# ---------------------------------------------------------------------------
|
|
|
|
class TestSetTokensAbsoluteExpiry:
|
|
def test_set_tokens_persists_absolute_expires_at(self, tmp_path, monkeypatch):
|
|
"""Tokens round-tripped through disk must encode absolute expiry."""
|
|
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
|
from mcp.shared.auth import OAuthToken
|
|
|
|
from tools.mcp_oauth import HermesTokenStorage
|
|
|
|
storage = HermesTokenStorage("srv")
|
|
before = time.time()
|
|
asyncio.run(
|
|
storage.set_tokens(
|
|
OAuthToken(
|
|
access_token="a",
|
|
token_type="Bearer",
|
|
expires_in=3600,
|
|
refresh_token="r",
|
|
)
|
|
)
|
|
)
|
|
after = time.time()
|
|
|
|
on_disk = json.loads(
|
|
(tmp_path / "mcp-tokens" / "srv.json").read_text()
|
|
)
|
|
assert "expires_at" in on_disk, (
|
|
"Fix A: set_tokens must record an absolute expires_at wall-clock "
|
|
"timestamp alongside the SDK's serialized token so cold-loads "
|
|
"can compute correct remaining TTL."
|
|
)
|
|
assert before + 3600 <= on_disk["expires_at"] <= after + 3600
|
|
|
|
def test_set_tokens_without_expires_in_omits_expires_at(
|
|
self, tmp_path, monkeypatch
|
|
):
|
|
"""Tokens without a TTL must not gain a fabricated expires_at."""
|
|
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
|
from mcp.shared.auth import OAuthToken
|
|
|
|
from tools.mcp_oauth import HermesTokenStorage
|
|
|
|
storage = HermesTokenStorage("srv")
|
|
asyncio.run(
|
|
storage.set_tokens(
|
|
OAuthToken(
|
|
access_token="a",
|
|
token_type="Bearer",
|
|
refresh_token="r",
|
|
)
|
|
)
|
|
)
|
|
|
|
on_disk = json.loads(
|
|
(tmp_path / "mcp-tokens" / "srv.json").read_text()
|
|
)
|
|
assert "expires_at" not in on_disk
|
|
|
|
class TestGetTokensReconstructsExpiresIn:
|
|
def test_get_tokens_uses_expires_at_for_remaining_ttl(
|
|
self, tmp_path, monkeypatch
|
|
):
|
|
"""Round-trip: expires_in on read must reflect time remaining."""
|
|
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
|
from mcp.shared.auth import OAuthToken
|
|
|
|
from tools.mcp_oauth import HermesTokenStorage
|
|
|
|
storage = HermesTokenStorage("srv")
|
|
asyncio.run(
|
|
storage.set_tokens(
|
|
OAuthToken(
|
|
access_token="a",
|
|
token_type="Bearer",
|
|
expires_in=3600,
|
|
refresh_token="r",
|
|
)
|
|
)
|
|
)
|
|
|
|
# Wait briefly so the remaining TTL is measurably less than 3600.
|
|
time.sleep(0.05)
|
|
|
|
reloaded = asyncio.run(storage.get_tokens())
|
|
assert reloaded is not None
|
|
assert reloaded.expires_in is not None
|
|
# Should be slightly less than 3600 after the 50ms sleep.
|
|
assert 3500 < reloaded.expires_in <= 3600
|
|
|
|
def test_get_tokens_returns_zero_ttl_for_expired_token(
|
|
self, tmp_path, monkeypatch
|
|
):
|
|
"""An already-expired token reloaded from disk must report expires_in=0."""
|
|
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
|
from tools.mcp_oauth import HermesTokenStorage, _get_token_dir
|
|
|
|
token_dir = _get_token_dir()
|
|
token_dir.mkdir(parents=True, exist_ok=True)
|
|
# Write an already-expired token file directly.
|
|
(token_dir / "srv.json").write_text(
|
|
json.dumps(
|
|
{
|
|
"access_token": "a",
|
|
"token_type": "Bearer",
|
|
"expires_in": 3600,
|
|
"expires_at": time.time() - 60, # expired 1 min ago
|
|
"refresh_token": "r",
|
|
}
|
|
)
|
|
)
|
|
|
|
storage = HermesTokenStorage("srv")
|
|
reloaded = asyncio.run(storage.get_tokens())
|
|
assert reloaded is not None
|
|
assert reloaded.expires_in == 0, (
|
|
"Expired token must reload with expires_in=0 so the SDK's "
|
|
"is_token_valid() returns False and preemptive refresh fires."
|
|
)
|
|
|
|
def test_get_tokens_legacy_file_without_expires_at_is_loadable(
|
|
self, tmp_path, monkeypatch
|
|
):
|
|
"""Existing on-disk files (pre-Fix-A) must still load without crashing.
|
|
|
|
Pre-existing token files have ``expires_in`` but no ``expires_at``.
|
|
Fix A falls back to the file's mtime as a best-effort wall-clock
|
|
proxy: a file whose (mtime + expires_in) is in the past clamps
|
|
expires_in to zero so the SDK refreshes on next request. A fresh
|
|
legacy-format file (mtime = now) keeps most of its TTL.
|
|
"""
|
|
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
|
from tools.mcp_oauth import HermesTokenStorage, _get_token_dir
|
|
|
|
token_dir = _get_token_dir()
|
|
token_dir.mkdir(parents=True, exist_ok=True)
|
|
# Legacy-shape file (no expires_at). Make it stale by backdating mtime
|
|
# well past its nominal expires_in.
|
|
legacy_path = token_dir / "srv.json"
|
|
legacy_path.write_text(
|
|
json.dumps(
|
|
{
|
|
"access_token": "a",
|
|
"token_type": "Bearer",
|
|
"expires_in": 3600,
|
|
"refresh_token": "r",
|
|
}
|
|
)
|
|
)
|
|
stale_time = time.time() - 7200 # 2hr ago, exceeds 3600s TTL
|
|
import os
|
|
|
|
os.utime(legacy_path, (stale_time, stale_time))
|
|
|
|
storage = HermesTokenStorage("srv")
|
|
reloaded = asyncio.run(storage.get_tokens())
|
|
assert reloaded is not None
|
|
assert reloaded.expires_in == 0, (
|
|
"Legacy file whose mtime + expires_in is in the past must report "
|
|
"expires_in=0 so the SDK refreshes on next request."
|
|
)
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# HermesMCPOAuthProvider._initialize — seed token_expiry_time
|
|
# ---------------------------------------------------------------------------
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_initialize_seeds_token_expiry_time_from_stored_tokens(
|
|
tmp_path, monkeypatch
|
|
):
|
|
"""Cold-load must populate context.token_expiry_time.
|
|
|
|
The SDK's base ``_initialize`` loads current_tokens but doesn't seed
|
|
token_expiry_time. Our subclass must do it so ``is_token_valid()``
|
|
reports correctly and the preemptive-refresh path fires when needed.
|
|
"""
|
|
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
|
from mcp.shared.auth import OAuthClientInformationFull, OAuthToken
|
|
from pydantic import AnyUrl
|
|
|
|
from tools.mcp_oauth import HermesTokenStorage
|
|
from tools.mcp_oauth_manager import _HERMES_PROVIDER_CLS, reset_manager_for_tests
|
|
|
|
assert _HERMES_PROVIDER_CLS is not None
|
|
reset_manager_for_tests()
|
|
|
|
storage = HermesTokenStorage("srv")
|
|
await storage.set_tokens(
|
|
OAuthToken(
|
|
access_token="a",
|
|
token_type="Bearer",
|
|
expires_in=7200,
|
|
refresh_token="r",
|
|
)
|
|
)
|
|
await storage.set_client_info(
|
|
OAuthClientInformationFull(
|
|
client_id="test-client",
|
|
redirect_uris=[AnyUrl("http://127.0.0.1:12345/callback")],
|
|
grant_types=["authorization_code", "refresh_token"],
|
|
response_types=["code"],
|
|
token_endpoint_auth_method="none",
|
|
)
|
|
)
|
|
|
|
from mcp.shared.auth import OAuthClientMetadata
|
|
|
|
metadata = OAuthClientMetadata(
|
|
redirect_uris=[AnyUrl("http://127.0.0.1:12345/callback")],
|
|
client_name="Hermes Agent",
|
|
)
|
|
provider = _HERMES_PROVIDER_CLS(
|
|
server_name="srv",
|
|
server_url="https://example.com/mcp",
|
|
client_metadata=metadata,
|
|
storage=storage,
|
|
redirect_handler=_noop_redirect,
|
|
callback_handler=_noop_callback,
|
|
)
|
|
|
|
await provider._initialize()
|
|
|
|
assert provider.context.token_expiry_time is not None, (
|
|
"Fix A: _initialize must seed context.token_expiry_time so "
|
|
"is_token_valid() correctly reports expiry on cold-load."
|
|
)
|
|
# Should be ~7200s in the future (fresh write).
|
|
assert provider.context.token_expiry_time > time.time() + 7000
|
|
assert provider.context.token_expiry_time <= time.time() + 7200 + 5
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_initialize_marks_zero_ttl_cold_loaded_token_invalid(
|
|
tmp_path, monkeypatch
|
|
):
|
|
"""An expired token must not pass the SDK's same-tick validity check.
|
|
|
|
``OAuthContext.update_token_expiry`` maps ``expires_in=0`` to ``time.time()``
|
|
and ``is_token_valid`` accepts equality. Cold-loaded expired tokens therefore
|
|
need an expiry that is already in the past before the SDK selects its refresh
|
|
or authorization-code path.
|
|
"""
|
|
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
|
from mcp.shared.auth import OAuthClientInformationFull, OAuthClientMetadata, OAuthToken
|
|
from pydantic import AnyUrl
|
|
|
|
from tools.mcp_oauth import HermesTokenStorage, _get_token_dir
|
|
from tools.mcp_oauth_manager import _HERMES_PROVIDER_CLS, reset_manager_for_tests
|
|
|
|
assert _HERMES_PROVIDER_CLS is not None
|
|
reset_manager_for_tests()
|
|
|
|
storage = HermesTokenStorage("srv")
|
|
await storage.set_tokens(
|
|
OAuthToken(
|
|
access_token="expired-access",
|
|
token_type="Bearer",
|
|
expires_in=3600,
|
|
refresh_token="refresh-token",
|
|
)
|
|
)
|
|
token_path = _get_token_dir() / "srv.json"
|
|
persisted = json.loads(token_path.read_text())
|
|
fixed_now = time.time()
|
|
persisted["expires_at"] = fixed_now - 60
|
|
token_path.write_text(json.dumps(persisted))
|
|
await storage.set_client_info(
|
|
OAuthClientInformationFull(
|
|
client_id="test-client",
|
|
redirect_uris=[AnyUrl("http://127.0.0.1:12345/callback")],
|
|
grant_types=["authorization_code", "refresh_token"],
|
|
response_types=["code"],
|
|
token_endpoint_auth_method="none",
|
|
)
|
|
)
|
|
|
|
provider = _HERMES_PROVIDER_CLS(
|
|
server_name="srv",
|
|
server_url="https://example.com/mcp",
|
|
client_metadata=OAuthClientMetadata(
|
|
redirect_uris=[AnyUrl("http://127.0.0.1:12345/callback")],
|
|
client_name="Hermes Agent",
|
|
),
|
|
storage=storage,
|
|
redirect_handler=_noop_redirect,
|
|
callback_handler=_noop_callback,
|
|
)
|
|
|
|
# Reproduce the SDK's equality boundary deterministically: its zero-TTL
|
|
# expiry is exactly ``time.time()``, and validity accepts ``<=``.
|
|
monkeypatch.setattr("mcp.client.auth.oauth2.time.time", lambda: fixed_now)
|
|
await provider._initialize()
|
|
|
|
assert provider.context.current_tokens is not None
|
|
assert provider.context.current_tokens.expires_in == 0
|
|
assert not provider.context.is_token_valid(), (
|
|
"An expired cold-loaded token must be invalid before the SDK chooses "
|
|
"between refresh and authorization-code flow."
|
|
)
|
|
|
|
async def _noop_redirect(_url: str) -> None:
|
|
return None
|
|
|
|
async def _noop_callback() -> tuple[str, str | None]:
|
|
raise AssertionError("callback handler should not be invoked in these tests")
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Pre-flight OAuth metadata discovery
|
|
# ---------------------------------------------------------------------------
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_initialize_prefetches_oauth_metadata_when_missing(
|
|
tmp_path, monkeypatch
|
|
):
|
|
"""Cold-load must pre-flight PRM + ASM discovery so ``_refresh_token``
|
|
has the correct ``token_endpoint`` before the first refresh attempt.
|
|
|
|
Without this, the SDK's ``_refresh_token`` falls back to
|
|
``{server_url}/token`` which is wrong for providers whose AS is at
|
|
a different origin. BetterStack specifically: MCP at
|
|
``mcp.betterstack.com`` but token_endpoint at
|
|
``betterstack.com/oauth/token``. Without pre-flight the refresh 404s
|
|
and we drop into full browser re-auth — visible to the user as an
|
|
unwanted OAuth browser prompt every time the process restarts.
|
|
"""
|
|
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
|
|
|
# The SDK's httpx flavour (httpx2 on mcp >= 2.0). _prefetch_oauth_metadata
|
|
# builds its client from the same module, so the MockTransport and the
|
|
# patched AsyncClient below have to come from there too.
|
|
from tools.mcp_tool import sdk_httpx
|
|
httpx = sdk_httpx()
|
|
from mcp.shared.auth import (
|
|
OAuthClientInformationFull,
|
|
OAuthClientMetadata,
|
|
OAuthToken,
|
|
)
|
|
from pydantic import AnyUrl
|
|
|
|
from tools.mcp_oauth import HermesTokenStorage
|
|
from tools.mcp_oauth_manager import _HERMES_PROVIDER_CLS, reset_manager_for_tests
|
|
|
|
assert _HERMES_PROVIDER_CLS is not None
|
|
reset_manager_for_tests()
|
|
|
|
storage = HermesTokenStorage("srv")
|
|
await storage.set_tokens(
|
|
OAuthToken(
|
|
access_token="a",
|
|
token_type="Bearer",
|
|
expires_in=3600,
|
|
refresh_token="r",
|
|
)
|
|
)
|
|
await storage.set_client_info(
|
|
OAuthClientInformationFull(
|
|
client_id="test-client",
|
|
redirect_uris=[AnyUrl("http://127.0.0.1:12345/callback")],
|
|
grant_types=["authorization_code", "refresh_token"],
|
|
response_types=["code"],
|
|
token_endpoint_auth_method="none",
|
|
)
|
|
)
|
|
|
|
# Route the AsyncClient used inside _prefetch_oauth_metadata through a
|
|
# MockTransport that mimics BetterStack's split-origin discovery:
|
|
# PRM at mcp.example.com/.well-known/oauth-protected-resource -> points to auth.example.com
|
|
# ASM at auth.example.com/.well-known/oauth-authorization-server -> token_endpoint at auth.example.com/oauth/token
|
|
seen_user_agents: list = []
|
|
|
|
def mock_handler(request: httpx.Request) -> httpx.Response:
|
|
url = str(request.url)
|
|
seen_user_agents.append(request.headers.get("User-Agent"))
|
|
if url.endswith("/.well-known/oauth-protected-resource"):
|
|
return httpx.Response(
|
|
200,
|
|
json={
|
|
"resource": "https://mcp.example.com",
|
|
"authorization_servers": ["https://auth.example.com"],
|
|
"scopes_supported": ["read", "write"],
|
|
"bearer_methods_supported": ["header"],
|
|
},
|
|
)
|
|
if url.endswith("/.well-known/oauth-authorization-server"):
|
|
return httpx.Response(
|
|
200,
|
|
json={
|
|
"issuer": "https://auth.example.com",
|
|
"authorization_endpoint": "https://auth.example.com/oauth/authorize",
|
|
"token_endpoint": "https://auth.example.com/oauth/token",
|
|
"registration_endpoint": "https://auth.example.com/oauth/register",
|
|
"response_types_supported": ["code"],
|
|
"grant_types_supported": ["authorization_code", "refresh_token"],
|
|
"code_challenge_methods_supported": ["S256"],
|
|
"token_endpoint_auth_methods_supported": ["none"],
|
|
"scopes_supported": ["read", "write"],
|
|
},
|
|
)
|
|
return httpx.Response(404)
|
|
|
|
transport = httpx.MockTransport(mock_handler)
|
|
|
|
# Patch the AsyncClient constructor used by _prefetch_oauth_metadata so
|
|
# it uses our mock transport instead of the real network.
|
|
real_httpx = httpx
|
|
|
|
original_async_client = real_httpx.AsyncClient
|
|
|
|
def patched_async_client(*args, **kwargs):
|
|
kwargs["transport"] = transport
|
|
return original_async_client(*args, **kwargs)
|
|
|
|
monkeypatch.setattr(real_httpx, "AsyncClient", patched_async_client)
|
|
|
|
metadata = OAuthClientMetadata(
|
|
redirect_uris=[AnyUrl("http://127.0.0.1:12345/callback")],
|
|
client_name="Hermes Agent",
|
|
)
|
|
provider = _HERMES_PROVIDER_CLS(
|
|
server_name="srv",
|
|
server_url="https://mcp.example.com",
|
|
client_metadata=metadata,
|
|
storage=storage,
|
|
redirect_handler=_noop_redirect,
|
|
callback_handler=_noop_callback,
|
|
)
|
|
|
|
await provider._initialize()
|
|
|
|
assert provider.context.protected_resource_metadata is not None, (
|
|
"Pre-flight must cache PRM for the SDK to reference later."
|
|
)
|
|
assert provider.context.oauth_metadata is not None, (
|
|
"Pre-flight must cache ASM so _refresh_token builds the correct "
|
|
"token_endpoint URL."
|
|
)
|
|
assert str(provider.context.oauth_metadata.token_endpoint) == (
|
|
"https://auth.example.com/oauth/token"
|
|
)
|
|
# Pre-flight discovery requests are SDK-built (no client default headers merged),
|
|
# so they must carry the stamped User-Agent or WAF-fronted providers 403 them (#113771).
|
|
from tools.mcp_oauth_provider import DEFAULT_AUTH_REQUEST_USER_AGENT
|
|
assert seen_user_agents and set(seen_user_agents) == {DEFAULT_AUTH_REQUEST_USER_AGENT}
|