auth_qwen.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. """Qwen OAuth (qwen-cli token file) runtime credentials and status.
  2. Split out of ``hermes_cli/auth.py``; origin helpers are imported lazily per function so
  3. ``hermes_cli.auth.<helper>`` patches still intercept and no cycle forms.
  4. """
  5. from __future__ import annotations
  6. import logging
  7. import json
  8. import os
  9. import time
  10. from pathlib import Path
  11. from typing import Any, Dict
  12. from hermes_cli.auth_constants import (
  13. AuthError, DEFAULT_QWEN_BASE_URL, QWEN_ACCESS_TOKEN_REFRESH_SKEW_SECONDS, QWEN_OAUTH_CLIENT_ID,
  14. QWEN_OAUTH_TOKEN_URL, _FORM_JSON_HEADERS, _qwen_err, httpx,
  15. )
  16. logger = logging.getLogger("hermes_cli.auth")
  17. _RERUN = "Re-run 'qwen auth qwen-oauth'."
  18. def _qwen_cli_auth_path() -> Path:
  19. return Path.home() / ".qwen" / "oauth_creds.json"
  20. def _read_qwen_cli_tokens() -> dict[str, Any]:
  21. from hermes_cli.auth import _qwen_cli_auth_path
  22. auth_path = _qwen_cli_auth_path()
  23. if not auth_path.exists():
  24. raise _qwen_err("Qwen CLI credentials not found. Run 'qwen auth qwen-oauth' first.", "qwen_auth_missing")
  25. try:
  26. data = json.loads(auth_path.read_text(encoding="utf-8-sig"))
  27. except Exception as exc:
  28. raise _qwen_err(
  29. f"Failed to read Qwen CLI credentials from {auth_path}: {exc}", "qwen_auth_read_failed",
  30. ) from exc
  31. if not isinstance(data, dict):
  32. raise _qwen_err(f"Invalid Qwen CLI credentials in {auth_path}.", "qwen_auth_invalid")
  33. return data
  34. def _save_qwen_cli_tokens(tokens: dict[str, Any]) -> Path:
  35. from hermes_cli.auth import _qwen_cli_auth_path, _save_private_json
  36. auth_path = _qwen_cli_auth_path()
  37. _save_private_json(auth_path, tokens, sort_keys=True)
  38. return auth_path
  39. def _qwen_access_token_is_expiring(expiry_date_ms: Any, skew_seconds: int = QWEN_ACCESS_TOKEN_REFRESH_SKEW_SECONDS) -> bool:
  40. try:
  41. expiry_ms = int(expiry_date_ms)
  42. except Exception:
  43. return True
  44. return (time.time() + max(0, int(skew_seconds))) * 1000 >= expiry_ms
  45. def _refresh_qwen_cli_tokens(tokens: dict[str, Any], timeout_seconds: float = 20.0) -> dict[str, Any]:
  46. refresh_token = str(tokens.get("refresh_token", "") or "").strip()
  47. if not refresh_token:
  48. raise _qwen_err(f"Qwen OAuth refresh token missing. {_RERUN}", "qwen_refresh_token_missing")
  49. try:
  50. response = httpx.post(
  51. QWEN_OAUTH_TOKEN_URL, headers=_FORM_JSON_HEADERS,
  52. data={"grant_type": "refresh_token", "refresh_token": refresh_token, "client_id": QWEN_OAUTH_CLIENT_ID},
  53. timeout=timeout_seconds,
  54. )
  55. except Exception as exc:
  56. raise _qwen_err(f"Qwen OAuth refresh failed: {exc}", "qwen_refresh_failed") from exc
  57. if response.status_code >= 400:
  58. body = response.text.strip()
  59. raise _qwen_err(
  60. f"Qwen OAuth refresh failed. {_RERUN}" + (f" Response: {body}" if body else ""), "qwen_refresh_failed",
  61. )
  62. try:
  63. payload = response.json()
  64. except Exception as exc:
  65. raise _qwen_err(f"Qwen OAuth refresh returned invalid JSON: {exc}", "qwen_refresh_invalid_json") from exc
  66. if not isinstance(payload, dict) or not str(payload.get("access_token", "") or "").strip():
  67. raise _qwen_err("Qwen OAuth refresh response missing access_token.", "qwen_refresh_invalid_response")
  68. try:
  69. expires_in_seconds = int(payload.get("expires_in"))
  70. except Exception:
  71. expires_in_seconds = 6 * 60 * 60
  72. refreshed = {
  73. "access_token": str(payload.get("access_token", "") or "").strip(),
  74. "refresh_token": str(payload.get("refresh_token", refresh_token) or refresh_token).strip(),
  75. "token_type": str(payload.get("token_type", tokens.get("token_type", "Bearer")) or "Bearer").strip() or "Bearer",
  76. "resource_url": str(payload.get("resource_url", tokens.get("resource_url", "portal.qwen.ai")) or "portal.qwen.ai").strip(),
  77. "expiry_date": int(time.time() * 1000) + max(1, expires_in_seconds) * 1000,
  78. }
  79. _save_qwen_cli_tokens(refreshed)
  80. return refreshed
  81. def _mark_qwen_oauth_active(creds: dict[str, Any]) -> None:
  82. """Set active_provider to qwen-oauth with a minimal state entry (tokens stay in the Qwen CLI file)."""
  83. from hermes_cli.auth import _auth_store_lock, _load_auth_store, _save_auth_store, _save_provider_state
  84. with _auth_store_lock():
  85. auth_store = _load_auth_store()
  86. state: dict[str, Any] = {"base_url": str(creds["base_url"])} if creds.get("base_url") else {}
  87. _save_provider_state(auth_store, "qwen-oauth", state)
  88. _save_auth_store(auth_store)
  89. def _qwen_base_url() -> str:
  90. return os.getenv("HERMES_QWEN_BASE_URL", "").strip().rstrip("/") or DEFAULT_QWEN_BASE_URL
  91. def resolve_qwen_runtime_credentials(
  92. *, force_refresh: bool = False, refresh_if_expiring: bool = True,
  93. refresh_skew_seconds: int = QWEN_ACCESS_TOKEN_REFRESH_SKEW_SECONDS,
  94. ) -> dict[str, Any]:
  95. from hermes_cli.auth import _qwen_cli_auth_path, _refresh_qwen_cli_tokens
  96. tokens = _read_qwen_cli_tokens()
  97. should_refresh = bool(force_refresh)
  98. if not should_refresh and refresh_if_expiring:
  99. should_refresh = _qwen_access_token_is_expiring(tokens.get("expiry_date"), refresh_skew_seconds)
  100. if should_refresh:
  101. tokens = _refresh_qwen_cli_tokens(tokens)
  102. access_token = str(tokens.get("access_token", "") or "").strip()
  103. if not access_token:
  104. raise _qwen_err(f"Qwen OAuth access token missing. {_RERUN}", "qwen_access_token_missing")
  105. return {
  106. "provider": "qwen-oauth",
  107. "base_url": _qwen_base_url(),
  108. "api_key": access_token, "source": "qwen-cli", "expires_at_ms": tokens.get("expiry_date"),
  109. "auth_file": str(_qwen_cli_auth_path()),
  110. }
  111. def get_qwen_auth_status() -> dict[str, Any]:
  112. from hermes_cli.auth import _qwen_cli_auth_path, resolve_qwen_runtime_credentials
  113. auth_path = _qwen_cli_auth_path()
  114. try:
  115. # Refresh-validate: otherwise stale CLI tokens read as "logged in" and break `hermes model`.
  116. creds = resolve_qwen_runtime_credentials(refresh_if_expiring=True)
  117. return {
  118. "logged_in": True, "auth_file": str(auth_path), "source": creds.get("source"),
  119. "api_key": creds.get("api_key"), "expires_at_ms": creds.get("expires_at_ms"),
  120. }
  121. except AuthError as exc:
  122. return {"logged_in": False, "auth_file": str(auth_path), "error": str(exc)}