diff --git a/code/sdk/python/ap2/sdk/constraints.py b/code/sdk/python/ap2/sdk/constraints.py index 48aed798..bc29e490 100644 --- a/code/sdk/python/ap2/sdk/constraints.py +++ b/code/sdk/python/ap2/sdk/constraints.py @@ -92,6 +92,8 @@ def evaluate( violations: list[str] = [] amount = closed_mandate.payment_amount + if amount.amount < 0: + violations.append(f'Amount {amount.amount} cannot be negative') if ( self.constraint.currency and amount.currency != self.constraint.currency @@ -103,6 +105,7 @@ def evaluate( if ( self.constraint.min is not None and amount.amount < self.constraint.min + and amount.amount >= 0 ): violations.append( f'Amount {amount.amount} below minimum {self.constraint.min}' @@ -291,6 +294,14 @@ def evaluate( closed_mandate: PaymentMandate, open_checkout_hash: str | None = None, ) -> list[str]: + if closed_mandate.payment_amount.amount < 0: + return [ + ( + 'Payment amount ' + f'{closed_mandate.payment_amount.amount} cannot be negative' + ) + ] + if closed_mandate.payment_amount.currency != self.constraint.currency: return [ 'Budget currency mismatch: expected ' diff --git a/code/sdk/python/ap2/tests/constraints_tests.py b/code/sdk/python/ap2/tests/constraints_tests.py index 910c97fc..80876bfb 100644 --- a/code/sdk/python/ap2/tests/constraints_tests.py +++ b/code/sdk/python/ap2/tests/constraints_tests.py @@ -229,6 +229,29 @@ def test_payment_amount_no_min(): assert violations == [] +def test_payment_amount_negative_rejected(): + """Negative payment amount is rejected even if min is absent.""" + violations = check_payment_constraints( + _open_payment( + constraints=[ + AmountRange(max=2000, currency='USD'), + ] + ), + _closed_payment(payment_amount=Amount(amount=-100, currency='USD')), + ) + assert any('cannot be negative' in v for v in violations) + + violations_with_min = check_payment_constraints( + _open_payment( + constraints=[ + AmountRange(min=500, max=2000, currency='USD'), + ] + ), + _closed_payment(payment_amount=Amount(amount=-100, currency='USD')), + ) + assert any('cannot be negative' in v for v in violations_with_min) + + # ── check_payment_constraints – amount boundary cases (parameterized) ──── @@ -492,6 +515,20 @@ def test_payment_budget_missing_context(): ) +def test_payment_budget_negative_amount_rejected(): + """Negative payment amount is rejected by budget evaluator.""" + violations = check_payment_constraints( + _open_payment( + constraints=[ + Budget(max=10.0, currency='USD'), + ] + ), + _closed_payment(payment_amount=Amount(amount=-100, currency='USD')), + mandate_context=MandateContext(total_amount=500, total_uses=1), + ) + assert any('cannot be negative' in v for v in violations) + + # ── check_payment_constraints – execution_date ───────────────────────────