oauth.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. """User OAuth helper for the Google Chat gateway adapter.
  2. Google Chat's ``media.upload`` rejects service-account auth, so for native file
  3. attachments each user grants the bot ``chat.messages.create`` ONCE in their own DM;
  4. the bot stores per-user refresh tokens and uploads *as the user*
  5. (https://developers.google.com/chat/api/guides/auth/users). Library API for the
  6. adapter plus a CLI driven by ``/setup-files`` (``--help``; ``--email`` omitted ==
  7. legacy single-user mode). Files under ``${HERMES_HOME}``: ``google_chat_user_tokens/
  8. <email>.json`` (per-user) / ``google_chat_user_token.json`` (legacy); pending PKCE state
  9. in ``google_chat_user_oauth_pending[/<email>].json``; ``google_chat_user_client_secret.json``.
  10. """
  11. from __future__ import annotations
  12. import argparse
  13. import json
  14. import logging
  15. import os
  16. import re
  17. import stat
  18. import sys
  19. from importlib.metadata import version as _distribution_version
  20. from pathlib import Path
  21. from typing import Any, List, NoReturn, Optional, Tuple
  22. from packaging.requirements import Requirement
  23. from hermes_constants import display_hermes_home, get_hermes_home
  24. from utils import atomic_write_text
  25. # Pinned legacy logger name so operator log filters keep matching (see adapter.py).
  26. logger = logging.getLogger("gateway.platforms.google_chat_user_oauth")
  27. # Filesystem-safe key: lowercase, keep ``[a-z0-9._-@]`` so token files stay
  28. # human-readable under ``ls ~/.hermes/google_chat_user_tokens/``.
  29. _EMAIL_FS_RE = re.compile(r"[^a-z0-9._@-]+")
  30. # Least privilege: chat.messages.create covers BOTH media.upload and the
  31. # subsequent messages.create; no drive.file or other scopes.
  32. SCOPES: list[str] = ["https://www.googleapis.com/auth/chat.messages.create"]
  33. # Declared extras (pyproject) and the exact pins they carry; the pins double as the
  34. # staleness probe so a half-synced interpreter is repaired instead of trusted.
  35. _DEPENDENCY_EXTRAS = ["google", "google-chat"]
  36. _REQUIRED_PACKAGES = [
  37. "google-cloud-pubsub==2.39.0",
  38. "google-api-python-client==2.201.0",
  39. "google-auth==2.62.0",
  40. "google-auth-oauthlib==1.5.0",
  41. "google-auth-httplib2==0.4.4",
  42. "httplib2==0.32.0",
  43. "pyasn1==0.6.5",
  44. ]
  45. # Google deprecated the ``oob`` flow: use a localhost redirect that is expected
  46. # to FAIL; the user pastes the code from the failed browser URL back into chat.
  47. _REDIRECT_URI = "http://localhost:1"
  48. def _sanitize_email(email: str) -> str:
  49. cleaned = _EMAIL_FS_RE.sub("_", (email or "").strip().lower())
  50. return cleaned or "_unknown_"
  51. def _token_rel(email: Optional[str]) -> str:
  52. """HERMES_HOME-relative token file: per-user under the tokens dir, else the legacy path."""
  53. return f"google_chat_user_tokens/{_sanitize_email(email)}.json" if email else "google_chat_user_token.json"
  54. def _user_tokens_dir() -> Path:
  55. return get_hermes_home() / "google_chat_user_tokens"
  56. def _token_path(email: Optional[str] = None) -> Path:
  57. """Per-user token path for ``email``, or the legacy single-user path."""
  58. return get_hermes_home() / _token_rel(email)
  59. def _client_secret_path() -> Path:
  60. return get_hermes_home() / "google_chat_user_client_secret.json"
  61. def _pending_auth_path(email: Optional[str] = None) -> Path:
  62. if email:
  63. return get_hermes_home() / "google_chat_user_oauth_pending" / f"{_sanitize_email(email)}.json"
  64. return get_hermes_home() / "google_chat_user_oauth_pending.json"
  65. # -- Library API — called from the adapter at runtime -------------------------
  66. def _refresh_and_persist(creds: Any, token_path: Path, request_cls: Any, *, failure_msg: str) -> Optional[Any]:
  67. """Refresh expired creds and write them back; None when unusable or refresh fails."""
  68. if creds.valid:
  69. return creds
  70. if creds.expired and creds.refresh_token:
  71. try:
  72. creds.refresh(request_cls())
  73. except Exception as exc:
  74. logger.warning("[google_chat_user_oauth] %s: %s", failure_msg, exc)
  75. return None
  76. _persist_credentials(creds, token_path)
  77. return creds
  78. # Token exists but is unusable (e.g. revoked, no refresh token).
  79. return None
  80. def load_user_credentials(email: Optional[str] = None) -> Optional[Any]:
  81. """Load + validate persisted user OAuth credentials.
  82. ``None`` email → legacy single-user path. Returns ``None`` (never raises) when
  83. no token is stored, the token is corrupt, or refresh fails — callers treat
  84. that as "user has not run /setup-files yet".
  85. """
  86. token_path = _token_path(email)
  87. if not token_path.exists():
  88. return None
  89. # Hand-provisioned / legacy token files commonly end up 0o644; warn the owner.
  90. from utils import warn_if_credential_file_broadly_readable
  91. warn_if_credential_file_broadly_readable(token_path, label="[google_chat_user_oauth]", log=logger)
  92. try:
  93. from google.oauth2.credentials import Credentials
  94. from google.auth.transport.requests import Request
  95. except ImportError:
  96. logger.warning(
  97. "[google_chat_user_oauth] google-auth not installed; user-OAuth "
  98. "attachment delivery is disabled. Run `hermes setup` to install Google Chat support."
  99. )
  100. return None
  101. try:
  102. # No scopes: the user may have authorized a subset, and passing scopes
  103. # makes refresh validate them strictly.
  104. creds = Credentials.from_authorized_user_file(str(token_path))
  105. except Exception as exc:
  106. logger.warning("[google_chat_user_oauth] token at %s is corrupt: %s", token_path, exc)
  107. return None
  108. return _refresh_and_persist(
  109. creds, token_path, Request, failure_msg="token refresh failed (user should re-run /setup-files)",
  110. )
  111. def refresh_or_none(creds: Any, email: Optional[str] = None) -> Optional[Any]:
  112. """Refresh ``creds`` if expired; ``None`` on failure (caller falls back to the
  113. text-notice path). ``email`` selects where the refreshed token is written."""
  114. if creds is None:
  115. return None
  116. if creds.valid:
  117. return creds
  118. try:
  119. from google.auth.transport.requests import Request
  120. except ImportError:
  121. return None
  122. return _refresh_and_persist(creds, _token_path(email), Request, failure_msg="refresh failed")
  123. def build_user_chat_service(creds: Any) -> Any:
  124. """Chat API client authenticated as the user (for media.upload + messages.create)."""
  125. from googleapiclient.discovery import build as build_service
  126. return build_service("chat", "v1", credentials=creds, cache_discovery=False)
  127. def list_authorized_emails() -> list[str]:
  128. """Sanitized emails with stored per-user tokens (admin display only, not trust;
  129. excludes the legacy single-user token whose owner is unknown)."""
  130. d = _user_tokens_dir()
  131. if not d.exists():
  132. return []
  133. return sorted(f.stem for f in d.iterdir() if f.is_file() and f.suffix == ".json")
  134. def _persist_credentials(creds: Any, token_path: Path) -> None:
  135. """Persist refreshed credentials atomically with private permissions."""
  136. try:
  137. _write_private_json(token_path, _normalize_authorized_user_payload(json.loads(creds.to_json())))
  138. except Exception:
  139. logger.debug("[google_chat_user_oauth] failed to persist credentials at %s", token_path, exc_info=True)
  140. # -- CLI commands — driven by the agent via /setup-files ----------------------
  141. def _normalize_authorized_user_payload(payload: dict) -> dict:
  142. """Ensure the persisted token JSON has the type field google-auth expects."""
  143. normalized = dict(payload)
  144. if not normalized.get("type"):
  145. normalized["type"] = "authorized_user"
  146. return normalized
  147. def _chmod_quiet(path: Path, mode: int) -> None:
  148. try:
  149. os.chmod(path, mode)
  150. except OSError:
  151. pass
  152. def _write_private_json(path: Path, data: Any) -> None:
  153. """Atomically write JSON with 0o600 permissions (0o700 parent) where supported."""
  154. from hermes_constants import mkdir_under_hermes_home
  155. mkdir_under_hermes_home(path.parent)
  156. _chmod_quiet(path.parent, 0o700)
  157. # mkstemp's 0o600 temp + atomic rename never exposes the token at process umask.
  158. atomic_write_text(path, json.dumps(data, indent=2, ensure_ascii=False), create_mode=0o600)
  159. _chmod_quiet(path, stat.S_IRUSR | stat.S_IWUSR)
  160. def _fail(*lines: str) -> NoReturn:
  161. """Print CLI error lines and exit 1."""
  162. for line in lines:
  163. print(line)
  164. sys.exit(1)
  165. def _ensure_deps() -> None:
  166. """Check exact dependency versions; install if stale; exit on failure."""
  167. if _missing_required_packages() and not install_deps():
  168. sys.exit(1)
  169. def _missing_required_packages() -> list[str]:
  170. """Return exact requirements absent or stale in this interpreter."""
  171. missing = []
  172. for spec in _REQUIRED_PACKAGES:
  173. requirement = Requirement(spec)
  174. try:
  175. installed = _distribution_version(requirement.name)
  176. satisfied = requirement.specifier.contains(installed, prereleases=True)
  177. except Exception:
  178. satisfied = False
  179. if not satisfied:
  180. missing.append(spec)
  181. return missing
  182. def install_deps() -> bool:
  183. missing = _missing_required_packages()
  184. if not missing:
  185. print("Dependencies already installed.")
  186. return True
  187. print("Installing Google Chat dependencies...")
  188. try:
  189. import pm
  190. pm.sync_venv(_DEPENDENCY_EXTRAS, explicit=True)
  191. remaining = _missing_required_packages()
  192. if remaining:
  193. raise RuntimeError("dependencies remain stale after install: " + " ".join(remaining))
  194. print("Dependencies installed. Restart Hermes to activate any new dependency environment.")
  195. return True
  196. except Exception as exc:
  197. print(f"ERROR: Failed to install dependencies: {exc}")
  198. print("Run `hermes setup` to repair the managed installation, then retry.")
  199. return False
  200. def check_auth(email: Optional[str] = None) -> bool:
  201. """Print status; return True if creds are usable."""
  202. token_path = _token_path(email)
  203. if not token_path.exists():
  204. print(f"NOT_AUTHENTICATED: No token at {token_path}")
  205. return False
  206. if load_user_credentials(email) is None:
  207. print(f"TOKEN_INVALID: Re-run /setup-files (path: {token_path})")
  208. return False
  209. print(f"AUTHENTICATED: Token valid at {token_path}")
  210. return True
  211. def store_client_secret(path: str) -> None:
  212. """Validate and copy the user's OAuth client_secret.json into HERMES_HOME."""
  213. src = Path(path).expanduser().resolve()
  214. if not src.exists():
  215. _fail(f"ERROR: File not found: {src}")
  216. try:
  217. data = json.loads(src.read_text(encoding="utf-8-sig"))
  218. except json.JSONDecodeError:
  219. _fail("ERROR: File is not valid JSON.")
  220. if "installed" not in data and "web" not in data:
  221. _fail(
  222. "ERROR: Not a Google OAuth client secret file (missing 'installed' or 'web' key).",
  223. "Download from: https://console.cloud.google.com/apis/credentials")
  224. target = _client_secret_path()
  225. _write_private_json(target, data)
  226. print(f"OK: Client secret saved to {target}")
  227. def _save_pending_auth(*, state: str, code_verifier: str, email: Optional[str] = None) -> None:
  228. _write_private_json(
  229. _pending_auth_path(email),
  230. {"state": state, "code_verifier": code_verifier, "redirect_uri": _REDIRECT_URI, "email": email or ""},
  231. )
  232. def _load_pending_auth(email: Optional[str] = None) -> dict:
  233. pending = _pending_auth_path(email)
  234. if not pending.exists():
  235. _fail("ERROR: No pending OAuth session found. Run --auth-url first.")
  236. try:
  237. data = json.loads(pending.read_text(encoding="utf-8-sig"))
  238. except Exception as exc:
  239. _fail(f"ERROR: Could not read pending OAuth session: {exc}", "Run --auth-url again to start a fresh session.")
  240. if not data.get("state") or not data.get("code_verifier"):
  241. _fail("ERROR: Pending OAuth session is missing PKCE data.", "Run --auth-url again.")
  242. return data
  243. def _callback_params(code_or_url: str) -> Optional[dict]:
  244. """Query params of a pasted failed-redirect URL; ``None`` for a raw auth code."""
  245. if not code_or_url.startswith("http"):
  246. return None
  247. from urllib.parse import parse_qs, urlparse
  248. return parse_qs(urlparse(code_or_url).query)
  249. def _extract_code_and_state(code_or_url: str) -> tuple[str, Optional[str]]:
  250. """Accept a raw auth code OR the full failed-redirect URL the user pastes."""
  251. params = _callback_params(code_or_url)
  252. if params is None:
  253. return code_or_url, None
  254. if "code" not in params:
  255. _fail("ERROR: No 'code' parameter found in URL.")
  256. return params["code"][0], params.get("state", [None])[0]
  257. def _require_client_secret() -> None:
  258. if not _client_secret_path().exists():
  259. _fail("ERROR: No client secret stored. Run --client-secret first.")
  260. def get_auth_url(email: Optional[str] = None) -> None:
  261. """Print the OAuth URL for the user to visit; persists PKCE state under ``email``
  262. so two users can be mid-flow in parallel."""
  263. _require_client_secret()
  264. _ensure_deps()
  265. from google_auth_oauthlib.flow import Flow
  266. flow = Flow.from_client_secrets_file(
  267. str(_client_secret_path()), scopes=SCOPES, redirect_uri=_REDIRECT_URI, autogenerate_code_verifier=True,
  268. )
  269. auth_url, state = flow.authorization_url(access_type="offline", prompt="consent")
  270. _save_pending_auth(state=state, code_verifier=flow.code_verifier, email=email)
  271. print(auth_url)
  272. def exchange_auth_code(code: str, email: Optional[str] = None) -> None:
  273. """Exchange an auth code (or pasted redirect URL) for a refresh token stored
  274. at the per-user path for ``email`` (legacy single-user path when None)."""
  275. _require_client_secret()
  276. pending_auth = _load_pending_auth(email)
  277. raw_callback = code
  278. code, returned_state = _extract_code_and_state(code)
  279. if returned_state and returned_state != pending_auth["state"]:
  280. _fail("ERROR: OAuth state mismatch. Run --auth-url again to start a fresh session.")
  281. _ensure_deps()
  282. from google_auth_oauthlib.flow import Flow
  283. granted_scopes = list(SCOPES)
  284. params = _callback_params(raw_callback) if isinstance(raw_callback, str) else None
  285. scope_val = (params.get("scope") or [""])[0].strip() if params is not None else ""
  286. if scope_val:
  287. granted_scopes = scope_val.split()
  288. flow = Flow.from_client_secrets_file(
  289. str(_client_secret_path()), scopes=granted_scopes,
  290. redirect_uri=pending_auth.get("redirect_uri", _REDIRECT_URI), state=pending_auth["state"],
  291. code_verifier=pending_auth["code_verifier"])
  292. try:
  293. # Accept partial scopes — user may deselect items in the consent screen.
  294. os.environ["OAUTHLIB_RELAX_TOKEN_SCOPE"] = "1"
  295. flow.fetch_token(code=code)
  296. except Exception as exc:
  297. _fail(f"ERROR: Token exchange failed: {exc}", "The code may have expired. Run --auth-url to get a fresh URL.")
  298. creds = flow.credentials
  299. token_payload = _normalize_authorized_user_payload(json.loads(creds.to_json()))
  300. actually_granted = list(getattr(creds, "granted_scopes", None) or [])
  301. if actually_granted:
  302. token_payload["scopes"] = actually_granted
  303. elif granted_scopes != SCOPES:
  304. token_payload["scopes"] = granted_scopes
  305. token_path = _token_path(email)
  306. _write_private_json(token_path, token_payload)
  307. _pending_auth_path(email).unlink(missing_ok=True)
  308. print(f"OK: Authenticated. Token saved to {token_path}")
  309. print(f"Profile path: {display_hermes_home()}/{_token_rel(email)}")
  310. def revoke(email: Optional[str] = None) -> None:
  311. """Revoke the stored token with Google and delete it locally."""
  312. token_path = _token_path(email)
  313. if not token_path.exists():
  314. print("No token to revoke.")
  315. return
  316. _ensure_deps()
  317. from google.oauth2.credentials import Credentials
  318. from google.auth.transport.requests import Request
  319. try:
  320. creds = Credentials.from_authorized_user_file(str(token_path), SCOPES)
  321. if creds.expired and creds.refresh_token:
  322. creds.refresh(Request())
  323. import urllib.request
  324. urllib.request.urlopen(
  325. urllib.request.Request(
  326. f"https://oauth2.googleapis.com/revoke?token={creds.token}",
  327. method="POST",
  328. headers={"Content-Type": "application/x-www-form-urlencoded"}),
  329. timeout=15)
  330. print("Token revoked with Google.")
  331. except Exception as exc:
  332. print(f"Remote revocation failed (token may already be invalid): {exc}")
  333. token_path.unlink(missing_ok=True)
  334. _pending_auth_path(email).unlink(missing_ok=True)
  335. print(f"Deleted {token_path}")
  336. def main() -> None:
  337. parser = argparse.ArgumentParser(
  338. description="Google Chat user-OAuth setup for Hermes (native attachment delivery)"
  339. )
  340. group = parser.add_mutually_exclusive_group(required=True)
  341. group.add_argument("--check", action="store_true", help="Check if auth is valid (exit 0=yes, 1=no)")
  342. group.add_argument("--client-secret", metavar="PATH", help="Store OAuth client_secret.json")
  343. group.add_argument("--auth-url", action="store_true", help="Print OAuth URL for user to visit")
  344. group.add_argument("--auth-code", metavar="CODE", help="Exchange auth code for token")
  345. group.add_argument("--revoke", action="store_true", help="Revoke and delete stored token")
  346. group.add_argument("--install-deps", action="store_true", help="Install Python dependencies")
  347. parser.add_argument(
  348. "--email", metavar="EMAIL", default=None,
  349. help="Scope operation to a specific user's token (default: legacy single-user path)")
  350. args = parser.parse_args()
  351. email = args.email or None
  352. if args.check:
  353. sys.exit(0 if check_auth(email) else 1)
  354. elif args.client_secret:
  355. store_client_secret(args.client_secret)
  356. elif args.auth_url:
  357. get_auth_url(email)
  358. elif args.auth_code:
  359. exchange_auth_code(args.auth_code, email)
  360. elif args.revoke:
  361. revoke(email)
  362. elif args.install_deps:
  363. sys.exit(0 if install_deps() else 1)
  364. if __name__ == "__main__":
  365. main()