跳到正文
DEV Community· Yuya AI Lab·· 1 小時前AI 評分69

智能體獲批 $40 卻扣款 $60:以純 Python 將付款綁定至批准金額

Your Agent Approved $40 and Charged $60: Binding Spend to the Approval in Pure Python

AI 導讀

Yuya AI Lab 分享一套純 Python 智能體付款授權實作,凍結已批准金額並核對付款請求,避免扣款超出原有批准。在 1,200 次重報價流程中,沿用最新金額造成 414 次超額付款(34.5%),合共 $5,816.23 未獲批准支出;按批准金額執行則會要求再次確認。方案以請求指紋避免同一付款重試造成重複扣款,並以 HMAC-SHA256 收據鏈驗證紀錄;密鑰須存於帳本以外。

正文

A customer taps Approve on a $40.00 charge. Four seconds later your agent charges $60.00. The API returns 200, the workflow goes green, and nobody notices until the dispute email arrives three weeks later.

I have been building the boring plumbing around agent spending — quotes, approvals, retries, receipts — for a set of personal automation pipelines. The pattern that fails most often is not a missing guardrail. It is that the approval never existed as a value. The agent held a reference to "the order", re-read the total when it was finally ready to pay, and paid whatever the cart said at that moment.

This post is the fix I settled on: freeze the approved amount, check the request against it, consume the approval exactly once, and write a tamper-evident receipt as you go. Everything below is pure Python standard library, and every number comes from a seeded harness you can rerun.

The approval was a variable, not a value

Consider the natural way to write this:

order = get_cart(cart_id)
user_approved(order)          # human sees $40.00
...
charge(order.total)           # whatever order.total is now

Between those two lines, the world moves. A shipping estimate resolves. Tax is calculated for the first time. A discount expires. The merchant re-quotes. order is the same object, so nothing looks suspicious, and the charge is "consistent" with the object — just not with the human.

I replayed 1,200 purchase flows where the merchant re-quotes between approval and charge: 30% of flows drift up by 5–40%, 18% drift down. An agent that binds to the latest value overcharged in 414 of 1,200 flows (34.5%), for $5,816.23 of unapproved spend across the run. Median overcharge: $10.68. Max: $51.87. Not one of those charges would raise an exception.

An agent that binds to the approval charges $0 unapproved — and asks the human again in those same 414 cases. That is the trade you want: 34.5% of flows get a second confirmation instead of a surprise. Boring, visible friction beats a silent overcharge.

Represent money so it cannot drift

Two rules carry most of the weight: integer minor units, and a frozen approval object that the payment path cannot mutate.

from dataclasses import dataclass

@dataclass(frozen=True)
class Money:
    minor: int                 # cents; never a float
    currency: str = "USD"

    def __post_init__(self):
        if isinstance(self.minor, bool) or not isinstance(self.minor, int):
            raise TypeError("amount must be integer minor units")
        if len(self.currency) != 3 or not self.currency.isupper():
            raise ValueError("currency must be ISO-4217 uppercase")

@dataclass(frozen=True)
class Approval:
    approval_id: str
    quote_id: str
    merchant: str
    amount: Money
    nonce: str
    expires_at: float
    approved_by: str = "user"
    max_amount: Money | None = None   # ceiling if the human set one

    @property
    def ceiling_minor(self) -> int:
        return self.max_amount.minor if self.max_amount else self.amount.minor

frozen=True is not decoration. It means no code path can quietly rewrite approval.amount after the human said yes, and it makes approval_id usable as an idempotency anchor.

Floats are worth banning explicitly rather than by convention. In 1,000 simulated carts of 40 line items, 682 (68.2%) produced a float total whose repr was not the exact cent value — one example was 948.5499999999997 for a $948.55 cart. A receipt that hashes that string is not reproducible; a receipt that hashes the integer is.

Six checks before the provider is called

The guard is deliberately dull. Here are the checks in order, trimmed of logging:

