master
Drew Owens v0.8.31: dashboard first run reads amber with the next step, not red (issue #13) af56b86
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
#!/usr/bin/env python3
"""Offline tests for `adom-google dashboard` (the Hydrogen Dock Bar card, issue #10).

No network and no real token. Like tests/test_people.py, it loads bin/adom-google as a module under
a throwaway HOME seeded with FAKE tokens and replaces `requests` with canned Google / gateway
answers. The per-account probe (normally its own process) runs in-process here so the fakes apply;
the singleton tests run the real CLI as a subprocess on a HOME with no accounts, so they make no
network calls either.

    python3 tests/test_dashboard.py      # exits non-zero on any failure
"""
import contextlib, hashlib, http.client, http.server, importlib.machinery, importlib.util, io, json, os
import re, shutil, signal, site, socket, subprocess, sys, tempfile, threading, time, unittest

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.join(HERE, "..")
BIN = os.path.join(ROOT, "bin", "adom-google")
G = "https://www.googleapis.com/auth/"
GW = "https://gateway.example.test"
# `requests` may live in the REAL home's user site; a subprocess under a throwaway HOME needs it on the path.
USER_SITE = site.getusersitepackages()

# Every string below is a FAKE credential. The point of the suite is that none of them ever
# appears in anything the dashboard serves.
RT = {"default": "1//RT-default-SECRET-0001aaaaaaaa", "personal": "1//RT-personal-SECRET-0002bbbbbbbb",
      "broken": "1//RT-broken-SECRET-0003cccccccc"}
AT_OLD = {a: f"ya29.OLD-{a}-ACCESS-SECRET-0004dddd" for a in RT}
AT_NEW = {a: f"ya29.NEW-{a}-ACCESS-SECRET-0005eeee" for a in RT}
CLIENT_SECRET = "GOCSPX-fake-CLIENT-SECRET-0006ffff"
ALL_SECRETS = list(RT.values()) + list(AT_OLD.values()) + list(AT_NEW.values()) + [CLIENT_SECRET]

SAFE = ["gmail.modify", "contacts", "drive.file", "calendar.events", "tasks", "chat.messages",
        "chat.spaces.readonly", "chat.spaces.create", "directory.readonly"]
GRANTED = {
    "default": [G + s for s in SAFE if s != "directory.readonly"],          # Google dropped one: drift
    "personal": [G + s for s in ("calendar.events", "contacts", "tasks", "drive.file", "gmail.send", "gmail.compose")],
    "broken": [G + "drive"],
}
EMAIL = {"default": "[email protected]", "personal": "[email protected]"}


class Resp:
    def __init__(self, status, body):
        self.status_code, self._body = status, body
        self.text = json.dumps(body)
        self.content = self.text.encode()

    def json(self):
        return self._body


class FakeGoogle:
    """Canned answers keyed by token. Records refreshes, so a test can prove fresh tokens existed."""
    def __init__(self):
        self.calls, self.refreshes = [], []
        self.by_token = {}
        for a in RT:
            self.by_token[AT_OLD[a]] = a
            self.by_token[AT_NEW[a]] = a

    def post(self, url, json=None, data=None, **kw):
        self.calls.append(("POST", url))
        if url.endswith("/refresh"):
            acct = next(a for a, t in RT.items() if t == (json or {}).get("refresh_token"))
            if acct == "broken":
                return Resp(400, {"error": "invalid_grant"})
            self.refreshes.append(acct)
            return Resp(200, {"access_token": AT_NEW[acct], "expires_in": 3600})
        raise AssertionError(f"unexpected POST {url}")

    def get(self, url, params=None, **kw):
        self.calls.append(("GET", url))
        if "tokeninfo" in url:
            acct = self.by_token.get((params or {}).get("access_token"))
            if not acct:
                return Resp(400, {"error": "invalid_token"})
            body = {"scope": " ".join(GRANTED[acct]), "expires_in": 3000, "aud": "client.apps.googleusercontent.com"}
            if acct == "personal":
                body["email"] = EMAIL["personal"]
            return Resp(200, body)
        if url == GW + "/health":
            return Resp(200, {"ok": True, "service": "oauth-gateway", "brokerApps": ["adom-google", "adom-connector"]})
        return self.request("GET", url, params=params, **kw)

    def request(self, method, url, headers=None, params=None, **kw):
        self.calls.append((method, url))
        acct = self.by_token.get(((headers or {}).get("Authorization") or "").replace("Bearer ", ""))
        if url.endswith("/gmail/v1/users/me/profile") and acct in EMAIL:
            return Resp(200, {"emailAddress": EMAIL[acct], "messagesTotal": 999})
        return Resp(403, {"error": {"code": 403, "status": "PERMISSION_DENIED"}})


def rt_tag(rt):
    return hashlib.sha256(rt.encode()).hexdigest()[:16]


def make_home():
    """default (safe, cached token VALID, email cached), personal (Connector, cached token EXPIRED),
    broken (refresh is rejected), unauth (an account dir with a provider but no token)."""
    home = tempfile.mkdtemp(prefix="ag-dash-")
    base = os.path.join(home, ".config", "adom-google")
    now = time.time()

    def write(path, obj):
        os.makedirs(os.path.dirname(path), exist_ok=True)
        with open(path, "w") as f:
            json.dump(obj, f)
        os.chmod(path, 0o600)

    write(os.path.join(base, "provider.json"), {"gateway_url": GW, "client_id": "cid.apps.googleusercontent.com",
                                               "client_secret": CLIENT_SECRET, "app": "adom-google"})
    write(os.path.join(base, "config.json"), {
        "refresh_token": RT["default"], "access_token": AT_OLD["default"], "access_expires": now + 3000,
        "broker": True, "mode": "safe", "app": "adom-google", "scopes": [G + s for s in SAFE],
        "account_email": EMAIL["default"], "account_email_for": rt_tag(RT["default"])})
    write(os.path.join(base, "accounts", "personal", "provider.json"),
          {"gateway_url": GW, "client_id": "connector.apps.googleusercontent.com", "app": "adom-connector", "broker": True})
    write(os.path.join(base, "accounts", "personal", "config.json"), {
        "refresh_token": RT["personal"], "access_token": AT_OLD["personal"], "access_expires": now - 10,
        "broker": True, "mode": "personal", "app": "adom-connector", "scopes": GRANTED["personal"]})
    write(os.path.join(base, "accounts", "broken", "config.json"), {
        "refresh_token": RT["broken"], "access_token": AT_OLD["broken"], "access_expires": now - 10,
        "broker": True, "mode": "full", "scopes": [G + "drive"]})
    write(os.path.join(base, "accounts", "unauth", "provider.json"), {"gateway_url": GW, "client_id": "x", "app": "adom-google"})
    return home


def snapshot(root):
    out = {}
    for d, _, files in os.walk(root):
        for f in files:
            p = os.path.join(d, f)
            with open(p, "rb") as fh:
                out[os.path.relpath(p, root)] = (hashlib.sha256(fh.read()).hexdigest(), os.stat(p).st_mtime_ns)
    return out


_LOAD_LOCK = threading.Lock()


def load(home, account="default", fake=None):
    os.environ["HOME"] = home
    for k in ("ADOM_GOOGLE_ACCOUNT", "OAUTH_GATEWAY_URL", "OAUTH_GATEWAY_WS", "ADOM_GOOGLE_CLIENT_ID",
              "ADOM_GOOGLE_CLIENT_SECRET", "ADOM_GOOGLE_APP", "ADOM_GOOGLE_BROKER", "ADOM_DOCK_WEBVIEW",
              "VSCODE_PROXY_URI"):
        os.environ.pop(k, None)
    sys.argv = ["adom-google"] + (["--account", account] if account != "default" else [])
    loader = importlib.machinery.SourceFileLoader(f"adom_google_dash_{account}", BIN)
    mod = importlib.util.module_from_spec(importlib.util.spec_from_loader(loader.name, loader))
    loader.exec_module(mod)
    if fake:
        mod.requests.request, mod.requests.get, mod.requests.post = fake.request, fake.get, fake.post
    return mod


def run_probe(home, account, fake):
    """What `adom-google --account <a> dashboard --probe-account` prints, run in-process."""
    with _LOAD_LOCK:
        mod = load(home, account, fake)
        out, err = io.StringIO(), io.StringIO()
        sys.argv = ["adom-google", "dashboard", "--probe-account"]
        with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
            mod.main()
        return out.getvalue(), err.getvalue()


class Http:
    def __init__(self, port):
        self.port = port

    def __call__(self, method, path, body=None, headers=None):
        c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=10)
        c.request(method, path, body=body, headers=headers or {})
        r = c.getresponse()
        data = r.read()
        c.close()
        return r.status, {k.lower(): v for k, v in r.getheaders()}, data


