From e78544fcaf2a2b9182b0b8b4ab00ae2ccce85a39 Mon Sep 17 00:00:00 2001 From: Xubin Ren <52506698+Re-bin@users.noreply.github.com> Date: Fri, 25 Sep 2026 15:19:49 +0800 Subject: [PATCH] feat(linear): manage member access from WebUI Implement NAN-158 with installation-scoped access switches, effective legacy approval fallback, live team membership checks, and deployment guidance. --- docs/guides/linear-agent.md | 70 +++++- nanobot/channels/linear/access.py | 21 ++ nanobot/channels/linear/client.py | 85 ++++++- nanobot/channels/linear/connect.py | 47 ++++ nanobot/channels/linear/runtime.py | 48 +++- nanobot/channels/linear/state.py | 35 +++ nanobot/channels/linear/tests/conftest.py | 12 + nanobot/channels/linear/tests/test_linear.py | 8 +- .../linear/tests/test_member_access.py | 217 ++++++++++++++++++ .../linear/tests/webui/LinearPanel.test.tsx | 4 +- .../linear/webui/LinearHelpContent.tsx | 10 +- .../linear/webui/LinearMemberAccess.tsx | 142 ++++++++++++ nanobot/channels/linear/webui/LinearPanel.tsx | 3 + nanobot/channels/linear/webui/api.ts | 10 +- nanobot/channels/linear/webui/locales/en.json | 14 ++ nanobot/channels/linear/webui/locales/es.json | 14 ++ nanobot/channels/linear/webui/locales/fr.json | 14 ++ nanobot/channels/linear/webui/locales/id.json | 14 ++ nanobot/channels/linear/webui/locales/ja.json | 14 ++ nanobot/channels/linear/webui/locales/ko.json | 14 ++ .../channels/linear/webui/locales/pt-BR.json | 14 ++ nanobot/channels/linear/webui/locales/vi.json | 14 ++ .../channels/linear/webui/locales/zh-CN.json | 2 +- .../channels/linear/webui/locales/zh-TW.json | 2 +- nanobot/channels/linear/webui/types.ts | 15 ++ webui/src/tests/linear-member-access.test.tsx | 104 +++++++++ 26 files changed, 920 insertions(+), 27 deletions(-) create mode 100644 nanobot/channels/linear/access.py create mode 100644 nanobot/channels/linear/tests/conftest.py create mode 100644 nanobot/channels/linear/tests/test_member_access.py create mode 100644 nanobot/channels/linear/webui/LinearMemberAccess.tsx create mode 100644 webui/src/tests/linear-member-access.test.tsx diff --git a/docs/guides/linear-agent.md b/docs/guides/linear-agent.md index 884067b50..805c73c97 100644 --- a/docs/guides/linear-agent.md +++ b/docs/guides/linear-agent.md @@ -16,9 +16,9 @@ and confirm that webhook delivery is enabled before testing a task. - An ordinary issue comment does not invoke nanobot. - A follow-up inside the existing Agent Session continues the same nanobot session without another @mention. -- Linear's stop control asks nanobot to cancel the active turn without requiring - the sender to complete pairing first. An activity already delivered to Linear - cannot be recalled. +- Linear's stop control asks nanobot to cancel the active turn. The sender must + have access, just as for other requests. An activity already delivered to + Linear cannot be recalled. - nanobot reports its acknowledgement, tool activity, reasoning, and final answer as native Linear Agent Activities. - Button choices are sent as Linear selection activities, and local outbound @@ -231,11 +231,37 @@ refreshes each workspace installation separately. 4. Send a follow-up inside that Agent Session. You do not need to @mention the app again there. -If **Allowed Linear users** is empty, the first mention returns a nanobot pairing -code. Approve the pending request in the WebUI pairing dialog, then repeat the -prompt in the same Agent Session. For a static allowlist, enter Linear user IDs -in **Allowed Linear users**. Enter `*` only if every member of every connected -workspace should be able to invoke the agent. +Before inviting teammates, open **Member access** under the authorized workspace +in **Settings → Channels → Linear**. Search for a member and switch on **Allow +… to use nanobot**. Wait for **Member access saved.** They can then mention the +agent without copying a pairing code or authorizing another OAuth installation. + +The list contains active human members of teams this app can access. It does not +grant access to additional Linear teams or to the nanobot admin UI. Names are for +display; permissions use stable user IDs scoped to the OAuth client and workspace. +Use **Refresh members** to refresh the directory and effective permission state. +If a read or save fails, the UI reports the failure and requires a refresh before +another edit; it does not pretend a switch was saved. + +New members are off by default. Existing pairing approvals and **Advanced → +Allowed Linear users** remain valid until explicitly overridden by a member +switch. An explicit **off** wins over both legacy approvals and `*`, even if a +new pairing code is subsequently approved. Use the switch to enable that member +again. If you keep `*`, new members will still be allowed automatically; the UI +displays a warning. Remove `*` to require approval for new members. + +Pairing remains a fallback for members without an explicit switch setting: +approve their pending request in the WebUI pairing dialog, then repeat the prompt +in the same Agent Session. You may also keep a static list of IDs in **Allowed +Linear users**. Other channels' pairing behavior is unchanged. + +At request admission nanobot checks current team membership through the app's +Linear API authorization, including active status and excluding app accounts. +Directory/API failure does not authorize a task; transient failures use the +channel's bounded webhook retry path. This adds API requests and latency, rather +than relying on stale cached permissions. Turning a member off blocks new +requests (including stop requests); it does not cancel already admitted/running +tasks or recall replies. Administrators should stop ongoing tasks separately. By default, reasoning is posted as Linear thought activities. Turn off **Show reasoning** under **Advanced** for a quieter session. Use **Configure Linear @@ -243,6 +269,32 @@ MCP**, to the left of **Create Linear app**, to open Linear MCP's connection settings when prompts need to search, edit, or transition issues. Pairing and access guidance is available in the dialog's **Help** menu. +### Updating a remote installation + +Member management includes both Python channel code and WebUI assets. A local +branch does not update an already running remote gateway, and the browser UI +served by that remote gateway is not replaced by installing a local client. + +1. Develop and test in a separate checkout with test-only config/state. Do not + copy production OAuth tokens, model keys, or pairing state into a development + profile, or run a second gateway against the production webhook installation. +2. After review and deployment approval, back up the remote config, pairing file, + and Linear SQLite state consistently (stop the gateway or use SQLite backup; + copying just the database while WAL writes are active is not sufficient). +3. Update the remote source and dependencies to the reviewed revision, build the + WebUI from that same revision, and restart the gateway. Preserve remote + credentials and state. Existing OAuth scopes and webhook routes need not change. +4. Verify member listing, the existing owner's access, enable/disable behavior, + and that the admin UI remains private. Grant teammate access only deliberately. + +Member switches are stored in the instance's `linear/state.sqlite3`, separately +from legacy pairing and config. Older code ignores those overrides: **do not +blindly roll back after revoking access with a switch**, because old code could +re-enable a member through a retained pairing approval or wildcard. Keep the +channel disabled during rollback until the older allowlist/pairing configuration +has been reconciled. Ordinary restarts and reconnecting the same OAuth app keep +the saved member choices. + ## Verify the setup The setup is complete when all of these checks pass: @@ -338,7 +390,7 @@ secret. | The local health URL does not load | Start **Connect Linear** or enable the connected channel, then check the configured listen host and port. | | **Agent didn't start**, **nanobot failed to start**, or a session stays on **Thinking…** without a response | First check **Webhooks → Delivery status** in the Linear app. If **Disabled**, enable it from **…**. Confirm the current Webhook URL and `AgentSessionEvent` subscription, then select **Retry** in the Linear session. OAuth success and a working `/linear/health` endpoint do not prove that Linear is sending events. | | An @mention still gets no response with delivery enabled | Inspect **Webhook delivery failures** in the Linear app and run `nanobot gateway logs`. A 404 points to the webhook path; a 502 points to the listener or tunnel; a 401 can indicate a signing-secret mismatch or stale event timestamp. Confirm the Client ID and signing secret belong to the same app and the workspace authorization has not been revoked. | -| The first @mention returns a pairing code | Approve it in the WebUI pairing dialog, then repeat the prompt in the same Agent Session. Alternatively, configure a narrow **Allowed Linear users** list. | +| The first @mention returns a pairing code | Enable the member under the workspace's **Member access**, or approve the code in the WebUI pairing dialog, then repeat the prompt. An explicit off switch must be changed in **Member access**; pairing or allowlist changes do not override it. | | Normal comments do nothing | This is intentional. Start a task by @mentioning the app, or continue inside an existing Agent Session. | | Delegating an issue does not start a session | Reconnect the workspace so the installation grants `app:assignable`, then confirm the app can be selected as the issue delegate. | | The agent can discuss an issue but cannot search or change it | Connect the Linear MCP app from **Configure Linear MCP**. The native channel transports the conversation but does not add issue-management tools. | diff --git a/nanobot/channels/linear/access.py b/nanobot/channels/linear/access.py new file mode 100644 index 000000000..09a31d017 --- /dev/null +++ b/nanobot/channels/linear/access.py @@ -0,0 +1,21 @@ +"""Installation-scoped member choices, with non-destructive legacy approval fallback.""" + +from nanobot.channels.linear.config import LinearConfig +from nanobot.channels.linear.state import LinearStateStore +from nanobot.pairing.store import is_approved + + +def member_allowed( + config: LinearConfig, state: LinearStateStore, organization_id: str, user_id: str, +) -> bool: + installation = state.installation(organization_id) + if installation is None or installation.oauth_client_id != config.client_id: + return False + choice = state.member_access(config.client_id, organization_id, user_id) + if choice is not None: + return choice + return ( + "*" in config.allow_from + or user_id in config.allow_from + or is_approved("linear", user_id) + ) diff --git a/nanobot/channels/linear/client.py b/nanobot/channels/linear/client.py index 03498c3e7..e7169b2ec 100644 --- a/nanobot/channels/linear/client.py +++ b/nanobot/channels/linear/client.py @@ -6,7 +6,7 @@ import asyncio import mimetypes import time from pathlib import Path -from typing import Any, cast +from typing import Any, TypedDict, cast import httpx @@ -22,6 +22,12 @@ MAX_UPLOAD_BYTES = 40 * 1024 * 1024 MAX_DOWNLOAD_BYTES = 40 * 1024 * 1024 +class LinearMember(TypedDict): + id: str + name: str + teams: list[str] + + class LinearApiError(RuntimeError): """Linear returned a transport, authentication, or GraphQL error.""" @@ -108,6 +114,83 @@ class LinearClient: installation = await self._refresh(organization_id, force=True) return await self._graphql_with_token(installation.access_token, query, variables) + async def list_members( + self, organization_id: str, *, user_id: str | None = None, + ) -> list[LinearMember]: + """Read active humans in teams visible to this app, never workspace-wide users. + + A filtered lookup is also used at request admission: departed members and + revoked team access must not keep working through old local approvals. + No stale directory cache is used to authorize a request. + """ + teams = await self._connection_nodes( + organization_id, + """query NanobotMemberTeams($after: String) { + teams(first: 50, after: $after) { + nodes { id name } pageInfo { hasNextPage endCursor } + } + }""", + {}, ("teams",), + ) + members: dict[str, LinearMember] = {} + for team in teams: + team_id = _required_string(team, "id") + team_name = _required_string(team, "name") + nodes = await self._connection_nodes( + organization_id, + """query NanobotTeamMembers($team: String!, $after: String, $filter: UserFilter) { + team(id: $team) { + members(first: 50, after: $after, filter: $filter) { + nodes { id name active app } + pageInfo { hasNextPage endCursor } + } + } + }""", + {"team": team_id, "filter": {"id": {"eq": user_id}} if user_id else None}, + ("team", "members"), + ) + for node in nodes: + if not isinstance(node.get("active"), bool) or not isinstance(node.get("app"), bool): + raise LinearApiError("Linear returned an incomplete member identity") + if node["active"] is not True or node["app"] is True: + continue + member_id = _required_string(node, "id") + name = _required_string(node, "name") + if user_id is not None and member_id != user_id: + raise LinearApiError("Linear returned an unexpected member identity") + member = members.setdefault(member_id, {"id": member_id, "name": name, "teams": []}) + if team_name not in member["teams"]: + member["teams"].append(team_name) + return sorted(members.values(), key=lambda member: (member["name"].casefold(), member["id"])) + + async def _connection_nodes( + self, organization_id: str, query: str, variables: dict[str, Any], path: tuple[str, ...], + ) -> list[dict[str, Any]]: + nodes: list[dict[str, Any]] = [] + cursor: str | None = None + seen: set[str] = set() + for _ in range(200): + connection = await self.graphql(organization_id, query, {**variables, "after": cursor}) + for key in path: + connection = _required_mapping(connection, key) + raw_nodes = connection.get("nodes") + if not isinstance(raw_nodes, list): + raise LinearApiError("Linear returned an invalid member directory") + for raw_node in cast(list[object], raw_nodes): + if not isinstance(raw_node, dict): + raise LinearApiError("Linear returned an invalid member directory") + nodes.append(cast(dict[str, Any], raw_node)) + page = _required_mapping(connection, "pageInfo") + if page.get("hasNextPage") is False: + return nodes + if page.get("hasNextPage") is not True: + raise LinearApiError("Linear returned incomplete pagination information") + cursor = _required_string(page, "endCursor") + if cursor in seen: + raise LinearApiError("Linear returned a repeated member directory cursor") + seen.add(cursor) + raise LinearApiError("Linear member directory is too large; no partial result was saved") + async def create_activity( self, organization_id: str, diff --git a/nanobot/channels/linear/connect.py b/nanobot/channels/linear/connect.py index 72ac6ccde..247f5fe2c 100644 --- a/nanobot/channels/linear/connect.py +++ b/nanobot/channels/linear/connect.py @@ -8,6 +8,7 @@ from dataclasses import dataclass, field from typing import Any, cast from nanobot.channels.connect import ChannelConnectError, QueryParams, query_first +from nanobot.channels.linear.access import member_allowed from nanobot.channels.linear.client import LinearApiError, LinearClient from nanobot.channels.linear.config import LinearConfig from nanobot.channels.linear.oauth import ( @@ -49,6 +50,19 @@ class LinearConnectStore: if not organization_id: raise ChannelConnectError("missing Linear workspace") return await self.disconnect(organization_id) + if operation in {"members", "member_access"}: + organization_id = (query_first(query, "organization_id") or "").strip() + if not organization_id: + raise ChannelConnectError("missing Linear workspace") + user_id: str | None = None + allowed: bool | None = None + if operation == "member_access": + user_id = (query_first(query, "user_id") or "").strip() + raw_allowed = query_first(query, "allowed") + if not user_id or raw_allowed not in {"true", "false"}: + raise ChannelConnectError("member access requires a user ID and true/false") + allowed = raw_allowed == "true" + return await self.members(organization_id, user_id=user_id, allowed=allowed) if operation != "connect": raise ChannelConnectError(f"unsupported Linear connect operation: {operation}") return await self.start(force=_query_bool(query, "force")) @@ -180,6 +194,39 @@ class LinearConnectStore: "redirect_uri": config.redirect_uri if config.public_base_url else "", } + async def members( + self, organization_id: str, *, user_id: str | None = None, allowed: bool | None = None, + ) -> dict[str, Any]: + config = _load_linear_config() + state = LinearStateStore() + installation = state.installation(organization_id) + if installation is None or installation.oauth_client_id != config.client_id: + raise ChannelConnectError("Linear workspace is not connected", status=404) + client = LinearClient(config, state) + try: + members = await client.list_members(organization_id, user_id=user_id) + except LinearApiError as exc: + raise ChannelConnectError(f"Unable to read Linear members: {exc}", status=502) from exc + finally: + await client.close() + if user_id is not None and allowed is not None: + if not any(member["id"] == user_id for member in members): + raise ChannelConnectError("Member is not active in an accessible Linear team", status=404) + try: + state.set_member_access(config.client_id, organization_id, user_id, allowed=allowed) + except ValueError as exc: + raise ChannelConnectError(str(exc), status=409) from exc + return { + "session_id": "", + "status": "members" if allowed is None else "member_access_saved", + "organization_id": organization_id, + "legacy_allow_all": "*" in config.allow_from, + "members": [ + {**member, "allowed": member_allowed(config, state, organization_id, member["id"])} + for member in members + ], + } + async def disconnect(self, organization_id: str) -> dict[str, Any]: config = _load_linear_config() state = LinearStateStore() diff --git a/nanobot/channels/linear/runtime.py b/nanobot/channels/linear/runtime.py index e73fd07e8..03741edb1 100644 --- a/nanobot/channels/linear/runtime.py +++ b/nanobot/channels/linear/runtime.py @@ -16,11 +16,13 @@ from nanobot.bus.events import InboundMessage, OutboundMessage from nanobot.bus.outbound_events import ContextCompactionEvent, ProgressEvent, RetryWaitEvent from nanobot.bus.queue import MessageBus from nanobot.channels.base import BaseChannel +from nanobot.channels.linear.access import member_allowed from nanobot.channels.linear.client import MAX_DOWNLOAD_BYTES, LinearApiError, LinearClient from nanobot.channels.linear.config import LinearConfig from nanobot.channels.linear.server import LinearServerLease, acquire_http_server from nanobot.channels.linear.state import LinearStateStore, QueuedWebhook from nanobot.config.paths import get_media_dir +from nanobot.pairing import PAIRING_CODE_META_KEY from nanobot.security.network import validate_url_target from nanobot.utils.helpers import safe_filename @@ -100,7 +102,29 @@ class LinearChannel(BaseChannel): def start_error_message(self, error: Exception) -> str | None: return f"Linear channel failed to start: {error}" + def is_allowed(self, sender_id: str) -> bool: + # _handle_message accepts a separate authorization subject, while the + # actual sender ID (including legacy pairing codes) remains unchanged. + try: + subject: object = json.loads(sender_id) + except (ValueError, TypeError): + return False + if not isinstance(subject, list): + return False + parts = cast(list[object], subject) + if len(parts) != 2: + return False + organization_id, user_id = parts + if not isinstance(organization_id, str) or not isinstance(user_id, str): + return False + return member_allowed(self.config, self._state, organization_id, user_id) + async def send(self, msg: OutboundMessage) -> None: + if PAIRING_CODE_META_KEY in msg.metadata: + msg.content = ( + "Ask your nanobot administrator to enable your access in Linear member settings. " + "Alternatively, an administrator can approve this pairing request.\n\n" + msg.content + ) event = msg.event if isinstance(event, ContextCompactionEvent): if event.phase == "succeeded": @@ -355,7 +379,7 @@ class LinearChannel(BaseChannel): if str(session.get("organizationId") or organization_id) != organization_id: raise LinearPayloadError("organization mismatch") installation = self._state.installation(organization_id) - if installation is None: + if installation is None or installation.oauth_client_id != self.config.client_id: raise LinearPayloadError("organization is not installed") activity = _optional_object(payload.get("agentActivity")) if activity and str(activity.get("userId") or "") == installation.app_user_id: @@ -368,6 +392,7 @@ class LinearChannel(BaseChannel): ).strip() if not sender_id: raise LinearPayloadError("missing sender identity") + authorization_id = json.dumps([organization_id, sender_id]) issue_context = _issue_context(session) prompt_content = _prompt_text( payload, session, activity, action, issue_context=issue_context, @@ -397,7 +422,25 @@ class LinearChannel(BaseChannel): self._routes[agent_session_id] = cast(dict[str, Any], metadata["linear"]) if len(self._routes) > 1000: self._routes.pop(next(iter(self._routes))) + choice = self._state.member_access(self.config.client_id, organization_id, sender_id) + if choice is False: + await self._create_activity( + agent_session_id, metadata, + {"type": "response", "body": "Access is disabled. Ask your nanobot administrator to enable your access in Linear member settings."}, + key="access-denied", + ) + return + if self.is_allowed(authorization_id): + client = self._client + if client is None: + raise RuntimeError("Linear HTTP client is not initialized") + # Read current membership on admission, without caching grants. API + # failures take the normal error path and never publish an agent turn. + if not await client.list_members(organization_id, user_id=sender_id): + raise LinearPayloadError("sender is not active in an accessible Linear team") if signal == "stop": + if not self.is_allowed(authorization_id): + return await self.bus.publish_inbound( InboundMessage( channel=self.name, @@ -411,7 +454,7 @@ class LinearChannel(BaseChannel): return media: list[str] = [] context_delivered = False - if self.is_allowed(sender_id): + if self.is_allowed(authorization_id): await self._create_activity( agent_session_id, metadata, @@ -436,6 +479,7 @@ class LinearChannel(BaseChannel): metadata=metadata, session_key=f"linear:{organization_id}:{agent_session_id}", is_dm=True, + authorization_id=authorization_id, ) if context_delivered: self._issue_contexts[agent_session_id] = issue_context diff --git a/nanobot/channels/linear/state.py b/nanobot/channels/linear/state.py index 7fd9cf50d..546cdd864 100644 --- a/nanobot/channels/linear/state.py +++ b/nanobot/channels/linear/state.py @@ -82,6 +82,13 @@ class LinearStateStore: delivery_id TEXT PRIMARY KEY, received_at REAL NOT NULL ); + CREATE TABLE IF NOT EXISTS member_access ( + oauth_client_id TEXT NOT NULL, + organization_id TEXT NOT NULL, + user_id TEXT NOT NULL, + allowed INTEGER NOT NULL CHECK (allowed IN (0, 1)), + PRIMARY KEY (oauth_client_id, organization_id, user_id) + ); """ ) columns = { @@ -175,6 +182,34 @@ class LinearStateStore: (organization_id,), ) + def member_access(self, client_id: str, organization_id: str, user_id: str) -> bool | None: + """An explicit choice overrides legacy pairing and allowFrom, including '*'.""" + with self._guard, self._connect() as connection: + row = connection.execute( + "SELECT allowed FROM member_access " + "WHERE oauth_client_id = ? AND organization_id = ? AND user_id = ?", + (client_id, organization_id, user_id), + ).fetchone() + return bool(row["allowed"]) if row is not None else None + + def set_member_access( + self, client_id: str, organization_id: str, user_id: str, *, allowed: bool, + ) -> None: + with self._guard, self._connect() as connection: + connection.execute("BEGIN IMMEDIATE") + installed = connection.execute( + "SELECT 1 FROM installations WHERE oauth_client_id = ? AND organization_id = ?", + (client_id, organization_id), + ).fetchone() + if installed is None: + raise ValueError("Linear workspace is not connected") + connection.execute( + "INSERT INTO member_access (oauth_client_id, organization_id, user_id, allowed) " + "VALUES (?, ?, ?, ?) ON CONFLICT(oauth_client_id, organization_id, user_id) " + "DO UPDATE SET allowed = excluded.allowed", + (client_id, organization_id, user_id, int(allowed)), + ) + def enqueue_webhook(self, delivery_id: str, payload: dict[str, Any]) -> bool: serialized = json.dumps(payload, separators=(",", ":"), ensure_ascii=False) with self._guard, self._connect() as connection: diff --git a/nanobot/channels/linear/tests/conftest.py b/nanobot/channels/linear/tests/conftest.py new file mode 100644 index 000000000..ca7fcf783 --- /dev/null +++ b/nanobot/channels/linear/tests/conftest.py @@ -0,0 +1,12 @@ +"""Keep Linear installation and permission state out of the user's real profile.""" + +from pathlib import Path + +import pytest + + +@pytest.fixture(autouse=True) +def isolate_linear_state(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr( + "nanobot.channels.linear.state.get_runtime_subdir", lambda _name: tmp_path / "linear", + ) diff --git a/nanobot/channels/linear/tests/test_linear.py b/nanobot/channels/linear/tests/test_linear.py index 70361606d..0b9bb5603 100644 --- a/nanobot/channels/linear/tests/test_linear.py +++ b/nanobot/channels/linear/tests/test_linear.py @@ -28,7 +28,7 @@ from nanobot.bus.queue import MessageBus from nanobot.channels.linear import client as linear_client from nanobot.channels.linear import connect as linear_connect from nanobot.channels.linear import runtime as linear_runtime -from nanobot.channels.linear.client import LinearApiError, LinearClient +from nanobot.channels.linear.client import LinearApiError, LinearClient, LinearMember from nanobot.channels.linear.config import LinearConfig, validate_public_base_url from nanobot.channels.linear.oauth import OAUTH_FLOWS, authorization_url from nanobot.channels.linear.runtime import LinearChannel @@ -660,6 +660,11 @@ class _FakeLinearClient: self.activities: list[dict[str, Any]] = [] self.downloads: list[str] = [] + async def list_members( + self, _organization_id: str, *, user_id: str | None = None, + ) -> list[LinearMember]: + return [{"id": user_id or "user-1", "name": "Member", "teams": ["Team"]}] + async def create_activity( self, organization_id: str, @@ -976,7 +981,6 @@ async def test_inbound_attachments_enforce_the_count_limit( @pytest.mark.asyncio async def test_prompted_stop_signal_becomes_priority_stop_command(tmp_path: Path) -> None: channel, client = _runtime(tmp_path) - channel.config.allow_from = [] await channel._process_webhook( # pyright: ignore[reportPrivateUsage] "delivery-2", _agent_webhook(action="prompted", signal="stop"), diff --git a/nanobot/channels/linear/tests/test_member_access.py b/nanobot/channels/linear/tests/test_member_access.py new file mode 100644 index 000000000..e8df60951 --- /dev/null +++ b/nanobot/channels/linear/tests/test_member_access.py @@ -0,0 +1,217 @@ +from __future__ import annotations + +import json +from dataclasses import replace +from pathlib import Path +from typing import Any +from unittest.mock import AsyncMock + +import httpx +import pytest + +from nanobot.channels.linear import connect as linear_connect +from nanobot.channels.linear.access import member_allowed +from nanobot.channels.linear.client import LinearApiError, LinearClient +from nanobot.channels.linear.runtime import LinearPayloadError +from nanobot.channels.linear.state import LinearStateStore +from nanobot.channels.linear.tests.test_linear import ( + _agent_webhook, + _config, + _installation, + _runtime, +) +from nanobot.pairing.store import approve_code, generate_code + + +@pytest.mark.parametrize("legacy", ["pairing", "allowlist", "wildcard", "none"]) +def test_member_choice_overrides_legacy_and_survives_restart(tmp_path: Path, legacy: str) -> None: + config = _config() + config.allow_from = ["*"] if legacy == "wildcard" else ["user-1"] if legacy == "allowlist" else [] + if legacy == "pairing": + approve_code(generate_code("linear", "user-1")) + state = LinearStateStore(tmp_path / "state.sqlite3") + state.save_installation(_installation()) + assert member_allowed(config, state, "org-1", "user-1") is (legacy != "none") + state.set_member_access(config.client_id, "org-1", "user-1", allowed=False) + # A new legacy approval must not resurrect an explicit off switch. + approve_code(generate_code("linear", "user-1")) + reopened = LinearStateStore(state.path) + assert not member_allowed(config, reopened, "org-1", "user-1") + reopened.set_member_access(config.client_id, "org-1", "user-1", allowed=True) + assert member_allowed(config, state, "org-1", "user-1") + + +def test_access_is_scoped_to_app_and_workspace(tmp_path: Path) -> None: + state = LinearStateStore(tmp_path / "state.sqlite3") + state.save_installation(_installation()) + state.save_installation(replace(_installation(), organization_id="org-2")) + config = _config() + config.allow_from = [] + state.set_member_access(config.client_id, "org-1", "user-1", allowed=True) + assert not member_allowed(config, state, "org-2", "user-1") + with pytest.raises(ValueError, match="not connected"): + state.set_member_access("other-client", "org-1", "user-1", allowed=True) + state.save_installation(replace(_installation(), oauth_client_id="other-client")) + assert not member_allowed(config, state, "org-1", "user-1") + state.delete_installation("org-1") + assert not member_allowed(config, state, "org-1", "user-1") + + +def connection(nodes: list[dict[str, Any]], cursor: str | None = None) -> dict[str, Any]: + return {"nodes": nodes, "pageInfo": {"hasNextPage": cursor is not None, "endCursor": cursor}} + + +async def test_directory_paginates_teams_and_members_filters_apps_and_deduplicates(tmp_path: Path) -> None: + state = LinearStateStore(tmp_path / "state.sqlite3") + state.save_installation(_installation()) + calls: list[dict[str, Any]] = [] + + def handler(request: httpx.Request) -> httpx.Response: + body = json.loads(request.content) + variables = body["variables"] + calls.append(variables) + assert request.headers["Authorization"] == "Bearer access" + if "NanobotMemberTeams" in body["query"]: + teams = connection([{"id": "t1", "name": "One"}], "team-next") if not variables["after"] else connection([{"id": "t2", "name": "Two"}]) + return httpx.Response(200, json={"data": {"teams": teams}}) + human = {"id": "u1", "name": "Yongru", "active": True, "app": False} + if variables["team"] == "t1" and not variables["after"]: + members = connection([human, {**human, "id": "bot", "app": True}], "member-next") + elif variables["after"]: + members = connection([{**human, "id": "inactive", "active": False}]) + else: + members = connection([human]) + return httpx.Response(200, json={"data": {"team": {"members": members}}}) + + async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http: + client = LinearClient(_config(), state, http) + assert await client.list_members("org-1") == [{"id": "u1", "name": "Yongru", "teams": ["One", "Two"]}] + assert len(calls) == 5 + + +async def test_filtered_lookup_sends_user_filter(tmp_path: Path) -> None: + state = LinearStateStore(tmp_path / "state.sqlite3") + client = LinearClient(_config(), state) + client.graphql = AsyncMock(side_effect=[ + {"teams": connection([{"id": "t1", "name": "Team"}])}, + {"team": {"members": connection([{"id": "u1", "name": "Yongru", "active": True, "app": False}])}}, + ]) + try: + assert len(await client.list_members("org-1", user_id="u1")) == 1 + assert client.graphql.call_args.args[2]["filter"] == {"id": {"eq": "u1"}} + finally: + await client.close() + + +@pytest.mark.parametrize("response", [ + {"teams": {"nodes": []}}, + {"teams": {"nodes": [], "pageInfo": {"hasNextPage": True, "endCursor": None}}}, + {"teams": connection([{"id": "t1"}])}, +]) +async def test_incomplete_directory_fails_closed(tmp_path: Path, response: dict[str, Any]) -> None: + client = LinearClient(_config(), LinearStateStore(tmp_path / "state.sqlite3")) + client.graphql = AsyncMock(return_value=response) + try: + with pytest.raises(LinearApiError): + await client.list_members("org-1") + finally: + await client.close() + + +async def test_repeated_cursor_does_not_loop_or_return_partial_roster(tmp_path: Path) -> None: + client = LinearClient(_config(), LinearStateStore(tmp_path / "state.sqlite3")) + client.graphql = AsyncMock(return_value={"teams": connection([], "repeated")}) + try: + with pytest.raises(LinearApiError, match="repeated"): + await client.list_members("org-1") + assert client.graphql.await_count == 2 + finally: + await client.close() + + +async def test_member_management_reads_effective_access_and_saves_without_pairing( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + config = _config() + config.allow_from = [] + state = LinearStateStore(tmp_path / "state.sqlite3") + state.save_installation(_installation()) + fake = AsyncMock() + fake.list_members.return_value = [{"id": "user-1", "name": "Yongru", "teams": ["Team"]}] + monkeypatch.setattr(linear_connect, "_load_linear_config", lambda: config) + monkeypatch.setattr(linear_connect, "LinearStateStore", lambda: state) + monkeypatch.setattr(linear_connect, "LinearClient", lambda *_args: fake) + store = linear_connect.LinearConnectStore() + params = {"operation": ["members"], "organization_id": ["org-1"]} + assert (await store.handle("start", params))["members"][0]["allowed"] is False + for value in ("true", "false"): + result = await store.handle("start", {**params, "operation": ["member_access"], "user_id": ["user-1"], "allowed": [value]}) + assert result["status"] == "member_access_saved" + assert result["members"][0]["allowed"] is (value == "true") + assert not member_allowed(config, state, "org-1", "user-1") + fake.close.assert_awaited() + + +@pytest.mark.parametrize("failure", ["unavailable", "out_of_scope", "invalid_boolean", "other_app"]) +async def test_failed_management_does_not_grant_access( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, failure: str, +) -> None: + state = LinearStateStore(tmp_path / "state.sqlite3") + state.save_installation(replace(_installation(), oauth_client_id="other" if failure == "other_app" else "client-id")) + fake = AsyncMock() + fake.list_members.return_value = [] + if failure == "unavailable": + fake.list_members.side_effect = LinearApiError("Rate limited", retryable=True) + monkeypatch.setattr(linear_connect, "_load_linear_config", _config) + monkeypatch.setattr(linear_connect, "LinearStateStore", lambda: state) + monkeypatch.setattr(linear_connect, "LinearClient", lambda *_args: fake) + with pytest.raises(linear_connect.ChannelConnectError): + await linear_connect.LinearConnectStore().handle("start", { + "operation": ["member_access"], "organization_id": ["org-1"], + "user_id": ["user-1"], "allowed": ["yes" if failure == "invalid_boolean" else "true"], + }) + assert state.member_access("client-id", "org-1", "user-1") is None + + +async def test_enabled_member_can_run_without_pairing_and_disable_blocks_even_stop(tmp_path: Path) -> None: + channel, client = _runtime(tmp_path) + channel.config.allow_from = [] + channel._state.set_member_access("client-id", "org-1", "user-1", allowed=True) + await channel._process_webhook("enabled", _agent_webhook()) + inbound = await channel.bus.consume_inbound() + assert inbound.sender_id == "user-1" + assert inbound.session_key == "linear:org-1:session-1" + channel._state.set_member_access("client-id", "org-1", "user-1", allowed=False) + channel.config.allow_from = ["*"] + approve_code(generate_code("linear", "user-1")) + await channel._process_webhook("disabled", _agent_webhook()) + await channel._process_webhook("disabled-stop", _agent_webhook(action="prompted", signal="stop")) + assert channel.bus.inbound.empty() + assert "Access is disabled" in client.activities[-1]["content"]["body"] + + +@pytest.mark.parametrize("failure", ["departed", "api_error"]) +async def test_admission_rechecks_membership_and_never_uses_stale_approvals(tmp_path: Path, failure: str) -> None: + channel, client = _runtime(tmp_path) + client.list_members = AsyncMock(return_value=[]) + expected = LinearPayloadError + if failure == "api_error": + client.list_members.side_effect = LinearApiError("Unavailable", retryable=True) + expected = LinearApiError + with pytest.raises(expected): + await channel._process_webhook("no-access", _agent_webhook()) + assert channel.bus.inbound.empty() + assert client.downloads == [] + assert client.activities == [] + + +async def test_revocation_during_attachment_download_is_checked_before_publish(tmp_path: Path) -> None: + channel, client = _runtime(tmp_path) + + async def revoke_during_download(*_args: Any, **_kwargs: Any) -> tuple[list[str], list[str]]: + channel._state.set_member_access("client-id", "org-1", "user-1", allowed=False) + return [], [] + + channel._download_prompt_media = revoke_during_download + await channel._process_webhook("race", _agent_webhook()) + assert channel.bus.inbound.empty() diff --git a/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx b/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx index 159346c46..7fdacb15c 100644 --- a/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx +++ b/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx @@ -111,9 +111,9 @@ describe("Linear channel UI", () => { renderSettingsView({ initialSection: "channels" }); fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" })); await screen.findByRole("textbox", { name: "OAuth client ID" }); - expect(screen.queryByText("Pair on first use; connect Linear MCP to search or edit issues.")).not.toBeInTheDocument(); + expect(screen.queryByText(/Use Member access to approve teammates/)).not.toBeInTheDocument(); fireEvent.keyDown(screen.getByRole("button", { name: "Help" }), { key: "ArrowDown" }); - expect(await screen.findByText("Pair on first use; connect Linear MCP to search or edit issues.")).toBeVisible(); + expect(await screen.findByText(/Use Member access to approve teammates/)).toBeVisible(); fireEvent.keyDown(screen.getByRole("menu"), { key: "Escape" }); fireEvent.click(await screen.findByRole("button", { name: "Configure Linear MCP" })); const dialog = await screen.findByRole("dialog", { name: "Linear" }); diff --git a/nanobot/channels/linear/webui/LinearHelpContent.tsx b/nanobot/channels/linear/webui/LinearHelpContent.tsx index 8bfb4b0b4..4e8186fe9 100644 --- a/nanobot/channels/linear/webui/LinearHelpContent.tsx +++ b/nanobot/channels/linear/webui/LinearHelpContent.tsx @@ -1,22 +1,16 @@ import { useTranslation } from "react-i18next"; import { channelTranslator } from "@/channel-plugins/i18n"; -import type { ChannelPluginHelpProps } from "@/channel-plugins/types"; import { DropdownMenuSeparator } from "@/components/ui/dropdown-menu"; -export function LinearHelpContent({ feature }: ChannelPluginHelpProps) { +export function LinearHelpContent() { const { t } = useTranslation(); const tx = channelTranslator(t, "linear"); - const allowFrom = feature.config_values?.["channels.linear.allowFrom"]?.trim() ?? ""; return ( <>
- {allowFrom === "*" - ? tx("custom.accessAll", "Every member of an authorized workspace can run this agent.") - : allowFrom - ? tx("custom.accessRestricted", "Only the Linear user IDs listed in Advanced can run this agent.") - : tx("custom.accessPairing", "Pair on first use; connect Linear MCP to search or edit issues.")} + {tx("members.guide", "Use Member access to approve teammates without pairing codes. Existing approvals still work unless switched off. Connect Linear MCP to search or edit issues.")}
+ {tx("members.help", "Choose who can use nanobot in Linear without a pairing code. This does not grant access to the nanobot admin UI. Turning access off blocks new requests, not tasks already running.")} +
+ {allowAll ?+ {tx("members.allowAll", "Advanced settings currently allow all members (*), including new members. Individual off switches still take precedence. Remove * to require approval for new members.")} +
: null} ++ {error} {tx("members.retry", "Refresh members to check the current state and try again.")} +
: null} + {!busy && !error && visible.length === 0 ?+ {tx("members.empty", "No matching active members in the teams this app can access.")} +
: null} +{member.name}
+{member.teams.join(" · ")}
+ {members.some((other) => other.id !== member.id && other.name === member.name) ? +{member.id}
: null} +