Review the prerequisites
Suitable for: Ability to read simple Python functions and dictionaries.
- Schema
- A contract describing the shape, type and constraints of fields; valid fields do not prove that the caller has operation permissions.
- trusted context
- The identity and tenant obtained after server-side authentication cannot directly trust the identity filled in the model.
- side effects
- Writes to the outside world, such as payments, releases, or deletes.
- status version
- A version of the current state of the resource, used to discover changes that have occurred since the check.
How does the mechanism work?
- Candidate parameters
The model proposes actions and parameters.
- structure and semantics
Check fields, types, units, and associated constraints.
- identity and status
Check the real permissions and current business status.
- Execution and receipt
Execute conditionally and verify the results and business evidence.
Implementation · Build it
Run a cross-tenant counterexample
Objectives of this level: Parameter verification and trusted identity checking can be implemented separately.
Inspect the two lab functions
validate_shape manually validates one payment tool. It rejects extra fields, empty accounts, and amounts that are non-integer or non-positive. It is no general JSON Schema engine. After shape validation, authorize checks the account table and trusted actor for tenant membership, action permission, and balance.
Include an adversarial request
The demo intentionally supplies a well-formed account B while the caller belongs to tenant-a and B belongs to tenant-b. Expected results are shape_valid=true, authorized=false, and business_writes=0. Testing only a successful request against one's own account cannot establish tenant isolation.
Extend the normal path carefully
This lesson makes no real payment. Production balance and state checks must occur within a transaction or conditional write that handles races. A balance change between checking and writing invalidates the old decision. Restrict error details so other tenants' account information is not returned to the model.
Run experiments and observe counterexamples
Manual parameter and authorization checks for specific tools; no real payments, full schema implementation, transactional deductions, or dynamic permissions platform.
Python 3.10+ · Runs by default using only the standard library · Runs on your computer
- Running a counterexample that is legal but cross-tenant
- Change trusted identities and permissions, compare wrong branches
- Additional testing of status changes after design check
python3 tool_contracts.pyView the entry-point script
"""A specific tool's manual validator, not a JSON Schema implementation."""
import json
def validate_shape(params):
if type(params) is not dict or set(params) != {"account", "amount_cents"}:
raise ValueError("shape")
if not isinstance(params["account"], str) or not params["account"]:
raise ValueError("account")
if type(params["amount_cents"]) is not int or params["amount_cents"] <= 0:
raise ValueError("amount")
def authorize(params, actor, accounts):
validate_shape(params)
account = accounts.get(params["account"])
if account is None or account["tenant"] != actor["tenant"]:
raise PermissionError("not allowed")
if "pay" not in actor["permissions"]:
raise PermissionError("not allowed")
if params["amount_cents"] > account["balance"]:
raise ValueError("balance")
def demo():
params = dict(account="B", amount_cents=100)
actor = dict(tenant="tenant-a", permissions=["pay"])
accounts = {"B": dict(tenant="tenant-b", balance=1000)}
validate_shape(params)
try:
authorize(params, actor, accounts)
except PermissionError:
return dict(shape_valid=True, authorized=False, business_writes=0)
raise AssertionError("cross-tenant request was accepted")
if __name__ == "__main__":
print(json.dumps(demo(), sort_keys=True))
Expected output when running locally
{"authorized": false, "business_writes": 0, "shape_valid": true}- Structure and authorization results are presented separately.
- Cross-tenant requests have no business effect
- Online business competition needs to be verified separately
Acceptance task for this level
Run tool_contracts.py; change the account ownership, remove the pay permission, and replace the amount with True.
Check each item after completion
- The original request authorization failed and no business was written.
- Same tenant but no pay permission is still rejected
- Boolean values cannot pass as integer amounts
Save your own processes, code and results. Acceptance requirements are provided here, and course mastery status will not be automatically graded or saved at this time.
Hide the answer and check your understanding
If you check the balance first and then deduct the money after one minute, is the check result still reliable?
Expand reference derivation
Not necessarily. Balances and permissions may change and should be rechecked at execution boundaries or through transactions and resource version conditions to ensure constraints between checks and writes.
Further explanations and practice
When encountering unfamiliar principles, first read the implementation, continuous questioning and migration cases, and then independently explain the premise and boundaries. Answers and notes are saved to the original account record.
Sources and verification scope
The principles are based on public information; the numbers, cases and tasks are the teaching design of this website. Offline experiments verify the range noted on this page, and the learning effect still needs to be judged through independent tasks and feedback.