def free_port():
    s = socket.socket()
    s.bind(("127.0.0.1", 0))
    p = s.getsockname()[1]
    s.close()
    return p


class ServerCase(unittest.TestCase):
    """One in-process dashboard over the four seeded accounts, with every probe run for real."""

    @classmethod
    def setUpClass(cls):
        cls.home = make_home()
        cls.fake = FakeGoogle()
        cls.before = snapshot(cls.home)
        cls.mod = load(cls.home, "default", cls.fake)
        cls.probe_out = {}

        def probe(name):
            out, _ = run_probe(cls.home, name, cls.fake)
            cls.probe_out[name] = out
            return json.loads(out.strip().splitlines()[-1])

        cls.mod._dash_run_probe = probe
        os.environ["HOME"] = cls.home
        cls.srv, cls.state = cls.mod._dash_make_server(0, start_threads=False)
        cls.http = Http(cls.state.port)
        cls.status_before_probe = cls.state.status()
        cls.state.probe_once()
        threading.Thread(target=cls.srv.serve_forever, daemon=True).start()
        cls.after = snapshot(cls.home)

    @classmethod
    def tearDownClass(cls):
        cls.srv.shutdown()
        cls.srv.server_close()

    def get_json(self, path):
        st, h, body = self.http("GET", path)
        self.assertEqual(st, 200, body[:300])
        return h, json.loads(body)

    # --- /api/status ------------------------------------------------------------------------------
    def test_status_shape_and_cors(self):
        h, st = self.get_json("/api/status")
        self.assertEqual(h.get("access-control-allow-origin"), "*")
        self.assertEqual(st["app"], "adom-google-dashboard")
        self.assertEqual(st["version"], self.mod.ADOM_GOOGLE_VERSION)
        self.assertIn(st["state"], ("ok", "warn", "fail", "unknown"))
        self.assertEqual([f["id"] for f in st["facets"]], ["dashboard", "gateway", "accounts", "token", "services"])
        for f in st["facets"]:
            self.assertEqual(set(f), {"id", "label", "state", "short", "detail", "_hint"}, f)
            self.assertIn(f["state"], ("ok", "warn", "fail", "unknown"))
            self.assertLessEqual(len(f["short"].split()), 4, f["short"])       # pill text is short by construction
            if f["state"] in ("warn", "fail"):
                self.assertTrue(f["_hint"], f"non-green pill without a next step: {f}")
        by = {f["id"]: f for f in st["facets"]}
        self.assertEqual(by["gateway"]["short"], "answering")
        self.assertEqual(by["accounts"]["state"], "warn")
        self.assertEqual(by["accounts"]["short"], "3/4 signed in")
        self.assertEqual(by["token"]["short"], "1 failing")
        self.assertEqual(by["token"]["_hint"], "adom-google --account broken auth")
        self.assertEqual(st["state"], "warn")                                  # rollup = worst facet
        # preflight answers with CORS; /health too (the dock probes cross-origin)
        code, h2, _ = self.http("OPTIONS", "/api/status")
        self.assertEqual(code, 204)
        self.assertEqual(h2.get("access-control-allow-origin"), "*")
        h3, health = self.get_json("/health")
        self.assertEqual(h3.get("access-control-allow-origin"), "*")
        self.assertEqual(health["app"], "adom-google-dashboard")
        self.assertFalse(health["stale"])

    def test_status_is_gray_before_the_first_probe(self):
        st = self.status_before_probe
        self.assertEqual(st["state"], "unknown")
        self.assertTrue(all(f["state"] == "unknown" and f["short"] == "checking"
                            for f in st["facets"] if f["id"] != "dashboard"))
        self.assertTrue(all(f["_hint"] is None for f in st["facets"] if f["state"] == "unknown"))

    def test_accounts_route_is_same_origin_only(self):
        st, h, _ = self.http("GET", "/api/accounts")
        self.assertEqual(st, 200)
        self.assertNotIn("access-control-allow-origin", h)
        _, _, status_body = self.http("GET", "/api/status")
        for e in EMAIL.values():                                    # the CORS-open payload carries no email
            self.assertNotIn(e, status_body.decode())

    # --- secrets ----------------------------------------------------------------------------------
    def test_no_token_string_in_any_response(self):
        self.assertTrue(self.fake.refreshes, "fresh tokens were never minted, so this test proves nothing")
        bodies = []
        for method, path, body in [("GET", "/", None), ("GET", "/index.html", None), ("GET", "/health", None),
                                   ("GET", "/api/status", None), ("GET", "/api/accounts", None),
                                   ("GET", "/icon.svg", None), ("GET", "/newbie-panel.js", None),
                                   ("GET", "/nonsense", None), ("POST", "/api/recheck", b"{}"),
                                   ("OPTIONS", "/api/status", None), ("POST", "/api/shutdown", b"{}")]:
            st, h, data = self.http(method, path, body, {"Content-Type": "application/json"} if body else None)
            bodies.append(json.dumps(h) + data.decode("utf-8", "replace"))
        bodies += list(self.probe_out.values())                      # and what each probe process printed
        blob = "\n".join(bodies)
        for secret in ALL_SECRETS:
            self.assertNotIn(secret, blob)
        for pat in (r"ya29\.", r"1//", r"GOCSPX-", r"refresh_token", r"client_secret"):
            self.assertIsNone(re.search(pat, blob.replace("newbie", "")), pat)

    def test_redactor_scrubs_token_shapes(self):
        msg = f"tokeninfo failed: https://x/?access_token={AT_NEW['default']}&a=1 {RT['default']} {CLIENT_SECRET}"
        red = self.mod._dash_redact(msg, [RT["default"]])
        for s in (AT_NEW["default"], RT["default"], CLIENT_SECRET):
            self.assertNotIn(s, red)
        self.assertIn("[redacted]", red)

    def test_probe_writes_nothing_to_disk(self):
        self.assertEqual(self.before, self.after, "a probe or the server wrote into HOME")

    def test_probe_cannot_start_auth(self):
        # negative control: with the probe's patches applied, the widen path must refuse, loudly
        with _LOAD_LOCK:
            home = make_home()
            mod = load(home, "default", FakeGoogle())
            out = io.StringIO()
            sys.argv = ["adom-google", "dashboard", "--probe-account"]
            with contextlib.redirect_stdout(out):
                mod.main()
            import types
            with self.assertRaises(RuntimeError), contextlib.redirect_stdout(io.StringIO()):
                mod.cmd_scopes(types.SimpleNamespace(json=True, require=["youtube"], auto_widen=True, url_file=None))
        self.assertFalse(any("accounts.google.com" in u for _, u in self.fake.calls))

    # --- grouping, widen commands, multiple accounts ----------------------------------------------
    def accounts(self):
        _, d = self.get_json("/api/accounts")
        return {a["account"]: a for a in d["accounts"]}

    def test_multiple_accounts(self):
        acc = self.accounts()
        self.assertEqual(list(acc), ["default", "broken", "personal", "unauth"])
        self.assertEqual(acc["default"]["email"], "[email protected]")
        self.assertEqual(acc["personal"]["email"], "[email protected]")
        self.assertEqual(acc["default"]["tier"], "safe mode (narrow Drive)")
        self.assertEqual(acc["personal"]["app"], "adom-connector")
        self.assertEqual(acc["default"]["refresh"]["state"], "ok")             # cached token valid: forced in memory
        self.assertEqual(acc["personal"]["refresh"]["state"], "ok")            # cached token expired: scopes refreshed
        self.assertEqual(sorted(self.fake.refreshes), ["default", "personal"])  # exactly one refresh each
        self.assertEqual(acc["broken"]["refresh"]["state"], "fail")
        self.assertEqual(acc["broken"]["refresh"]["fix"], "adom-google --account broken auth")
        self.assertFalse(acc["unauth"]["authorized"])
        self.assertEqual(acc["unauth"]["refresh"]["fix"], "adom-google --account unauth auth")
        self.assertEqual(acc["unauth"]["services"], [])

    def test_service_grouping_and_widen_commands(self):
        acc = self.accounts()
        d = {s["key"]: s for s in acc["default"]["services"]}
        self.assertEqual([s["key"] for s in acc["default"]["services"]],
                         ["gmail", "drive", "docs", "calendar", "tasks", "contacts", "chat", "directory", "youtube"])
        self.assertEqual(d["gmail"]["state"], "usable")
        self.assertEqual((d["drive"]["state"], d["drive"]["note"]), ("limited", "only files adom-google creates or opens"))
        self.assertEqual(d["drive"]["widen"], "adom-google scopes --require drive --auto-widen")
        self.assertEqual(d["docs"]["state"], "limited")
        self.assertEqual(d["calendar"]["state"], "limited")
        self.assertEqual(d["chat"]["state"], "usable")
        self.assertIsNone(d["chat"]["widen"])
        self.assertEqual(d["directory"]["state"], "missing")
        self.assertEqual(d["directory"]["widen"], "adom-google scopes --require directory.readonly --auto-widen")
        self.assertEqual(d["youtube"]["state"], "opt-in")
        self.assertEqual(d["youtube"]["widen"], "adom-google scopes --require youtube.upload youtube --auto-widen")
        self.assertEqual(acc["default"]["drift"], ["directory.readonly"])
        p = {s["key"]: s for s in acc["personal"]["services"]}
        self.assertEqual(p["gmail"]["state"], "limited")
        self.assertIn("cannot read the inbox", p["gmail"]["note"])
        self.assertEqual(p["gmail"]["widen"], "adom-google --account personal scopes --require gmail.modify --auto-widen")
        self.assertEqual(p["directory"]["state"], "n/a")                       # gmail.com has no directory
        self.assertIsNone(p["directory"]["widen"])
        self.assertEqual(p["chat"]["widen"], "adom-google --account personal scopes --require chat.messages chat.spaces --auto-widen")
        b = {s["key"]: s for s in acc["broken"]["services"]}
        self.assertEqual(b, {}, "a failed refresh must not report services it never read")
        _, st = self.get_json("/api/status")
        svc = next(f for f in st["facets"] if f["id"] == "services")
        self.assertEqual((svc["state"], svc["short"]), ("warn", "7 of 8 usable"))
        self.assertEqual(svc["_hint"], "adom-google scopes --require directory.readonly --auto-widen")

    def test_combined_drive_grants_are_described_together(self):
        rows = {r["key"]: r for r in self.mod._dash_services([G + "drive.readonly", G + "drive.file"], "safe", "", "default")}
        self.assertEqual(rows["drive"]["note"], "reads everything, edits only files adom-google creates or opens")
        self.assertEqual(rows["docs"]["note"], "reads everything, edits only files adom-google creates or opens")
        self.assertEqual(rows["docs"]["widen"], "adom-google scopes --require documents spreadsheets presentations --auto-widen")
        mixed = {r["key"]: r for r in self.mod._dash_services([G + "documents"], "full", "", "default")}
        self.assertEqual(mixed["docs"]["state"], "limited")
        self.assertEqual(mixed["docs"]["note"], "Sheets: not granted; Slides: not granted")

    def test_full_tier_is_all_usable_and_safe_chat_widen(self):
        full = [G + s for s in ("gmail.modify", "contacts", "drive", "spreadsheets", "documents", "presentations",
                                "calendar", "tasks", "chat.messages", "chat.spaces", "directory.readonly")]
        rows = {r["key"]: r for r in self.mod._dash_services(full, "full", "[email protected]", "default")}
        self.assertTrue(all(r["state"] == "usable" for k, r in rows.items() if k != "youtube"), rows)
        self.assertEqual(rows["youtube"]["state"], "opt-in")
        safe = self.mod._dash_services([G + "chat.messages"], "safe", "[email protected]", "work")
        chat = next(r for r in safe if r["key"] == "chat")
        self.assertEqual(chat["state"], "limited")
        self.assertEqual(chat["widen"], "adom-google --account work scopes --require chat.spaces.readonly --auto-widen")

    # --- page, module, guards ---------------------------------------------------------------------
    def test_page_bytes(self):
        st, h, page = self.http("GET", "/")
        self.assertEqual(st, 200)
        self.assertIn("no-store", h["cache-control"])
        text = page.decode()
        self.assertNotIn("\x08", text)                         # no regex escape eaten into a backspace
        for ph in ("__DASH_BOOT__", "__DASH_MARK__", "__DASH_TAB__"):
            self.assertNotIn(ph, text)                         # every placeholder replaced
        self.assertIn('<script src="newbie-panel.js"></script>', text)
        self.assertIn("<title>Google</title>", text)
        for e in EMAIL.values():                               # emails are fetched, never baked into HTML
            self.assertNotIn(e, text)
        boot = json.loads(re.search(r"window\.__DASH__ = (\{.*?\});</script>", text).group(1))
        self.assertEqual(boot["say"], self.mod.DASH_SAY)
        self.assertEqual(boot["slug"], "adom-google")
        if shutil.which("node"):
            scripts = re.findall(r"<script>([\s\S]*?)</script>", text)
            tmp = tempfile.NamedTemporaryFile("w", suffix=".js", delete=False)
            tmp.write("\n;\n".join(scripts))
            tmp.close()
            r = subprocess.run(["node", "--check", tmp.name], capture_output=True, text=True)
            os.unlink(tmp.name)
            self.assertEqual(r.returncode, 0, r.stderr)

    def test_panel_module_is_the_vendored_bytes(self):
        st, h, js = self.http("GET", "/newbie-panel.js")
        self.assertEqual(st, 200)
        with open(os.path.join(ROOT, "vendor", "newbie-panel.js"), "rb") as f:
            self.assertEqual(hashlib.sha256(js).hexdigest(), hashlib.sha256(f.read()).hexdigest())
        _, health = self.get_json("/health")
        self.assertEqual(health["panel"]["sha256"], hashlib.sha256(js).hexdigest())

    def test_icon_route_is_the_favicon_file(self):
        st, h, svg = self.http("GET", "/icon.svg")
        self.assertEqual(st, 200)
        self.assertEqual(h["content-type"], "image/svg+xml")
        with open(os.path.join(ROOT, "docs", "img", "dock-google.svg"), "rb") as f:
            self.assertEqual(svg, f.read())

    def test_unknown_paths_404_and_preflight_only_real_routes(self):
        self.assertEqual(self.http("GET", "/nonsense")[0], 404)
        self.assertEqual(self.http("OPTIONS", "/nonsense")[0], 404)
        code, h, _ = self.http("OPTIONS", "/ai-threads/run-prompt")
        self.assertEqual(code, 204)
        self.assertNotIn("access-control-allow-origin", h)     # wired, but never granted cross-origin

    def test_host_and_origin_guards(self):
        self.assertEqual(self.http("GET", "/", headers={"Host": "evil.example"})[0], 403)
        self.assertEqual(self.http("GET", "/api/accounts", headers={"Host": "attacker.test:80"})[0], 403)
        code, _, _ = self.http("POST", "/ai-threads/run-prompt", b'{"new":true,"prompt":"x","submit":true}',
                               {"Origin": "http://evil.example", "Content-Type": "application/json"})
        self.assertEqual(code, 403)
        code, _, _ = self.http("POST", "/api/recheck", b"{}", {"Origin": f"http://127.0.0.1:{self.state.port}"})
        self.assertEqual(code, 200)

    def test_relayed_requests_are_refused(self):
        # what the container's public VS Code proxy delivers: loopback peer, public Host, forwarding headers
        os.environ["VSCODE_PROXY_URI"] = "https://box-abc.adom.cloud/proxy/{{port}}/"
        try:
            for hdrs in ({"Host": "box-abc.adom.cloud", "X-Forwarded-For": "203.0.113.9"},
                         {"X-Forwarded-For": "203.0.113.9"}, {"CF-Connecting-IP": "203.0.113.9"},
                         {"X-Forwarded-Host": "box-abc.adom.cloud"}, {"Host": "box-abc.adom.cloud"}):
                for path in ("/", "/api/accounts", "/api/status", "/health"):
                    code, _, body = self.http("GET", path, headers=hdrs)
                    self.assertEqual(code, 403, (hdrs, path))
                    self.assertNotIn(b"[email protected]", body)
        finally:
            os.environ.pop("VSCODE_PROXY_URI", None)

    def test_shutdown_needs_the_token(self):
        code, _, _ = self.http("POST", "/api/shutdown", b"{}", {"X-Dashboard-Token": "wrong"})
        self.assertEqual(code, 403)
        self.assertEqual(self.http("GET", "/health")[0], 200)

    def test_bound_to_loopback_only(self):
        self.assertEqual(self.srv.server_address[0], "127.0.0.1")


