Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .cspell/custom-words.txt
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,15 @@ CMSPI
cmwallet
cncf
Cobo
codegen
Connor
contentnegotiation
credman
Crossmint
cryptographical
CYGPATTERN
Dafiti
datamodel
disclosable
Disclosable
davecgh
Expand Down Expand Up @@ -127,6 +129,10 @@ Payoneer
paypal
Payplug
pids
PISP
pisp
Pisps
pisps
pmezard
proguard
Proguard
Expand Down
23 changes: 23 additions & 0 deletions code/sdk/python/ap2/sdk/constraint_validation.py
Original file line number Diff line number Diff line change
@@ -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
12 changes: 10 additions & 2 deletions code/sdk/python/ap2/sdk/generated/open_payment_mandate.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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)
178 changes: 178 additions & 0 deletions code/sdk/python/ap2/tests/constraint_parsing_tests.py
Original file line number Diff line number Diff line change
@@ -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)
10 changes: 9 additions & 1 deletion code/sdk/schemas/README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
# SDK model generation

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.
23 changes: 21 additions & 2 deletions code/sdk/schemas/generate.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Script to generate pydantic models from json schemas."""

import json
import os
import shutil
import subprocess
Expand Down Expand Up @@ -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,
Expand All @@ -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',
Expand Down
Loading