Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(marketplace): read Slack user grants from one token object
rubenluetke10-beep957411209dc7
diff --git a/jarvis/marketplace/auth/oauth_pkce_loopback.py b/jarvis/marketplace/auth/oauth_pkce_loopback.pyindex ab930e73fc..d4cc0e03b4 100644--- a/jarvis/marketplace/auth/oauth_pkce_loopback.py+++ b/jarvis/marketplace/auth/oauth_pkce_loopback.py@@ -120,6 +120,46 @@ def _refresh_expires_at(payload: dict) -> datetime | None:return datetime.now(UTC) + timedelta(seconds=seconds)+@dataclass(frozen=True)+class _GrantFields:+ access: str | None+ refresh: str | None+ expires_at: datetime | None+ scope: str | None+++def _grant_fields(payload: dict) -> _GrantFields:+ """Read one token set from a token-endpoint answer, never mixing sources.++ Slack's user-scope code exchange nests the user token under+ ``authed_user`` (``access_token``, ``refresh_token``, ``expires_in``,+ ``scope``); the top level then belongs to a bot token, if any. A Slack+ refresh of a user token answers at the top level instead, as every other+ provider does. Taking all four fields from the same object keeps a bot's+ refresh token from ever being paired with a user's access token.+ """+ nested = payload.get("authed_user")+ source = nested if isinstance(nested, dict) and nested.get("access_token") else payload+ expires_at: datetime | None = None+ try:+ expires_in = source.get("expires_in")+ if expires_in is not None:+ expires_at = datetime.now(UTC) + timedelta(seconds=int(expires_in))+ except (TypeError, ValueError):+ # An unreadable lifetime is not fatal: the token works until the+ # provider says otherwise, and the tool refreshes on that answer.+ log.debug("token response carried an unreadable expires_in; treating as unknown")+ access = source.get("access_token")+ refresh = source.get("refresh_token")+ scope = source.get("scope")+ return _GrantFields(+ access=str(access) if access else None,+ refresh=str(refresh) if refresh else None,+ expires_at=expires_at,+ scope=str(scope) if scope else None,+ )++@dataclassclass _PendingPkceFlow:config: PkceLoopbackConfig@@ -300,33 +340,28 @@ class PkceLoopbackHandler:detail = sanitize_provider_error(r.text)raise RuntimeError(f"token exchange HTTP {r.status_code}: {detail}")payload = r.json()+ if not isinstance(payload, dict):+ raise RuntimeError("token response was not a JSON object")# Slack wraps success/failure in "ok" plus error codes; many other# providers return error inline. Handle both shapes.if payload.get("ok") is False:err = sanitize_provider_error(str(payload.get("error", "unknown")))raise RuntimeError(f"token exchange failed: {err}")# Slack's response nests the user token under `authed_user`.- access = payload.get("authed_user", {}).get("access_token") or payload.get("access_token")+ grant = _grant_fields(payload)+ access = grant.accessif not access:raise RuntimeError("token response missing access_token")- refresh = payload.get("authed_user", {}).get("refresh_token") or payload.get(- "refresh_token"- )- expires_in = payload.get("authed_user", {}).get("expires_in") or payload.get("expires_in")- expires_at = (- datetime.now(UTC) + timedelta(seconds=int(expires_in))- if expires_in is not None- else None- )+ refresh = grant.refresh+ expires_at = grant.expires_atextra: dict[str, str] = {}team = payload.get("team", {})if isinstance(team, dict) and team.get("id"):extra["team_id"] = team["id"]if isinstance(team, dict) and team.get("name"):extra["team_name"] = team["name"]- scope = payload.get("authed_user", {}).get("scope") or payload.get("scope")- if scope:- extra["scope"] = scope+ if grant.scope:+ extra["scope"] = grant.scopegrant_ends = _refresh_expires_at(payload)if grant_ends is not None:extra["refresh_expires_at"] = grant_ends.isoformat()@@ -393,26 +428,34 @@ class PkceLoopbackHandler:detail = sanitize_provider_error(r.text)raise RuntimeError(f"refresh HTTP {r.status_code}: {detail}")payload = r.json()+ if not isinstance(payload, dict):+ raise RuntimeError("refresh response was not a JSON object")if payload.get("ok") is False:err = payload.get("error", "unknown")- if err in ("invalid_grant", "token_revoked", "invalid_refresh_token"):+ # Slack answers an expired or rotated-away refresh token (PKCE+ # refresh tokens end after 30 days) with these codes; only a new+ # sign-in heals them.+ if err in (+ "invalid_grant",+ "token_revoked",+ "invalid_refresh_token",+ "token_expired",+ ):raise RuntimeError("revoked")raise RuntimeError(f"refresh failed: {sanitize_provider_error(str(err))}")- access = payload.get("authed_user", {}).get("access_token") or payload.get("access_token")+ # A Slack user-token refresh answers at the top level; the code+ # exchange nested it under `authed_user`. `_grant_fields` reads either.+ grant = _grant_fields(payload)+ access = grant.accessif not access:raise RuntimeError("refresh missing access_token")- new_refresh = (- payload.get("authed_user", {}).get("refresh_token")- or payload.get("refresh_token")- or current.refresh- )- expires_in = payload.get("authed_user", {}).get("expires_in") or payload.get("expires_in")- expires_at = (- datetime.now(UTC) + timedelta(seconds=int(expires_in))- if expires_in is not None- else None- )+ # Rotation hands out a new refresh token on every refresh; keep the old+ # one only when the provider does not rotate.+ new_refresh = grant.refresh or current.refresh+ expires_at = grant.expires_atextra = dict(current.extra)+ if grant.scope:+ extra["scope"] = grant.scopeextra["token_endpoint_auth_method"] = auth_methodgrant_ends = _refresh_expires_at(payload)if grant_ends is not None:diff --git a/tests/unit/marketplace/test_pkce_slack_user_grant.py b/tests/unit/marketplace/test_pkce_slack_user_grant.pynew file mode 100644index 0000000000..9a2ef737e8--- /dev/null+++ b/tests/unit/marketplace/test_pkce_slack_user_grant.py@@ -0,0 +1,189 @@+"""Slack PKCE user grants: nested exchange answer, top-level refresh answer.++A Slack PKCE app is a public client: neither the code exchange nor the refresh+may carry a client_secret when none is configured. The exchange nests the user+token under ``authed_user``; a user-token refresh answers at the top level.+"""++from __future__ import annotations++from datetime import UTC, datetime, timedelta++import httpx+import pytest++from jarvis.marketplace.auth.oauth_pkce_loopback import (+ PkceLoopbackConfig,+ PkceLoopbackHandler,+ _PendingPkceFlow,+)+from jarvis.marketplace.token_store import Tokens++_ACCESS = "xoxe.xoxp-1-user-access"+_ROTATED = "xoxe-1-rotated"+_FIRST = "xoxe-1-first"+++def _config() -> PkceLoopbackConfig:+ return PkceLoopbackConfig(+ plugin_id="slack",+ authorization_url="https://slack.com/oauth/v2/authorize",+ token_url="https://slack.com/api/oauth.v2.access", # noqa: S106+ client_id="111.222",+ callback_port=0,+ scopes=["search:read", "chat:write"],+ scope_param_name="user_scope",+ )+++def _capture(monkeypatch: pytest.MonkeyPatch, payload: dict) -> dict:+ captured: dict = {}++ async def _fake_post(self, url, *args, **kwargs): # noqa: ANN001, ANN002, ANN003+ captured["url"] = url+ captured["data"] = kwargs["data"]+ captured["headers"] = kwargs.get("headers", {})+ return httpx.Response(200, json=payload)++ monkeypatch.setattr(httpx.AsyncClient, "post", _fake_post)+ return captured+++async def test_exchange_reads_nested_user_token_without_secret(monkeypatch):+ captured = _capture(+ monkeypatch,+ {+ "ok": True,+ "app_id": "A1",+ "authed_user": {+ "id": "U1",+ "scope": "search:read,chat:write",+ "access_token": _ACCESS,+ "token_type": "user",+ "refresh_token": _FIRST,+ "expires_in": 43200,+ },+ "team": {"id": "T1", "name": "Team"},+ "enterprise": None,+ "is_enterprise_install": False,+ },+ )+ cfg = _config()+ pending = _PendingPkceFlow(+ config=cfg,+ callback_server=None,+ code_verifier="verifier",+ redirect_uri="http://127.0.0.1:3118/oauth/callback",+ )++ before = datetime.now(UTC)+ tokens = await PkceLoopbackHandler(cfg)._exchange(pending, code="code") # noqa: SLF001++ assert "client_secret" not in captured["data"]+ assert "Authorization" not in captured["headers"]+ assert captured["data"]["code_verifier"] == "verifier"+ assert tokens.access == _ACCESS+ assert tokens.refresh == _FIRST+ assert tokens.expires_at is not None+ assert before + timedelta(hours=11) < tokens.expires_at < before + timedelta(hours=13)+ assert tokens.extra["scope"] == "search:read,chat:write"+ assert tokens.extra["team_id"] == "T1"+ assert tokens.extra["token_endpoint_auth_method"] == "none" # noqa: S105 — a method name+ assert "client_secret" not in tokens.extra+++async def test_exchange_never_pairs_a_bot_refresh_with_the_user_token(monkeypatch):+ _capture(+ monkeypatch,+ {+ "ok": True,+ "access_token": "xoxb-bot",+ "refresh_token": "xoxe-1-bot-refresh",+ "expires_in": 999,+ "authed_user": {"id": "U1", "access_token": _ACCESS},+ },+ )+ cfg = _config()+ pending = _PendingPkceFlow(+ config=cfg, callback_server=None, code_verifier="v", redirect_uri="http://x"+ )+ tokens = await PkceLoopbackHandler(cfg)._exchange(pending, code="code") # noqa: SLF001+ assert tokens.access == _ACCESS+ assert tokens.refresh is None+ assert tokens.expires_at is None+++async def test_exchange_tolerates_null_authed_user(monkeypatch):+ _capture(+ monkeypatch,+ {"ok": True, "authed_user": None, "access_token": _ACCESS, "expires_in": "60"},+ )+ cfg = _config()+ pending = _PendingPkceFlow(+ config=cfg, callback_server=None, code_verifier="v", redirect_uri="http://x"+ )+ tokens = await PkceLoopbackHandler(cfg)._exchange(pending, code="code") # noqa: SLF001+ assert tokens.access == _ACCESS+ assert tokens.expires_at is not None+++async def test_refresh_reads_top_level_user_token_and_rotates(monkeypatch):+ captured = _capture(+ monkeypatch,+ {+ "ok": True,+ "access_token": "xoxe.xoxp-1-renewed",+ "expires_in": 43200,+ "refresh_token": _ROTATED,+ "token_type": "user",+ "scope": "search:read,chat:write",+ },+ )+ current = Tokens(+ access=_ACCESS,+ refresh=_FIRST,+ extra={"client_id": "111.222", "token_endpoint_auth_method": "none"},+ )+ tokens = await PkceLoopbackHandler(_config()).refresh(current)++ assert captured["data"] == {+ "grant_type": "refresh_token",+ "refresh_token": _FIRST,+ "client_id": "111.222",+ }+ assert tokens.access == "xoxe.xoxp-1-renewed"+ assert tokens.refresh == _ROTATED+ assert tokens.expires_at is not None+ assert "client_secret" not in tokens.extra+++async def test_refresh_also_accepts_nested_user_token(monkeypatch):+ _capture(+ monkeypatch,+ {+ "ok": True,+ "authed_user": {+ "access_token": "xoxe.xoxp-1-nested",+ "refresh_token": _ROTATED,+ "expires_in": 43200,+ },+ },+ )+ current = Tokens(access=_ACCESS, refresh=_FIRST, extra={"client_id": "111.222"})+ tokens = await PkceLoopbackHandler(_config()).refresh(current)+ assert tokens.access == "xoxe.xoxp-1-nested"+ assert tokens.refresh == _ROTATED++[email protected]("code", ["invalid_refresh_token", "token_expired", "token_revoked"])+async def test_dead_slack_refresh_token_reports_revoked(monkeypatch, code):+ _capture(monkeypatch, {"ok": False, "error": code})+ current = Tokens(access=_ACCESS, refresh=_FIRST, extra={"client_id": "111.222"})+ with pytest.raises(RuntimeError, match="^revoked$"):+ await PkceLoopbackHandler(_config()).refresh(current)