class YouTubeGrantCase(unittest.TestCase):
    """Issue #12: YouTube on the account's separate YouTube grant counts for the YouTube row, and
    the grant's own tokens never reach a probe line."""
    YT_RT, YT_AT = "1//yt-grant-refresh-SECRET", "ya29.yt-grant-access-SECRET"

    def _home(self, grant_works=True):
        home = make_home()
        p = os.path.join(home, ".config", "adom-google", "config.json")
        cfg = json.load(open(p))
        cfg["grants"] = {"youtube": {"refresh_token": self.YT_RT, "access_token": self.YT_AT,
                                     "access_expires": time.time() + (3000 if grant_works else -10),
                                     "broker": True, "mode": "youtube", "app": "adom-google",
                                     "scopes": [G + "youtube.upload", G + "youtube"]}}
        with open(p, "w") as f:
            json.dump(cfg, f)
        return home

    def _fake(self, grant_works=True):
        fake, yt_at = FakeGoogle(), self.YT_AT
        get0, post0 = fake.get, fake.post
        def get(url, params=None, **kw):
            if "tokeninfo" in url and (params or {}).get("access_token") == yt_at:
                return Resp(200, {"scope": G + "youtube.upload " + G + "youtube"})
            return get0(url, params=params, **kw)
        def post(url, json=None, data=None, **kw):
            if url.endswith("/refresh") and (json or {}).get("refresh_token") == self.YT_RT:
                return Resp(400, {"error": "invalid_grant"})
            return post0(url, json=json, data=data, **kw)
        fake.get, fake.post = get, post
        return fake

    def test_grant_counts_for_youtube_and_its_tokens_never_leak(self):
        home = self._home()
        out, err = run_probe(home, "default", self._fake())
        self.assertNotIn(self.YT_RT, out + err)
        self.assertNotIn(self.YT_AT, out + err)
        p = json.loads(out.strip().splitlines()[-1])
        self.assertEqual(sorted(p["youtube_grant"]), sorted([G + "youtube.upload", G + "youtube"]))
        mod = load(home)
        row = next(r for r in mod._dash_account_view(p)["services"] if r["key"] == "youtube")
        self.assertEqual(row["state"], "usable")
        self.assertIn("separate YouTube grant", row["note"])
        self.assertIsNone(row["widen"])

    def test_dead_grant_says_so_and_offers_rebind(self):
        home = self._home(grant_works=False)
        out, err = run_probe(home, "default", self._fake(grant_works=False))
        self.assertNotIn(self.YT_RT, out + err)
        p = json.loads(out.strip().splitlines()[-1])
        self.assertEqual(p["youtube_grant"], [])
        mod = load(home)
        row = next(r for r in mod._dash_account_view(p)["services"] if r["key"] == "youtube")
        self.assertIn("no longer works", row["note"])
        self.assertIn("auth --youtube --rebind", row["widen"])


