← Commit history

Fix: auth works when the saved refresh token is dead (0.8.32)

Drew Owens ·970d973375 · ·parent 35b9565
auth's scope-drop warning refreshed the old token via _access_token(), which sys.exit()s on a failed refresh; the warning only caught RequestException, so a revoked or expired token stopped auth before it printed a consent URL. It now uses _tokeninfo_scopes(), which never exits. Adds tests/test_dead_token_reauth.py. Co-Authored-By: Claude Opus 5.5 <[email protected]>
2 files changed +91−21
bin/adom-google+17−21
@@ -23,7 +23,7 @@ See `adom-google help`. """ import sys, os, re, json, base64, argparse, urllib.parse, ssl, socket, hashlib, secrets, struct, time, subprocess, shutil -ADOM_GOOGLE_VERSION = "0.8.31"+ADOM_GOOGLE_VERSION = "0.8.32" if sys.argv[1:2] == ["--version"]:     print(f"adom-google {ADOM_GOOGLE_VERSION}")     sys.exit(0)@@ -3624,27 +3624,23 @@ def _cmd_auth_impl(a, as_json, real_out):     # SAFETY NET for every path, not just --auto-widen: a Google consent REPLACES the grant, so     # any currently-held scope missing from this request is silently revoked on Allow. Warn loudly     # and offer the exact command that keeps everything. Best-effort: never block auth on it.+    # _tokeninfo_scopes() never exits: a dead or revoked refresh token is None here (it holds+    # nothing, so there is nothing to warn about). Calling _access_token() directly sys.exit()ed+    # on a failed refresh, so a dead token used to stop `auth`, the one command that fixes it.     if not preserve and cfg.get("refresh_token") and target == "main":-        try:-            tok = _access_token(cfg)-            r = requests.get("https://oauth2.googleapis.com/tokeninfo",-                             params={"access_token": tok}, timeout=20)-            if r.status_code == 200:-                held = set(r.json().get("scope", "").split())-                dropping = sorted(held - set(scopes))-                if keeps_yt:-                    dropping = [x for x in dropping if not _is_yt_scope(x)]-                if dropping:-                    tails = ", ".join(s.split("/")[-1] for s in dropping)-                    sys.stderr.write(-                        "\n⚠ THIS CONSENT WOULD REVOKE SCOPES YOU CURRENTLY HOLD:\n"-                        f"    {tails}\n"-                        "  Approving replaces your grant with only what is requested here.\n"-                        "  To ADD a capability while keeping everything, cancel and run:\n"-                        f"    adom-google scopes --require <scope> --auto-widen\n"-                        "  (or re-run this command with the flag that includes them, e.g. --admin)\n\n")-        except requests.RequestException:-            pass+        held = set(_tokeninfo_scopes(cfg) or [])+        dropping = sorted(held - set(scopes))+        if keeps_yt:+            dropping = [x for x in dropping if not _is_yt_scope(x)]+        if dropping:+            tails = ", ".join(s.split("/")[-1] for s in dropping)+            sys.stderr.write(+                "\n⚠ THIS CONSENT WOULD REVOKE SCOPES YOU CURRENTLY HOLD:\n"+                f"    {tails}\n"+                "  Approving replaces your grant with only what is requested here.\n"+                "  To ADD a capability while keeping everything, cancel and run:\n"+                f"    adom-google scopes --require <scope> --auto-widen\n"+                "  (or re-run this command with the flag that includes them, e.g. --admin)\n\n")     if a.manual:         return _auth_manual(cfg, scopes, mode)     # Gateway flow — one static redirect, code routed back over WebSocket. Needs a provider.
tests/test_dead_token_reauth.pyadded+74
@@ -0,0 +1,74 @@+#!/usr/bin/env python3+"""Offline regression tests: `adom-google auth` must work when the saved refresh token is dead.++Before 0.8.32, auth's "would this consent revoke scopes you hold?" warning refreshed the OLD token+through _access_token(), which sys.exit()s on a failed refresh. The warning only caught+requests.RequestException, so a revoked or expired token killed `auth` with+"Gateway token refresh failed (400). Re-run `adom-google auth`." before it printed a consent URL:+the one command that fixes a dead token could not run. No network, no real token, no gateway.++    python3 tests/test_dead_token_reauth.py      # exits non-zero on any failure+"""+import json, os, sys, unittest++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from test_youtube_auth import G, Resp, cfg_of, load, run  # noqa: E402++FULL_HELD = [G + s for s in ("gmail.modify", "contacts", "drive", "chat.messages")]+++def kill_token(mod, cdir, calls, status=400):+    """Expire the cached access token and make the gateway refuse the refresh token."""+    path = os.path.join(cdir, "config.json")+    cfg = json.load(open(path))+    cfg["access_token"], cfg["access_expires"] = "stale-at", 0+    with open(path, "w") as f:+        json.dump(cfg, f)++    def refuse_refresh(url, json=None, data=None, **kw):+        if url.endswith("/refresh"):+            calls["refresh"].append((json or {}).get("refresh_token"))+            return Resp(status, {"error": "invalid_grant"})+        raise AssertionError(f"unexpected POST {url}")+    mod.requests.post = refuse_refresh+++class DeadTokenReauthTests(unittest.TestCase):+    def test_auth_with_dead_refresh_token_reaches_consent_and_saves_new_token(self):+        mod, home, cdir, calls = load(held=FULL_HELD)+        kill_token(mod, cdir, calls)+        code, out, err = run(mod, ["auth"])+        self.assertEqual(code, 0, err)+        self.assertNotIn("Gateway token refresh failed", err)+        self.assertEqual(calls["ws"], 1, "auth must reach the consent flow")+        self.assertEqual(calls["refresh"], ["main-rt"], "the dead token is tried once, quietly")+        self.assertEqual(cfg_of(cdir)["refresh_token"], "new-rt", "the new token replaces the dead one")+        self.assertNotIn("WOULD REVOKE", err, "nothing is held by a dead token, so nothing to warn about")++    def test_auth_json_with_dead_refresh_token_prints_one_success_line(self):+        mod, home, cdir, calls = load(held=FULL_HELD)+        kill_token(mod, cdir, calls)+        code, out, err = run(mod, ["auth", "--json"])+        self.assertEqual(code, 0, err)+        line = json.loads(out.strip().splitlines()[-1])+        self.assertTrue(line["ok"] and line["authorized"])++    def test_auth_on_named_account_with_dead_token(self):+        mod, home, cdir, calls = load(account="personal", held=FULL_HELD)+        kill_token(mod, cdir, calls, status=401)+        code, out, err = run(mod, ["auth"])+        self.assertEqual(code, 0, err)+        self.assertEqual(calls["ws"], 1)+        self.assertEqual(cfg_of(cdir)["refresh_token"], "new-rt")++    def test_live_token_still_gets_the_revoke_warning(self):+        # The fix must not silence the safety net when the old token works.+        mod, home, cdir, calls = load(held=FULL_HELD + [G + "admin.directory.group"])+        code, out, err = run(mod, ["auth"])+        self.assertEqual(code, 0, err)+        self.assertIn("WOULD REVOKE", err)+        self.assertIn("admin.directory.group", err)+++if __name__ == "__main__":+    unittest.main(verbosity=1)