From f43ae9b34754bf578f409a2836f0c5564af5b00a Mon Sep 17 00:00:00 2001 From: Xubin Ren <52506698+Re-bin@users.noreply.github.com> Date: Sat, 26 Sep 2026 17:31:20 +0800 Subject: [PATCH] fix(linear): guard installation lifecycle against stale requests --- docs/guides/linear-agent.md | 5 + nanobot/channels/linear/client.py | 11 +- nanobot/channels/linear/connect.py | 7 +- nanobot/channels/linear/state.py | 36 ++- .../linear/tests/test_installation_races.py | 232 ++++++++++++++++++ 5 files changed, 286 insertions(+), 5 deletions(-) create mode 100644 nanobot/channels/linear/tests/test_installation_races.py diff --git a/docs/guides/linear-agent.md b/docs/guides/linear-agent.md index 27400cd83..6dbce3687 100644 --- a/docs/guides/linear-agent.md +++ b/docs/guides/linear-agent.md @@ -348,6 +348,11 @@ allow that installation in Linear; changing a nanobot field cannot bypass this. If a step fails, the UI reports an incomplete reset; removed workspaces stay removed, and you can retry the remaining steps. +If authorization changes while a member refresh or removal is in progress, +nanobot discards the stale result instead of restoring a removed connection or +overwriting a new authorization. Refresh the workspace/member list and retry the +action against the current connection. + Neither removal nor reset deletes the Linear workspace, app, issues or comments, nor nanobot conversation history or pairing approvals. Deleting the app itself is a separate action in Linear. After removing and reconnecting a workspace, diff --git a/nanobot/channels/linear/client.py b/nanobot/channels/linear/client.py index a4cd91dea..1e4c6ef60 100644 --- a/nanobot/channels/linear/client.py +++ b/nanobot/channels/linear/client.py @@ -436,6 +436,8 @@ class LinearClient: raise LinearApiError( f"No Linear OAuth installation for organization {organization_id}" ) + if installation.oauth_client_id != self.config.client_id: + raise LinearApiError("Linear authorization changed; reconnect the workspace") if not force and installation.expires_at > time.time() + 60: return installation token = await self._token_request( @@ -455,6 +457,7 @@ class LinearClient: refresh_token=_required_string(token, "refresh_token"), expires_at=time.time() + _expires_in(token), scope=_scopes(token.get("scope")) or installation.scope, + authorized_at=installation.authorized_at, ) missing_scopes = set(LINEAR_SCOPES) - set(refreshed.scope) if missing_scopes: @@ -462,7 +465,13 @@ class LinearClient: "Refreshed Linear authorization is missing required scope(s): " + ", ".join(sorted(missing_scopes)) ) - self.state.save_installation(refreshed) + # Other clients/processes can remove, reauthorize or rotate this grant + # while the HTTP request is in flight. Never persist or use a stale result. + if not self.state.refresh_installation(installation, refreshed): + raise LinearApiError( + "Linear authorization changed during token refresh; retry the request", + retryable=True, + ) return refreshed async def _token_request(self, form: dict[str, str]) -> dict[str, Any]: diff --git a/nanobot/channels/linear/connect.py b/nanobot/channels/linear/connect.py index eb989dd67..59d18181c 100644 --- a/nanobot/channels/linear/connect.py +++ b/nanobot/channels/linear/connect.py @@ -263,7 +263,12 @@ class LinearConnectStore: ) from exc finally: await client.close() - state.delete_installation(organization_id) + removed = state.delete_installation(organization_id, expected=installation) + if not removed and state.installation(organization_id) is not None: + raise ChannelConnectError( + "Linear workspace authorization changed while disconnecting. Refresh and try again.", + status=409, + ) installations = _installation_payloads(state, config.client_id) return { "session_id": "", diff --git a/nanobot/channels/linear/state.py b/nanobot/channels/linear/state.py index 9e4f7d4d6..c570e39a2 100644 --- a/nanobot/channels/linear/state.py +++ b/nanobot/channels/linear/state.py @@ -7,7 +7,7 @@ import os import sqlite3 import threading import time -from dataclasses import dataclass +from dataclasses import dataclass, field from pathlib import Path from typing import Any, cast @@ -24,6 +24,8 @@ class LinearInstallation: expires_at: float scope: tuple[str, ...] = () organization_name: str = "" + # Store-owned lifecycle metadata, separate from the credential value's equality. + authorized_at: float = field(default=0, compare=False) @dataclass(frozen=True, slots=True) @@ -158,6 +160,28 @@ class LinearStateStore: ), ) + def refresh_installation( + self, previous: LinearInstallation, refreshed: LinearInstallation, + ) -> bool: + """Rotate only the credentials read before the request, never insert a grant.""" + if (refreshed.organization_id != previous.organization_id + or refreshed.oauth_client_id != previous.oauth_client_id): + raise ValueError("A token refresh cannot change the Linear workspace or app") + with self._guard, self._connect() as connection: + result = connection.execute( + """ + UPDATE installations + SET access_token = ?, refresh_token = ?, expires_at = ?, scope_json = ?, updated_at = ? + WHERE organization_id = ? AND oauth_client_id = ? AND authorized_at = ? + AND access_token = ? AND refresh_token = ? + """, + (refreshed.access_token, refreshed.refresh_token, refreshed.expires_at, + json.dumps(refreshed.scope), time.time(), previous.organization_id, + previous.oauth_client_id, previous.authorized_at, + previous.access_token, previous.refresh_token), + ) + return result.rowcount == 1 + def installation(self, organization_id: str) -> LinearInstallation | None: with self._guard, self._connect() as connection: row = connection.execute( @@ -189,17 +213,22 @@ class LinearStateStore: def delete_installation( self, organization_id: str, *, oauth_client_id: str | None = None, - revoked_at: float | None = None, + revoked_at: float | None = None, expected: LinearInstallation | None = None, ) -> bool: """Remove an installation, ignoring revocations from an older authorization.""" with self._guard, self._connect() as connection: connection.execute("BEGIN IMMEDIATE") current = connection.execute( - "SELECT oauth_client_id, authorized_at FROM installations WHERE organization_id = ?", + "SELECT * FROM installations WHERE organization_id = ?", (organization_id,), ).fetchone() if current is None: return False + if expected is not None and ( + _installation_from_row(current) != expected + or float(current["authorized_at"]) != expected.authorized_at + ): + return False if oauth_client_id is not None and current["oauth_client_id"] != oauth_client_id: return False if revoked_at is not None and revoked_at < float(current["authorized_at"]): @@ -351,6 +380,7 @@ def _installation_from_row(row: sqlite3.Row) -> LinearInstallation: expires_at=float(row["expires_at"]), scope=scope, organization_name=str(row["organization_name"]), + authorized_at=float(row["authorized_at"]), ) diff --git a/nanobot/channels/linear/tests/test_installation_races.py b/nanobot/channels/linear/tests/test_installation_races.py new file mode 100644 index 000000000..9869dd0aa --- /dev/null +++ b/nanobot/channels/linear/tests/test_installation_races.py @@ -0,0 +1,232 @@ +"""Delayed network responses must not restore or overwrite workspace authorizations.""" + +from __future__ import annotations + +import asyncio +import time +from dataclasses import replace +from datetime import datetime, timezone +from pathlib import Path + +import httpx +import pytest + +from nanobot.channels.linear import connect as linear_connect +from nanobot.channels.linear.client import LinearApiError, LinearClient +from nanobot.channels.linear.state import LinearStateStore +from nanobot.channels.linear.tests.test_linear import _config, _installation, _runtime + + +@pytest.mark.parametrize("replacement", ["removed", "reauthorized", "same_tokens", "other_app"]) +async def test_member_read_cannot_restore_or_overwrite_a_changed_installation( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, replacement: str, +) -> None: + state = LinearStateStore(tmp_path / "linear.sqlite3") + original = replace(_installation(), expires_at=0) + state.save_installation(original) + state.set_member_access("client-id", "org-1", "user-1", allowed=False) + state.save_installation(replace(_installation(), organization_id="org-2")) + entered, release = asyncio.Event(), asyncio.Event() + requests: list[str] = [] + + async def handler(request: httpx.Request) -> httpx.Response: + requests.append(request.url.path) + if request.url.path == "/oauth/token": + entered.set() + await release.wait() + return httpx.Response(200, json={ + "access_token": "late-access", "refresh_token": "late-refresh", + "expires_in": 86400, + "scope": "read write app:mentionable app:assignable", + }) + if request.url.path == "/oauth/revoke": + return httpx.Response(200) + return httpx.Response(200, json={"data": {"teams": { + "nodes": [], "pageInfo": {"hasNextPage": False, "endCursor": None}, + }}}) + + async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http: + monkeypatch.setattr(linear_connect, "_load_linear_config", _config) + monkeypatch.setattr(linear_connect, "LinearStateStore", lambda: LinearStateStore(state.path)) + monkeypatch.setattr(linear_connect, "LinearClient", lambda config, store: LinearClient(config, store, http)) + api = linear_connect.LinearConnectStore() + pending = asyncio.create_task(api.handle("start", { + "operation": ["members"], "organization_id": ["org-1"], + })) + try: + await asyncio.wait_for(entered.wait(), 2) + result = await api.handle("start", { + "operation": ["disconnect"], "organization_id": ["org-1"], + }) + assert [item["organization_id"] for item in result["installations"]] == ["org-2"] + revoked_at = datetime.now(timezone.utc).isoformat() + if replacement != "removed": + state.save_installation(replace( + original, + access_token=original.access_token if replacement == "same_tokens" else "new-grant", + refresh_token=original.refresh_token if replacement == "same_tokens" else "new-refresh", + oauth_client_id="other-client" if replacement == "other_app" else "client-id", + ), reauthorize=True) + state.set_member_access( + "other-client" if replacement == "other_app" else "client-id", + "org-1", "user-1", allowed=False, + ) + expected = state.installation("org-1") + release.set() + with pytest.raises(linear_connect.ChannelConnectError, match="authorization changed"): + await pending + assert "/graphql" not in requests # Never use a discarded refresh result. + assert LinearStateStore(state.path).installation("org-1") == expected + assert state.installation("org-2") is not None + if expected is None: + assert state.member_access("client-id", "org-1", "user-1") is None + else: + assert state.member_access(expected.oauth_client_id, "org-1", "user-1") is False + # The genuine removal notice can arrive after the network response. + channel, _ = _runtime(tmp_path / "runtime") + channel._state = state # pyright: ignore[reportPrivateUsage] + channel._process_lifecycle_event({ # pyright: ignore[reportPrivateUsage] + "action": "revoked", "organizationId": "org-1", "createdAt": revoked_at, + }) + assert state.installation("org-1") == expected + finally: + release.set() + await asyncio.gather(pending, return_exceptions=True) + + +async def test_late_refresh_cannot_overwrite_another_clients_rotation(tmp_path: Path) -> None: + state = LinearStateStore(tmp_path / "linear.sqlite3") + state.save_installation(replace(_installation(), expires_at=0)) + state.set_member_access("client-id", "org-1", "user-1", allowed=False) + entered, release = asyncio.Event(), asyncio.Event() + count = 0 + tokens_used: list[str] = [] + + async def handler(request: httpx.Request) -> httpx.Response: + nonlocal count + if request.url.path == "/oauth/token": + count += 1 + number = count + if number == 1: + entered.set() + await release.wait() + return httpx.Response(200, json={ + "access_token": f"access-{number}", "refresh_token": f"refresh-{number}", + "expires_in": 86400, + "scope": "read write app:mentionable app:assignable", + }) + tokens_used.append(request.headers["Authorization"]) + return httpx.Response(200, json={"data": {"viewer": {"id": "app-user-1"}}}) + + async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http: + first = LinearClient(_config(), LinearStateStore(state.path), http) + second = LinearClient(_config(), LinearStateStore(state.path), http) + pending = asyncio.create_task(first.graphql("org-1", "query Test { viewer { id } }", {})) + try: + await asyncio.wait_for(entered.wait(), 2) + await second.graphql("org-1", "query Test { viewer { id } }", {}) + winner = state.installation("org-1") + release.set() + with pytest.raises(LinearApiError, match="authorization changed") as error: + await pending + assert error.value.retryable + assert state.installation("org-1") == winner + assert state.member_access("client-id", "org-1", "user-1") is False + # Retrying reads the winner's credentials, without another rotation. + await first.graphql("org-1", "query Test { viewer { id } }", {}) + assert count == 2 + assert tokens_used == ["Bearer access-2", "Bearer access-2"] + finally: + release.set() + await asyncio.gather(pending, return_exceptions=True) + + +async def test_normal_refresh_preserves_authorization_and_member_choices( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + state = LinearStateStore(tmp_path / "linear.sqlite3") + monkeypatch.setattr(time, "time", lambda: 1000.0) + state.save_installation(replace(_installation(), expires_at=0)) + state.set_member_access("client-id", "org-1", "user-1", allowed=False) + + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == "/oauth/token": + return httpx.Response(200, json={ + "access_token": "rotated", "refresh_token": "rotated-refresh", + "expires_in": 86400, + "scope": "read write app:mentionable app:assignable", + }) + assert request.headers["Authorization"] == "Bearer rotated" + return httpx.Response(200, json={"data": {"viewer": {"id": "app-user-1"}}}) + + monkeypatch.setattr(time, "time", lambda: 2000.0) + async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http: + await LinearClient(_config(), state, http).graphql("org-1", "query Test { viewer { id } }", {}) + reopened = LinearStateStore(state.path) + rotated = reopened.installation("org-1") + assert rotated is not None and rotated.access_token == "rotated" + assert rotated.authorized_at == 1000.0 + assert reopened.member_access("client-id", "org-1", "user-1") is False + # Refresh is not a new grant: a real revocation from before the refresh still wins. + assert reopened.delete_installation("org-1", revoked_at=1500.0) + + +async def test_forced_refresh_does_not_use_a_different_apps_credentials(tmp_path: Path) -> None: + state = LinearStateStore(tmp_path / "linear.sqlite3") + state.save_installation(_installation()) + requests = 0 + + def handler(_request: httpx.Request) -> httpx.Response: + nonlocal requests + requests += 1 + # The app changed while an earlier API request was in flight. + state.save_installation(replace(_installation(), oauth_client_id="other-app")) + return httpx.Response(401) + + async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http: + with pytest.raises(LinearApiError, match="authorization changed"): + await LinearClient(_config(), state, http).graphql("org-1", "query Test { viewer { id } }", {}) + assert requests == 1 # No refresh request with another app's token. + + +@pytest.mark.parametrize("replacement", ["reauthorized", "same_tokens", "other_app"]) +async def test_delayed_disconnect_keeps_a_new_authorization( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, replacement: str, +) -> None: + state = LinearStateStore(tmp_path / "linear.sqlite3") + original = _installation() + state.save_installation(original) + entered, release = asyncio.Event(), asyncio.Event() + + async def handler(request: httpx.Request) -> httpx.Response: + assert request.url.path == "/oauth/revoke" + entered.set() + await release.wait() + return httpx.Response(200) + + async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http: + monkeypatch.setattr(linear_connect, "_load_linear_config", _config) + monkeypatch.setattr(linear_connect, "LinearStateStore", lambda: LinearStateStore(state.path)) + monkeypatch.setattr(linear_connect, "LinearClient", lambda config, store: LinearClient(config, store, http)) + pending = asyncio.create_task(linear_connect.LinearConnectStore().handle("start", { + "operation": ["disconnect"], "organization_id": ["org-1"], + })) + try: + await asyncio.wait_for(entered.wait(), 2) + client_id = "other-client" if replacement == "other_app" else "client-id" + state.save_installation(replace( + original, oauth_client_id=client_id, + access_token=original.access_token if replacement == "same_tokens" else "new-grant", + refresh_token=original.refresh_token if replacement == "same_tokens" else "new-refresh", + ), reauthorize=True) + state.set_member_access(client_id, "org-1", "user-1", allowed=False) + expected = state.installation("org-1") + release.set() + with pytest.raises(linear_connect.ChannelConnectError, match="authorization changed") as error: + await pending + assert error.value.status == 409 + assert state.installation("org-1") == expected + assert state.member_access(client_id, "org-1", "user-1") is False + finally: + release.set() + await asyncio.gather(pending, return_exceptions=True)