class FirstRunCase(unittest.TestCase):
    """Issue #13: a fresh install waiting for sign-in reads amber (needs you), never red, and says
    exactly what to do, including when the user's organization has not set Google sign-in up."""
    def setUp(self):
        self.mod = load(make_home())

    def view(self, account="default", gateway=None, authorized=False):
        return self.mod._dash_account_view({"account": account, "authorized": authorized, "gateway_url": gateway,
                                            "refresh": {"ok": None}, "granted": None})

    def facets(self, views, gateways=None, setup=None):
        f = self.mod._dash_facets(views, gateways or {}, False, self.mod.ADOM_GOOGLE_VERSION,
                                  self.mod.ADOM_GOOGLE_VERSION, True, setup=setup)
        return {x["id"]: x for x in f}, self.mod._dash_rollup(f)

    def test_org_provides_sign_in_is_amber_with_auth(self):
        by, roll = self.facets([self.view()], setup={"checked": True, "found": ["acme"],
                                                     "gateway_url": "https://gw.acme.example", "gateway_ok": True})
        self.assertEqual(roll, "warn", "a fresh install must never paint the dock LED red")
        self.assertEqual((by["gateway"]["state"], by["gateway"]["short"]), ("ok", "ready via acme"))
        self.assertEqual(by["accounts"]["state"], "warn")
        self.assertEqual(by["accounts"]["_hint"], "adom-google auth")
        self.assertEqual(by["token"]["state"], "unknown")

    def test_no_org_setup_says_so_and_points_at_the_connector(self):
        by, roll = self.facets([self.view()], setup={"checked": True, "found": [], "orgs": ["acme"]})
        self.assertEqual(roll, "warn")
        self.assertEqual((by["gateway"]["state"], by["gateway"]["short"]), ("warn", "not set up"))
        self.assertIn("has not set up Google sign-in", by["gateway"]["detail"])
        self.assertIn("connect-personal", by["gateway"]["detail"])
        self.assertEqual(by["gateway"]["_hint"], "adom-google connect-personal")
        self.assertEqual(by["accounts"]["_hint"], "adom-google connect-personal")
        fr = self.mod._dash_first_run([self.view()], {}, {"checked": True, "found": []})
        self.assertIn("has not set up", fr["title"])
        self.assertEqual(fr["steps"][0], "adom-google connect-personal")

    def test_org_settings_unreadable_is_amber_not_red(self):
        by, roll = self.facets([self.view()], setup={"checked": False, "error": "the adom-wiki CLI is not signed in"})
        self.assertEqual(roll, "warn")
        self.assertEqual(by["gateway"]["state"], "warn")
        self.assertIn("adom-wiki CLI is not signed in", by["gateway"]["detail"])

    def test_connector_profile_not_signed_in_points_at_that_profile(self):
        gw = "https://gw.example"
        views = [self.view(), self.view("personal", gateway=gw)]
        by, roll = self.facets(views, gateways={gw: {"ok": True}})
        self.assertEqual(roll, "warn")
        self.assertEqual(by["gateway"]["state"], "ok")
        self.assertEqual(by["accounts"]["_hint"], "adom-google --account personal auth")
        fr = self.mod._dash_first_run(views, {gw: {"ok": True}}, None)
        self.assertEqual(fr["steps"], ["adom-google --account personal auth"])

    def test_real_failures_stay_red(self):
        by, roll = self.facets([self.view()], setup={"checked": True, "found": ["acme"],
                                                     "gateway_url": "https://gw.acme.example", "gateway_ok": False})
        self.assertEqual((by["gateway"]["state"], roll), ("fail", "fail"))
        by, roll = self.facets([self.view(gateway="https://gw.example")], gateways={"https://gw.example": {"ok": False}})
        self.assertEqual((by["gateway"]["state"], roll), ("fail", "fail"))

    def test_first_run_panel_disappears_once_signed_in(self):
        self.assertIsNone(self.mod._dash_first_run([self.view(authorized=True)], {}, None))
        self.assertIsNone(self.mod._dash_first_run(None, {}, None))

    def test_discovery_is_read_only_and_never_carries_a_client_id(self):
        mod = self.mod
        calls = []
        def fake_wiki(args, timeout=25):
            calls.append(args)
            if args[0] == "whoami":
                return {"status": "ok", "data": {"orgs": [{"name": "acme"}]}}
            return {"status": "ok", "data": {"client_id": "cid-SECRETISH.apps.googleusercontent.com",
                                             "gateway_url": "https://gw.acme.example/"}}
        mod._wiki_json = fake_wiki
        mod._dash_gateway_health = lambda url: {"ok": True}
        home = os.environ["HOME"]
        before = snapshot(home)
        st = mod._dash_setup_discovery()
        self.assertEqual((st["checked"], st["found"], st["gateway_url"], st["gateway_ok"]),
                         (True, ["acme"], "https://gw.acme.example", True))
        self.assertNotIn("cid-SECRETISH", json.dumps(st))
        self.assertEqual(snapshot(home), before, "discovery must not write provider.json or anything else")
        self.assertTrue(all(a[0] in ("whoami", "settings") for a in calls))
        mod._wiki_json = lambda args, timeout=25: None
        st = mod._dash_setup_discovery()
        self.assertFalse(st["checked"])
        self.assertIn("not signed in", st["error"])

    def test_probe_reports_the_provider_of_an_unsigned_account(self):
        home = make_home()
        out, err = run_probe(home, "unauth", FakeGoogle())
        p = json.loads(out.strip().splitlines()[-1])
        self.assertFalse(p["authorized"])
        self.assertTrue(p["gateway_url"], "a configured provider must be reported even before sign-in")


