master
Drew Owens Fix: auth works when the saved refresh token is dead (0.8.32) 970d973
#!/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)