Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
fix(connected-accounts): SEC-339 gate initiate() warning on response Deprecation header
Composioc358ffaa3b22
diff --git a/.changeset/sec-339-deprecation-header-gate.md b/.changeset/sec-339-deprecation-header-gate.mdnew file mode 100644index 000000000..a7ade9793--- /dev/null+++ b/.changeset/sec-339-deprecation-header-gate.md@@ -0,0 +1,15 @@+---+'@composio/core': patch+---++Fix false-positive `initiate()` deprecation warning for custom auth configs (SEC-339 follow-up).++`composio.connectedAccounts.initiate()` previously emitted a one-time `console.warn` on every redirectable-OAuth response, regardless of whether the auth config was Composio-managed (subject to the 2026-07-03 cutover) or custom (unaffected). The wording was conditional ("If this auth config is Composio-managed…") so callers using their own OAuth apps could ignore it, but the warning still printed and caused noise in logs.++Apollo already emits the SEC-339 `Deprecation` / `Sunset` / `Link rel="deprecation"` headers (RFC 9745 / RFC 8594) **only** on the retiring branch — managed + redirectable OAuth. The SDK now reads the `Deprecation` header from the response (via `APIPromise.withResponse()`) and gates the warning on its presence. Custom auth configs and non-OAuth schemes get a clean response from the server and now stay silent in the SDK as well.++- **Behavior change:** No warning is emitted for `initiate()` calls against custom OAuth auth configs or non-OAuth schemes (API key, bearer, basic). Managed-OAuth callers continue to get exactly one warning per process, now with revised wording that points at the response's `Sunset` header for the precise cutover date.+- **No public API change:** `initiate()` returns the same `ConnectionRequest` shape and respects the same `allowMultiple` guard. `ComposioLegacyConnectedAccountsEndpointRetiredError` continues to surface from the 400 retired-path response.+- **Test scaffolding:** new mock helper `mockApiPromiseWithHeaders()` in `connectedAccounts.test.ts` wraps a value as an `APIPromise`-shaped thenable so the new tests can simulate apollo's header behavior. Pre-existing initiate tests using `mockResolvedValueOnce` continue to pass via the SDK's defensive fallback when `withResponse` is absent on the mock.++Python SDK gets the matching change in the same release train.diff --git a/python/composio/core/models/connected_accounts.py b/python/composio/core/models/connected_accounts.pyindex ad93fc1e3..877f7a0ba 100644--- a/python/composio/core/models/connected_accounts.py+++ b/python/composio/core/models/connected_accounts.py@@ -23,11 +23,6 @@ from .base import Resourcelogger = logging.getLogger(__name__)-# Schemes that take the redirectable OAuth path on the legacy-# `POST /api/v3/connected_accounts` endpoint, and so are subject to the-# 2026-05-08 / 2026-07-03 retirement when the auth config is Composio-managed.-_LEGACY_RETIRING_OAUTH_SCHEMES = frozenset({"OAUTH1", "OAUTH2", "DCR_OAUTH"})-# Mirrors TS `ConnectionRequest.ts:terminalErrorStates`. INACTIVE is excluded# on purpose — it can recover to ACTIVE._TERMINAL_CONNECTION_STATES: t.FrozenSet[str] = frozenset(@@ -478,13 +473,42 @@ class ConnectedAccounts:if alias is not None:connection["alias"] = alias+ # Use `with_raw_response.create` so we can read the SEC-339+ # `Deprecation` header (RFC 9745) the apollo retiring branch sets —+ # that header is emitted only when the auth config is Composio-managed+ # AND on a redirectable OAuth scheme, so it's the canonical signal+ # that this caller needs to migrate. Custom auth configs and non-OAuth+ # schemes never see the header, eliminating the false-positive warning+ # that an auth_scheme-only check produced for link()-unaffected callers.+ deprecation_header: t.Optional[str] = Nonetry:- response = self._client.connected_accounts.create(- auth_config={"id": auth_config_id},- connection=t.cast(- connected_account_create_params.Connection, connection- ),+ ca_client = self._client.connected_accounts+ raw_create = getattr(+ getattr(ca_client, "with_raw_response", None), "create", None)+ if callable(raw_create):+ raw = raw_create(+ auth_config={"id": auth_config_id},+ connection=t.cast(+ connected_account_create_params.Connection, connection+ ),+ )+ response = raw.parse() if callable(getattr(raw, "parse", None)) else raw+ headers = getattr(raw, "headers", None)+ if headers is not None and hasattr(headers, "get"):+ value = headers.get("Deprecation") or headers.get("deprecation")+ if isinstance(value, str):+ deprecation_header = value+ else:+ # Test mocks may not stub `with_raw_response`. Fall back to+ # the parsed-only path; the deprecation gate stays off (no+ # header to read).+ response = ca_client.create(+ auth_config={"id": auth_config_id},+ connection=t.cast(+ connected_account_create_params.Connection, connection+ ),+ )except BadRequestError as error:# When the server has flipped this org to the retired path, the# legacy endpoint returns 400 with a stable migration message.@@ -500,28 +524,20 @@ class ConnectedAccounts:) from errorraise- # Warn once per process when a successful initiate() lands on the- # redirectable-OAuth path. We can't tell from the response alone- # whether the auth config is Composio-managed (the field that- # determines whether the cutover applies), so the warning text is- # conditional in wording — custom-OAuth users can ignore it,- # Composio-managed-OAuth users see a clear pointer to link() before- # their org's cutover lands.+ # Warn once per process when apollo flags this response as on the+ # retiring path. Header presence is a 1:1 signal — custom auth+ # configs and non-OAuth schemes get a clean response and stay silent,+ # fixing the false-positive that auth_scheme-based detection+ # produced.global _legacy_initiate_warning_emitted- response_auth_scheme = getattr(response.connection_data, "auth_scheme", None)- if (- not _legacy_initiate_warning_emitted- and isinstance(response_auth_scheme, str)- and response_auth_scheme in _LEGACY_RETIRING_OAUTH_SCHEMES- ):+ if not _legacy_initiate_warning_emitted and deprecation_header:_legacy_initiate_warning_emitted = Truewarnings.warn("composio.connected_accounts.initiate() will stop working "- "for Composio-managed OAuth auth configs on 2026-05-08 (new "- "orgs) and 2026-07-03 (all orgs). If this auth config is "- "Composio-managed, switch to "- "composio.connected_accounts.link() before then. Custom "- "auth configs are unaffected. See "+ "for this auth config on or before 2026-07-03 (see Sunset "+ "header on the response). Switch to "+ "composio.connected_accounts.link() — same return shape, "+ "same allow_multiple semantics. ""https://docs.composio.dev/docs/changelog/2026/04/24",DeprecationWarning,stacklevel=2,diff --git a/python/tests/test_connected_accounts.py b/python/tests/test_connected_accounts.pyindex b18aace21..5246f1e84 100644--- a/python/tests/test_connected_accounts.py+++ b/python/tests/test_connected_accounts.py@@ -1,5 +1,6 @@import loggingimport time+import warningsfrom unittest.mock import Mock, patchimport pytest@@ -13,6 +14,22 @@ from composio.core.models.connected_accounts import ()+def _set_initiate_response(mock_client, body, headers=None):+ """SEC-339: route an `initiate()` mock response through the+ ``with_raw_response.create`` surface that the SDK consumes for+ deprecation-header gating.++ ``headers`` defaults to ``None`` (no Deprecation header → no warning,+ matching custom-auth-config / non-OAuth-scheme behavior). Pass+ ``{"Deprecation": "@..."}`` to simulate the apollo retiring branch.+ """+ raw = Mock()+ raw.parse.return_value = body+ raw.headers = headers or {}+ mock_client.connected_accounts.with_raw_response.create.return_value = raw+ return raw++class TestAuthScheme:def test_oauth2_with_access_token_sets_active_status(self):scheme = AuthScheme()@@ -322,7 +339,7 @@ class TestConnectedAccounts:mock_response.id = "conn-123"mock_response.connection_data.val.status = "PENDING"mock_response.connection_data.val.redirect_url = "https://redirect"- mock_client.connected_accounts.create.return_value = mock_response+ _set_initiate_response(mock_client, mock_response)connected_accounts.initiate(user_id="user-1", auth_config_id="auth-1")@@ -342,7 +359,7 @@ class TestConnectedAccounts:mock_response.id = "conn-123"mock_response.connection_data.val.status = "PENDING"mock_response.connection_data.val.redirect_url = "https://redirect"- mock_client.connected_accounts.create.return_value = mock_response+ _set_initiate_response(mock_client, mock_response)config = {"auth_scheme": "API_KEY",@@ -361,7 +378,9 @@ class TestConnectedAccounts:mock_client.connected_accounts.list.assert_called_once_with(user_ids=["user-1"], auth_config_ids=["auth-1"], statuses=["ACTIVE"])- call_kwargs = mock_client.connected_accounts.create.call_args.kwargs+ call_kwargs = (+ mock_client.connected_accounts.with_raw_response.create.call_args.kwargs+ )assert call_kwargs["auth_config"] == {"id": "auth-1"}assert call_kwargs["connection"]["user_id"] == "user-1"assert call_kwargs["connection"]["callback_url"] == "https://cb"@@ -473,7 +492,7 @@ class TestConnectedAccounts:mock_response.id = "conn-active"mock_response.connection_data.val.status = "ACTIVE"mock_response.connection_data.val.redirect_url = None- mock_client.connected_accounts.create.return_value = mock_response+ _set_initiate_response(mock_client, mock_response)scheme = AuthScheme()config = scheme.oauth2(@@ -504,3 +523,110 @@ class TestConnectedAccounts:mock_from_id.assert_called_once_with(id="conn-123", client=mock_client)mock_request.wait_for_connection.assert_called_once_with(timeout=42.0)assert result == "connected"+++# SEC-339: initiate() must gate its DeprecationWarning on the response+# `Deprecation` HTTP header (RFC 9745) that apollo emits only on the+# retiring branch (Composio-managed + redirectable OAuth). These tests pin+# that contract so the previous false-positive behavior — warning purely+# off auth_scheme, which over-fired for custom auth configs — can't come+# back. See https://docs.composio.dev/docs/changelog/2026/04/24+class TestInitiateDeprecationHeaderGate:+ @pytest.fixture+ def mock_client(self):+ client = Mock()+ client.connected_accounts.list = Mock()+ return client++ @pytest.fixture(autouse=True)+ def _reset_warning_flag(self):+ """Reset the module-level one-time warning guard before each test+ so warning emission is deterministic regardless of test order."""+ import composio.core.models.connected_accounts as ca_mod++ ca_mod._legacy_initiate_warning_emitted = False+ yield+ ca_mod._legacy_initiate_warning_emitted = False++ @staticmethod+ def _no_existing_accounts(mock_client):+ empty = Mock()+ empty.items = []+ mock_client.connected_accounts.list.return_value = empty++ @staticmethod+ def _make_response():+ body = Mock()+ body.id = "conn-dep"+ body.connection_data.val.status = "INITIATED"+ body.connection_data.val.redirect_url = "https://redirect"+ return body++ def test_warns_once_when_response_carries_deprecation_header(self, mock_client):+ """Managed + redirectable-OAuth path: apollo sets `Deprecation`,+ SDK emits a `DeprecationWarning` pointing callers at link()."""+ self._no_existing_accounts(mock_client)+ body = self._make_response()+ _set_initiate_response(+ mock_client,+ body,+ headers={+ "Deprecation": "@1776988800",+ "Sunset": "Fri, 08 May 2026 00:00:00 GMT",+ "Link": (+ "<https://docs.composio.dev/docs/changelog/2026/04/24>; "+ 'rel="deprecation"'+ ),+ },+ )++ connected_accounts = ConnectedAccounts(client=mock_client)+ with warnings.catch_warnings(record=True) as caught:+ warnings.simplefilter("always")+ req = connected_accounts.initiate(user_id="user-1", auth_config_id="auth-1")++ assert isinstance(req, ConnectionRequest)+ deprecations = [w for w in caught if issubclass(w.category, DeprecationWarning)]+ assert len(deprecations) == 1+ message = str(deprecations[0].message)+ assert "composio.connected_accounts.link()" in message+ assert "2026-07-03" in message++ def test_does_not_warn_when_response_has_no_deprecation_header(self, mock_client):+ """Custom auth config / non-OAuth scheme: apollo returns a clean+ response, SDK must stay silent. Regression for the prior+ auth_scheme-only check that over-fired here."""+ self._no_existing_accounts(mock_client)+ _set_initiate_response(mock_client, self._make_response(), headers={})++ connected_accounts = ConnectedAccounts(client=mock_client)+ with warnings.catch_warnings(record=True) as caught:+ warnings.simplefilter("always")+ connected_accounts.initiate(user_id="user-1", auth_config_id="auth-1")++ deprecations = [w for w in caught if issubclass(w.category, DeprecationWarning)]+ assert deprecations == []++ def test_warns_at_most_once_per_process_across_calls(self, mock_client):+ """The one-time guard must hold across multiple calls in the same+ process even when each response carries the Deprecation header."""+ self._no_existing_accounts(mock_client)+ # Same headers for both calls; helper rewires the same return on+ # each invocation, so both calls see the Deprecation header.+ _set_initiate_response(+ mock_client,+ self._make_response(),+ headers={"Deprecation": "@1776988800"},+ )++ connected_accounts = ConnectedAccounts(client=mock_client)+ with warnings.catch_warnings(record=True) as caught:+ warnings.simplefilter("always")+ connected_accounts.initiate(user_id="user-1", auth_config_id="auth-1")+ empty = Mock()+ empty.items = []+ mock_client.connected_accounts.list.return_value = empty+ connected_accounts.initiate(user_id="user-1", auth_config_id="auth-1")++ deprecations = [w for w in caught if issubclass(w.category, DeprecationWarning)]+ assert len(deprecations) == 1diff --git a/ts/packages/core/src/models/ConnectedAccounts.ts b/ts/packages/core/src/models/ConnectedAccounts.tsindex 36f9cc5aa..d47b539c9 100644--- a/ts/packages/core/src/models/ConnectedAccounts.ts+++ b/ts/packages/core/src/models/ConnectedAccounts.ts@@ -7,6 +7,7 @@*/import ComposioClient, { BadRequestError } from '@composio/client';import {+ ConnectedAccountCreateResponse,ConnectedAccountDeleteResponse,ConnectedAccountRefreshParams,ConnectedAccountRefreshResponse,@@ -45,11 +46,6 @@ import {import logger from '../utils/logger';import { ConnectionData } from '../types/connectedAccountAuthStates.types';-// Schemes that take the redirectable OAuth path on the legacy-// `POST /api/v3/connected_accounts` endpoint, and so are subject to the-// 2026-05-08 / 2026-07-03 retirement when the auth config is Composio-managed.-const LEGACY_RETIRING_OAUTH_SCHEMES = new Set(['OAUTH1', 'OAUTH2', 'DCR_OAUTH']);-// One-time-per-process guard so long-running services don't spam the deprecation// warning on every initiate() call.let _legacyInitiateWarningEmitted = false;@@ -232,9 +228,34 @@ export class ConnectedAccounts {},};- let response;+ let response: ConnectedAccountCreateResponse;+ let httpResponse: Response | undefined;try {- response = await this.client.connectedAccounts.create(createParams);+ // Chain `.withResponse()` so we can read the SEC-339 `Deprecation`+ // header (RFC 9745) the apollo retiring branch sets — that header is+ // emitted only when the auth config is Composio-managed AND on a+ // redirectable OAuth scheme, so it's the canonical signal that this+ // caller needs to migrate. Custom auth configs and non-OAuth schemes+ // never see the header, eliminating the false-positive warning that+ // an `auth_scheme`-only check produced for `link()`-unaffected callers.+ const apiCall = this.client.connectedAccounts.create(createParams);+ if (typeof (apiCall as { withResponse?: unknown }).withResponse === 'function') {+ const resolved = await (+ apiCall as unknown as {+ withResponse: () => Promise<{+ data: ConnectedAccountCreateResponse;+ response: Response;+ }>;+ }+ ).withResponse();+ response = resolved.data;+ httpResponse = resolved.response;+ } else {+ // Test mocks may return a plain Promise without `withResponse`.+ // Fall back to a naked await; the deprecation gate below stays+ // off in that case (no header to read).+ response = await apiCall;+ }} catch (error) {// When the server has flipped this org to the retired path, the legacy// endpoint returns 400 with a stable migration message. Surface it as@@ -253,25 +274,17 @@ export class ConnectedAccounts {throw error;}- // Warn once per process when a successful initiate() lands on the- // redirectable-OAuth path. We can't tell from the response alone whether- // the auth config is Composio-managed (the field that determines whether- // the cutover applies), so the warning text is conditional in wording —- // custom-OAuth users can ignore it, Composio-managed-OAuth users see a- // clear pointer to link() before their org's cutover lands.- const responseAuthScheme = response.connectionData?.authScheme;- if (- !_legacyInitiateWarningEmitted &&- typeof responseAuthScheme === 'string' &&- LEGACY_RETIRING_OAUTH_SCHEMES.has(responseAuthScheme)- ) {+ // Warn once per process when apollo flags this response as on the+ // retiring path. Header presence is a 1:1 signal — custom auth configs+ // and non-OAuth schemes get a clean response and stay silent, fixing+ // the false-positive that auth_scheme-based detection produced.+ if (!_legacyInitiateWarningEmitted && httpResponse?.headers.get('Deprecation')) {_legacyInitiateWarningEmitted = true;logger.warn('[Deprecation] composio.connectedAccounts.initiate() will stop ' +- 'working for Composio-managed OAuth auth configs on 2026-05-08 ' +- '(new orgs) and 2026-07-03 (all orgs). If this auth config is ' +- 'Composio-managed, switch to composio.connectedAccounts.link() ' +- 'before then. Custom auth configs are unaffected. See ' ++ 'working for this auth config on or before 2026-07-03 (see Sunset ' ++ 'header on the response). Switch to composio.connectedAccounts.link() — ' ++ 'same return shape, same allowMultiple semantics. ' +'https://docs.composio.dev/docs/changelog/2026/04/24');}diff --git a/ts/packages/core/test/connectedAccounts/connectedAccounts.test.ts b/ts/packages/core/test/connectedAccounts/connectedAccounts.test.tsindex abe1d1185..bb12f8057 100644--- a/ts/packages/core/test/connectedAccounts/connectedAccounts.test.ts+++ b/ts/packages/core/test/connectedAccounts/connectedAccounts.test.ts@@ -498,6 +498,120 @@ describe('ConnectedAccounts', () => {});});+ // SEC-339: initiate() must gate its deprecation warning on the response+ // `Deprecation` HTTP header (RFC 9745) that apollo emits only on the+ // retiring branch (Composio-managed + redirectable OAuth). These tests pin+ // that contract so the previous false-positive behavior — warning purely+ // off auth_scheme, which over-fired for custom auth configs — can't come+ // back. See https://docs.composio.dev/docs/changelog/2026/04/24+ describe('initiate deprecation header gate', () => {+ /** Wrap a value as an APIPromise-shaped thenable that also exposes+ * `.withResponse()` returning the value plus a synthesised Response+ * carrying the given headers. Mirrors the @composio/client APIPromise+ * surface that the SDK now consumes for header-aware deprecation. */+ function mockApiPromiseWithHeaders<T>(+ data: T,+ headers: Record<string, string> = {}+ ): Promise<T> & {+ withResponse: () => Promise<{ data: T; response: Response }>;+ } {+ const response = new Response(null, { headers: new Headers(headers) });+ const promise = Promise.resolve(data) as Promise<T> & {+ withResponse: () => Promise<{ data: T; response: Response }>;+ };+ promise.withResponse = () => Promise.resolve({ data, response });+ return promise;+ }++ const userId = 'user_dep';+ const authConfigId = 'auth_config_dep';+ const baseResponse = {+ id: 'conn_dep',+ connectionData: {+ val: {+ authScheme: AuthSchemeTypes.OAUTH2,+ status: 'INITIALIZING',+ redirectUrl: 'https://auth.example.com/connect',+ },+ },+ };++ /** Re-import the model with a fresh module-level+ * `_legacyInitiateWarningEmitted` so each test starts unwarned. */+ async function freshConnectedAccounts() {+ vi.resetModules();+ const { ConnectedAccounts: Fresh } = await import('../../src/models/ConnectedAccounts');+ const fresh = new Fresh(extendedMockClient as unknown as ComposioClient);+ const loggerMod = await import('../../src/utils/logger');+ const warnSpy = vi.spyOn(loggerMod.default, 'warn').mockImplementation(() => {});+ return { connectedAccounts: fresh, warnSpy };+ }++ it('warns once when response carries a Deprecation header (managed + OAuth retiring path)', async () => {+ const { connectedAccounts: fresh, warnSpy } = await freshConnectedAccounts();+ extendedMockClient.connectedAccounts.list.mockResolvedValueOnce({+ items: [],+ next_cursor: null,+ total_pages: 1,+ });+ extendedMockClient.connectedAccounts.create.mockReturnValueOnce(+ mockApiPromiseWithHeaders(baseResponse, {+ Deprecation: '@1776988800',+ Sunset: 'Fri, 08 May 2026 00:00:00 GMT',+ Link: '<https://docs.composio.dev/docs/changelog/2026/04/24>; rel="deprecation"',+ })+ );++ const req = await fresh.initiate(userId, authConfigId);++ expect(req).toHaveProperty('id', 'conn_dep');+ expect(warnSpy).toHaveBeenCalledTimes(1);+ expect(warnSpy.mock.calls[0]![0]).toMatch(/composio\.connectedAccounts\.link\(\)/);+ expect(warnSpy.mock.calls[0]![0]).toMatch(/2026-07-03/);+ });++ it('does NOT warn when response has no Deprecation header (custom auth config)', async () => {+ // Regression test: prior auth_scheme-only check warned for any+ // OAUTH2 response, including custom configs that are not subject+ // to the cutover. Header absence is the canonical "you're fine"+ // signal from apollo.+ const { connectedAccounts: fresh, warnSpy } = await freshConnectedAccounts();+ extendedMockClient.connectedAccounts.list.mockResolvedValueOnce({+ items: [],+ next_cursor: null,+ total_pages: 1,+ });+ extendedMockClient.connectedAccounts.create.mockReturnValueOnce(+ mockApiPromiseWithHeaders(baseResponse /* no Deprecation header */)+ );++ const req = await fresh.initiate(userId, authConfigId);++ expect(req).toHaveProperty('id', 'conn_dep');+ expect(warnSpy).not.toHaveBeenCalled();+ });++ it('warns at most once per process even across multiple managed-OAuth calls', async () => {+ const { connectedAccounts: fresh, warnSpy } = await freshConnectedAccounts();+ // Two consecutive managed-OAuth calls. Both responses carry the+ // Deprecation header, but the module-level guard should let only+ // the first one through.+ for (let i = 0; i < 2; i++) {+ extendedMockClient.connectedAccounts.list.mockResolvedValueOnce({+ items: [],+ next_cursor: null,+ total_pages: 1,+ });+ extendedMockClient.connectedAccounts.create.mockReturnValueOnce(+ mockApiPromiseWithHeaders(baseResponse, { Deprecation: '@1776988800' })+ );+ await fresh.initiate(userId, authConfigId);+ }++ expect(warnSpy).toHaveBeenCalledTimes(1);+ });+ });+describe('get', () => {it('should retrieve a connected account by nanoid and transform the response', async () => {const nanoid = 'conn_123';