class ProxyCase(unittest.TestCase):
    """The three Hydrogen control routes pass through byte for byte (control-api-proxy skill)."""

    def setUp(self):
        self.home = make_home()
        body = b'{"updater":  {"current_version":"1.0.250","build":1.0},\n "big":9007199254740993}'

        class Stub(http.server.BaseHTTPRequestHandler):
            def log_message(self, *a):
                pass

            def do_GET(self):
                data = body if self.path.startswith("/updater/status") else json.dumps({"echo": self.path}).encode()
                self.send_response(200); self.send_header("Content-Type", "application/json")
                self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data)

            def do_POST(self):
                n = int(self.headers.get("Content-Length") or 0)
                got = self.rfile.read(n)
                data = b'{"ok":true,"job":"j-1","state":"opening","got":' + json.dumps(got.decode()).encode() + b"}"
                self.send_response(207); self.send_header("Content-Type", "application/json")
                self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data)

        self.stub = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Stub)
        threading.Thread(target=self.stub.serve_forever, daemon=True).start()
        os.makedirs(os.path.join(self.home, ".adom"))
        self.ctl = os.path.join(self.home, ".adom", "hydrogen-control-url")
        with open(self.ctl, "w") as f:
            f.write(f"http://127.0.0.1:{self.stub.server_address[1]}\n")
        self.body = body
        mod = load(self.home, "default", FakeGoogle())
        mod._dash_run_probe = lambda n: {"account": n, "authorized": False}
        self.srv, self.state = mod._dash_make_server(0, start_threads=False)
        threading.Thread(target=self.srv.serve_forever, daemon=True).start()
        self.http = Http(self.state.port)

    def tearDown(self):
        for s in (self.srv, self.stub):
            s.shutdown(); s.server_close()

    def test_passthrough_is_byte_exact_and_keeps_status_and_query(self):
        code, _, data = self.http("GET", "/updater/status")
        self.assertEqual((code, data), (200, self.body))
        code, _, data = self.http("GET", "/ai-threads/run-prompt/status?job=abc-123")
        self.assertEqual(json.loads(data)["echo"], "/ai-threads/run-prompt/status?job=abc-123")
        sent = b'{"new":true,"prompt":"no action needed","submit":false}'
        code, _, data = self.http("POST", "/ai-threads/run-prompt", sent, {"Content-Type": "application/json"})
        self.assertEqual(code, 207)
        self.assertEqual(json.loads(json.loads(data)["got"]), json.loads(sent))

    def test_control_url_is_read_per_request_and_absence_is_503(self):
        dead = free_port()
        with open(self.ctl, "w") as f:
            f.write(f"http://127.0.0.1:{dead}\n")
        code, _, data = self.http("GET", "/updater/status")
        self.assertEqual(code, 503)
        self.assertIn("_hint", json.loads(data))


