From f7333f95063c97054f843edd1aca96185ed59b79 Mon Sep 17 00:00:00 2001 From: William Prussak Macarini Date: Fri, 13 Nov 2026 14:38:00 -0300 Subject: [PATCH 1/2] fix(sdk): reject payment constraints without a type --- .../python/ap2/sdk/constraint_validation.py | 23 +++ .../ap2/sdk/generated/open_payment_mandate.py | 12 +- .../ap2/tests/constraint_parsing_tests.py | 178 ++++++++++++++++++ code/sdk/schemas/README.md | 8 +- code/sdk/schemas/generate.py | 23 ++- 5 files changed, 239 insertions(+), 5 deletions(-) create mode 100644 code/sdk/python/ap2/sdk/constraint_validation.py create mode 100644 code/sdk/python/ap2/tests/constraint_parsing_tests.py diff --git a/code/sdk/python/ap2/sdk/constraint_validation.py b/code/sdk/python/ap2/sdk/constraint_validation.py new file mode 100644 index 00000000..13683b61 --- /dev/null +++ b/code/sdk/python/ap2/sdk/constraint_validation.py @@ -0,0 +1,23 @@ +"""Validation of payment constraint payloads before generated model parsing.""" + +from collections.abc import Iterable, Mapping + +from pydantic import ValidationInfo + + +def require_payment_constraint_types( + value: object, _info: ValidationInfo +) -> object: + """Require explicit types before defaults hide unrecognized constraints.""" + if not isinstance(value, Iterable) or isinstance( + value, (str, bytes, bytearray, Mapping) + ): + return value + + constraints = list(value) + for constraint in constraints: + if isinstance(constraint, Mapping) and 'type' not in constraint: + raise ValueError( + 'Payment constraint objects must declare their type.' + ) + return constraints diff --git a/code/sdk/python/ap2/sdk/generated/open_payment_mandate.py b/code/sdk/python/ap2/sdk/generated/open_payment_mandate.py index 8cb4ee28..ce2c473a 100644 --- a/code/sdk/python/ap2/sdk/generated/open_payment_mandate.py +++ b/code/sdk/python/ap2/sdk/generated/open_payment_mandate.py @@ -1,13 +1,14 @@ # generated by datamodel-codegen: # filename: open_payment_mandate.json -# timestamp: 2026-04-28T00:39:38+00:00 +# timestamp: 2026-11-13T17:35:56+00:00 from __future__ import annotations from enum import Enum from typing import Any, Literal -from pydantic import BaseModel, Field +from ap2.sdk.constraint_validation import require_payment_constraint_types +from pydantic import BaseModel, Field, ValidationInfo, field_validator from .types import amount, merchant from .types import payment_instrument as payment_instrument_1 @@ -198,3 +199,10 @@ class OpenPaymentMandate(BaseModel): exp: int | None = Field( default=None, description='The expiration timestamp as a Unix epoch.' ) + + @field_validator('constraints', mode='before') + @classmethod + def require_payment_constraint_types_validator( + cls, v: Any, info: ValidationInfo + ) -> Any: + return require_payment_constraint_types(v, info) diff --git a/code/sdk/python/ap2/tests/constraint_parsing_tests.py b/code/sdk/python/ap2/tests/constraint_parsing_tests.py new file mode 100644 index 00000000..7b70aa85 --- /dev/null +++ b/code/sdk/python/ap2/tests/constraint_parsing_tests.py @@ -0,0 +1,178 @@ +"""Regression tests for parsing payment constraints from untrusted payloads.""" + +import json + +import pytest + +from ap2.sdk.generated.open_payment_mandate import ( + AgentRecurrence, + AllowedPayees, + AllowedPaymentInstruments, + AllowedPisps, + AmountRange, + Budget, + ExecutionDate, + OpenPaymentMandate, + PaymentReference, +) +from pydantic import ValidationError + + +_CONSTRAINT_CASES = [ + pytest.param( + AgentRecurrence, + {'type': 'payment.agent_recurrence', 'frequency': 'MONTHLY'}, + id='agent_recurrence', + ), + pytest.param( + AllowedPayees, + { + 'type': 'payment.allowed_payees', + 'allowed': [{'id': 'merchant-1', 'name': 'Shop'}], + }, + id='allowed_payees', + ), + pytest.param( + AllowedPaymentInstruments, + { + 'type': 'payment.allowed_payment_instruments', + 'allowed': [{'id': 'instrument-1', 'type': 'credit'}], + }, + id='allowed_payment_instruments', + ), + pytest.param( + AllowedPisps, + { + 'type': 'payment.allowed_pisps', + 'allowed': [ + { + 'legal_name': 'Example PISP', + 'brand_name': 'Example', + 'domain_name': 'pisp.example', + } + ], + }, + id='allowed_pisps', + ), + pytest.param( + AmountRange, + {'type': 'payment.amount_range', 'currency': 'BRL', 'max': 5000}, + id='amount_range', + ), + pytest.param( + Budget, + {'type': 'payment.budget', 'currency': 'BRL', 'max': 50.0}, + id='budget', + ), + pytest.param( + ExecutionDate, + {'type': 'payment.execution_date'}, + id='execution_date_without_bounds', + ), + pytest.param( + PaymentReference, + { + 'type': 'payment.reference', + 'conditional_transaction_id': 'checkout-digest', + }, + id='payment_reference', + ), +] + + +def _payload(constraint): + """Include a valid checkout reference alongside the constraint under test.""" + return { + 'vct': 'mandate.payment.open.1', + 'cnf': {}, + 'constraints': [ + { + 'type': 'payment.reference', + 'conditional_transaction_id': 'checkout-digest', + }, + constraint, + ], + } + + +def _parse(payload, input_format): + if input_format == 'json': + return OpenPaymentMandate.model_validate_json(json.dumps(payload)) + return OpenPaymentMandate.model_validate(payload) + + +@pytest.mark.parametrize('input_format', ['python', 'json']) +@pytest.mark.parametrize( + 'constraint', + [ + pytest.param({}, id='empty_object'), + pytest.param({'foo': 'bar'}, id='unrecognized_fields'), + pytest.param({'type': 'payment.unknown'}, id='unknown_type'), + pytest.param({'type': None}, id='null_type'), + pytest.param({'type': 123}, id='non_string_type'), + pytest.param('payment.execution_date', id='non_object'), + ], +) +def test_rejects_unrecognized_payment_constraint(constraint, input_format): + """Unknown constraints must not become an unconstrained ExecutionDate.""" + with pytest.raises(ValidationError): + _parse(_payload(constraint), input_format) + + +@pytest.mark.parametrize('input_format', ['python', 'json']) +@pytest.mark.parametrize('constraint_type,payload', _CONSTRAINT_CASES) +def test_requires_payment_constraint_type( + constraint_type, payload, input_format +): + """Every wire constraint must explicitly declare its type discriminator.""" + without_type = { + key: value for key, value in payload.items() if key != 'type' + } + with pytest.raises(ValidationError): + _parse(_payload(without_type), input_format) + + +@pytest.mark.parametrize('input_format', ['python', 'json']) +@pytest.mark.parametrize('constraint_type,payload', _CONSTRAINT_CASES) +def test_valid_payment_constraint_round_trip( + constraint_type, payload, input_format +): + """Known wire constraints retain their type and values after serialization.""" + mandate = _parse(_payload(payload), input_format) + assert isinstance(mandate.constraints[1], constraint_type) + assert ( + mandate.constraints[1].model_dump(mode='json', exclude_none=True) + == payload + ) + restored = OpenPaymentMandate.model_validate_json(mandate.model_dump_json()) + assert isinstance(restored.constraints[1], constraint_type) + assert restored == mandate + + +@pytest.mark.parametrize('constraint_type,payload', _CONSTRAINT_CASES) +def test_typed_payment_constraint_keeps_default_type(constraint_type, payload): + """SDK callers can still construct a typed constraint without repeating type.""" + without_type = { + key: value for key, value in payload.items() if key != 'type' + } + constraint = constraint_type(**without_type) + mandate = OpenPaymentMandate.model_validate(_payload(constraint)) + assert mandate.constraints[1] is constraint + + +@pytest.mark.parametrize('container', [tuple, iter], ids=['tuple', 'iterator']) +def test_iterable_payment_constraints_require_types(container): + """Other supported iterable inputs must not bypass type validation.""" + payload = _payload({'foo': 'bar'}) + payload['constraints'] = container(payload['constraints']) + with pytest.raises(ValidationError): + OpenPaymentMandate.model_validate(payload) + + +@pytest.mark.parametrize('constraints', [None, 123, {'foo': 'bar'}]) +def test_invalid_constraint_container_raises_validation_error(constraints): + """Malformed containers still produce a Pydantic validation error.""" + payload = _payload({}) + payload['constraints'] = constraints + with pytest.raises(ValidationError): + OpenPaymentMandate.model_validate(payload) diff --git a/code/sdk/schemas/README.md b/code/sdk/schemas/README.md index c3af552a..8b297724 100644 --- a/code/sdk/schemas/README.md +++ b/code/sdk/schemas/README.md @@ -1,5 +1,11 @@ To generate pydantic models for use in sample code: ```sh -$ uv run --with datamodel-code-generator python3 code/sdk/schemas/generate.py +$ uv run --with datamodel-code-generator==0.87.0 python3 code/sdk/schemas/generate.py ``` + +The generator registers a pre-validation hook for payment constraints. It +requires a `type` on incoming constraint objects before generated defaults can +turn an unrecognized object into an empty constraint. Typed SDK constructors +retain their default type identifiers. Keep this hook when regenerating models; +the protocol schemas remain unchanged. diff --git a/code/sdk/schemas/generate.py b/code/sdk/schemas/generate.py index c71804e1..3483ba59 100644 --- a/code/sdk/schemas/generate.py +++ b/code/sdk/schemas/generate.py @@ -1,5 +1,6 @@ """Script to generate pydantic models from json schemas.""" +import json import os import shutil import subprocess @@ -29,8 +30,9 @@ def main(): for jf in json_files: shutil.copy(jf, temp_dir) - shutil.copytree(root_dir / 'types', temp_dir / 'types', dirs_exist_ok=True) - + shutil.copytree( + root_dir / 'types', temp_dir / 'types', dirs_exist_ok=True + ) command = [ sys.executable, @@ -48,6 +50,23 @@ def main(): '--use-title-as-name', '--use-default-kwarg', '--use-default', + '--validators', + json.dumps( + { + 'OpenPaymentMandate': { + 'validators': [ + { + 'field': 'constraints', + 'function': ( + 'ap2.sdk.constraint_validation.' + 'require_payment_constraint_types' + ), + 'mode': 'before', + } + ], + }, + } + ), '--field-extra-keys', 'x-selectively-disclosable-field', 'x-selectively-disclosable-array', From f21731f26ee210820d92ea196f1cd4e6dd286a67 Mon Sep 17 00:00:00 2001 From: William Prussak Macarini Date: Fri, 13 Nov 2026 14:46:08 -0300 Subject: [PATCH 2/2] docs(sdk): fix generation guide and SDK spelling --- .cspell/custom-words.txt | 6 ++++++ code/sdk/schemas/README.md | 4 +++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/.cspell/custom-words.txt b/.cspell/custom-words.txt index ce73c361..1c0063ba 100644 --- a/.cspell/custom-words.txt +++ b/.cspell/custom-words.txt @@ -22,6 +22,7 @@ CMSPI cmwallet cncf Cobo +codegen Connor contentnegotiation credman @@ -29,6 +30,7 @@ Crossmint cryptographical CYGPATTERN Dafiti +datamodel disclosable Disclosable davecgh @@ -127,6 +129,10 @@ Payoneer paypal Payplug pids +PISP +pisp +Pisps +pisps pmezard proguard Proguard diff --git a/code/sdk/schemas/README.md b/code/sdk/schemas/README.md index 8b297724..b83a6a97 100644 --- a/code/sdk/schemas/README.md +++ b/code/sdk/schemas/README.md @@ -1,7 +1,9 @@ +# SDK model generation + To generate pydantic models for use in sample code: ```sh -$ uv run --with datamodel-code-generator==0.87.0 python3 code/sdk/schemas/generate.py +uv run --with datamodel-code-generator==0.87.0 python3 code/sdk/schemas/generate.py ``` The generator registers a pre-validation hook for payment constraints. It