# 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
1077 lines
39 KiB
Python
1077 lines
39 KiB
Python
"""Tests for auth subcommands backed by the credential pool."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import json
|
|
import time
|
|
from unittest.mock import patch
|
|
|
|
import pytest
|
|
import hermes_yaml as yaml
|
|
|
|
|
|
def _write_auth_store(tmp_path, payload: dict) -> None:
|
|
hermes_home = tmp_path / "hermes"
|
|
hermes_home.mkdir(parents=True, exist_ok=True)
|
|
(hermes_home / "auth.json").write_text(json.dumps(payload, indent=2))
|
|
|
|
|
|
def _write_groq_provider_config(
|
|
tmp_path, *, provider_key="groq", name="Groq", base_url=None
|
|
) -> None:
|
|
hermes_home = tmp_path / "hermes"
|
|
hermes_home.mkdir(parents=True, exist_ok=True)
|
|
(hermes_home / "config.yaml").write_text(
|
|
yaml.safe_dump(
|
|
{
|
|
"providers": {
|
|
provider_key: {
|
|
"name": name,
|
|
"base_url": base_url or "https://api.groq.com/openai/v1",
|
|
"key_env": "GROQ_API_KEY",
|
|
"discover_models": True,
|
|
}
|
|
}
|
|
}
|
|
),
|
|
encoding="utf-8",
|
|
)
|
|
|
|
|
|
def _jwt_with_email(email: str) -> str:
|
|
header = base64.urlsafe_b64encode(b'{"alg":"RS256","typ":"JWT"}').rstrip(b"=").decode()
|
|
payload = base64.urlsafe_b64encode(
|
|
json.dumps({"email": email}).encode()
|
|
).rstrip(b"=").decode()
|
|
return f"{header}.{payload}.signature"
|
|
|
|
|
|
def _codex_pool_only_store(*, exhausted: bool = False) -> dict:
|
|
entry = {
|
|
"id": "codex-1",
|
|
"label": "codex@example.com",
|
|
"auth_type": "oauth",
|
|
"priority": 0,
|
|
"source": "manual:device_code",
|
|
"access_token": _jwt_with_email("codex@example.com"),
|
|
"refresh_token": "refresh-token",
|
|
"base_url": "https://chatgpt.com/backend-api/codex",
|
|
"last_refresh": "2026-06-15T10:00:00Z",
|
|
}
|
|
if exhausted:
|
|
entry.update(
|
|
{
|
|
"last_status": "exhausted",
|
|
"last_status_at": time.time(),
|
|
"last_error_code": 429,
|
|
"last_error_reason": "usage_limit_reached",
|
|
"last_error_message": "The usage limit has been reached",
|
|
"last_error_reset_at": time.time() + 3600,
|
|
}
|
|
)
|
|
return {
|
|
"version": 1,
|
|
"active_provider": "openai-codex",
|
|
"providers": {},
|
|
"credential_pool": {"openai-codex": [entry]},
|
|
}
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _clear_provider_env(monkeypatch):
|
|
for key in (
|
|
"OPENROUTER_API_KEY",
|
|
"OPENAI_API_KEY",
|
|
"ANTHROPIC_API_KEY",
|
|
"ANTHROPIC_TOKEN",
|
|
"CLAUDE_CODE_OAUTH_TOKEN",
|
|
):
|
|
monkeypatch.delenv(key, raising=False)
|
|
|
|
|
|
def test_auth_add_api_key_persists_manual_entry(tmp_path, monkeypatch):
|
|
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
|
|
monkeypatch.delenv("OPENROUTER_API_KEY", raising=False)
|
|
monkeypatch.delenv("OPENAI_API_KEY", raising=False)
|
|
_write_auth_store(tmp_path, {"version": 1, "providers": {}})
|
|
|
|
from hermes_cli.auth_commands import auth_add_command
|
|
|
|
class _Args:
|
|
provider = "openrouter"
|
|
auth_type = "api-key"
|
|
api_key = "sk-or-manual"
|
|
label = "personal"
|
|
|
|
auth_add_command(_Args())
|
|
|
|
payload = json.loads((tmp_path / "hermes" / "auth.json").read_text())
|
|
entries = payload["credential_pool"]["openrouter"]
|
|
entry = next(item for item in entries if item["source"] == "manual")
|
|
assert entry["label"] == "personal"
|
|
assert entry["auth_type"] == "api_key"
|
|
assert entry["source"] == "manual"
|
|
assert entry["access_token"] == "sk-or-manual"
|
|
|
|
|
|
def test_auth_add_migrates_legacy_prefixed_key_for_configured_provider(
|
|
tmp_path, monkeypatch
|
|
):
|
|
hermes_home = tmp_path / "hermes"
|
|
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
|
|
monkeypatch.delenv("GROQ_API_KEY", raising=False)
|
|
_write_auth_store(
|
|
tmp_path,
|
|
{
|
|
"version": 1,
|
|
"providers": {},
|
|
"credential_pool": {
|
|
"custom:groq": [
|
|
{
|
|
"id": "legacy-key",
|
|
"label": "legacy",
|
|
"auth_type": "api_key",
|
|
"priority": 0,
|
|
"source": "manual",
|
|
"access_token": "gsk-legacy",
|
|
}
|
|
]
|
|
},
|
|
},
|
|
)
|
|
_write_groq_provider_config(tmp_path)
|
|
|
|
from hermes_cli.auth_commands import auth_add_command
|
|
|
|
class _Args:
|
|
provider = "groq"
|
|
auth_type = "api-key"
|
|
api_key = "gsk-new"
|
|
label = "new"
|
|
|
|
auth_add_command(_Args())
|
|
|
|
payload = json.loads((hermes_home / "auth.json").read_text(encoding="utf-8"))
|
|
assert "custom:groq" not in payload["credential_pool"]
|
|
assert {
|
|
entry["access_token"] for entry in payload["credential_pool"]["groq"]
|
|
} == {"gsk-legacy", "gsk-new"}
|
|
|
|
|
|
def test_auth_add_migrates_display_name_derived_legacy_pool_key(
|
|
tmp_path, monkeypatch
|
|
):
|
|
hermes_home = tmp_path / "hermes"
|
|
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
|
|
monkeypatch.delenv("GROQ_API_KEY", raising=False)
|
|
_write_auth_store(
|
|
tmp_path,
|
|
{
|
|
"version": 1,
|
|
"providers": {},
|
|
"credential_pool": {
|
|
"custom:groq": [
|
|
{
|
|
"id": "legacy-key",
|
|
"label": "legacy",
|
|
"auth_type": "api_key",
|
|
"priority": 0,
|
|
"source": "manual",
|
|
"access_token": "gsk-legacy",
|
|
}
|
|
]
|
|
},
|
|
},
|
|
)
|
|
_write_groq_provider_config(tmp_path, provider_key="groq-cloud", name="Groq")
|
|
|
|
from hermes_cli.auth_commands import auth_add_command
|
|
|
|
class _Args:
|
|
provider = "groq-cloud"
|
|
auth_type = "api-key"
|
|
api_key = "gsk-new"
|
|
label = "new"
|
|
|
|
with patch("hermes_cli.models.clear_provider_models_cache"):
|
|
auth_add_command(_Args())
|
|
|
|
payload = json.loads((hermes_home / "auth.json").read_text(encoding="utf-8"))
|
|
assert "custom:groq" not in payload["credential_pool"]
|
|
assert {
|
|
entry["access_token"]
|
|
for entry in payload["credential_pool"]["groq-cloud"]
|
|
} == {"gsk-legacy", "gsk-new"}
|
|
|
|
|
|
def test_auth_add_non_registry_configured_provider_preserves_endpoint(
|
|
tmp_path, monkeypatch
|
|
):
|
|
hermes_home = tmp_path / "hermes"
|
|
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
|
|
_write_auth_store(tmp_path, {"version": 1, "providers": {}})
|
|
_write_groq_provider_config(
|
|
tmp_path,
|
|
provider_key="private-groq",
|
|
base_url="https://private.example/v1",
|
|
)
|
|
|
|
from hermes_cli.auth_commands import auth_add_command
|
|
|
|
auth_add_command(
|
|
type(
|
|
"Args",
|
|
(),
|
|
{
|
|
"provider": "private-groq",
|
|
"auth_type": "api-key",
|
|
"api_key": "private-key",
|
|
"label": "private",
|
|
},
|
|
)()
|
|
)
|
|
|
|
payload = json.loads((hermes_home / "auth.json").read_text(encoding="utf-8"))
|
|
entry = payload["credential_pool"]["private-groq"][0]
|
|
assert entry["base_url"] == "https://private.example/v1"
|
|
|
|
|
|
def test_auth_list_includes_non_registry_configured_provider(
|
|
tmp_path, monkeypatch, capsys
|
|
):
|
|
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
|
|
_write_groq_provider_config(tmp_path, provider_key="private-groq")
|
|
_write_auth_store(
|
|
tmp_path,
|
|
{
|
|
"version": 1,
|
|
"providers": {},
|
|
"credential_pool": {
|
|
"private-groq": [
|
|
{
|
|
"id": "private-key",
|
|
"label": "private",
|
|
"auth_type": "api_key",
|
|
"priority": 0,
|
|
"source": "manual",
|
|
"access_token": "secret",
|
|
}
|
|
]
|
|
},
|
|
},
|
|
)
|
|
|
|
from hermes_cli.auth_commands import auth_list_command
|
|
|
|
auth_list_command(type("Args", (), {"provider": None})())
|
|
|
|
assert "private-groq" in capsys.readouterr().out
|
|
|
|
|
|
def test_interactive_auth_add_normalizes_display_name_to_provider_key(
|
|
tmp_path, monkeypatch
|
|
):
|
|
hermes_home = tmp_path / "hermes"
|
|
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
|
|
_write_auth_store(tmp_path, {"version": 1, "providers": {}})
|
|
_write_groq_provider_config(
|
|
tmp_path, provider_key="groq-cloud", name="Groq Enterprise"
|
|
)
|
|
|
|
from hermes_cli import auth_commands
|
|
|
|
answers = iter(["Groq Enterprise", "primary"])
|
|
monkeypatch.setattr(auth_commands, "line_input", lambda _prompt: next(answers))
|
|
monkeypatch.setattr(auth_commands, "masked_secret_prompt", lambda _prompt: "gsk-test")
|
|
|
|
auth_commands._interactive_add()
|
|
|
|
payload = json.loads((hermes_home / "auth.json").read_text(encoding="utf-8"))
|
|
assert "custom:groq-enterprise" not in payload["credential_pool"]
|
|
assert payload["credential_pool"]["groq-cloud"][0]["access_token"] == "gsk-test"
|
|
|
|
|
|
def test_auth_add_explicit_custom_provider_keeps_prefixed_pool_key(
|
|
tmp_path, monkeypatch
|
|
):
|
|
hermes_home = tmp_path / "hermes"
|
|
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
|
|
_write_auth_store(tmp_path, {"version": 1, "providers": {}})
|
|
_write_groq_provider_config(
|
|
tmp_path,
|
|
name="Groq Proxy",
|
|
base_url="https://proxy.example/v1",
|
|
)
|
|
|
|
from hermes_cli.auth_commands import auth_add_command
|
|
|
|
class _Args:
|
|
provider = "custom:groq"
|
|
auth_type = "api-key"
|
|
api_key = "proxy-key"
|
|
label = "proxy"
|
|
|
|
auth_add_command(_Args())
|
|
|
|
payload = json.loads((hermes_home / "auth.json").read_text(encoding="utf-8"))
|
|
assert "custom:groq" in payload["credential_pool"]
|
|
assert "groq" not in payload["credential_pool"]
|
|
|
|
|
|
def test_auth_add_nous_oauth_persists_pool_entry(tmp_path, monkeypatch):
|
|
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
|
|
_write_auth_store(tmp_path, {"version": 1, "providers": {}})
|
|
token = _jwt_with_email("nous@example.com")
|
|
monkeypatch.setattr(
|
|
"hermes_cli.auth._nous_device_code_login",
|
|
lambda **kwargs: {
|
|
"portal_base_url": "https://portal.example.com",
|
|
"inference_base_url": "https://inference.example.com/v1",
|
|
"client_id": "hermes-cli",
|
|
"scope": "inference:invoke",
|
|
"token_type": "Bearer",
|
|
"access_token": token,
|
|
"refresh_token": "refresh-token",
|
|
"obtained_at": "2026-03-23T10:00:00+00:00",
|
|
"expires_at": "2026-03-23T11:00:00+00:00",
|
|
"expires_in": 3600,
|
|
"agent_key": token,
|
|
"agent_key_id": None,
|
|
"agent_key_expires_at": "2026-03-23T10:30:00+00:00",
|
|
"agent_key_expires_in": 1800,
|
|
"agent_key_reused": False,
|
|
"agent_key_obtained_at": "2026-03-23T10:00:10+00:00",
|
|
"tls": {"insecure": False, "ca_bundle": None},
|
|
},
|
|
)
|
|
|
|
from hermes_cli.auth_commands import auth_add_command
|
|
|
|
class _Args:
|
|
provider = "nous"
|
|
auth_type = "oauth"
|
|
api_key = None
|
|
label = None
|
|
portal_url = None
|
|
inference_url = None
|
|
client_id = None
|
|
scope = None
|
|
no_browser = False
|
|
timeout = None
|
|
insecure = False
|
|
ca_bundle = None
|
|
|
|
auth_add_command(_Args())
|
|
|
|
payload = json.loads((tmp_path / "hermes" / "auth.json").read_text())
|
|
|
|
# Pool has exactly one canonical `device_code` entry — not a duplicate
|
|
# pair of `manual:device_code` + `device_code` (the latter would be
|
|
# materialised by _seed_from_singletons on every load_pool).
|
|
entries = payload["credential_pool"]["nous"]
|
|
device_code_entries = [
|
|
item for item in entries if item["source"] == "device_code"
|
|
]
|
|
assert len(device_code_entries) == 1, entries
|
|
assert not any(item["source"] == "manual:device_code" for item in entries)
|
|
entry = device_code_entries[0]
|
|
assert entry["source"] == "device_code"
|
|
assert entry["agent_key"] == token
|
|
assert entry["portal_base_url"] == "https://portal.example.com"
|
|
|
|
# `hermes auth add nous` must also populate providers.nous so the
|
|
# 401-recovery path (resolve_nous_runtime_credentials) can refresh an
|
|
# invoke JWT when the token expires. If this mirror is missing, recovery
|
|
# raises "Hermes is not logged into Nous Portal" and the agent dies.
|
|
singleton = payload["providers"]["nous"]
|
|
assert singleton["access_token"] == token
|
|
assert singleton["refresh_token"] == "refresh-token"
|
|
assert singleton["agent_key"] == token
|
|
assert singleton["portal_base_url"] == "https://portal.example.com"
|
|
assert singleton["inference_base_url"] == "https://inference.example.com/v1"
|
|
|
|
|
|
def test_auth_add_nous_oauth_honors_custom_label(tmp_path, monkeypatch):
|
|
"""`hermes auth add nous --type oauth --label <name>` must preserve the
|
|
custom label end-to-end — it was silently dropped in the first cut of the
|
|
persist_nous_credentials helper because `--label` wasn't threaded through.
|
|
"""
|
|
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
|
|
_write_auth_store(tmp_path, {"version": 1, "providers": {}})
|
|
token = _jwt_with_email("nous@example.com")
|
|
monkeypatch.setattr(
|
|
"hermes_cli.auth._nous_device_code_login",
|
|
lambda **kwargs: {
|
|
"portal_base_url": "https://portal.example.com",
|
|
"inference_base_url": "https://inference.example.com/v1",
|
|
"client_id": "hermes-cli",
|
|
"scope": "inference:invoke",
|
|
"token_type": "Bearer",
|
|
"access_token": token,
|
|
"refresh_token": "refresh-token",
|
|
"obtained_at": "2026-03-23T10:00:00+00:00",
|
|
"expires_at": "2026-03-23T11:00:00+00:00",
|
|
"expires_in": 3600,
|
|
"agent_key": token,
|
|
"agent_key_id": None,
|
|
"agent_key_expires_at": "2026-03-23T10:30:00+00:00",
|
|
"agent_key_expires_in": 1800,
|
|
"agent_key_reused": False,
|
|
"agent_key_obtained_at": "2026-03-23T10:00:10+00:00",
|
|
"tls": {"insecure": False, "ca_bundle": None},
|
|
},
|
|
)
|
|
|
|
from hermes_cli.auth_commands import auth_add_command
|
|
|
|
class _Args:
|
|
provider = "nous"
|
|
auth_type = "oauth"
|
|
api_key = None
|
|
label = "my-nous"
|
|
portal_url = None
|
|
inference_url = None
|
|
client_id = None
|
|
scope = None
|
|
no_browser = False
|
|
timeout = None
|
|
insecure = False
|
|
ca_bundle = None
|
|
|
|
auth_add_command(_Args())
|
|
|
|
payload = json.loads((tmp_path / "hermes" / "auth.json").read_text())
|
|
|
|
# Custom label reaches the pool entry …
|
|
pool_entry = payload["credential_pool"]["nous"][0]
|
|
assert pool_entry["source"] == "device_code"
|
|
assert pool_entry["label"] == "my-nous"
|
|
|
|
# … and survives in providers.nous so a subsequent load_pool() re-seeds
|
|
# it without reverting to the auto-derived fingerprint.
|
|
assert payload["providers"]["nous"]["label"] == "my-nous"
|
|
|
|
|
|
def test_auth_add_codex_oauth_keeps_distinct_pool_accounts(tmp_path, monkeypatch):
|
|
"""Two ``hermes auth add openai-codex`` runs for different ChatGPT
|
|
accounts must produce two independent pool entries with distinct tokens.
|
|
|
|
Regression for #39236: the add path used to route through the singleton
|
|
``_save_codex_tokens`` save, so the second login overwrote the first
|
|
account's singleton-mirrored ``device_code`` entry instead of adding a
|
|
second independent one. ``hermes auth list`` showed two labels sharing
|
|
one token pair, and rotation silently always used the latest account.
|
|
"""
|
|
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
|
|
_write_auth_store(tmp_path, {"version": 1, "providers": {}})
|
|
first_token = _jwt_with_email("first-codex@example.com")
|
|
second_token = _jwt_with_email("second-codex@example.com")
|
|
logins = iter(
|
|
[
|
|
{
|
|
"tokens": {
|
|
"access_token": first_token,
|
|
"refresh_token": "first-refresh-token",
|
|
},
|
|
"base_url": "https://chatgpt.com/backend-api/codex",
|
|
"last_refresh": "2026-03-23T10:00:00Z",
|
|
},
|
|
{
|
|
"tokens": {
|
|
"access_token": second_token,
|
|
"refresh_token": "second-refresh-token",
|
|
},
|
|
"base_url": "https://chatgpt.com/backend-api/codex",
|
|
"last_refresh": "2026-03-23T10:05:00Z",
|
|
},
|
|
]
|
|
)
|
|
monkeypatch.setattr("hermes_cli.auth._codex_device_code_login", lambda: next(logins))
|
|
|
|
from hermes_cli.auth_commands import auth_add_command
|
|
from agent.credential_pool import load_pool
|
|
|
|
class _Args:
|
|
provider = "openai-codex"
|
|
auth_type = "oauth"
|
|
api_key = None
|
|
label = None
|
|
|
|
auth_add_command(_Args())
|
|
auth_add_command(_Args())
|
|
|
|
pool = load_pool("openai-codex")
|
|
entries = pool.entries()
|
|
|
|
assert [entry.source for entry in entries] == [
|
|
"manual:device_code",
|
|
"manual:device_code",
|
|
]
|
|
assert [entry.label for entry in entries] == [
|
|
"first-codex@example.com",
|
|
"second-codex@example.com",
|
|
]
|
|
assert [entry.access_token for entry in entries] == [first_token, second_token]
|
|
assert [entry.refresh_token for entry in entries] == [
|
|
"first-refresh-token",
|
|
"second-refresh-token",
|
|
]
|
|
|
|
payload = json.loads((tmp_path / "hermes" / "auth.json").read_text())
|
|
# No singleton block — the add path is now pool-only.
|
|
assert "openai-codex" not in payload.get("providers", {})
|
|
# First add activated the provider; second add left it as-is.
|
|
assert payload["active_provider"] == "openai-codex"
|
|
|
|
|
|
def _codex_jwt(email: str, account_id: str, subject: str) -> str:
|
|
header = base64.urlsafe_b64encode(b'{"alg":"RS256","typ":"JWT"}').rstrip(b"=").decode()
|
|
claims = {"email": email, "sub": subject, "https://api.openai.com/auth": {"chatgpt_account_id": account_id}}
|
|
payload = base64.urlsafe_b64encode(json.dumps(claims).encode()).rstrip(b"=").decode()
|
|
return f"{header}.{payload}.signature"
|
|
|
|
|
|
def _add_codex_twice(tmp_path, monkeypatch, capsys, second_token: str) -> str:
|
|
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
|
|
_write_auth_store(tmp_path, {"version": 1, "providers": {}})
|
|
codex_login = {"base_url": "https://chatgpt.com/backend-api/codex", "last_refresh": "2026-09-01T00:00:00Z"}
|
|
logins = iter([
|
|
{"tokens": {"access_token": _codex_jwt("me@example.com", "acct-A", "user-1"), "refresh_token": "rt-1"}, **codex_login},
|
|
{"tokens": {"access_token": second_token, "refresh_token": "rt-2"}, **codex_login},
|
|
])
|
|
monkeypatch.setattr("hermes_cli.auth._codex_device_code_login", lambda: next(logins))
|
|
from hermes_cli.auth_commands import auth_add_command
|
|
|
|
class _Args:
|
|
provider = "openai-codex"
|
|
auth_type = "oauth"
|
|
api_key = None
|
|
label = None
|
|
|
|
auth_add_command(_Args())
|
|
capsys.readouterr()
|
|
auth_add_command(_Args())
|
|
return capsys.readouterr().err
|
|
|
|
|
|
def test_auth_add_codex_warns_when_login_is_same_account_as_pooled_entry(tmp_path, monkeypatch, capsys):
|
|
"""A second ``hermes auth add openai-codex`` for the SAME OpenAI account must tell the user
|
|
which existing credential it duplicates (#47096): the two logins share one token family and
|
|
the provider revokes the older one, so the extra entry buys no quota. Different accounts
|
|
get no warning — they rotate independently.
|
|
"""
|
|
from agent.credential_pool import load_pool
|
|
|
|
err = _add_codex_twice(tmp_path, monkeypatch, capsys, _codex_jwt("me@example.com", "acct-A", "user-1"))
|
|
assert "me@example.com" in err
|
|
# The warning informs; it never blocks the add.
|
|
assert len(load_pool("openai-codex").entries()) == 2
|
|
|
|
|
|
def test_codex_auth_status_reports_pool_only_credential(tmp_path, monkeypatch):
|
|
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
|
|
_write_auth_store(tmp_path, _codex_pool_only_store())
|
|
|
|
from hermes_cli.auth import get_codex_auth_status
|
|
|
|
status = get_codex_auth_status()
|
|
|
|
assert status["logged_in"] is True
|
|
assert status["source"] == "pool:codex@example.com"
|
|
|
|
|
|
def test_codex_runtime_pool_only_rate_limit_is_not_missing_auth(tmp_path, monkeypatch):
|
|
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
|
|
_write_auth_store(tmp_path, _codex_pool_only_store(exhausted=True))
|
|
|
|
from hermes_cli.auth import AuthError, CODEX_RATE_LIMITED_CODE, resolve_codex_runtime_credentials
|
|
|
|
with pytest.raises(AuthError) as exc_info:
|
|
resolve_codex_runtime_credentials()
|
|
|
|
assert exc_info.value.code == CODEX_RATE_LIMITED_CODE
|
|
assert exc_info.value.relogin_required is False
|
|
|
|
|
|
def test_auth_add_xai_oauth_keeps_distinct_pool_accounts(tmp_path, monkeypatch):
|
|
"""Two ``hermes auth add xai-oauth`` runs must produce independent pool entries.
|
|
|
|
Regression for the same collapse class as #39236 / #42316 for Codex: the
|
|
add path used to route through the singleton ``_save_xai_oauth_tokens``
|
|
save, so the second login overwrote the first account's singleton-mirrored
|
|
``device_code`` entry instead of adding a second independent one.
|
|
"""
|
|
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
|
|
_write_auth_store(tmp_path, {"version": 1, "providers": {}})
|
|
first_token = "xai-access-token-account-a"
|
|
second_token = "xai-access-token-account-b"
|
|
logins = iter(
|
|
[
|
|
{
|
|
"tokens": {
|
|
"access_token": first_token,
|
|
"refresh_token": "first-xai-refresh",
|
|
"id_token": "",
|
|
"token_type": "Bearer",
|
|
},
|
|
"discovery": {"token_endpoint": "https://auth.x.ai/token"},
|
|
"redirect_uri": "",
|
|
"base_url": "https://api.x.ai/v1",
|
|
"last_refresh": "2026-07-10T10:00:00Z",
|
|
"source": "oauth-device-code",
|
|
},
|
|
{
|
|
"tokens": {
|
|
"access_token": second_token,
|
|
"refresh_token": "second-xai-refresh",
|
|
"id_token": "",
|
|
"token_type": "Bearer",
|
|
},
|
|
"discovery": {"token_endpoint": "https://auth.x.ai/token"},
|
|
"redirect_uri": "",
|
|
"base_url": "https://api.x.ai/v1",
|
|
"last_refresh": "2026-07-10T10:05:00Z",
|
|
"source": "oauth-device-code",
|
|
},
|
|
]
|
|
)
|
|
monkeypatch.setattr(
|
|
"hermes_cli.auth._xai_oauth_device_code_login",
|
|
lambda **kwargs: next(logins),
|
|
)
|
|
|
|
from hermes_cli.auth_commands import auth_add_command
|
|
from agent.credential_pool import load_pool
|
|
|
|
class _Args:
|
|
provider = "xai-oauth"
|
|
auth_type = "oauth"
|
|
api_key = None
|
|
label = None
|
|
timeout = None
|
|
no_browser = False
|
|
|
|
# Distinct labels so order is unambiguous even without JWT email claims.
|
|
class _ArgsA(_Args):
|
|
label = "xai-heavy"
|
|
|
|
class _ArgsB(_Args):
|
|
label = "xai-premium"
|
|
|
|
auth_add_command(_ArgsA())
|
|
auth_add_command(_ArgsB())
|
|
|
|
pool = load_pool("xai-oauth")
|
|
entries = pool.entries()
|
|
|
|
assert [entry.source for entry in entries] == [
|
|
"manual:device_code",
|
|
"manual:device_code",
|
|
]
|
|
assert [entry.label for entry in entries] == ["xai-heavy", "xai-premium"]
|
|
assert [entry.access_token for entry in entries] == [first_token, second_token]
|
|
assert [entry.refresh_token for entry in entries] == [
|
|
"first-xai-refresh",
|
|
"second-xai-refresh",
|
|
]
|
|
|
|
payload = json.loads((tmp_path / "hermes" / "auth.json").read_text())
|
|
# No singleton block — the add path is now pool-only.
|
|
assert "xai-oauth" not in payload.get("providers", {})
|
|
# First add activated the provider; second add left it as-is.
|
|
assert payload["active_provider"] == "xai-oauth"
|
|
|
|
|
|
def test_auth_remove_reindexes_priorities(tmp_path, monkeypatch):
|
|
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
|
|
# Prevent pool auto-seeding from host env vars and file-backed sources
|
|
monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)
|
|
monkeypatch.delenv("ANTHROPIC_TOKEN", raising=False)
|
|
monkeypatch.delenv("CLAUDE_CODE_OAUTH_TOKEN", raising=False)
|
|
monkeypatch.setattr(
|
|
"agent.credential_pool._seed_from_singletons",
|
|
lambda provider, entries: (False, set()),
|
|
)
|
|
_write_auth_store(
|
|
tmp_path,
|
|
{
|
|
"version": 1,
|
|
"credential_pool": {
|
|
"anthropic": [
|
|
{
|
|
"id": "cred-1",
|
|
"label": "primary",
|
|
"auth_type": "api_key",
|
|
"priority": 0,
|
|
"source": "manual",
|
|
"access_token": "sk-ant-api-primary",
|
|
},
|
|
{
|
|
"id": "cred-2",
|
|
"label": "secondary",
|
|
"auth_type": "api_key",
|
|
"priority": 1,
|
|
"source": "manual",
|
|
"access_token": "sk-ant-api-secondary",
|
|
},
|
|
]
|
|
},
|
|
},
|
|
)
|
|
|
|
from hermes_cli.auth_commands import auth_remove_command
|
|
|
|
class _Args:
|
|
provider = "anthropic"
|
|
target = "1"
|
|
|
|
auth_remove_command(_Args())
|
|
|
|
payload = json.loads((tmp_path / "hermes" / "auth.json").read_text())
|
|
entries = payload["credential_pool"]["anthropic"]
|
|
assert len(entries) == 1
|
|
assert entries[0]["label"] == "secondary"
|
|
assert entries[0]["priority"] == 0
|
|
|
|
|
|
def test_auth_remove_codex_migrates_legacy_dict_suppression(tmp_path, monkeypatch):
|
|
"""Removing a Codex credential must tolerate legacy dict suppression data."""
|
|
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
|
|
store = _codex_pool_only_store()
|
|
primary = store["credential_pool"]["openai-codex"][0]
|
|
primary.update({"id": "codex-qb", "label": "qb"})
|
|
store["suppressed_sources"] = {"openai-codex": {"legacy": True}}
|
|
_write_auth_store(tmp_path, store)
|
|
|
|
from hermes_cli.auth_commands import auth_remove_command
|
|
|
|
class _Args:
|
|
provider = "openai-codex"
|
|
target = "qb"
|
|
|
|
auth_remove_command(_Args())
|
|
|
|
payload = json.loads((tmp_path / "hermes" / "auth.json").read_text(encoding="utf-8"))
|
|
assert payload.get("credential_pool", {}).get("openai-codex", []) == []
|
|
assert payload["suppressed_sources"]["openai-codex"] == [
|
|
"legacy",
|
|
"device_code",
|
|
"manual:device_code",
|
|
]
|
|
|
|
from agent.credential_pool import load_pool
|
|
|
|
assert load_pool("openai-codex").peek() is None
|
|
|
|
|
|
def test_clear_provider_auth_removes_provider_pool_entries(tmp_path, monkeypatch):
|
|
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
|
|
_write_auth_store(
|
|
tmp_path,
|
|
{
|
|
"version": 1,
|
|
"active_provider": "anthropic",
|
|
"providers": {
|
|
"anthropic": {"access_token": "legacy-token"},
|
|
},
|
|
"credential_pool": {
|
|
"anthropic": [
|
|
{
|
|
"id": "cred-1",
|
|
"label": "primary",
|
|
"auth_type": "oauth",
|
|
"priority": 0,
|
|
"source": "manual:hermes_pkce",
|
|
"access_token": "pool-token",
|
|
}
|
|
],
|
|
"openrouter": [
|
|
{
|
|
"id": "cred-2",
|
|
"label": "other-provider",
|
|
"auth_type": "api_key",
|
|
"priority": 0,
|
|
"source": "manual",
|
|
"access_token": "sk-or-test",
|
|
}
|
|
],
|
|
},
|
|
},
|
|
)
|
|
|
|
from hermes_cli.auth import clear_provider_auth
|
|
|
|
assert clear_provider_auth("anthropic") is True
|
|
|
|
payload = json.loads((tmp_path / "hermes" / "auth.json").read_text())
|
|
assert payload["active_provider"] is None
|
|
assert "anthropic" not in payload.get("providers", {})
|
|
assert "anthropic" not in payload.get("credential_pool", {})
|
|
assert "openrouter" in payload.get("credential_pool", {})
|
|
|
|
|
|
def test_logout_resets_codex_config_when_auth_state_already_cleared(tmp_path, monkeypatch, capsys):
|
|
"""`hermes logout --provider openai-codex` must still clear model.provider.
|
|
|
|
Users can end up with auth.json already cleared but config.yaml still set to
|
|
openai-codex. Previously logout reported no auth state and left the agent
|
|
pinned to the Codex provider.
|
|
"""
|
|
hermes_home = tmp_path / "hermes"
|
|
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
|
|
_write_auth_store(tmp_path, {"version": 1, "providers": {}, "credential_pool": {}})
|
|
(hermes_home / "config.yaml").write_text(
|
|
"model:\n"
|
|
" default: gpt-5.3-codex\n"
|
|
" provider: openai-codex\n"
|
|
" base_url: https://chatgpt.com/backend-api/codex\n"
|
|
)
|
|
|
|
from types import SimpleNamespace
|
|
from hermes_cli.auth import logout_command
|
|
|
|
logout_command(SimpleNamespace(provider="openai-codex"))
|
|
|
|
config_text = (hermes_home / "config.yaml").read_text()
|
|
assert "provider: auto" in config_text
|
|
assert "base_url: https://openrouter.ai/api/v1" in config_text
|
|
|
|
|
|
def test_unsuppress_credential_source_clears_marker(tmp_path, monkeypatch):
|
|
"""unsuppress_credential_source() removes a previously-set marker."""
|
|
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
|
|
_write_auth_store(tmp_path, {"version": 1})
|
|
|
|
from hermes_cli.auth import suppress_credential_source, unsuppress_credential_source, is_source_suppressed
|
|
|
|
suppress_credential_source("openai-codex", "device_code")
|
|
assert is_source_suppressed("openai-codex", "device_code") is True
|
|
|
|
cleared = unsuppress_credential_source("openai-codex", "device_code")
|
|
assert cleared is True
|
|
assert is_source_suppressed("openai-codex", "device_code") is False
|
|
|
|
payload = json.loads((tmp_path / "hermes" / "auth.json").read_text())
|
|
# Empty suppressed_sources dict should be cleaned up entirely
|
|
assert "suppressed_sources" not in payload
|
|
|
|
|
|
def test_unsuppress_credential_source_preserves_other_markers(tmp_path, monkeypatch):
|
|
"""Clearing one marker must not affect unrelated markers."""
|
|
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
|
|
_write_auth_store(tmp_path, {"version": 1})
|
|
|
|
from hermes_cli.auth import (
|
|
suppress_credential_source,
|
|
unsuppress_credential_source,
|
|
is_source_suppressed,
|
|
)
|
|
|
|
suppress_credential_source("openai-codex", "device_code")
|
|
suppress_credential_source("anthropic", "claude_code")
|
|
|
|
assert unsuppress_credential_source("openai-codex", "device_code") is True
|
|
assert is_source_suppressed("anthropic", "claude_code") is True
|
|
|
|
|
|
# =============================================================================
|
|
# Unified credential-source stickiness — every source Hermes reads from has a
|
|
# registered RemovalStep in agent.credential_sources, and every seeding path
|
|
# gates on is_source_suppressed. Below: one test per source proving remove
|
|
# sticks across a fresh load_pool() call.
|
|
# =============================================================================
|
|
|
|
|
|
def test_seed_from_singletons_respects_hermes_pkce_suppression(tmp_path, monkeypatch):
|
|
"""anthropic hermes_pkce must not re-seed from ~/.hermes/.anthropic_oauth.json when suppressed."""
|
|
hermes_home = tmp_path / "hermes"
|
|
hermes_home.mkdir(parents=True, exist_ok=True)
|
|
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
|
|
|
|
import hermes_yaml as yaml
|
|
(hermes_home / "config.yaml").write_text(yaml.safe_dump({"model": {"provider": "anthropic", "model": "claude"}}))
|
|
(hermes_home / "auth.json").write_text(json.dumps({
|
|
"version": 1,
|
|
"providers": {},
|
|
"suppressed_sources": {"anthropic": ["hermes_pkce"]},
|
|
}))
|
|
|
|
# Stub the readers so only hermes_pkce is "available"; claude_code returns None
|
|
import agent.anthropic_credentials as aa
|
|
monkeypatch.setattr(aa, "read_hermes_oauth_credentials", lambda: {
|
|
"accessToken": "tok", "refreshToken": "r", "expiresAt": 9999999999000,
|
|
})
|
|
monkeypatch.setattr(aa, "read_claude_code_credentials", lambda: None)
|
|
|
|
from agent.credential_pool import _seed_from_singletons
|
|
entries = []
|
|
changed, active = _seed_from_singletons("anthropic", entries)
|
|
# hermes_pkce suppressed, claude_code returns None → nothing should be seeded
|
|
assert entries == []
|
|
assert "hermes_pkce" not in active
|
|
|
|
|
|
def test_auth_remove_copilot_suppresses_all_variants(tmp_path, monkeypatch):
|
|
"""Removing any copilot source must suppress gh_cli + all env:* variants
|
|
so the duplicate-seed paths don't resurrect the credential.
|
|
"""
|
|
hermes_home = tmp_path / "hermes"
|
|
hermes_home.mkdir(parents=True, exist_ok=True)
|
|
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
|
|
|
|
# The copilot pool entry is no longer persisted directly in auth.json —
|
|
# `(copilot, gh_cli)` is borrowed and stripped by
|
|
# sanitize_borrowed_credential_payload (PR #31416, May 2026). Tokens are
|
|
# hydrated at runtime via resolve_copilot_token(). Mock that path so the
|
|
# pool has an entry to remove.
|
|
_write_auth_store(
|
|
tmp_path,
|
|
{
|
|
"version": 1,
|
|
"credential_pool": {"copilot": []},
|
|
},
|
|
)
|
|
|
|
from types import SimpleNamespace
|
|
from hermes_cli.auth import is_source_suppressed
|
|
from hermes_cli.auth_commands import auth_remove_command
|
|
|
|
with patch(
|
|
"hermes_cli.copilot_auth.resolve_copilot_token",
|
|
return_value=("ghp_fake", "gh"),
|
|
), patch(
|
|
"hermes_cli.copilot_auth.get_copilot_api_token",
|
|
return_value=("ghu_fake_api", None),
|
|
):
|
|
auth_remove_command(SimpleNamespace(provider="copilot", target="1"))
|
|
|
|
assert is_source_suppressed("copilot", "gh_cli")
|
|
assert is_source_suppressed("copilot", "env:COPILOT_GITHUB_TOKEN")
|
|
assert is_source_suppressed("copilot", "env:GH_TOKEN")
|
|
assert is_source_suppressed("copilot", "env:GITHUB_TOKEN")
|
|
|
|
|
|
def test_auth_remove_env_seeded_dotenv_with_bom_no_shell_hint(tmp_path, monkeypatch, capsys):
|
|
"""A Notepad-edited .env carries a UTF-8 BOM. The dotenv-vs-shell
|
|
detector must still see the first variable as living in .env (and not
|
|
warn about a phantom shell export). Regression for the reader that
|
|
dropped encoding='utf-8-sig' and misread the BOM'd first line.
|
|
"""
|
|
hermes_home = tmp_path / "hermes"
|
|
hermes_home.mkdir(parents=True, exist_ok=True)
|
|
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
|
|
|
|
monkeypatch.delenv("DEEPSEEK_API_KEY", raising=False)
|
|
# BOM prefix (utf-8-sig) + the target var as the FIRST line.
|
|
(hermes_home / ".env").write_bytes(
|
|
b"\xef\xbb\xbfDEEPSEEK_API_KEY=sk-ds-only\n"
|
|
)
|
|
monkeypatch.setenv("DEEPSEEK_API_KEY", "sk-ds-only")
|
|
|
|
_write_auth_store(
|
|
tmp_path,
|
|
{
|
|
"version": 1,
|
|
"credential_pool": {
|
|
"deepseek": [{
|
|
"id": "env-1",
|
|
"label": "DEEPSEEK_API_KEY",
|
|
"auth_type": "api_key",
|
|
"priority": 0,
|
|
"source": "env:DEEPSEEK_API_KEY",
|
|
"access_token": "sk-ds-only",
|
|
}]
|
|
},
|
|
},
|
|
)
|
|
|
|
from types import SimpleNamespace
|
|
from hermes_cli.auth_commands import auth_remove_command
|
|
auth_remove_command(SimpleNamespace(provider="deepseek", target="1"))
|
|
|
|
out = capsys.readouterr().out
|
|
assert "DEEPSEEK_API_KEY" not in (hermes_home / ".env").read_text(encoding="utf-8-sig")
|
|
assert "still set in your shell environment" not in out
|
|
|
|
|
|
def test_auth_add_openrouter_oauth_persists_pkce_key_without_touching_api_key_default(tmp_path, monkeypatch):
|
|
"""`hermes auth add openrouter --type oauth` stores the PKCE-minted key as an ``api_key`` pool row
|
|
(OpenRouter returns a plain key, no refresh pair) that ``resolve_provider("auto")`` picks up with no
|
|
env var — same as a pasted key; the bare `--api-key` path keeps its API-key default."""
|
|
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
|
|
monkeypatch.delenv("OPENROUTER_API_KEY", raising=False)
|
|
monkeypatch.delenv("OPENAI_API_KEY", raising=False)
|
|
_write_auth_store(tmp_path, {"version": 1, "providers": {}})
|
|
monkeypatch.setattr("hermes_cli.auth._openrouter_pkce_login", lambda **kw: {"api_key": "sk-or-v1-from-pkce"})
|
|
|
|
from hermes_cli.auth import resolve_provider
|
|
from hermes_cli.auth_commands import auth_add_command
|
|
|
|
class _Oauth:
|
|
provider = "openrouter"
|
|
auth_type = "oauth"
|
|
api_key = None
|
|
label = "browser-login"
|
|
timeout = None
|
|
no_browser = True
|
|
|
|
class _Plain:
|
|
provider = "openrouter"
|
|
auth_type = None # no --type: must NOT fall into the OAuth flow
|
|
api_key = "sk-or-v1-pasted"
|
|
label = "pasted"
|
|
|
|
auth_add_command(_Oauth())
|
|
# No env var, no config.yaml provider: the pooled PKCE key alone must make openrouter resolvable.
|
|
assert resolve_provider("auto") == "openrouter"
|
|
auth_add_command(_Plain())
|
|
|
|
payload = json.loads((tmp_path / "hermes" / "auth.json").read_text())
|
|
by_source = {e["source"]: e for e in payload["credential_pool"]["openrouter"]}
|
|
assert by_source["manual:openrouter_pkce"]["auth_type"] == "api_key"
|
|
assert by_source["manual:openrouter_pkce"]["access_token"] == "sk-or-v1-from-pkce"
|
|
assert by_source["manual:openrouter_pkce"]["base_url"] == "https://openrouter.ai/api/v1"
|
|
assert by_source["manual"]["access_token"] == "sk-or-v1-pasted"
|
|
|
|
|
|
def test_openrouter_loopback_callback_binds_nonce_path_and_rejects_forged_redirect(monkeypatch):
|
|
"""The CSRF nonce lives in the callback PATH (OpenRouter echoes no ``state``): a redirect that
|
|
knows the port but not the nonce is a 404 and never yields a code; the genuine path does."""
|
|
import threading
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
import hermes_cli.auth_openrouter as orm
|
|
|
|
seen: dict = {}
|
|
|
|
def _browser(url):
|
|
callback = urllib.parse.parse_qs(urllib.parse.urlparse(url).query)["callback_url"][0]
|
|
seen["callback"] = callback
|
|
forged = callback.rsplit("/", 1)[0] + "/forged-nonce?code=evil"
|
|
|
|
def _redirects():
|
|
try:
|
|
urllib.request.urlopen(forged, timeout=5)
|
|
except urllib.error.HTTPError as exc:
|
|
seen["forged_status"] = exc.code
|
|
with urllib.request.urlopen(f"{callback}?code=good-code", timeout=5) as resp:
|
|
seen["genuine_status"] = resp.status
|
|
|
|
threading.Thread(target=_redirects, daemon=True).start()
|
|
return True
|
|
|
|
monkeypatch.setattr(orm, "_can_open_graphical_browser", lambda: True)
|
|
monkeypatch.setattr(orm.webbrowser, "open", _browser)
|
|
|
|
code = orm._openrouter_loopback_code(
|
|
{"code_challenge": "c", "code_challenge_method": "S256"}, open_browser=True, timeout_seconds=10)
|
|
|
|
parsed = urllib.parse.urlparse(seen["callback"])
|
|
assert parsed.hostname == "127.0.0.1" and parsed.path.startswith("/callback/") and len(parsed.path) > 20
|
|
assert seen["forged_status"] == 404
|
|
assert seen["genuine_status"] == 200
|
|
assert code == "good-code"
|