Skip to content

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.

feat(marketplace): route shipped Google and Slack clients through the token broker

rubenluetke10-beepd4a85cf030e4
diff --git a/jarvis/marketplace/auth/oauth_pkce_loopback.py b/jarvis/marketplace/auth/oauth_pkce_loopback.py
index d4cc0e03b4..980442117c 100644
--- a/jarvis/marketplace/auth/oauth_pkce_loopback.py
+++ b/jarvis/marketplace/auth/oauth_pkce_loopback.py
@@ -75,6 +75,12 @@ class PkceLoopbackConfig:
# authorize request carries `access_type=offline` + `prompt=consent`.
offline_access: bool = False
client_auth_method: Literal["client_secret_post", "client_secret_basic"] = "client_secret_post"
+ # Family key of a ``publisher_clients.SHIPPED_TOKEN_BROKERS`` entry. Set
+ # only for the shipped public client of a provider that demands a client
+ # secret: the code exchange then goes to that broker (and, when the broker
+ # has one, the browser redirect to its https callback) instead of
+ # ``token_url``, with no secret. ``None`` means the provider directly.
+ token_broker: str | None = None
def token_auth_method(self, secret: str | None) -> str:
"""Honor X's endpoint contract, including legacy installed catalogs."""
@@ -99,6 +105,24 @@ def _basic_token_header(client_id: str, secret: str | None, method: str) -> dict
return {"Authorization": "Basic " + base64.b64encode(credentials).decode("ascii")}
+def _broker(family: str | None):
+ """Resolve a token-broker family, failing loudly when it vanished.
+
+ A grant issued through a broker can only be exchanged or refreshed there:
+ the provider refuses it without the secret the app does not hold.
+ """
+ if not family:
+ return None
+ from jarvis.marketplace.publisher_clients import token_broker
+
+ broker = token_broker(family)
+ if broker is None:
+ raise RuntimeError(
+ f"the {family} token broker is no longer available; reconnect the plugin"
+ )
+ return broker
+
+
def _refresh_expires_at(payload: dict) -> datetime | None:
"""When the provider caps the refresh grant itself, return when it ends.
@@ -213,7 +237,7 @@ class PkceLoopbackHandler:
"in use, or the hosted callback base URL is unreachable)"
) from exc
- redirect_uri = callback_server.redirect_uri
+ redirect_uri = self._redirect_uri(callback_server.redirect_uri)
verifier, challenge = pkce_pair()
sid = session_id()
@@ -235,6 +259,18 @@ class PkceLoopbackHandler:
expires_at_ms=int((datetime.now(UTC) + timedelta(minutes=5)).timestamp() * 1000),
)
+ def _redirect_uri(self, listener_uri: str) -> str:
+ """The redirect_uri sent to the provider.
+
+ Normally the local listener's own address. A token broker with an
+ https callback (Slack) replaces it: the provider redirects the browser
+ there, and the broker bounces the request on to the same listener.
+ """
+ broker = _broker(self._config.token_broker)
+ if broker is not None and broker.redirect_uri:
+ return broker.redirect_uri
+ return listener_uri
+
def _authorize_params(self, *, redirect_uri: str, state: str, challenge: str) -> dict[str, str]:
"""Build the authorize query params. Extracted so the optional
`resource` / `offline_access` extensions are unit-testable without
@@ -312,28 +348,31 @@ class PkceLoopbackHandler:
"grant_type": "authorization_code",
"redirect_uri": pending.redirect_uri,
}
- if (
- pending.config.client_secret
- and pending.config.token_auth_method(pending.config.client_secret)
- == "client_secret_post"
- ):
- body["client_secret"] = pending.config.client_secret
- if pending.config.resource:
- body["resource"] = pending.config.resource
+ broker = _broker(pending.config.token_broker)
+ if broker is not None:
+ # The broker adds the shipped client's secret itself and refuses
+ # any field beyond the grant, so no secret and no extras go out.
+ token_url = broker.token_url
+ client_secret = None
+ auth_method = "none"
+ else:
+ token_url = pending.config.token_url
+ client_secret = pending.config.client_secret
+ auth_method = pending.config.token_auth_method(client_secret)
+ if client_secret and auth_method == "client_secret_post":
+ body["client_secret"] = client_secret
+ if pending.config.resource:
+ body["resource"] = pending.config.resource
timeout = httpx.Timeout(pending.config.timeout_seconds)
async with httpx.AsyncClient(timeout=timeout) as client:
r = await client.post(
- pending.config.token_url,
+ token_url,
data=body,
headers={
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
"User-Agent": "Personal-Jarvis/1.0",
- **_basic_token_header(
- pending.config.client_id,
- pending.config.client_secret,
- pending.config.token_auth_method(pending.config.client_secret),
- ),
+ **_basic_token_header(pending.config.client_id, client_secret, auth_method),
},
)
if r.status_code != 200:
@@ -379,11 +418,12 @@ class PkceLoopbackHandler:
# remain bound to their issuing client. Keeping the pair inside the same
# protected token blob makes refresh independent of that drift.
extra["client_id"] = pending.config.client_id
- extra["token_endpoint_auth_method"] = pending.config.token_auth_method(
- pending.config.client_secret
- )
- if pending.config.client_secret:
- extra["client_secret"] = pending.config.client_secret
+ extra["token_endpoint_auth_method"] = auth_method
+ if client_secret:
+ extra["client_secret"] = client_secret
+ if broker is not None:
+ # A brokered grant can only ever be refreshed through the broker.
+ extra["token_broker"] = pending.config.token_broker
return Tokens(access=access, refresh=refresh, expires_at=expires_at, extra=extra)
async def refresh(self, current: Tokens) -> Tokens:
@@ -398,25 +438,43 @@ class PkceLoopbackHandler:
if bound_client_id:
client_id = bound_client_id
client_secret = current.extra.get("client_secret")
+ # The grant's own broker marker decides, never today's config: an
+ # expert override added later must not reroute a brokered grant,
+ # and a brokered client must not reroute an expert's grant. A
+ # secret-less grant of a shipped broker client without the marker
+ # can likewise only be refreshed through that broker.
+ broker_family = current.extra.get("token_broker")
+ if not broker_family and not client_secret:
+ from jarvis.marketplace.publisher_clients import broker_family_for_client
+
+ broker_family = broker_family_for_client(client_id)
else:
client_id = self._config.client_id
client_secret = self._config.client_secret
+ broker_family = self._config.token_broker
+ broker = _broker(broker_family)
refresh_body = {
"grant_type": "refresh_token",
"refresh_token": current.refresh,
"client_id": client_id,
}
- auth_method = current.extra.get(
- "token_endpoint_auth_method"
- ) or self._config.token_auth_method(client_secret)
- if client_secret and auth_method == "client_secret_post":
- refresh_body["client_secret"] = client_secret
- if self._config.resource:
- refresh_body["resource"] = self._config.resource
+ if broker is not None:
+ token_url = broker.token_url
+ client_secret = None
+ auth_method = "none"
+ else:
+ token_url = self._config.token_url
+ auth_method = current.extra.get(
+ "token_endpoint_auth_method"
+ ) or self._config.token_auth_method(client_secret)
+ if client_secret and auth_method == "client_secret_post":
+ refresh_body["client_secret"] = client_secret
+ if self._config.resource:
+ refresh_body["resource"] = self._config.resource
timeout = httpx.Timeout(self._config.timeout_seconds)
async with httpx.AsyncClient(timeout=timeout) as client:
r = await client.post(
- self._config.token_url,
+ token_url,
data=refresh_body,
headers={
"Accept": "application/json",
@@ -470,6 +528,8 @@ class PkceLoopbackHandler:
extra["client_secret"] = client_secret
else:
extra.pop("client_secret", None)
+ if broker is not None:
+ extra["token_broker"] = broker_family
return Tokens(
access=access,
refresh=new_refresh,
diff --git a/jarvis/marketplace/connect_helpers.py b/jarvis/marketplace/connect_helpers.py
index beffebc9a1..69384ceb51 100644
--- a/jarvis/marketplace/connect_helpers.py
+++ b/jarvis/marketplace/connect_helpers.py
@@ -12,7 +12,8 @@ import logging
from typing import TYPE_CHECKING
if TYPE_CHECKING:
- from jarvis.marketplace.auth import AuthHandler
+ from jarvis.marketplace.auth import AuthHandler, PkceLoopbackConfig
+ from jarvis.marketplace.catalog import OAuthPkceLoopbackAuth
from jarvis.marketplace.token_store import TokenStore
log = logging.getLogger(__name__)
@@ -109,6 +110,43 @@ def resolve_pkce_client(
return client_id, client_secret
+def build_pkce_config(plugin_id: str, auth: OAuthPkceLoopbackAuth) -> PkceLoopbackConfig:
+ """The one PKCE handler config used by connect AND refresh.
+
+ Resolves the effective client and, for a shipped client whose provider
+ demands a secret, its token broker — so a connect and the refresh
+ scheduler can never disagree about where tokens are exchanged.
+ """
+ from jarvis.marketplace.auth import PkceLoopbackConfig
+ from jarvis.marketplace.publisher_clients import broker_family_for_client
+
+ client_id, client_secret = resolve_pkce_client(plugin_id, auth.client_id, auth.client_secret)
+ # Only the shipped client WITHOUT a secret goes through a broker — exactly
+ # the pair ``resolve_client`` yields at its shipped-client step. A client
+ # that carries its own secret (expert override, publisher secret) always
+ # talks to the provider directly.
+ broker = None if client_secret else broker_family_for_client(client_id)
+ return PkceLoopbackConfig(
+ plugin_id=plugin_id,
+ authorization_url=auth.authorization_url,
+ token_url=auth.token_url,
+ client_id=client_id,
+ client_secret=client_secret,
+ callback_port=auth.callback_port or 0,
+ scopes=list(auth.scopes),
+ scope_separator=auth.scope_separator,
+ # Slack-specific: PKCE-enabled apps must use user_scope= per
+ # docs.slack.dev/authentication/using-pkce. When the catalog marks a
+ # plugin user-scopes-only, route the param.
+ scope_param_name="user_scope" if auth.user_scopes_only else "scope",
+ callback_path=auth.callback_path,
+ resource=auth.resource,
+ offline_access=auth.offline_access,
+ client_auth_method=auth.client_auth_method,
+ token_broker=broker,
+ )
+
+
def build_handler_from_catalog(plugin_id: str) -> AuthHandler | None:
"""Return the AuthHandler for a catalog plugin, or ``None`` if the plugin
is unknown or uses a non-refreshable auth mode (e.g. ``pat_paste``)."""
@@ -117,7 +155,6 @@ def build_handler_from_catalog(plugin_id: str) -> AuthHandler | None:
DeviceFlowConfig,
DeviceFlowHandler,
HostedMcpDcrHandler,
- PkceLoopbackConfig,
PkceLoopbackHandler,
)
from jarvis.marketplace.catalog import (
@@ -151,26 +188,7 @@ def build_handler_from_catalog(plugin_id: str) -> AuthHandler | None:
)
)
if isinstance(auth, OAuthPkceLoopbackAuth):
- client_id, client_secret = resolve_pkce_client(
- plugin_id, auth.client_id, auth.client_secret
- )
- return PkceLoopbackHandler(
- PkceLoopbackConfig(
- plugin_id=plugin_id,
- authorization_url=auth.authorization_url,
- token_url=auth.token_url,
- client_id=client_id,
- client_secret=client_secret,
- callback_port=auth.callback_port or 0,
- scopes=list(auth.scopes),
- scope_separator=auth.scope_separator,
- scope_param_name="user_scope" if auth.user_scopes_only else "scope",
- callback_path=auth.callback_path,
- resource=auth.resource,
- offline_access=auth.offline_access,
- client_auth_method=auth.client_auth_method,
- )
- )
+ return PkceLoopbackHandler(build_pkce_config(plugin_id, auth))
return None # pat_paste / allowlist — no refreshable OAuth handler
diff --git a/jarvis/marketplace/publisher_clients.py b/jarvis/marketplace/publisher_clients.py
index 4b80b6fa91..f04473bcd0 100644
--- a/jarvis/marketplace/publisher_clients.py
+++ b/jarvis/marketplace/publisher_clients.py
@@ -19,6 +19,9 @@ Precedence for one ``<family>`` (e.g. ``microsoft``):
shared client without a code change.
3. Shipped public client: ``SHIPPED_PUBLIC_CLIENT_IDS``. A public client id
built into the app, used by every install with zero setup. Not a secret.
+ When the family also has a ``SHIPPED_TOKEN_BROKERS`` entry, the provider
+ insists on a client secret the app cannot carry, so the code exchange and
+ every refresh go to that broker, which adds the secret server-side.
4. Catalog value: the ``client_id`` shipped in ``seed_catalog.json`` (or a
user's ``data/`` override). Only used when it is a real client id, never
a ``REPLACE_WITH_*`` placeholder.
@@ -38,6 +41,7 @@ instead of inventing a client id. A family listed in
from __future__ import annotations
import logging
+from dataclasses import dataclass
from typing import Literal
log = logging.getLogger(__name__)
@@ -59,12 +63,81 @@ ClientSource = Literal["publisher", "own", "catalog", "missing"]
# GitHub is the "Personal Jarvis" OAuth App owned by the PersonalJarvis
# organisation: Device Flow enabled, non-expiring user tokens, no client secret
# (the device flow never sends one).
+# Google is the "Personal Jarvis" Desktop client: loopback PKCE on the plugins'
+# fixed 127.0.0.1 ports. Its token endpoint still refuses a code exchange or
+# refresh without the client secret, so the family uses a token broker below.
+# Slack is the publicly distributed "Personal Jarvis" Slack app. Slack only
+# allows https redirect URLs for it, and web-redirect tokens need the secret,
+# so the family uses a token broker with an https redirect below.
SHIPPED_PUBLIC_CLIENT_IDS: dict[str, str] = {
"github": "Ov23liaA2KfHbfVOelcx",
+ "google": "940985062784-4t8h10q3ggt6b1317ajjb9u0eriop2m7.apps.googleusercontent.com",
"microsoft": "1986efcb-f871-4ffa-8df7-64c04dd3ab56",
+ "slack": "11871821947191.12101850377302",
}
+@dataclass(frozen=True)
+class TokenBroker:
+ """A project-run token endpoint that adds a shipped client's secret.
+
+ ``token_url`` replaces the provider's token endpoint for the code exchange
+ and every refresh. ``redirect_uri``, when set, is the https address the
+ provider redirects the browser to instead of the app's loopback listener;
+ the broker bounces that request on to the loopback listener, which still
+ listens on the catalog's port and path. The code exchange then sends the
+ same ``redirect_uri``, as OAuth requires.
+ """
+
+ token_url: str
+ redirect_uri: str | None = None
+
+
+_BROKER_BASE = "https://token.personaljarvis.ai/oauth"
+
+# Token brokers for shipped clients whose provider requires a client secret.
+# The broker is a small project-run Cloudflare Worker (source: the website
+# repository, ``workers/token-broker``) that accepts only the
+# authorization_code grant (PKCE verifier required, redirect_uri restricted to
+# loopback or to the broker's own callback) and the refresh_token grant, adds
+# the shipped client's id and secret, and returns the provider's answer
+# unchanged. It stores and logs nothing. The app sends no client secret there
+# and never holds one, so every install type — desktop bundle, pip, CLI —
+# works with zero setup.
+# A broker is used ONLY for grants issued to the shipped client: an expert
+# override or a ``publisher_<family>_oauth_*`` secret talks to the provider's
+# token endpoint directly with its own secret. Revocation never needs a secret
+# and always goes straight to the provider.
+SHIPPED_TOKEN_BROKERS: dict[str, TokenBroker] = {
+ "google": TokenBroker(token_url=f"{_BROKER_BASE}/google/token"),
+ "slack": TokenBroker(
+ token_url=f"{_BROKER_BASE}/slack/token",
+ redirect_uri=f"{_BROKER_BASE}/slack/callback",
+ ),
+}
+
+
+def token_broker(family: str | None) -> TokenBroker | None:
+ """The shipped-client token broker of ``family``, if it has one."""
+ if not family:
+ return None
+ return SHIPPED_TOKEN_BROKERS.get(family)
+
+
+def broker_family_for_client(client_id: str | None) -> str | None:
+ """The broker family whose shipped client is ``client_id``, else ``None``.
+
+ Lets a refresh find the broker for a grant stored without the broker
+ marker: a grant bound to the shipped client can only be refreshed there.
+ """
+ if not client_id:
+ return None
+ for family, shipped in SHIPPED_PUBLIC_CLIENT_IDS.items():
+ if shipped == client_id and family in SHIPPED_TOKEN_BROKERS:
+ return family
+ return None
+
+
def publisher_secret_names(family: str) -> tuple[str, str]:
"""Secret-store key + env fallback for a family's publisher client id."""
return f"publisher_{family}_oauth_client_id", f"PUBLISHER_{family.upper()}_OAUTH_CLIENT_ID"
@@ -78,18 +151,33 @@ def publisher_secret_names_secret(family: str) -> tuple[str, str]:
)
-def resolve_publisher_client(
+@dataclass(frozen=True)
+class ResolvedClient:
+ """The effective OAuth client for one plugin and where its tokens go.
+
+ ``token_broker`` names the ``SHIPPED_TOKEN_BROKERS`` family whose broker
+ performs the code exchange and refresh, or is ``None`` for the provider's
+ own token endpoint. It is set only for the shipped public client.
+ """
+
+ client_id: str
+ client_secret: str | None
+ source: ClientSource
+ token_broker: str | None = None
+
+
+def resolve_client(
plugin_id: str,
catalog_client_id: str,
catalog_client_secret: str | None,
-) -> tuple[str, str | None, ClientSource]:
- """Resolve the effective ``(client_id, client_secret, source)``.
+) -> ResolvedClient:
+ """Resolve the effective client, its source, and its token broker.
Precedence: expert BYO secret > publisher secret > shipped public client
- > catalog value. An unset/empty secret never displaces a better value.
- A placeholder catalog id with nothing provisioned resolves to
- ``("...", None, "missing")`` with the catalog placeholder preserved so
- callers can keep reporting the honest 409.
+ (plus its broker, when the family has one) > catalog value. An unset/empty
+ secret never displaces a better value. A placeholder catalog id with
+ nothing provisioned resolves to source ``missing`` with the catalog
+ placeholder preserved so callers can keep reporting the honest 409.
"""
from jarvis.marketplace.connect_helpers import (
is_placeholder_client_id,
@@ -101,38 +189,56 @@ def resolve_publisher_client(
# No family mapping: the catalog client is authoritative (DCR plugins
# never reach here; static non-family clients stay untouched).
if is_placeholder_client_id(catalog_client_id):
- return catalog_client_id, catalog_client_secret, "missing"
- return catalog_client_id, catalog_client_secret, "catalog"
+ return ResolvedClient(catalog_client_id, catalog_client_secret, "missing")
+ return ResolvedClient(catalog_client_id, catalog_client_secret, "catalog")
from jarvis.core.config import get_secret
# 1. Expert override (bring-your-own-client). Kept first so an explicit
- # user choice always wins over anything provisioned.
+ # user choice always wins over anything provisioned. Talks to the
+ # provider directly with the expert's own secret.
own_id = get_secret(f"{family}_oauth_client_id", f"{family.upper()}_OAUTH_CLIENT_ID")
own_secret = get_secret(
f"{family}_oauth_client_secret", f"{family.upper()}_OAUTH_CLIENT_SECRET"
)
if own_id and not is_placeholder_client_id(own_id):
- return own_id, own_secret or catalog_client_secret, "own"
+ return ResolvedClient(own_id, own_secret or catalog_client_secret, "own")
- # 2. Publisher-provisioned shared client (the standard path).
+ # 2. Publisher-provisioned shared client from the secret store. The
+ # distribution holds this secret itself, so no broker is involved.
pub_id_key, pub_id_env = publisher_secret_names(family)
pub_sec_key, pub_sec_env = publisher_secret_names_secret(family)
pub_id = get_secret(pub_id_key, pub_id_env)
if pub_id and not is_placeholder_client_id(pub_id):
pub_secret = get_secret(pub_sec_key, pub_sec_env)
- return pub_id, pub_secret or catalog_client_secret, "publisher"
+ return ResolvedClient(pub_id, pub_secret or catalog_client_secret, "publisher")
- # 3. Public client id built into the app. No secret is paired with it.
+ # 3. Public client id built into the app. No secret is paired with it; a
+ # family whose provider demands one exchanges tokens through its broker.
shipped = SHIPPED_PUBLIC_CLIENT_IDS.get(family, "")
if shipped and not is_placeholder_client_id(shipped):
- return shipped, None, "publisher"
+ broker = family if family in SHIPPED_TOKEN_BROKERS else None
+ return ResolvedClient(shipped, None, "publisher", broker)
# 4. Catalog value, if real.
if not is_placeholder_client_id(catalog_client_id):
- return catalog_client_id, catalog_client_secret, "catalog"
+ return ResolvedClient(catalog_client_id, catalog_client_secret, "catalog")
- return catalog_client_id, catalog_client_secret, "missing"
+ return ResolvedClient(catalog_client_id, catalog_client_secret, "missing")
+
+
+def resolve_publisher_client(
+ plugin_id: str,
+ catalog_client_id: str,
+ catalog_client_secret: str | None,
+) -> tuple[str, str | None, ClientSource]:
+ """Resolve the effective ``(client_id, client_secret, source)``.
+
+ Tuple form of :func:`resolve_client` for callers that never need the
+ token broker (status payloads, device flow).
+ """
+ resolved = resolve_client(plugin_id, catalog_client_id, catalog_client_secret)
+ return resolved.client_id, resolved.client_secret, resolved.source
def is_standard_ready(
@@ -146,10 +252,16 @@ def is_standard_ready(
__all__ = [
- "ClientSource",
"SHIPPED_PUBLIC_CLIENT_IDS",
+ "SHIPPED_TOKEN_BROKERS",
+ "ClientSource",
+ "ResolvedClient",
+ "TokenBroker",
+ "broker_family_for_client",
"is_standard_ready",
"publisher_secret_names",
"publisher_secret_names_secret",
+ "resolve_client",
"resolve_publisher_client",
+ "token_broker",
]
diff --git a/jarvis/ui/web/marketplace_routes.py b/jarvis/ui/web/marketplace_routes.py
index 3d4b421312..04793f748e 100644
--- a/jarvis/ui/web/marketplace_routes.py
+++ b/jarvis/ui/web/marketplace_routes.py
@@ -52,7 +52,6 @@ from jarvis.marketplace.auth import (
DeviceFlowHandler,
FlowResult,
HostedMcpDcrHandler,
- PkceLoopbackConfig,
PkceLoopbackHandler,
get_registry,
sanitize_provider_error,
@@ -741,15 +740,15 @@ async def connect_start(
# Resolve the effective client from secrets so a reconnect uses the
# operator's real Google client, not the catalog placeholder (the same
# resolution the refresh scheduler uses — connect/refresh stay in sync).
+ # The shared builder also routes a shipped client's token exchange
+ # through its broker when the provider demands a secret.
from jarvis.marketplace.connect_helpers import (
+ build_pkce_config,
is_placeholder_client_id,
- resolve_pkce_client,
)
- _pkce_client_id, _pkce_client_secret = resolve_pkce_client(
- plugin_id, spec.auth.client_id, spec.auth.client_secret
- )
- if is_placeholder_client_id(_pkce_client_id):
+ pkce_config = build_pkce_config(plugin_id, spec.auth)
+ if is_placeholder_client_id(pkce_config.client_id):
detail = (
f"oauth client not configured for plugin {plugin_id!r}: no "
"publisher-provisioned shared client is installed yet and "
@@ -765,26 +764,7 @@ async def connect_start(
"via the dialog's token fallback."
)
raise HTTPException(status_code=409, detail=detail)
- handler = PkceLoopbackHandler(
- PkceLoopbackConfig(
- plugin_id=plugin_id,
- authorization_url=spec.auth.authorization_url,
- token_url=spec.auth.token_url,
- client_id=_pkce_client_id,
- client_secret=_pkce_client_secret,
- callback_port=spec.auth.callback_port or 0,
- scopes=list(spec.auth.scopes),
- scope_separator=spec.auth.scope_separator,
- # Slack-specific: PKCE-enabled apps must use user_scope= per
- # docs.slack.dev/authentication/using-pkce. When the catalog
- # marks a plugin user-scopes-only, route the param.
- scope_param_name=("user_scope" if spec.auth.user_scopes_only else "scope"),
- callback_path=spec.auth.callback_path,
- resource=spec.auth.resource,
- offline_access=spec.auth.offline_access,
- client_auth_method=spec.auth.client_auth_method,
- )
- )
+ handler = PkceLoopbackHandler(pkce_config)
else:
raise HTTPException(
status_code=400,
diff --git a/tests/unit/marketplace/test_connect_helpers.py b/tests/unit/marketplace/test_connect_helpers.py
index 56977ae72e..fe13f15d9f 100644
--- a/tests/unit/marketplace/test_connect_helpers.py
+++ b/tests/unit/marketplace/test_connect_helpers.py
@@ -16,6 +16,7 @@ from jarvis.marketplace.connect_helpers import (
is_placeholder_client_id,
resolve_pkce_client,
)
+from jarvis.marketplace.publisher_clients import SHIPPED_PUBLIC_CLIENT_IDS
from jarvis.marketplace.token_store import InMemoryBackend, Tokens, TokenStore
@@ -134,14 +135,35 @@ def test_gmail_handler_uses_google_secret_over_catalog_placeholder(
assert handler._config.client_secret == "GOCSPX-realsecret"
-def test_gmail_handler_falls_back_to_catalog_when_no_secret(
+def test_gmail_handler_uses_shipped_client_and_broker_when_no_secret(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- # No secret configured -> catalog value is used unchanged. A real client_id
- # in the catalog still works; the placeholder still builds a handler (it is
- # NOT dropped to None, so a refresh attempt happens and the scheduler can
- # flag needs_reauth — never a silent green "connected").
+ # No secret configured -> the shipped Google client wins over the catalog
+ # value, carries no secret, and routes its token calls through the broker.
+ monkeypatch.setattr(
+ "jarvis.marketplace.catalog_data.load_catalog",
+ lambda: _Catalog([_Spec("gmail", auth=_gmail_auth())]),
+ )
+ monkeypatch.setattr(
+ "jarvis.core.config.get_secret", lambda key, env_fallback=None: None
+ )
+
+ handler = build_handler_from_catalog("gmail")
+ assert isinstance(handler, PkceLoopbackHandler)
+ assert handler._config.client_id == SHIPPED_PUBLIC_CLIENT_IDS["google"]
+ assert handler._config.client_secret is None
+ assert handler._config.token_broker == "google" # noqa: S105 - a family name
+
+
+def test_gmail_handler_falls_back_to_catalog_without_a_shipped_client(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # A family with no shipped client uses the catalog value unchanged. A real
+ # client_id in the catalog still works; the placeholder still builds a
+ # handler (it is NOT dropped to None, so a refresh attempt happens and the
+ # scheduler can flag needs_reauth — never a silent green "connected").
real_in_catalog = "catalog-456.apps.googleusercontent.com"
+ monkeypatch.delitem(SHIPPED_PUBLIC_CLIENT_IDS, "google")
monkeypatch.setattr(
"jarvis.marketplace.catalog_data.load_catalog",
lambda: _Catalog([_Spec("gmail", auth=_gmail_auth(client_id=real_in_catalog))]),
@@ -153,13 +175,15 @@ def test_gmail_handler_falls_back_to_catalog_when_no_secret(
handler = build_handler_from_catalog("gmail")
assert isinstance(handler, PkceLoopbackHandler)
assert handler._config.client_id == real_in_catalog
+ assert handler._config.token_broker is None
def test_non_google_pkce_ignores_google_secret(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- # A non-Google PKCE plugin (e.g. Slack) keeps its own real catalog client_id
- # and must NOT be hijacked by the shared google_oauth secret.
+ # A non-Google PKCE plugin (e.g. Slack) keeps its own client and must NOT
+ # be hijacked by the shared google_oauth secret. Without a shipped Slack
+ # client the real catalog client_id is used.
slack_auth = OAuthPkceLoopbackAuth(
mode="oauth_pkce_loopback",
authorization_url="https://slack.com/oauth/v2/authorize",
@@ -167,6 +191,7 @@ def test_non_google_pkce_ignores_google_secret(
client_id="slack-real.id",
scopes=["chat:write"],
)
+ monkeypatch.delitem(SHIPPED_PUBLIC_CLIENT_IDS, "slack")
monkeypatch.setattr(
"jarvis.marketplace.catalog_data.load_catalog",
lambda: _Catalog([_Spec("slack", auth=slack_auth)]),
@@ -248,10 +273,23 @@ def test_resolve_pkce_client_asana_prefers_secret(
assert csec == "asana-sec"
-def test_resolve_pkce_client_slack_falls_back_to_catalog_when_no_secret(
+def test_resolve_pkce_client_slack_uses_shipped_client_when_no_secret(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # No slack_oauth secret set -> the shipped Slack app, with no secret (its
+ # broker holds it), beats the catalog value.
+ monkeypatch.setattr(
+ "jarvis.core.config.get_secret", lambda key, env_fallback=None: None
+ )
+ cid, csec = resolve_pkce_client("slack", "slack.real.id", "slack.real.secret")
+ assert cid == SHIPPED_PUBLIC_CLIENT_IDS["slack"]
+ assert csec is None
+
+
+def test_resolve_pkce_client_slack_falls_back_to_catalog_without_shipped_client(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- # No slack_oauth secret set -> the real catalog client_id is used unchanged.
+ monkeypatch.delitem(SHIPPED_PUBLIC_CLIENT_IDS, "slack")
monkeypatch.setattr(
"jarvis.core.config.get_secret", lambda key, env_fallback=None: None
)
diff --git a/tests/unit/marketplace/test_token_broker.py b/tests/unit/marketplace/test_token_broker.py
new file mode 100644
index 0000000000..0b3a9bede0
--- /dev/null
+++ b/tests/unit/marketplace/test_token_broker.py
@@ -0,0 +1,460 @@
+"""Shipped OAuth clients whose provider demands a secret go through a broker.
+
+Google (Desktop client) and Slack (distributed app) refuse code exchange and
+refresh without the client secret. The app never holds it: grants issued to
+the SHIPPED client are exchanged and refreshed through the project's token
+broker, which adds the secret server-side. Expert overrides and publisher
+secrets keep talking to the provider directly. Fakes only: the HTTP layer is
+replaced by a recording ``post`` and secrets by a dict lookup.
+"""
+
+# The "token_*" fields compared below hold family names and endpoint URLs,
+# never credentials; bandit's password heuristic misreads them.
+# ruff: noqa: S105
+
+from __future__ import annotations
+
+from urllib.parse import parse_qs, urlsplit
+
+import httpx
+import pytest
+
+from jarvis.marketplace.auth.oauth_pkce_loopback import (
+ PkceLoopbackConfig,
+ PkceLoopbackHandler,
+ _PendingPkceFlow,
+)
+from jarvis.marketplace.catalog import OAuthPkceLoopbackAuth
+from jarvis.marketplace.connect_helpers import build_pkce_config
+from jarvis.marketplace.publisher_clients import (
+ SHIPPED_PUBLIC_CLIENT_IDS,
+ SHIPPED_TOKEN_BROKERS,
+ broker_family_for_client,
+ is_standard_ready,
+ resolve_client,
+)
+from jarvis.marketplace.token_store import Tokens
+
+GOOGLE_ID = SHIPPED_PUBLIC_CLIENT_IDS["google"]
+SLACK_ID = SHIPPED_PUBLIC_CLIENT_IDS["slack"]
+GOOGLE_BROKER = SHIPPED_TOKEN_BROKERS["google"]
+SLACK_BROKER = SHIPPED_TOKEN_BROKERS["slack"]
+GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token" # noqa: S105 - endpoint, not a secret
+SLACK_TOKEN_URL = "https://slack.com/api/oauth.v2.access" # noqa: S105 - endpoint, not a secret
+PLACEHOLDER = "REPLACE_WITH_JARVIS_GOOGLE_CLIENT_ID"
+EXPERT_SECRET = "expert-secret-value" # noqa: S105 - test value
+PUBLISHER_SECRET = "publisher-secret-value" # noqa: S105 - test value
+GOOGLE_PLUGINS = (
+ "gmail",
+ "google_drive",
+ "google_calendar",
+ "youtube_music",
+ "youtube_studio",
+ "google_cloud",
+)
+
+
+def _secrets(monkeypatch: pytest.MonkeyPatch, values: dict[str, str]) -> None:
+ monkeypatch.setattr(
+ "jarvis.core.config.get_secret",
+ lambda key, env_fallback=None: values.get(key),
+ )
+
+
+class _Recorder:
+ """Stands in for ``httpx.AsyncClient.post`` and remembers each call."""
+
+ def __init__(self, payload: dict, status: int = 200) -> None:
+ self.payload = payload
+ self.status = status
+ self.calls: list[dict] = []
+
+ def install(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ recorder = self
+
+ async def _post(self, url, *args, **kwargs): # noqa: ANN001, ANN002, ANN003
+ recorder.calls.append({"url": url, **kwargs})
+ return httpx.Response(recorder.status, json=recorder.payload)
+
+ monkeypatch.setattr(httpx.AsyncClient, "post", _post)
+
+
+def _google_auth() -> OAuthPkceLoopbackAuth:
+ return OAuthPkceLoopbackAuth(
+ mode="oauth_pkce_loopback",
+ authorization_url="https://accounts.google.com/o/oauth2/v2/auth",
+ token_url=GOOGLE_TOKEN_URL,
+ client_id=PLACEHOLDER,
+ callback_port=3121,
+ callback_path="",
+ scopes=["https://www.googleapis.com/auth/gmail.readonly"],
+ offline_access=True,
+ )
+
+
+def _slack_auth() -> OAuthPkceLoopbackAuth:
+ return OAuthPkceLoopbackAuth(
+ mode="oauth_pkce_loopback",
+ authorization_url="https://slack.com/oauth/v2/authorize",
+ token_url=SLACK_TOKEN_URL,
+ client_id="REPLACE_WITH_JARVIS_SLACK_APP_CLIENT_ID",
+ callback_port=3118,
+ scopes=["chat:write"],
+ user_scopes_only=True,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Resolution precedence: own > publisher secret > shipped + broker > missing
+# ---------------------------------------------------------------------------
+
+
+def test_expert_override_wins_and_talks_to_google_directly(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _secrets(
+ monkeypatch,
+ {
+ "google_oauth_client_id": "own.apps.googleusercontent.com",
+ "google_oauth_client_secret": EXPERT_SECRET,
+ "publisher_google_oauth_client_id": "pub.apps.googleusercontent.com",
+ "publisher_google_oauth_client_secret": PUBLISHER_SECRET,
+ },
+ )
+ resolved = resolve_client("gmail", PLACEHOLDER, None)
+ assert (resolved.client_id, resolved.client_secret, resolved.source) == (
+ "own.apps.googleusercontent.com",
+ EXPERT_SECRET,
+ "own",
+ )
+ assert resolved.token_broker is None
+ assert build_pkce_config("gmail", _google_auth()).token_broker is None
+
+
+def test_publisher_secret_beats_shipped_client_without_broker(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _secrets(
+ monkeypatch,
+ {
+ "publisher_google_oauth_client_id": "pub.apps.googleusercontent.com",
+ "publisher_google_oauth_client_secret": PUBLISHER_SECRET,
+ },
+ )
+ resolved = resolve_client("gmail", PLACEHOLDER, None)
+ assert (resolved.client_id, resolved.client_secret, resolved.source) == (
+ "pub.apps.googleusercontent.com",
+ PUBLISHER_SECRET,
+ "publisher",
+ )
+ assert resolved.token_broker is None
+ assert build_pkce_config("gmail", _google_auth()).token_broker is None
+
+
[email protected]("plugin_id", GOOGLE_PLUGINS)
+def test_shipped_client_uses_broker_with_zero_setup(
+ monkeypatch: pytest.MonkeyPatch, plugin_id: str
+) -> None:
+ _secrets(monkeypatch, {})
+ resolved = resolve_client(plugin_id, PLACEHOLDER, None)
+ assert (resolved.client_id, resolved.client_secret, resolved.source) == (
+ GOOGLE_ID,
+ None,
+ "publisher",
+ )
+ assert resolved.token_broker == "google"
+ assert is_standard_ready(plugin_id, PLACEHOLDER) is True
+
+
+def test_family_without_shipped_client_stays_missing(monkeypatch: pytest.MonkeyPatch) -> None:
+ _secrets(monkeypatch, {})
+ monkeypatch.delitem(SHIPPED_PUBLIC_CLIENT_IDS, "google")
+ resolved = resolve_client("gmail", PLACEHOLDER, None)
+ assert resolved.source == "missing"
+ assert resolved.token_broker is None
+ assert is_standard_ready("gmail", PLACEHOLDER) is False
+
+
+def test_shipped_slack_client_uses_its_broker(monkeypatch: pytest.MonkeyPatch) -> None:
+ _secrets(monkeypatch, {})
+ config = build_pkce_config("slack", _slack_auth())
+ assert config.client_id == SLACK_ID
+ assert config.client_secret is None
+ assert config.token_broker == "slack"
+ assert config.scope_param_name == "user_scope"
+
+
+def test_broker_family_lookup_is_exact() -> None:
+ assert broker_family_for_client(GOOGLE_ID) == "google"
+ assert broker_family_for_client(SLACK_ID) == "slack"
+ assert broker_family_for_client(SHIPPED_PUBLIC_CLIENT_IDS["microsoft"]) is None
+ assert broker_family_for_client("own.apps.googleusercontent.com") is None
+ assert broker_family_for_client(None) is None
+
+
+def test_brokers_are_https_on_the_project_host() -> None:
+ for broker in SHIPPED_TOKEN_BROKERS.values():
+ for url in filter(None, (broker.token_url, broker.redirect_uri)):
+ parts = urlsplit(url)
+ assert parts.scheme == "https"
+ assert parts.hostname == "token.personaljarvis.ai"
+
+
+# ---------------------------------------------------------------------------
+# Code exchange
+# ---------------------------------------------------------------------------
+
+
+def _config(family: str | None, *, secret: str | None = None) -> PkceLoopbackConfig:
+ return PkceLoopbackConfig(
+ plugin_id="gmail",
+ authorization_url="https://accounts.google.com/o/oauth2/v2/auth",
+ token_url=GOOGLE_TOKEN_URL,
+ client_id=GOOGLE_ID if family else "own.apps.googleusercontent.com",
+ client_secret=secret,
+ callback_port=3121,
+ scopes=["https://www.googleapis.com/auth/gmail.readonly"],
+ offline_access=True,
+ token_broker=family,
+ )
+
+
+def _pending(config: PkceLoopbackConfig, redirect: str) -> _PendingPkceFlow:
+ return _PendingPkceFlow(
+ config=config,
+ callback_server=None,
+ code_verifier="v" * 43,
+ redirect_uri=redirect,
+ )
+
+
+async def test_exchange_goes_to_broker_without_secret(monkeypatch: pytest.MonkeyPatch) -> None:
+ recorder = _Recorder({"access_token": "ya29.a", "refresh_token": "1//r", "expires_in": 3599})
+ recorder.install(monkeypatch)
+ config = _config("google")
+
+ tokens = await PkceLoopbackHandler(config)._exchange( # noqa: SLF001
+ _pending(config, "http://127.0.0.1:3121"), code="4/code"
+ )
+
+ (call,) = recorder.calls
+ assert call["url"] == GOOGLE_BROKER.token_url
+ assert call["data"] == {
+ "client_id": GOOGLE_ID,
+ "code": "4/code",
+ "code_verifier": "v" * 43,
+ "grant_type": "authorization_code",
+ "redirect_uri": "http://127.0.0.1:3121",
+ }
+ assert "Authorization" not in call["headers"]
+ assert tokens.access == "ya29.a"
+ assert tokens.extra["client_id"] == GOOGLE_ID
+ assert tokens.extra["token_broker"] == "google"
+ assert tokens.extra["token_endpoint_auth_method"] == "none"
+ assert "client_secret" not in tokens.extra
+
+
+async def test_expert_exchange_goes_to_google_with_own_secret(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ recorder = _Recorder({"access_token": "ya29.a", "refresh_token": "1//r", "expires_in": 3599})
+ recorder.install(monkeypatch)
+ config = _config(None, secret=EXPERT_SECRET)
+
+ tokens = await PkceLoopbackHandler(config)._exchange( # noqa: SLF001
+ _pending(config, "http://127.0.0.1:3121"), code="4/code"
+ )
+
+ (call,) = recorder.calls
+ assert call["url"] == GOOGLE_TOKEN_URL
+ assert call["data"]["client_secret"] == EXPERT_SECRET
+ assert tokens.extra["client_secret"] == EXPERT_SECRET
+ assert "token_broker" not in tokens.extra
+
+
+async def test_broker_errors_surface_like_provider_errors(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _Recorder({"error": "invalid_grant", "error_description": "Bad Request"}, 400).install(
+ monkeypatch
+ )
+ config = _config("google")
+ with pytest.raises(RuntimeError, match="HTTP 400"):
+ await PkceLoopbackHandler(config)._exchange( # noqa: SLF001
+ _pending(config, "http://127.0.0.1:3121"), code="4/code"
+ )
+
+
+# ---------------------------------------------------------------------------
+# Refresh — routed by the GRANT, not by today's config
+# ---------------------------------------------------------------------------
+
+
+async def test_brokered_grant_refreshes_through_broker_even_after_expert_override(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ recorder = _Recorder({"access_token": "ya29.new", "expires_in": 3599})
+ recorder.install(monkeypatch)
+ expert_config = _config(None, secret=EXPERT_SECRET)
+ grant = Tokens(
+ access="ya29.old",
+ refresh="1//r",
+ extra={"client_id": GOOGLE_ID, "token_broker": "google"},
+ )
+
+ tokens = await PkceLoopbackHandler(expert_config).refresh(grant)
+
+ (call,) = recorder.calls
+ assert call["url"] == GOOGLE_BROKER.token_url
+ assert call["data"] == {
+ "grant_type": "refresh_token",
+ "refresh_token": "1//r",
+ "client_id": GOOGLE_ID,
+ }
+ assert tokens.access == "ya29.new"
+ assert tokens.refresh == "1//r"
+ assert tokens.extra["token_broker"] == "google"
+ assert "client_secret" not in tokens.extra
+
+
+async def test_expert_grant_refreshes_directly_even_when_shipped_client_is_active(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ recorder = _Recorder({"access_token": "ya29.new", "expires_in": 3599})
+ recorder.install(monkeypatch)
+ grant = Tokens(
+ access="ya29.old",
+ refresh="1//r",
+ extra={
+ "client_id": "own.apps.googleusercontent.com",
+ "client_secret": EXPERT_SECRET,
+ "token_endpoint_auth_method": "client_secret_post",
+ },
+ )
+
+ await PkceLoopbackHandler(_config("google")).refresh(grant)
+
+ (call,) = recorder.calls
+ assert call["url"] == GOOGLE_TOKEN_URL
+ assert call["data"]["client_secret"] == EXPERT_SECRET
+
+
+async def test_shipped_grant_without_marker_still_refreshes_through_broker(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ recorder = _Recorder({"access_token": "ya29.new", "expires_in": 3599})
+ recorder.install(monkeypatch)
+ grant = Tokens(access="a", refresh="1//r", extra={"client_id": GOOGLE_ID})
+
+ tokens = await PkceLoopbackHandler(_config(None, secret=EXPERT_SECRET)).refresh(grant)
+
+ assert recorder.calls[0]["url"] == GOOGLE_BROKER.token_url
+ assert "client_secret" not in recorder.calls[0]["data"]
+ assert tokens.extra["token_broker"] == "google"
+
+
+async def test_legacy_grant_follows_current_brokered_config(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ recorder = _Recorder({"access_token": "ya29.new", "expires_in": 3599})
+ recorder.install(monkeypatch)
+
+ tokens = await PkceLoopbackHandler(_config("google")).refresh(
+ Tokens(access="a", refresh="1//r")
+ )
+
+ assert recorder.calls[0]["url"] == GOOGLE_BROKER.token_url
+ assert tokens.extra["client_id"] == GOOGLE_ID
+ assert tokens.extra["token_broker"] == "google"
+
+
+async def test_vanished_broker_asks_for_reconnect(monkeypatch: pytest.MonkeyPatch) -> None:
+ recorder = _Recorder({"access_token": "x"})
+ recorder.install(monkeypatch)
+ grant = Tokens(access="a", refresh="r", extra={"client_id": "c", "token_broker": "gone"})
+ with pytest.raises(RuntimeError, match="reconnect"):
+ await PkceLoopbackHandler(_config(None)).refresh(grant)
+ assert recorder.calls == []
+
+
+# ---------------------------------------------------------------------------
+# Slack: https redirect through the broker, loopback listener unchanged
+# ---------------------------------------------------------------------------
+
+
+class _FakeListener:
+ """A loopback callback server that never binds a socket."""
+
+ redirect_uri = "http://127.0.0.1:3118/oauth/callback"
+
+ def __init__(self) -> None:
+ self.started = False
+
+ async def start(self) -> None:
+ self.started = True
+
+ async def stop(self) -> None:
+ self.started = False
+
+
+async def test_slack_authorize_uses_broker_callback_while_listening_locally(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _secrets(monkeypatch, {})
+ listener = _FakeListener()
+ seen: dict = {}
+
+ def _make(state, **kwargs): # noqa: ANN001, ANN003
+ seen.update(kwargs)
+ return listener
+
+ monkeypatch.setattr("jarvis.marketplace.auth.oauth_pkce_loopback.make_callback_server", _make)
+ handler = PkceLoopbackHandler(build_pkce_config("slack", _slack_auth()))
+
+ session = await handler.start(None)
+
+ assert listener.started is True
+ assert seen["fixed_port"] == 3118
+ assert seen["callback_path"] == "/oauth/callback"
+ query = parse_qs(urlsplit(session.open_url).query)
+ assert query["redirect_uri"] == [SLACK_BROKER.redirect_uri]
+ assert query["client_id"] == [SLACK_ID]
+ assert session.redirect_uri == SLACK_BROKER.redirect_uri
+ pending = handler._pending[session.flow_id] # noqa: SLF001
+ assert pending.redirect_uri == SLACK_BROKER.redirect_uri
+ await handler.cancel(session)
+
+
+async def test_slack_exchange_sends_the_broker_callback(monkeypatch: pytest.MonkeyPatch) -> None:
+ recorder = _Recorder(
+ {"ok": True, "authed_user": {"access_token": "xoxp-1", "expires_in": 43200}}
+ )
+ recorder.install(monkeypatch)
+ _secrets(monkeypatch, {})
+ config = build_pkce_config("slack", _slack_auth())
+
+ tokens = await PkceLoopbackHandler(config)._exchange( # noqa: SLF001
+ _pending(config, SLACK_BROKER.redirect_uri), code="slack-code"
+ )
+
+ (call,) = recorder.calls
+ assert call["url"] == SLACK_BROKER.token_url
+ assert call["data"]["redirect_uri"] == SLACK_BROKER.redirect_uri
+ assert "client_secret" not in call["data"]
+ assert tokens.extra["token_broker"] == "slack"
+
+
+def test_google_keeps_the_loopback_redirect(monkeypatch: pytest.MonkeyPatch) -> None:
+ _secrets(monkeypatch, {})
+ handler = PkceLoopbackHandler(build_pkce_config("gmail", _google_auth()))
+ assert handler._redirect_uri("http://127.0.0.1:3121") == "http://127.0.0.1:3121" # noqa: SLF001