def authorize(self, req, now):
    fp = fingerprint(req)
    ap = self._approvals.get(req.approval_id)

    if ap is None:                       return deny(DENY_NO_APPROVAL)
    if now > ap.expires_at:              return deny(DENY_EXPIRED)
    if req.merchant != ap.merchant:      return deny(DENY_MERCHANT)
    if req.amount.currency != ap.amount.currency:
                                         return deny(DENY_CURRENCY)
    if req.amount.minor > ap.ceiling_minor:
        return deny(DENY_OVER_CEILING, excess=req.amount.minor - ap.ceiling_minor)
    if req.nonce and req.nonce != ap.nonce:
                                         return deny(DENY_NONCE)

    prior = self._consumed.get(ap.approval_id)
    if prior and prior["fingerprint"] == fp:
        return allow(ALLOW_RETRY)        # same logical charge, do not capture again
    if prior:
        return deny(DENY_APPROVAL_REUSED)

    self._consumed[ap.approval_id] = {"fingerprint": fp, "amount_minor": req.amount.minor}
    return allow(ALLOW)
Code Traps
deny_no_approval Agent invented an approval id, or the ledger was rotated
deny_expired Approval from last week replayed by a cron retry
deny_merchant Approval for shop-a used at shop-b after a redirect
deny_currency $40 approved, 40 EUR charged (numeric match, 7% more money)
deny_over_ceiling The $40 → $60 case, and the $5 tax surprise
deny_nonce Two approvals for the same cart; the stale one is used
deny_approval_reused The same "yes" stretched over a second purchase

The currency check looks pedantic until it happens: "40" is a valid amount in both currencies, and only the code stops it.

Single-use approval, retry-safe request

The two requirements look contradictory: an approval must be spendable once, but a network retry must not become a second charge. The resolution is to separate the approval from the attempt.

def fingerprint(req):
    return sha256(canonical_bytes({
        "approval_id": req.approval_id,
        "merchant": req.merchant,
        "amount_minor": req.amount.minor,
        "currency": req.amount.currency,
        "sku": req.sku,
    })).hexdigest()

The fingerprint is the identity of the logical charge and deliberately ignores the attempt id. It is also the idempotency key sent to the provider:

decision = guard.authorize(req, now)
if not decision.allowed:
    return ChargeOutcome("denied", decision.code)
ref = provider.charge(idem_key=decision.fingerprint, amount_minor=req.amount.minor)

In 500 flows with a 20% timeout rate where half of timeouts actually capture, an agent that generated a fresh UUID per attempt double-charged 49 flows (9.8%), for $2,080 of duplicate captures. The fingerprint key double-charged 0.

Honesty about the cost: 4 of 500 guarded flows ended unresolved rather than double-charged. A timeout is not proof of failure, so the guard reports unknown and leaves the charge for reconciliation instead of guessing. If your code turns unknown into "retry with a new key", you have rebuilt the bug.

The reuse case is the one that bites hardest. Approving $40 and then requesting $60 on that same approval was allowed in 300 of 300 flows by a naive implementation — $6,000 of unapproved spend — and refused 300 of 300 by the guard with deny_over_ceiling. That is the single check that would have prevented the opening anecdote.

What tolerance actually buys

Teams often replace the ceiling with a tolerance ("allow 5% over"). I tested that on 1,500 flows where the quote already included tax, checkout added shipping/service/small-order fees, and 20% of flows carried a legitimate 0.1–0.6% bank FX variance.

  • 76.1% of flows ended up above the quoted total at checkout; median excess $6.99 (shipping), p90 +33%, max +43.6%.
  • An exact ceiling allowed 20.2% of flows (the FX cases, which fit) and denied 275 legitimate FX charges (18.3%).
  • A +5% tolerance still authorised 283 over-ceiling charges worth $644.40, while denying 183 legitimate FX flows (12.2%).
  • A +10% tolerance authorised 568 over-ceiling charges worth $2,170.50 and still denied 116 legitimate flows.
Policy Allowed Over-ceiling allowed Excess authorised Legit FX denied
exact (0) 20.2% 0 $0.00 18.3%
+1 cent 20.2% 0 $0.00 18.3%
+1% 24.1% 58 $10.89 14.5%
+5% 39.1% 283 $644.40 12.2%
+10% 58.1% 568 $2,170.50 7.7%

Read the last two columns together: the tolerance is either too tight to admit real variance or loose enough to authorise hundreds of dollars. Percentage slack is a blunt instrument. A better pattern is an exact ceiling plus a first-class deny_over_ceiling that carries the delta, so the UI can show "the total went up $6.99 for shipping — approve again?" — one tap, no ambiguity, and the decision is the human's.