class ManifestCase(unittest.TestCase):
    def setUp(self):
        self.mod = load(tempfile.mkdtemp(), "default")
        with open(os.path.join(ROOT, "dockbar.json")) as f:
            self.dock = json.load(f)

    def test_dockbar_matches_the_cli(self):
        d = self.dock
        self.assertEqual(d["dock_manifest"], "1.2.0")
        self.assertEqual(d["say"], self.mod.DASH_SAY)
        self.assertTrue(4 <= len(d["say"]) <= 6)
        self.assertEqual(d["webview"], {"title": "Google", "favicon": "docs/img/dock-google.svg"})
        self.assertEqual(d["health"]["url"], "/api/status")
        self.assertEqual(d["launch"]["mode"], "container_command")
        steps = d["launch"]["steps"]
        self.assertIn("adom-wiki pkg install adom/adom-google", steps[0]["run"])
        self.assertNotIn("skip_if", steps[0])            # install-or-update: never pin users to v1
        self.assertEqual([s for s in steps if s.get("await") == "url"], [steps[-1]])
        self.assertIn("exec adom-google dashboard --print-url", steps[-1]["run"])
        for s in steps:
            self.assertIn('PATH="$HOME/.local/bin:$PATH"', s["run"])
        ai = d["launch"]["ai"]
        self.assertEqual(ai["prompt"], self.mod.DASH_DEMO_PROMPT)
        self.assertEqual(ai["submit"], "staged")
        self.assertIn("only READS", ai["prompt"])
        for verb in ("chat send", "gmail send", "--auto-widen`", "drive upload"):
            self.assertNotIn(f"`adom-google {verb}", ai["prompt"])

    def test_dockbar_passes_the_wiki_validator_rules(self):
        # The rules of validateDockManifest (adom-inc/git-wiki lib/workspace.js), which the wiki runs
        # on every push/publish and which reject the manifest with DOCK_MANIFEST_INVALID.
        d = self.dock
        self.assertRegex(str(d["dock_manifest"]), r"^\d+\.\d+(\.\d+)?$")
        self.assertTrue(d["webview"]["title"].strip())
        self.assertTrue(d["health"]["url"].startswith("/"))
        L = d["launch"]
        self.assertIn(L["mode"], ("webview", "container_command", "ai_thread"))
        self.assertTrue(1 <= len(L["steps"]) <= 12)
        for s in L["steps"]:
            self.assertTrue(s["run"].strip())
            self.assertIn(s.get("await", "url"), ("url",))
            self.assertGreater(float(s.get("timeout_seconds", 1)), 0)
        self.assertTrue(any(s.get("await") == "url" for s in L["steps"]))
        self.assertIn(L.get("console", "show"), ("show", "hide"))
        self.assertIn(L.get("on_ready", "navigate_placeholder"), ("navigate_placeholder", "hand_to_ai"))
        self.assertIn(L["ai"].get("thread", "new"), ("new", "existing"))
        self.assertIn(L["ai"].get("thread_fallback", "new"), ("new", "current"))
        self.assertIn(L["ai"].get("submit", "staged"), ("staged", "auto"))

    def test_favicon_is_a_line_drawing_and_matches_the_cli(self):
        with open(os.path.join(ROOT, "docs", "img", "dock-google.svg")) as f:
            svg = f.read()
        self.assertEqual(svg, self.mod.DASH_ICON_SVG)
        self.assertIn('fill="none"', svg)
        self.assertIn('stroke="#e6edf3"', svg)                # a favicon cannot inherit currentColor
        self.assertIsNone(re.search(r'fill="(?!none)', svg))
        self.assertIsNone(re.search(r'<rect[^>]*width="24"', svg))

    def test_files_ship_to_the_page_repo(self):
        with open(os.path.join(ROOT, "package.json")) as f:
            files = json.load(f)["files"]
        for p in ("dockbar.json", "docs/img/dock-google.svg", "vendor/newbie-panel.js"):
            self.assertIn(p, files)
            self.assertTrue(os.path.isfile(os.path.join(ROOT, p)), p)
        with open(os.path.join(ROOT, ".adomignore")) as f:
            ignored = [l.strip() for l in f if l.strip() and not l.startswith("#")]
        for p in ("dockbar.json", "docs/", "docs/img/", "vendor/"):
            self.assertNotIn(p, ignored)
        with open(os.path.join(ROOT, "install.sh")) as f:
            self.assertIn("newbie-panel.js", f.read())


