AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(stripe-link): enrich the approval sheet, handle requires_action (#14063)
Nicholas Tindle1eda9e4a8982
diff --git a/autogpt_platform/backend/backend/blocks/stripe_link/_auth.py b/autogpt_platform/backend/backend/blocks/stripe_link/_auth.pyindex 61cc21a077..30c37280f5 100644--- a/autogpt_platform/backend/backend/blocks/stripe_link/_auth.py+++ b/autogpt_platform/backend/backend/blocks/stripe_link/_auth.py@@ -7,6 +7,7 @@ acquisition flow is handled by ``StripeLinkDeviceAuthHandler`` in``backend/integrations/oauth/stripe_link.py``."""+import loggingfrom typing import Any, Literalimport httpx@@ -26,6 +27,11 @@ from backend.integrations.providers import ProviderNameLINK_DEFAULT_SCOPES = ["userinfo:read", "payment_methods.agentic"]+logger = logging.getLogger(__name__)++# Upstream error text reaches a block `error` output, which is persisted.+MAX_ERROR_DETAIL_CHARS = 500+StripeLinkCredentials = OAuth2Credentials# `credentials_types` carries two different things at once: the *shape* of the@@ -107,5 +113,44 @@ async def link_api_request(headers=headers,json=body,)- response.raise_for_status()+ # `is_success`, not `not is_error`: the latter is 4xx/5xx only, so a+ # 3xx would fall straight through to `.json()` — and redirects are not+ # followed. A moved endpoint would read as an empty wallet, or raise a+ # bare KeyError with the redirect invisible.+ if not response.is_success:+ # Link explains itself in a structured `error.message`; surface+ # that rather than a bare "400 Bad Request" with the explanation+ # discarded. That is how the SPT merchant-field constraint stayed+ # hidden during development.+ try:+ detail = response.json().get("error", {}).get("message")+ # ValueError: not JSON. AttributeError/TypeError: JSON, but not+ # the object shape we index into. Anything else is our bug, and+ # masking it as "API text" would hide it.+ except (ValueError, AttributeError, TypeError):+ detail = None++ if detail:+ # Bounded like the raw-body log below: this string becomes a+ # persisted block output, and a multi-KB message from Link or+ # an intercepting gateway has no business there either.+ raise RuntimeError(+ f"Link API error ({response.status_code}): "+ f"{str(detail)[:MAX_ERROR_DETAIL_CHARS]}"+ )++ # No usable message. The raw body goes to the logs rather than+ # into the exception, because that string becomes a block `error`+ # output — persisted with the execution and surfaced in agent+ # transcripts — and an arbitrary upstream body has no business+ # there.+ logger.error(+ "Link API %s %s failed: %s %s",+ method,+ path,+ response.status_code,+ response.text[:500],+ )+ raise RuntimeError(f"Link API error ({response.status_code})")+return response.json()diff --git a/autogpt_platform/backend/backend/blocks/stripe_link/spend_request.py b/autogpt_platform/backend/backend/blocks/stripe_link/spend_request.pyindex d661a677ba..e21f723318 100644--- a/autogpt_platform/backend/backend/blocks/stripe_link/spend_request.py+++ b/autogpt_platform/backend/backend/blocks/stripe_link/spend_request.py@@ -9,8 +9,9 @@ card or shared payment token from the user's Link wallet.import loggingimport refrom typing import Any+from urllib.parse import quote-from pydantic import field_validator+from pydantic import field_validator, model_validatorfrom backend.blocks._base import (Block,@@ -97,6 +98,29 @@ def _project_payment_method(pm: dict[str, Any]) -> dict[str, Any]:# ---------------------------------------------------------------------------# Shared helpers# ---------------------------------------------------------------------------+# Only the token path sends a `credential_type`; the card path omits it and+# lets Link default. There is deliberately no CREDENTIAL_TYPE_CARD constant —+# it read as though the card request sends one, which invites someone to start+# sending a field Link does not expect.+CREDENTIAL_TYPE_SPT = "shared_payment_token"++# The key Link returns card data under — a response envelope, not a request+# value, and free to diverge from anything sent.+CARD_RESPONSE_KEY = "card"+++def _nested_dict(source: Any, *keys: str) -> dict[str, Any]:+ """Walk nested dict keys, yielding {} at the first non-dict.++ `.get(key, {})` only defaults when the key is *missing*, and Link sends+ explicit nulls — so a `None` mid-chain raises AttributeError.+ """+ current: Any = source+ for key in keys:+ if not isinstance(current, dict):+ return {}+ current = current.get(key)+ return current if isinstance(current, dict) else {}# ---------------------------------------------------------------------------@@ -195,8 +219,174 @@ class StripeLinkListPaymentMethodsBlock(Block):# ----------------------------------------------------------------------------# Block: Create Spend Request+# Presentation fields shared by both create blocks# ---------------------------------------------------------------------------+def _presentation_body(input_data: "_BaseSpendRequestInput") -> dict[str, Any]:+ """Approval-sheet fields common to both spend-request types.++ Each is omitted when empty rather than sent as [] / {}: these drive how the+ request is presented to the user, and an explicit empty is not the same as+ "unspecified".+ """+ body: dict[str, Any] = {}+ if input_data.line_items:+ body["line_items"] = input_data.line_items+ if input_data.totals:+ body["totals"] = input_data.totals+ if input_data.metadata:+ body["metadata"] = input_data.metadata+ return body+++async def _create_spend_request(+ api_request: Any,+ credentials: StripeLinkCredentials,+ input_data: "_BaseSpendRequestInput",+ merchant_identity: dict[str, Any],+) -> dict[str, Any]:+ """POST a spend request, differing only in how the merchant is named.++ The base-schema rationale applies here too: leaving the two bodies+ copy-pasted means a field added later lands on one create block and not+ the other.+ """+ return await api_request(+ credentials,+ "POST",+ "/spend_requests",+ body={+ "payment_details": input_data.payment_method_id,+ **merchant_identity,+ "context": input_data.context,+ "amount": input_data.amount,+ "currency": input_data.currency,+ "request_approval": input_data.request_approval,+ "test": input_data.test_mode,+ **_presentation_body(input_data),+ },+ )+++# ---------------------------------------------------------------------------+# Block: Create Card Spend Request+# ---------------------------------------------------------------------------+# ---------------------------------------------------------------------------+# Shared spend-request schema+# ---------------------------------------------------------------------------+class _BaseSpendRequestInput(BlockSchemaInput):+ """Fields common to both spend-request types.++ The two create blocks differ only in how the merchant is identified — name+ and URL for a card, network ID for a Shared Payment Token. Everything else+ is the same request, so it lives here rather than being copied into each,+ where a later field would inevitably be added to only one of them.+ """++ credentials: StripeLinkCredentialsInput = StripeLinkCredentialsField()+ payment_method_id: str = SchemaField(+ description="ID of the payment method to use (from list payment methods)"+ )+ context: str = SchemaField(+ description=(+ "Description of the purchase context (min 100 characters). "+ "Shown to the user when they approve the request."+ ),+ # Enforced, not just documented: this is the text the user reads+ # when deciding whether to approve a charge.+ min_length=100,+ )+ amount: int = SchemaField(+ description=(+ "Amount in the currency's smallest unit — cents for USD, but "+ "whole units for zero-decimal currencies like JPY (max 50000)"+ ),+ ge=1,+ le=50000,+ )+ currency: str = SchemaField(description="3-letter ISO currency code", default="usd")+ request_approval: bool = SchemaField(+ description=(+ "If true, immediately sends a push notification to the user "+ "for approval. Otherwise, call request-approval separately."+ ),+ default=True,+ )+ test_mode: bool = SchemaField(+ description=(+ "Use Stripe test mode — no real money moves. A card request yields "+ "the 4242… test card; a token request yields a test token."+ ),+ default=False,+ )+ line_items: list[dict[str, Any]] = SchemaField(+ description=(+ "Itemised breakdown shown to the user on the approval sheet. "+ "Each item takes `name` (required) plus optional `quantity`, "+ "`unit_amount`, `description`, `sku`, `url`, `image_url` and "+ "`product_url`."+ ),+ default_factory=list,+ advanced=True,+ )+ totals: list[dict[str, Any]] = SchemaField(+ description=(+ "Total lines shown on the approval sheet. Each takes `type`, "+ "`display_text` and `amount`. `type` is one of: subtotal, tax, "+ "total, items_base_amount, items_discount, discount, "+ "fulfillment, shipping, fee, gift_wrap, tip, store_credit."+ ),+ default_factory=list,+ advanced=True,+ )+ metadata: dict[str, str] = SchemaField(+ description=(+ "Arbitrary key/value data stored on the spend request. Max 50 "+ "keys; keys <= 40 chars, values <= 500 chars."+ ),+ default_factory=dict,+ advanced=True,+ )++ @model_validator(mode="after")+ def _totals_must_match_the_authorized_amount(self):+ """The approval sheet is the only aggregate control in this flow.++ `line_items` and `totals` are agent-supplied and rendered to the user+ verbatim, so an untrusted upstream node could show a "total" of $4.99+ while the credential issued is for `amount`. Nothing else caps+ spending, so the headline the user reads has to be the number they are+ actually authorizing.+ """+ for entry in self.totals:+ if not isinstance(entry, dict) or entry.get("type") != "total":+ continue+ stated = entry.get("amount")+ if stated is not None and stated != self.amount:+ raise ValueError(+ f"totals entry of type 'total' is {stated} but the spend "+ f"request authorizes {self.amount}; the approval sheet must "+ "show the amount actually being authorized"+ )+ return self+++class _SpendRequestCreatedOutput(BlockSchemaOutput):+ """What creating a spend request returns, for either credential type."""++ spend_request_id: str = SchemaField(description="ID of the created spend request")+ status: str = SchemaField(+ description="Status: created, pending_approval, approved, denied, etc."+ )+ approval_url: str = SchemaField(+ description="URL the user can visit to approve (if not using push)",+ default="",+ )+ error: str = SchemaField(+ description="Error message if the request failed",+ default="",+ )++class StripeLinkCreateCardSpendRequestBlock(Block):"""Create a spend request for a one-time-use virtual card.@@ -212,70 +402,22 @@ class StripeLinkCreateCardSpendRequestBlock(Block):# only replaces names it can find on the block instance._link_api_request = staticmethod(link_api_request)- class Input(BlockSchemaInput):- credentials: StripeLinkCredentialsInput = StripeLinkCredentialsField()- payment_method_id: str = SchemaField(- description="ID of the payment method to use (from list payment methods)"- )+ class Input(_BaseSpendRequestInput):merchant_name: str = SchemaField(- description="Name of the merchant for this purchase"+ description="Name of the merchant, shown on the approval sheet.")merchant_url: str = SchemaField(description="URL of the merchant website")- context: str = SchemaField(- description=(- "Description of the purchase context (min 100 characters). "- "Shown to the user when they approve the request."- ),- # Enforced, not just documented: this is the text the user reads- # when deciding whether to approve a charge.- min_length=100,- )- amount: int = SchemaField(- description=(- "Amount in the currency's smallest unit — cents for USD, but "- "whole units for zero-decimal currencies like JPY (max 50000)"- ),- ge=1,- le=50000,- )- currency: str = SchemaField(- description="3-letter ISO currency code", default="usd"- )- request_approval: bool = SchemaField(- description=(- "If true, immediately sends a push notification to the user "- "for approval. Otherwise, call request-approval separately."- ),- default=True,- )- test_mode: bool = SchemaField(- description="Use test mode (fake card 4242424242424242)",- default=False,- )- class Output(BlockSchemaOutput):- spend_request_id: str = SchemaField(- description="ID of the created spend request"- )- status: str = SchemaField(- description="Status: created, pending_approval, approved, denied, etc."- )- approval_url: str = SchemaField(- description="URL the user can visit to approve (if not using push)",- default="",- )- error: str = SchemaField(- description="Error message if the request failed",- default="",- )+ class Output(_SpendRequestCreatedOutput):+ passdef __init__(self):super().__init__(id="932c3c12-1e80-4392-8fb3-37824eb8a427",description=("Create a Stripe Link spend request for a one-time virtual "- "card. Self-hosted only; on AutoGPT Cloud use the Shared "- "Payment Token flow with the MPP blocks instead."+ "card. Self-hosted only; on AutoGPT Cloud use Create Token "+ "Spend Request with the MPP blocks instead."),categories={BlockCategory.DATA},disabled=CARD_FLOW_DISABLED,@@ -311,19 +453,13 @@ class StripeLinkCreateCardSpendRequestBlock(Block):**kwargs: Any,) -> BlockOutput:try:- result = await self._link_api_request(+ result = await _create_spend_request(+ self._link_api_request,credentials,- "POST",- "/spend_requests",- body={- "payment_details": input_data.payment_method_id,+ input_data,+ {"merchant_name": input_data.merchant_name,"merchant_url": input_data.merchant_url,- "context": input_data.context,- "amount": input_data.amount,- "currency": input_data.currency,- "request_approval": input_data.request_approval,- "test": input_data.test_mode,},)# Note: do NOT also call POST /spend_requests/{id}/request_approval@@ -339,6 +475,115 @@ class StripeLinkCreateCardSpendRequestBlock(Block):yield "error", str(e)+# ---------------------------------------------------------------------------+# Block: Create Token Spend Request+# ---------------------------------------------------------------------------+class StripeLinkCreateTokenSpendRequestBlock(Block):+ """+ Create a spend request for a Shared Payment Token.++ The SPT authorises a charge at a merchant speaking the Machine Payments+ Protocol (HTTP 402). The merchant is identified by `network_id` from its+ 402 challenge rather than by name and URL — Link rejects merchant_name and+ merchant_url outright for this credential type.++ Available on every deployment: an SPT is a token rather than a card+ number, and `StripeLinkMPPPayBlock` consumes it in-process without ever+ emitting it.+ """++ # Exposed as a class attribute so `test_mock` can patch it; the harness+ # only replaces names it can find on the block instance.+ _link_api_request = staticmethod(link_api_request)++ class Input(_BaseSpendRequestInput):+ network_id: str = SchemaField(+ description=(+ "Merchant network ID, read from the merchant's HTTP 402 "+ "`WWW-Authenticate: Payment` challenge — see the Get Payment "+ "Challenge block. This identifies the merchant in place of "+ "merchant_name/merchant_url."+ ),+ min_length=1,+ )++ @field_validator("network_id")+ @classmethod+ def _network_id_must_not_be_blank(cls, value: str) -> str:+ """`min_length=1` accepts " ".++ Without a real network ID Link receives a request with no merchant+ identity at all and fails obscurely, so catch it at the boundary.+ A trim guard existed before the block split removed the cross-field+ validator it lived on.+ """+ if not value.strip():+ raise ValueError(+ "network_id is required — read it from the merchant's HTTP "+ "402 challenge (see the Get Payment Challenge block)"+ )+ return value++ class Output(_SpendRequestCreatedOutput):+ pass++ def __init__(self):+ super().__init__(+ id="b12877be-06cd-4a96-bf79-438bb4cb5517",+ description=(+ "MPP step 2 of 3: create a Stripe Link spend request for a "+ "Shared Payment Token, using the network ID from the "+ "merchant's 402 challenge. Step 3 is MPP Pay."+ ),+ categories={BlockCategory.DATA},+ input_schema=self.Input,+ output_schema=self.Output,+ test_input={+ "credentials": TEST_CREDENTIALS_INPUT,+ "payment_method_id": "csmrpd_test",+ "network_id": "profile_test",+ "context": "x" * 100,+ "amount": 1000,+ },+ test_credentials=TEST_CREDENTIALS,+ test_output=[+ ("spend_request_id", "lsrq_test123"),+ ("status", "pending_approval"),+ ],+ test_mock={+ "_link_api_request": lambda *args, **kwargs: {+ "id": "lsrq_test123",+ "status": "pending_approval",+ "approval_url": "",+ }+ },+ )++ async def run(+ self,+ input_data: Input,+ *,+ credentials: StripeLinkCredentials,+ **kwargs: Any,+ ) -> BlockOutput:+ try:+ result = await _create_spend_request(+ self._link_api_request,+ credentials,+ input_data,+ {+ "credential_type": CREDENTIAL_TYPE_SPT,+ "network_id": input_data.network_id.strip(),+ },+ )+ yield "spend_request_id", result["id"]+ yield "status", result["status"]+ if result.get("approval_url"):+ yield "approval_url", result["approval_url"]+ except Exception as e:+ yield "error", str(e)++# ---------------------------------------------------------------------------# Block: Get Spend Request Status# ---------------------------------------------------------------------------@@ -348,8 +593,12 @@ class StripeLinkGetSpendRequestStatusBlock(Block):Every flow needs this step — a freshly created request is`pending_approval` until the user acts in the Link app, and both the card- and MPP paths must wait for `approved` before they can do anything. It- carries no payment credential, so it runs on every deployment.+ and MPP paths must wait for `approved` before they can spend. It carries+ no payment credential, so it runs on every deployment.++ It also reports `requires_action`, which is neither success nor failure:+ the card or account needs attention (typically 3D Secure) before approval+ can proceed."""# Exposed as a class attribute so `test_mock` can patch it; the harness@@ -367,10 +616,34 @@ class StripeLinkGetSpendRequestStatusBlock(Block):class Output(BlockSchemaOutput):status: str = SchemaField(description=(- "Current status: pending_approval, approved, denied, expired. "- "Wait for `approved` before spending the credential."+ "Current status: pending_approval, requires_action, approved, "+ "denied, expired. Wait for `approved` before spending."))+ next_action_type: str = SchemaField(+ description=(+ "Set when status is `requires_action`: what the user must "+ "resolve before approval can proceed, e.g. a 3D Secure "+ "challenge. Empty otherwise."+ ),+ default="",+ )+ next_action_message: str = SchemaField(+ description="Human-readable explanation of the required action",+ default="",+ )+ next_action_url: str = SchemaField(+ description="Where the user resolves the required action",+ default="",+ )+ auto_resumes: bool = SchemaField(+ description=(+ "True when the request clears itself once the action is done "+ "(3D Secure), so keep polling. False means it needs a fresh "+ "spend request."+ ),+ default=False,+ )error: str = SchemaField(description="Error message if the request failed",default="",@@ -408,9 +681,31 @@ class StripeLinkGetSpendRequestStatusBlock(Block):result = await self._link_api_request(credentials,"GET",- f"/spend_requests/{input_data.spend_request_id}",+ f"/spend_requests/{quote(input_data.spend_request_id, safe='')}",)- yield "status", result["status"]++ status = result["status"]+ yield "status", status++ # For 3D Secure the resolution is `auto_resume` and the request+ # clears itself, so the caller should keep polling rather than give+ # up; anything else needs a fresh request.+ if status == "requires_action":+ action = _nested_dict(+ result, "status_details", "requires_action", "next_action"+ )+ # `or ""`, not `get(..., "")`: Link sends explicit nulls, and+ # a None yielded into a str-typed output fails the output+ # jsonschema check *outside* this try, hard-failing the node+ # after `status` was already emitted.+ yield "next_action_type", action.get("type") or ""+ yield "next_action_message", action.get("display_message") or ""+ yield "next_action_url", action.get("action_url") or ""+ # Unknown or missing resolution keeps the caller polling. The+ # unsafe direction is "needs a fresh request": the agent makes+ # a second spend request, the first auto-resumes, and the user+ # can end up approving two credentials for one purchase.+ yield "auto_resumes", action.get("resolution") != "new_spend_request"except Exception as e:yield "error", str(e)@@ -546,7 +841,7 @@ class StripeLinkRetrieveCardBlock(Block):result = await self._link_api_request(credentials,"GET",- f"/spend_requests/{input_data.spend_request_id}?include=card",+ f"/spend_requests/{quote(input_data.spend_request_id, safe='')}?include=card",)status = result["status"]@@ -566,7 +861,7 @@ class StripeLinkRetrieveCardBlock(Block):)return- card = result.get("card")+ card = _nested_dict(result, CARD_RESPONSE_KEY)if card:yield "card_number", card.get("number", "")yield "card_cvc", card.get("cvc", "")diff --git a/autogpt_platform/backend/backend/blocks/stripe_link/spend_request_test.py b/autogpt_platform/backend/backend/blocks/stripe_link/spend_request_test.pyindex 5cd1c6b357..ca47e35d5e 100644--- a/autogpt_platform/backend/backend/blocks/stripe_link/spend_request_test.py+++ b/autogpt_platform/backend/backend/blocks/stripe_link/spend_request_test.py@@ -1,28 +1,38 @@-"""Deployment gating for the Stripe Link spend-request blocks.+"""Spend-request block behaviour, and the deployment gate on the card flow.The virtual-card flow is self-hosted only: block outputs are persisted withthe execution and surface into AutoPilot transcripts, so a PAN there iscardholder data at rest and a stored CVC is prohibited outright. The blocks-are split along that line — card create/retrieve are gated, while the pieces-the Shared Payment Token flow needs stay available everywhere.+are split along that line — card create/retrieve are gated, while everything+the Shared Payment Token flow needs stays available on every deployment."""+from typing import Any++import httpximport pytestfrom pydantic import ValidationError+from backend.blocks.stripe_link import _authfrom backend.blocks.stripe_link import spend_request as srfrom backend.blocks.stripe_link._auth import TEST_CREDENTIALS, TEST_CREDENTIALS_INPUT+CONTEXT = "x" * 100+CARD_BLOCKS = (sr.StripeLinkCreateCardSpendRequestBlock,sr.StripeLinkRetrieveCardBlock,)ALWAYS_AVAILABLE_BLOCKS = (sr.StripeLinkListPaymentMethodsBlock,+ sr.StripeLinkCreateTokenSpendRequestBlock,sr.StripeLinkGetSpendRequestStatusBlock,)+# ---------------------------------------------------------------------------+# Deployment gating+# ---------------------------------------------------------------------------def test_card_blocks_are_unavailable_on_cloud(monkeypatch):monkeypatch.setattr(sr, "CARD_FLOW_DISABLED", True)@@ -37,12 +47,12 @@ def test_card_blocks_are_available_when_self_hosted(monkeypatch):assert block_cls().disabled is False, block_cls.__name__-def test_the_spt_flow_survives_on_cloud(monkeypatch):+def test_the_token_flow_survives_on_cloud(monkeypatch):"""Gating the card flow must not take the token flow with it.Creating a spend request is pointless unless something can wait for the- user to approve it, so the status poll has to remain available even where- no card may be issued.+ user to approve it, so both the token create and the status poll have to+ remain available where no card may be issued."""monkeypatch.setattr(sr, "CARD_FLOW_DISABLED", True)@@ -50,23 +60,106 @@ def test_the_spt_flow_survives_on_cloud(monkeypatch):assert block_cls().disabled is False, block_cls.__name__-async def test_the_status_block_cannot_pull_card_data():- """It is the one spend-request block reachable on Cloud, so it must have- no way to ask Link for a card in the first place."""+def test_the_two_create_blocks_differ_only_in_merchant_identity():+ """They are the same request with a different way of naming the merchant.++ The split exists to make the card flow separately gateable, not to fork+ the schema — so everything except merchant identity has to come from the+ shared base, or a field added later lands on only one of them.+ """+ card = set(sr.StripeLinkCreateCardSpendRequestBlock().input_schema.model_fields)+ token = set(sr.StripeLinkCreateTokenSpendRequestBlock().input_schema.model_fields)++ assert card - token == {"merchant_name", "merchant_url"}+ assert token - card == {"network_id"}+ # Declared on the base, not copied into each block.+ assert card & token <= set(sr._BaseSpendRequestInput.model_fields)+++# ---------------------------------------------------------------------------+# Harness+# ---------------------------------------------------------------------------+def _capturing(block, payload: dict):+ """Patch the block's API seam, recording what was sent."""seen: dict = {}- block = sr.StripeLinkGetSpendRequestStatusBlock()async def _fake(credentials, method, path, body=None):+ seen["method"] = methodseen["path"] = path- return {"status": "approved", "card": {"number": "4242424242424242"}}+ seen["body"] = body+ return payloadobject.__setattr__(block, "_link_api_request", _fake)- inp = block.Input.model_validate(- {"credentials": TEST_CREDENTIALS_INPUT, "spend_request_id": "lsrq_test"}- )+ return seen++async def _run(block, inputs: dict, payload: dict) -> tuple[dict, dict]:+ seen = _capturing(block, payload)+ inp = block.Input.model_validate({"credentials": TEST_CREDENTIALS_INPUT, **inputs})outputs = {n: v async for n, v in block.run(inp, credentials=TEST_CREDENTIALS)}+ return outputs, seen+++CREATED = {"id": "lsrq_test", "status": "pending_approval"}+++async def run_create_card(**overrides) -> dict:+ _, seen = await _run(+ sr.StripeLinkCreateCardSpendRequestBlock(),+ {+ "payment_method_id": "csmrpd_test",+ "merchant_name": "Test Merchant",+ "merchant_url": "https://example.com",+ "context": CONTEXT,+ "amount": 1000,+ **overrides,+ },+ CREATED,+ )+ return seen["body"]+++async def run_create_token(**overrides) -> dict:+ _, seen = await _run(+ sr.StripeLinkCreateTokenSpendRequestBlock(),+ {+ "payment_method_id": "csmrpd_test",+ "network_id": "profile_test",+ "context": CONTEXT,+ "amount": 1000,+ **overrides,+ },+ CREATED,+ )+ return seen["body"]+++async def run_status(payload: dict) -> tuple[dict, dict]:+ return await _run(+ sr.StripeLinkGetSpendRequestStatusBlock(),+ {"spend_request_id": "lsrq_test"},+ payload,+ )+++async def run_card(payload: dict) -> tuple[dict, dict]:+ return await _run(+ sr.StripeLinkRetrieveCardBlock(),+ {"spend_request_id": "lsrq_test"},+ payload,+ )+++# ---------------------------------------------------------------------------+# Card vs status separation+# ---------------------------------------------------------------------------+async def test_the_status_block_cannot_pull_card_data():+ """It is the one spend-request read reachable on Cloud, so it must have no+ way to ask Link for a card in the first place."""+ outputs, seen = await run_status(+ {"status": "approved", "card": {"number": "4242424242424242"}}+ )assert "include" not in seen["path"]assert outputs["status"] == "approved"@@ -76,28 +169,279 @@ async def test_the_status_block_cannot_pull_card_data():@pytest.mark.asyncioasync def test_the_card_block_asks_for_the_card_without_an_opt_in():- """Availability is the control now, so there is no include_card flag to- forget to set."""- seen: dict = {}- block = sr.StripeLinkRetrieveCardBlock()-- async def _fake(credentials, method, path, body=None):- seen["path"] = path- return {+ """Availability is the control now, so there is no flag to forget."""+ outputs, seen = await run_card(+ {"status": "approved",- "card": {"number": "4242424242424242", "cvc": "123"},+ "card": {+ "number": "4242424242424242",+ "cvc": "123",+ "exp_month": 12,+ "exp_year": 2030,+ },}-- object.__setattr__(block, "_link_api_request", _fake)- inp = block.Input.model_validate(- {"credentials": TEST_CREDENTIALS_INPUT, "spend_request_id": "lsrq_test"})- outputs = {n: v async for n, v in block.run(inp, credentials=TEST_CREDENTIALS)}-assert "include=card" in seen["path"]assert outputs["card_number"] == "4242424242424242"assert outputs["card_cvc"] == "123"+ assert outputs["card_exp_month"] == 12+ assert outputs["card_exp_year"] == 2030+++async def test_a_non_object_card_does_not_crash_the_card_block():+ for payload_value in ("4242424242424242", None, []):+ outputs, _ = await run_card({"status": "approved", "card": payload_value})+ assert outputs["status"] == "approved"+ assert "error" not in outputs+ assert not outputs.get("card_number")+++# ---------------------------------------------------------------------------+# Create: card vs token+# ---------------------------------------------------------------------------+async def test_the_card_request_identifies_the_merchant_by_name_and_url():+ body = await run_create_card()++ assert body["merchant_name"] == "Test Merchant"+ assert body["merchant_url"] == "https://example.com"+ # Card is the default credential type; sending it explicitly is noise.+ assert "credential_type" not in body+ assert "network_id" not in body+++async def test_the_token_request_identifies_the_merchant_by_network_id():+ """Link rejects merchant_name/merchant_url outright for an SPT — the+ merchant comes from the 402 challenge's network ID instead."""+ body = await run_create_token()++ assert body["credential_type"] == sr.CREDENTIAL_TYPE_SPT+ assert body["network_id"] == "profile_test"+ assert "merchant_name" not in body+ assert "merchant_url" not in body+++async def test_a_token_request_without_a_network_id_is_rejected():+ """Otherwise Link gets a request with no merchant identity at all."""+ with pytest.raises(ValidationError):+ await run_create_token(network_id="")+++async def test_a_card_request_without_a_merchant_is_rejected():+ with pytest.raises(ValidationError):+ await run_create_card(merchant_name=None)+++async def test_context_below_the_minimum_is_rejected():+ """This is the text the user reads when approving a charge."""+ with pytest.raises(ValidationError):+ await run_create_card(context="too short")+++async def test_presentation_fields_are_omitted_when_unset():+ """An explicit empty is not the same as unspecified to the approval sheet."""+ for body in (await run_create_card(), await run_create_token()):+ assert "line_items" not in body+ assert "totals" not in body+ assert "metadata" not in body+++async def test_line_items_and_totals_reach_both_request_types():+ line_items = [{"name": "Widget", "quantity": 2, "unit_amount": 500}]+ totals = [{"type": "total", "display_text": "Total", "amount": 1000}]++ for body in (+ await run_create_card(line_items=line_items, totals=totals),+ await run_create_token(line_items=line_items, totals=totals),+ ):+ assert body["line_items"] == line_items+ assert body["totals"] == totals+++# ---------------------------------------------------------------------------+# 3D Secure, reported by the status block+# ---------------------------------------------------------------------------+async def test_three_d_secure_is_reported_as_resumable():+ """3DS clears itself, so the caller must keep polling rather than start over."""+ outputs, _ = await run_status(+ {+ "status": "requires_action",+ "status_details": {+ "requires_action": {+ "next_action": {+ "type": "three_d_secure",+ "display_message": "Confirm this payment with your bank",+ "action_url": "https://app.link.com/3ds/abc",+ "resolution": "auto_resume",+ }+ }+ },+ }+ )++ assert outputs["next_action_type"] == "three_d_secure"+ assert outputs["next_action_message"] == "Confirm this payment with your bank"+ assert outputs["next_action_url"] == "https://app.link.com/3ds/abc"+ assert outputs["auto_resumes"] is True+++async def test_non_resumable_action_is_flagged_as_such():+ outputs, _ = await run_status(+ {+ "status": "requires_action",+ "status_details": {+ "requires_action": {+ "next_action": {+ "type": "update_payment_method",+ "resolution": "new_spend_request",+ }+ }+ },+ }+ )++ assert outputs["auto_resumes"] is False+++async def test_a_null_status_details_does_not_break_requires_action():+ """`.get(key, {})` only defaults when the key is *missing*.++ An explicit null used to raise mid-chain, after `status` had already been+ yielded — so the block emitted a partial result and then errored.+ """+ outputs, _ = await run_status({"status": "requires_action", "status_details": None})++ assert outputs["status"] == "requires_action"+ assert outputs["next_action_type"] == ""+ assert "error" not in outputs+++async def test_an_approved_request_emits_no_action_fields():+ outputs, _ = await run_status({"status": "approved"})++ assert outputs["status"] == "approved"+ assert "next_action_type" not in outputs+++# ---------------------------------------------------------------------------+# Error surfacing+# ---------------------------------------------------------------------------+class _Resp:+ def __init__(self, payload: Any, text: str = "", status_code: int = 400):+ self.status_code = status_code+ self.is_error = status_code >= 400+ self.is_success = 200 <= status_code < 300+ self._payload = payload+ self.text = text++ def json(self):+ if self._payload is None:+ raise ValueError("not json")+ return self._payload+++async def test_link_error_message_is_surfaced_not_swallowed(monkeypatch):+ """`raise_for_status()` alone reports "400 Bad Request" and discards the+ explanation, which is how the SPT merchant-field constraint stayed hidden."""++ class _Client:+ async def __aenter__(self):+ return self++ async def __aexit__(self, *a):+ return False++ async def request(self, **kwargs):+ return _Resp({"error": {"message": "merchant_name is not allowed"}})++ monkeypatch.setattr(httpx, "AsyncClient", lambda *a, **kw: _Client())++ with pytest.raises(Exception, match="merchant_name is not allowed"):+ await sr.link_api_request(TEST_CREDENTIALS, "POST", "/spend_requests", {})+++async def test_link_error_falls_back_when_the_body_is_not_json(monkeypatch):+ class _Client:+ async def __aenter__(self):+ return self++ async def __aexit__(self, *a):+ return False++ async def request(self, **kwargs):+ return _Resp(None, text="<html>gateway timeout</html>")++ monkeypatch.setattr(httpx, "AsyncClient", lambda *a, **kw: _Client())++ with pytest.raises(Exception, match="400"):+ await sr.link_api_request(TEST_CREDENTIALS, "GET", "/spend_requests/x")+++async def test_metadata_reaches_the_request_body():+ """Only ever asserted for omission, so a wrong key name would pass."""+ meta = {"order_ref": "AG-123", "graph": "checkout"}++ for body in (+ await run_create_card(metadata=meta),+ await run_create_token(metadata=meta),+ ):+ assert body["metadata"] == meta+++async def test_a_whitespace_only_network_id_is_rejected():+ """`min_length=1` accepts " ".++ Link then gets a request with no merchant identity and fails obscurely.+ A trim guard existed before the block split removed the cross-field+ validator it lived on.+ """+ with pytest.raises(ValidationError, match="network_id"):+ await run_create_token(network_id=" ")+++async def test_a_wrong_shaped_error_body_falls_back_without_raising(monkeypatch):+ """The `except (ValueError, AttributeError, TypeError)` exists for bodies+ like {"error": "string"} / {"error": null}; only the non-JSON and+ well-formed shapes were covered."""++ for payload in ({"error": "just a string"}, {"error": None}, {"nope": 1}):++ class _Client:+ async def __aenter__(self):+ return self++ async def __aexit__(self, *a):+ return False++ async def request(self, **kwargs):+ return _Resp(payload, text="raw upstream body")++ monkeypatch.setattr(httpx, "AsyncClient", lambda *a, **kw: _Client())++ with pytest.raises(RuntimeError) as exc:+ await _auth.link_api_request(TEST_CREDENTIALS, "GET", "/spend_requests/x")++ # Falls back to the status code, and does not carry the raw body into+ # a string that becomes a persisted block output.+ assert "400" in str(exc.value)+ assert "raw upstream body" not in str(exc.value)def test_the_card_gate_predicate_itself_tracks_behave_as(monkeypatch):@@ -159,6 +503,115 @@ async def test_listed_payment_methods_are_projected_to_known_fields():@pytest.mark.asyncio+async def test_a_redirect_is_an_error_not_an_empty_result(monkeypatch):+ """`is_error` is 4xx/5xx only, and redirects are not followed.++ Treating a 3xx as success let it fall through to `.json()`: a moved+ endpoint would read as an empty wallet from list-payment-methods, or raise+ a bare KeyError from create, with the redirect invisible either way.+ """++ class _Client:+ async def __aenter__(self):+ return self++ async def __aexit__(self, *a):+ return False++ async def request(self, **kwargs):+ return _Resp(None, text="moved", status_code=308)++ monkeypatch.setattr(httpx, "AsyncClient", lambda *a, **kw: _Client())++ with pytest.raises(RuntimeError, match="308"):+ await _auth.link_api_request(TEST_CREDENTIALS, "GET", "/payment-details")+++async def test_an_unbounded_upstream_message_is_truncated(monkeypatch):+ """`error.message` becomes a persisted block output, same as the raw body+ the adjacent path already caps."""++ class _Client:+ async def __aenter__(self):+ return self++ async def __aexit__(self, *a):+ return False++ async def request(self, **kwargs):+ return _Resp({"error": {"message": "x" * 20_000}})++ monkeypatch.setattr(httpx, "AsyncClient", lambda *a, **kw: _Client())++ with pytest.raises(RuntimeError) as exc:+ await _auth.link_api_request(TEST_CREDENTIALS, "GET", "/spend_requests/x")++ assert len(str(exc.value)) < 1000+++async def test_a_total_that_misstates_the_amount_is_rejected():+ """The approval sheet is the only aggregate control, and it is+ agent-supplied — so the headline must be the amount authorized."""+ with pytest.raises(ValidationError, match="approval sheet"):+ await run_create_card(+ amount=50000,+ totals=[{"type": "total", "display_text": "Total", "amount": 499}],+ )++ # A matching total, and non-total lines, are untouched.+ body = await run_create_card(+ amount=1000,+ totals=[+ {"type": "subtotal", "display_text": "Sub", "amount": 900},+ {"type": "total", "display_text": "Total", "amount": 1000},+ ],+ )+ assert len(body["totals"]) == 2+++async def test_null_action_fields_do_not_hard_fail_the_node():+ """A None yielded into a str-typed output fails the output jsonschema+ check outside the block's try, killing the node after `status`."""+ outputs, _ = await run_status(+ {+ "status": "requires_action",+ "status_details": {+ "requires_action": {+ "next_action": {+ "type": None,+ "display_message": None,+ "action_url": None,+ }+ }+ },+ }+ )++ assert outputs["next_action_type"] == ""+ assert outputs["next_action_url"] == ""+ assert "error" not in outputs+++async def test_an_unknown_resolution_keeps_the_caller_polling():+ """Failing to `auto_resumes=False` is the unsafe direction: the agent+ creates a second spend request, the first auto-resumes, and the user can+ approve two credentials for one purchase."""+ outputs, _ = await run_status(+ {+ "status": "requires_action",+ "status_details": {+ "requires_action": {"next_action": {"resolution": "something_new"}}+ },+ }+ )++ assert outputs["auto_resumes"] is True++async def test_a_denied_request_emits_no_card_and_says_so():"""Inverting the status guard left the suite green: nothing asserted thenegative. A refused spend must not put a PAN in the execution record, anddiff --git a/autogpt_platform/backend/backend/integrations/oauth/stripe_link.py b/autogpt_platform/backend/backend/integrations/oauth/stripe_link.pyindex 16fb2ebe2c..cc60aa0cb5 100644--- a/autogpt_platform/backend/backend/integrations/oauth/stripe_link.py+++ b/autogpt_platform/backend/backend/integrations/oauth/stripe_link.py@@ -36,6 +36,33 @@ LINK_CLIENT_ID = "lwlpk_U7Qy7ThG69STZk"LINK_CLIENT_NAME = "AutoGPT"+# Link truncates `connection_label` at 32 characters, and the label is the+# headline of the approval sheet ("<label> is requesting to spend $X"), so an+# overlong host renders as e.g. "AutoGPT on prompt-neat-flea.ngro".+CONNECTION_LABEL_MAX_LEN = 32+++def _connection_label(platform_host: str) -> str:+ """Build the approval-sheet label, dropping the host if it will not fit."""+ if not platform_host:+ return LINK_CLIENT_NAME+ label = f"{LINK_CLIENT_NAME} on {platform_host}"+ if len(label) <= CONNECTION_LABEL_MAX_LEN:+ return label++ # A truncated host is worse than none: better a clean "AutoGPT" than+ # "AutoGPT on prompt-neat-flea.ngro".+ #+ # Falling back to the last two labels was tried and reverted. It reads well+ # for a corporate host (agpt.internal.mycompany.example -> mycompany.example)+ # but not for shared hosting: prompt-neat-flea.ngrok-free.app becomes+ # "AutoGPT on ngrok-free.app", which every ngrok user would also see. On the+ # sheet where someone decides whether to hand over money, a label that+ # implies an identity it does not carry is worse than a generic one, and+ # telling the two cases apart needs a public suffix list.+ return LINK_CLIENT_NAME++class StripeLinkDeviceAuthHandler(BaseDeviceAuthHandler):"""Device code handler for Stripe Link."""@@ -61,11 +88,7 @@ class StripeLinkDeviceAuthHandler(BaseDeviceAuthHandler):# container ID the user has never seen — the platform they are actually# connecting to is the useful half.platform_host = urlparse(app_config.platform_base_url or "").netloc- connection_label = (- f"{LINK_CLIENT_NAME} on {platform_host}"- if platform_host- else LINK_CLIENT_NAME- )+ connection_label = _connection_label(platform_host)# RFC 9396 rich authorization details. Link gates its read endpoints# (/balances, /transactions, /sources) on these source actions beingdiff --git a/autogpt_platform/backend/backend/integrations/oauth/stripe_link_test.py b/autogpt_platform/backend/backend/integrations/oauth/stripe_link_test.pyindex 6d0eb1cea0..fb3c50949b 100644--- a/autogpt_platform/backend/backend/integrations/oauth/stripe_link_test.py+++ b/autogpt_platform/backend/backend/integrations/oauth/stripe_link_test.py@@ -200,3 +200,24 @@ async def test_credentials_manager_resolves_the_device_handler():handler = await IntegrationCredentialsManager()._get_oauth_handler(credentials())assert isinstance(handler, StripeLinkDeviceAuthHandler)+++ "host, expected",+ [+ ("platform.agpt.co", "AutoGPT on platform.agpt.co"),+ # Link truncates at 32 chars, and this is the approval sheet's headline —+ # a clean name beats "AutoGPT on prompt-neat-flea.ngro".+ ("prompt-neat-flea.ngrok-free.app", "AutoGPT"),+ ("", "AutoGPT"),+ ],+)+def test_connection_label_never_exceeds_links_limit(host, expected):+ from backend.integrations.oauth.stripe_link import (+ CONNECTION_LABEL_MAX_LEN,+ _connection_label,+ )++ label = _connection_label(host)+ assert label == expected+ assert len(label) <= CONNECTION_LABEL_MAX_LENdiff --git a/docs/integrations/README.md b/docs/integrations/README.mdindex 0f4f841598..376b8173b2 100644--- a/docs/integrations/README.md+++ b/docs/integrations/README.md@@ -186,6 +186,7 @@ Below is a comprehensive list of all available blocks, categorized by their prim| [SQL Query](block-integrations/data.md#sql-query) | Execute a SQL query || [Screenshot Web Page](block-integrations/data.md#screenshot-web-page) | Takes a screenshot of a specified website using ScreenshotOne API || [Stripe Link Create Card Spend Request](block-integrations/stripe_link/spend_request.md#stripe-link-create-card-spend-request) | Create a Stripe Link spend request for a one-time virtual card |+| [Stripe Link Create Token Spend Request](block-integrations/stripe_link/spend_request.md#stripe-link-create-token-spend-request) | MPP step 2 of 3: create a Stripe Link spend request for a Shared Payment Token, using the network ID from the merchant's 402 challenge || [Stripe Link Get Shipping Address](block-integrations/stripe_link/profile.md#stripe-link-get-shipping-address) | Get the delivery addresses saved on the user's Link wallet, with the default one resolved for you || [Stripe Link Get Spend Request Status](block-integrations/stripe_link/spend_request.md#stripe-link-get-spend-request-status) | Check whether a Stripe Link spend request has been approved yet || [Stripe Link Get User Info](block-integrations/stripe_link/profile.md#stripe-link-get-user-info) | Get the Link account holder's name, email and phone |diff --git a/docs/integrations/block-integrations/stripe_link/spend_request.md b/docs/integrations/block-integrations/stripe_link/spend_request.mdindex 738c9af9f0..3d0a0379a3 100644--- a/docs/integrations/block-integrations/stripe_link/spend_request.md+++ b/docs/integrations/block-integrations/stripe_link/spend_request.md@@ -6,7 +6,7 @@ _Add a description of this category of blocks._## Stripe Link Create Card Spend Request### What it is-Create a Stripe Link spend request for a one-time virtual card. Self-hosted only; on AutoGPT Cloud use the Shared Payment Token flow with the MPP blocks instead.+Create a Stripe Link spend request for a one-time virtual card. Self-hosted only; on AutoGPT Cloud use Create Token Spend Request with the MPP blocks instead.### How it works<!-- MANUAL: how_it_works -->@@ -18,13 +18,57 @@ _Add technical explanation here._| Input | Description | Type | Required ||-------|-------------|------|----------|| payment_method_id | ID of the payment method to use (from list payment methods) | str | Yes |-| merchant_name | Name of the merchant for this purchase | str | Yes |+| context | Description of the purchase context (min 100 characters). Shown to the user when they approve the request. | str | Yes |+| amount | Amount in the currency's smallest unit — cents for USD, but whole units for zero-decimal currencies like JPY (max 50000) | int | Yes |+| currency | 3-letter ISO currency code | str | No |+| request_approval | If true, immediately sends a push notification to the user for approval. Otherwise, call request-approval separately. | bool | No |+| test_mode | Use Stripe test mode — no real money moves. A card request yields the 4242… test card; a token request yields a test token. | bool | No |+| line_items | Itemised breakdown shown to the user on the approval sheet. Each item takes `name` (required) plus optional `quantity`, `unit_amount`, `description`, `sku`, `url`, `image_url` and `product_url`. | List[Dict[str, Any]] | No |+| totals | Total lines shown on the approval sheet. Each takes `type`, `display_text` and `amount`. `type` is one of: subtotal, tax, total, items_base_amount, items_discount, discount, fulfillment, shipping, fee, gift_wrap, tip, store_credit. | List[Dict[str, Any]] | No |+| metadata | Arbitrary key/value data stored on the spend request. Max 50 keys; keys <= 40 chars, values <= 500 chars. | Dict[str, str] | No |+| merchant_name | Name of the merchant, shown on the approval sheet. | str | Yes || merchant_url | URL of the merchant website | str | Yes |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the request failed | str |+| spend_request_id | ID of the created spend request | str |+| status | Status: created, pending_approval, approved, denied, etc. | str |+| approval_url | URL the user can visit to approve (if not using push) | str |++### Possible use case+<!-- MANUAL: use_case -->+_Add practical use case examples here._+<!-- END MANUAL -->++---++## Stripe Link Create Token Spend Request++### What it is+MPP step 2 of 3: create a Stripe Link spend request for a Shared Payment Token, using the network ID from the merchant's 402 challenge. Step 3 is MPP Pay.++### How it works+<!-- MANUAL: how_it_works -->+_Add technical explanation here._+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| payment_method_id | ID of the payment method to use (from list payment methods) | str | Yes || context | Description of the purchase context (min 100 characters). Shown to the user when they approve the request. | str | Yes || amount | Amount in the currency's smallest unit — cents for USD, but whole units for zero-decimal currencies like JPY (max 50000) | int | Yes || currency | 3-letter ISO currency code | str | No || request_approval | If true, immediately sends a push notification to the user for approval. Otherwise, call request-approval separately. | bool | No |-| test_mode | Use test mode (fake card 4242424242424242) | bool | No |+| test_mode | Use Stripe test mode — no real money moves. A card request yields the 4242… test card; a token request yields a test token. | bool | No |+| line_items | Itemised breakdown shown to the user on the approval sheet. Each item takes `name` (required) plus optional `quantity`, `unit_amount`, `description`, `sku`, `url`, `image_url` and `product_url`. | List[Dict[str, Any]] | No |+| totals | Total lines shown on the approval sheet. Each takes `type`, `display_text` and `amount`. `type` is one of: subtotal, tax, total, items_base_amount, items_discount, discount, fulfillment, shipping, fee, gift_wrap, tip, store_credit. | List[Dict[str, Any]] | No |+| metadata | Arbitrary key/value data stored on the spend request. Max 50 keys; keys <= 40 chars, values <= 500 chars. | Dict[str, str] | No |+| network_id | Merchant network ID, read from the merchant's HTTP 402 `WWW-Authenticate: Payment` challenge — see the Get Payment Challenge block. This identifies the merchant in place of merchant_name/merchant_url. | str | Yes |### Outputs@@ -63,7 +107,11 @@ _Add technical explanation here._| Output | Description | Type ||--------|-------------|------|| error | Error message if the request failed | str |-| status | Current status: pending_approval, approved, denied, expired. Wait for `approved` before spending the credential. | str |+| status | Current status: pending_approval, requires_action, approved, denied, expired. Wait for `approved` before spending. | str |+| next_action_type | Set when status is `requires_action`: what the user must resolve before approval can proceed, e.g. a 3D Secure challenge. Empty otherwise. | str |+| next_action_message | Human-readable explanation of the required action | str |+| next_action_url | Where the user resolves the required action | str |+| auto_resumes | True when the request clears itself once the action is done (3D Secure), so keep polling. False means it needs a fresh spend request. | bool |### Possible use case<!-- MANUAL: use_case -->