Review the prerequisites
Suitable for: Know the function parameters and design the model tool for the first time.
- 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.
Foundation · Understand the concepts
Why is valid JSON insufficient to authorize a payment?
Objectives of this level: Can explain the difference between "well-formed" and "allowed to execute".
Understand tools as candidate function calls
A model tool call proposes arguments. After parsing account and amount_cents, the program must still decide whether to execute. A valid string can identify someone else's account, and a positive integer can exceed the balance. Shape, ownership, and business rules establish different facts.
Check four layers
Shape checks fields and types. Semantics checks units, ranges, and relationships such as dates. Authorization uses the actual signed-in identity to check resource and action permissions. State checks the current balance, approval, or resource version. A schema expresses many static constraints, but supplies no authenticated identity and does not query account ownership.
Use counterexamples to reveal gaps
A request asks to pay 100 cents from account B, which belongs to another tenant. Its shape is valid, but it must be rejected. Even the caller's own account may lack payment permission. Stable argument generation is one part of execution; the server remains responsible for business decisions.
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
List four types of checks: structure, unit, authority and status for the same payment parameter.
Check each item after completion
- The amount is expressed in cents
- The identity is obtained from the server session
- Indicates that the structure passed does not represent a cross-tenant request executable
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 the model fills in tenant_id as its own tenant, can it be used as the basis for authentication?
Expand reference derivation
No. Model parameters are input to be verified, and the trusted identity must come from the authentication context, and then checked with resource ownership and action permissions.
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.