"""OpenCode Go's sign-in runs on the device flow every subscription provider shares. It speaks JSON to its console, adds an organization to the grant, and builds its credential from the whole token response (access, rotating refresh, org). With the flow in `albedo_device_flow`, this is the test that keeps that shape working for the provider that uses it. The sign-in writes the daemon's own creds, so the class is exclusive. """ import json import time import unittest from harness import ( Albedo, Provider, daemon_resource, exclusive, exclusive_class, operation_id, text, ) from opencode_go_support import ACCESS_TOKEN, ORG, REFRESH_TOKEN, Console @exclusive_class class OpencodeGoLoginTests(unittest.TestCase): def setUp(self) -> None: self.console = daemon_resource("console", lambda: Console().start()) with self.console.lock: self.console.seen.clear() self.console.authorized = False def prepare(self, app): app.env["OPENCODE_CONSOLE_SERVER"] = self.console.url def test_the_device_sign_in_stores_an_org_scoped_account(self): provider = Provider(lambda _request: text("ok")) self.addCleanup(provider.close) app = Albedo( provider, providers={ "go": { "extension": "opencode-go", "baseUrl": provider.url, "model": "fixture-model", "protocol": "chat_completions", } }, prepare=self.prepare, ) app.__enter__() self.addCleanup(app.__exit__, None, None, None) login = operation_id() with app.api( f"/auth/logins/{login}", {"provider": "opencode-go", "flow": "browser", "values": {}}, method="PUT", ) as response: json.load(response) deadline = time.monotonic() + 30 while True: with app.api(f"/auth/logins/{login}") as response: state = json.load(response) if state.get("url") or state["state"] not in ("waiting", "exchanging"): break self.assertLess(time.monotonic(), deadline, state) time.sleep(0.05) self.assertTrue(state["url"].startswith(self.console.url), state) self.console.org_requested.clear() self.console.org_release.clear() self.addCleanup(self.console.org_release.set) self.console.authorize() self.assertTrue(self.console.org_requested.wait(10)) token_at = self.console.requests("/auth/device/token")[-1]["at"] while time.time_ns() // 1_000_000 <= int(token_at * 1000): time.sleep(0.001) lookups_finished_ms = time.time_ns() // 1_000_000 self.console.org_release.set() while state["state"] in ("waiting", "exchanging"): with app.api(f"/auth/logins/{login}") as response: state = json.load(response) self.assertLess(time.monotonic(), deadline, state) time.sleep(0.05) self.assertEqual(state["state"], "complete", state) stored = json.loads((app.home / "creds.json").read_text()) account = stored["accounts"]["opencode-go"] self.assertEqual(account["type"], "oauth", account) self.assertEqual(account["access"], ACCESS_TOKEN, account) self.assertEqual(account["refresh"], REFRESH_TOKEN, account) self.assertEqual(account["orgId"], ORG["id"], account) self.assertEqual(account["email"], "ana@example.com", account) self.assertGreaterEqual(account["expires"], lookups_finished_ms + 3_540_000) # The code request carried the console's own client identity and asked # for an organization scope; the polls named the device code. code_request = self.console.requests("/auth/device/code")[0]["body"] self.assertEqual(code_request["client_id"], "opencode-cli") self.assertTrue(code_request["supports_org_scope"]) polls = self.console.requests("/auth/device/token") self.assertTrue(polls, self.console.seen) self.assertEqual(polls[0]["body"]["device_code"], "opencode-device-code") @exclusive def test_expired_oauth_rotates_tokens_and_preserves_account_metadata(self) -> None: provider = Provider(lambda _request: text("renewed")) self.addCleanup(provider.close) account_id = operation_id() self.console.authorize() def prepare(app: Albedo) -> None: self.prepare(app) app.store_secrets( "accounts", { "opencode-go": { "type": "oauth", "_albedo_account_id": account_id, "access": "old-fixture-access", "refresh": "old-fixture-refresh", "expires": 0, "accountId": "user-1", "orgId": "old-org", "email": "ana@example.com", "selected": True, "server": self.console.url, "metadata": {"keep": "unknown"}, } }, ) with Albedo( provider, providers={ "go": { "extension": "opencode-go", "baseUrl": provider.url, "model": "fixture-model", "protocol": "chat_completions", "accountId": account_id, } }, prepare=prepare, ) as app: session = app.session() app.prompt(session, "renew").close() app.idle(session) self.assertEqual(len(provider.requests), 1, app.history(session)) headers = provider.requests[0]["headers"] self.assertEqual(headers["authorization"], f"Bearer {ACCESS_TOKEN}") self.assertEqual(headers["x-opencode-org-id"], ORG["id"]) stored = json.loads((app.home / "creds.json").read_text())["accounts"][ "opencode-go" ] self.assertIsInstance(stored, dict) self.assertEqual(stored["refresh"], REFRESH_TOKEN) self.assertEqual(stored["_albedo_account_id"], account_id) self.assertEqual(stored["metadata"], {"keep": "unknown"}) exchanges = self.console.requests("/auth/device/token") self.assertEqual(len(exchanges), 1, exchanges) self.assertEqual(exchanges[0]["body"]["grant_type"], "refresh_token") self.assertEqual( exchanges[0]["body"]["refresh_token"], "old-fixture-refresh" )