class SingletonCase(unittest.TestCase):
    """The real CLI as a subprocess, on a HOME with no accounts (so its probes make no network calls)."""

    def setUp(self):
        self.home = tempfile.mkdtemp(prefix="ag-dash-single-")
        self.env = {k: v for k, v in os.environ.items()
                    if not k.startswith(("ADOM_GOOGLE", "OAUTH_GATEWAY", "ADOM_DOCK", "VSCODE_PROXY"))}
        self.env.update(HOME=self.home, ADOM_GOOGLE_NO_DISCOVER="1",
                        PYTHONPATH=os.pathsep.join(p for p in (USER_SITE, os.environ.get("PYTHONPATH")) if p))
        self.port = free_port()
        self.pids = set()

    def tearDown(self):
        for pid in self.pids:                     # exact pids only, never a pattern
            try:
                os.kill(pid, signal.SIGTERM)
            except OSError:
                pass

    def cli(self, *args, script=BIN):
        return subprocess.run([sys.executable, script, "dashboard", *args], capture_output=True, text=True,
                              env=self.env, timeout=60)

    def health(self, port=None):
        c = http.client.HTTPConnection("127.0.0.1", port or self.port, timeout=5)
        c.request("GET", "/health")
        d = json.loads(c.getresponse().read())
        c.close()
        return d

    def listen_addr(self, port):
        with open("/proc/net/tcp") as f:
            for line in f.readlines()[1:]:
                cols = line.split()
                if cols[3] == "0A" and int(cols[1].split(":")[1], 16) == port:
                    return cols[1].split(":")[0]
        return None

    def test_print_url_singleton_and_version_retire(self):
        url = f"http://127.0.0.1:{self.port}/\n"
        r1 = self.cli("--print-url", "--port", str(self.port))
        self.assertEqual((r1.returncode, r1.stdout), (0, url), r1.stderr)
        h1 = self.health()
        self.pids.add(h1["pid"])
        self.assertEqual(self.listen_addr(self.port), "0100007F")            # 127.0.0.1, not 0.0.0.0
        state = os.path.join(self.home, ".cache", "adom-google", f"dashboard-{self.port}.json")
        self.assertEqual(oct(os.stat(state).st_mode & 0o777), "0o600")
        # second launch: same version -> reuse, same pid, still exactly the URL
        r2 = self.cli("--print-url", "--port", str(self.port))
        self.assertEqual((r2.returncode, r2.stdout), (0, url), r2.stderr)
        self.assertEqual(self.health()["pid"], h1["pid"])
        r3 = self.cli("--json", "--port", str(self.port))
        self.assertTrue(json.loads(r3.stdout)["reused"])
        # a DIFFERENT version on the same port retires the old one and takes over
        tmpbin = os.path.join(tempfile.mkdtemp(), "adom-google")
        with open(BIN) as f:
            src = f.read()
        with open(tmpbin, "w") as f:
            f.write(re.sub(r'^ADOM_GOOGLE_VERSION = "[^"]+"', 'ADOM_GOOGLE_VERSION = "9.9.9"', src, count=1, flags=re.M))
        r4 = self.cli("--print-url", "--port", str(self.port), script=tmpbin)
        self.assertEqual((r4.returncode, r4.stdout), (0, url), r4.stderr)
        self.assertIn("Restarting it", r4.stderr)
        h4 = self.health()
        self.pids.add(h4["pid"])
        self.assertEqual(h4["version"], "9.9.9")
        self.assertNotEqual(h4["pid"], h1["pid"])
        time.sleep(0.3)
        self.assertFalse(os.path.exists(f"/proc/{h1['pid']}") and open(f"/proc/{h1['pid']}/stat").read().split()[2] != "Z",
                         "the retired dashboard is still running")
        r5 = self.cli("--stop", "--port", str(self.port), script=tmpbin)
        self.assertEqual(r5.returncode, 0, r5.stderr)
        self.assertIsNone(self.listen_addr(self.port))

    def test_foreign_server_on_the_port_is_refused_not_killed(self):
        s = socket.socket()
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind(("127.0.0.1", self.port))
        s.listen(5)
        try:
            r = self.cli("--print-url", "--port", str(self.port))
            self.assertEqual(r.returncode, 1)
            self.assertEqual(r.stdout, "")                        # nothing for the dock to scrape
            self.assertIn("not the adom-google dashboard", r.stderr)
            self.assertIn("Hint:", r.stderr)
            self.assertIsNotNone(self.listen_addr(self.port))     # still ours to close, not killed
        finally:
            s.close()


if __name__ == "__main__":
    unittest.main(verbosity=2)