The receipt is the part that survives the incident

A guard that says "allowed" is useless three weeks later. You need a record that (a) lists what happened, (b) proves nothing was edited, and (c) can be handed to someone who does not trust your agent.

def canonical_bytes(obj):
    return json.dumps(obj, sort_keys=True, separators=(",", ":"),
                      ensure_ascii=False).encode("utf-8")

class Ledger:
    def __init__(self, key=None):
        self.key, self.entries = key, []

    def append(self, kind, payload, ts=None):
        prev = self.entries[-1]["hash"] if self.entries else "0" * 64
        core = {"seq": len(self.entries), "ts": ts, "kind": kind,
                "payload": payload, "prev": prev}
        entry = dict(core)
        entry["hash"] = (hmac.new(self.key, canonical_bytes(core), hashlib.sha256).hexdigest()
                         if self.key else hashlib.sha256(canonical_bytes(core)).hexdigest())
        self.entries.append(entry)
        return entry

def verify_chain(entries, key=None, anchor="0" * 64):
    prev = anchor
    for i, e in enumerate(entries):
        if e["seq"] != i:      return Report(False, i, "sequence_gap")
        if e["prev"] != prev:  return Report(False, i, "link_broken")
        core = {k: e[k] for k in ("seq", "ts", "kind", "payload", "prev")}
        expected = (hmac.new(key, canonical_bytes(core), hashlib.sha256).hexdigest()
                    if key else hashlib.sha256(canonical_bytes(core)).hexdigest())
        if not hmac.compare_digest(expected, e["hash"]):
            return Report(False, i, "hash_mismatch")
        prev = e["hash"]
    return Report(True, len(entries))

Canonical JSON matters more than it looks: 200 random key orderings of the same payload produce exactly 1 digest. Without sort_keys, the same value hashes differently depending on how the dict was built, and verification becomes a coin flip.

I attacked 300 receipts of 14 entries each, six ways, against three detectors:

Attack Shape check SHA-256 chain HMAC chain
Edit an amount 0% caught 100% 100%
Edit a merchant 0% caught 100% 100%
Delete an entry 0% caught 100% 100%
Swap two entries 0% caught 100% 100%
Append a forged entry 0% caught 0% 100%
Rewrite the amount, recompute every hash 0% caught 0% 100%

The shape check is the one most logging pipelines ship: every tampered receipt still "validates", because the fields have the right types. That is why a status code is not a receipt.

The two zeros are the interesting part. An unkeyed hash chain catches accidents and careless edits, but anyone who can write the log can also recompute the whole chain — and appending a well-formed forged entry is not even an edit. Keying it with HMAC-SHA256 fixes both, provided the key lives outside the log: environment variable, KMS, separate process. A key sitting next to the ledger is a checksum with extra steps.

Clean receipts verified 300/300 in both modes, so the detection is not bought with false positives.

Practical shape

  • Size and speed. A five-event charge receipt is 1,950 bytes; verifying it takes 34 µs. A 20,000-entry ledger appends in 210 ms (~10 µs/entry) and verifies in 130 ms (~6.5 µs/entry).
  • Export early. A receipt is a verifiable slice from the quote to the current head. Exported right after the charge, it is small; exported from a busy ledger later, it carries everything written in between (1,000 entries, 6.4 ms). Write it when the charge happens, and a tampered slice is still rejected.
  • Key custody is a deployment decision, not a coding one. Keyed receipts verify only for key holders; for an outside auditor, publish a daily head hash somewhere the agent cannot rewrite.
  • Reconciliation is a feature. unknown must be a first-class outcome with a queue and a human-visible receipt, not a prompt to retry.

The whole module is 416 lines including docstrings, with 35 unit tests covering expiry, currency, nonce, reuse, retry, deletion, reordering, chain rewriting, and receipt tampering. It runs on a Raspberry Pi and costs nothing per call, which matters when the alternative is a vendor whose free tier expires mid-incident.

The unglamorous conclusion: an approval is only real if it is a value, with a ceiling, a one-time spend, and a receipt that survives the argument about what happened.


I package the working version of this — ledger, guard, tests, and the seeded experiment harness — as part of the small automation templates I sell to solo builders: AI automation templates on Payhip. Disclosure: that is my own store. Every number in this post is reproducible from the code above without buying anything.

來源:DEV Community · dev.to