from dataclasses import dataclass


@dataclass(frozen=True)
class Context:
    tenant: str
    can_refund: bool


orders = {"O1": {"tenant": "t1", "refundable": 5000}}
approvals = {"O1": 3000}  # 演示用服务端可信状态


def authorize(ctx, arguments):
    if set(arguments) != {"order", "amount"}:
        raise ValueError("工具参数不符合契约")
    order = orders[arguments["order"]]
    amount = arguments["amount"]
    if not ctx.can_refund or order["tenant"] != ctx.tenant:
        raise PermissionError("无权操作该订单")
    ceiling = min(order["refundable"], approvals.get(arguments["order"], 0))
    if type(amount) is not int or not 0 < amount <= ceiling:
        raise PermissionError("金额超出有效授权")
    return "allowed"


ctx = Context("t1", True)  # 真实应用从认证层取得
assert authorize(ctx, {"order": "O1", "amount": 2000}) == "allowed"
for args in ({"order": "O1", "amount": 4000},
             {"order": "O1", "amount": 2000, "approved": True}):
    try:
        authorize(ctx, args)
    except (ValueError, PermissionError):
        pass
    else:
        raise AssertionError("未授权操作应被拒绝")
print("外部提供的批准声明无法越过服务端约束")
