Security, transactions and plans
Original on-site instruction. Practice and outside references are optional. Independent subject review and observed learner testing remain pending.
Identity, sessions and object authority
Authentication establishes a principal under a particular verification mechanism. Authorization decides whether that principal may perform an action on a particular object. A session connects several HTTP requests to application state without making HTTP itself remember the visitor. In a common server-side session design, an unpredictable identifier in a cookie refers to state held by the server. The cookie is a bearer credential: possession can be sufficient to act as that session. Do not put the password or an untrusted role assertion into a client-readable field and call it a verified session.
A complete account design needs secure credential handling, verified login, expiration, logout/revocation and recovery. Store passwords through a maintained framework's password-hashing facilities rather than reversible encryption or a hand-written digest scheme. Cookie Secure restricts transmission to secure contexts under its rules; HttpOnly prevents ordinary script access to the cookie; SameSite controls some cross-site sending behavior. None of these replaces authorization. A stolen session, an overly broad role or a route that omits ownership can remain a problem despite correct cookie attributes. Production choices require the framework's current security documentation and actual deployment checks.
For fictional customers A and B, derive the customer identity from the verified session, then query an order by both order ID and that identity or an explicit permission relation. A submitted `owner=A` field supplies data, not authority. An admin role must be obtained from trusted server-side membership/permission state and checked for the requested operation; it is not established by showing an admin button. A tenant filter must constrain the data retrieval before the response or retrieval context is assembled. Hiding another tenant's result after loading it into a shared context is a different, weaker boundary.
In Django, the configured authentication/session middleware can populate request.user from its supported mechanisms. A login-required check excludes anonymous access but does not by itself prove that an authenticated user owns order 10. A view or service still needs the object/permission check. Generic list and detail views reduce repetitive code; constrain their query sets to authorized objects, and do not expose every model field simply because the framework can serialize it. The admin site and public application have different audiences and permission responsibilities.
CSRF, XSS and server-side validation solve different failures
A browser can automatically attach cookies to eligible requests. Cross-site request forgery exploits that ambient authority: another site induces a request the victim did not intend. For state changes authenticated with browser cookies, use the framework's supported CSRF protection and an appropriate request/origin policy. A secret per-session/request token verified by the server can help distinguish an intended form from a forged submission; placing a token on a page without checking it does nothing. Keep GET free of state-changing business operations. SameSite is a useful additional control, not a reason to discard the application's complete CSRF design. Cross-origin resource sharing controls selected browser access to responses; it is not a general authorization or CSRF substitute.
Cross-site scripting changes data into executable browser content. Suppose an order description contains `<img src=x onerror=...>`. It remains ordinary text when assigned to a text node, but can create markup if inserted into an unsafe HTML sink. A framework template's default escaping helps in its supported output context; marking text safe, interpolating into script/URL contexts or constructing HTML manually can invalidate that protection. A content-security policy can reduce some consequences under a carefully deployed policy, but does not make arbitrary unsafe rendering correct. Treat validation, context-appropriate output handling, authorization and CSRF as separate controls with separate tests.
Model forms connect a declared form schema to validation and persistence. A GET can display an unbound form; a POST binds submitted data, checks validity and either redisplays associated errors or performs an authorized operation. Explicitly select permitted fields. Do not allow an ordinary visitor to set owner, staff status or an internal approval field merely because it exists on the model. The server can assign ownership from request.user after the form accepts the editable fields. A redirect after a successful POST can improve refresh behavior, but does not itself make retries idempotent. Keep the stable operation identity and payload-conflict policy from the native lesson.
Atomicity and isolation are different claims
Atomicity groups database changes so that the transaction commits or rolls back together under its documented conditions. Isolation determines what concurrent transactions may observe and which histories are allowed. A transaction can be atomic yet implement a wrong read-check-write business rule. At ordinary read-committed isolation in PostgreSQL, separate statements may observe different committed snapshots. Repeatable-read and serializable modes impose stronger rules with their own conflict/failure behavior; stronger isolation can require application retries. Do not transfer SQLite's locking behavior to PostgreSQL simply because both accept BEGIN and COMMIT.
Consider stock=5. Two workers each read 5 and propose selling 4. If each writes its independently computed final stock 1, the stored value conceals eight sold units. A conditional database update expresses the invariant at mutation time:
UPDATE inventory
SET stock=stock-4
WHERE id=:item_id AND stock>=4;The colon placeholder here is conceptual parameter notation; bind it using the actual driver's API. Require one affected row before inserting a successful local sale record, and include that insert in the same transaction. A zero-row result is unavailable or otherwise not accepted, not success with a surprising count. Under the chosen database's concurrent-update rules, test the competing operations using independent connections. A final stock of 1 alone is insufficient evidence: inspect the number and contents of committed sale records as well.
Optimistic concurrency answers a related but distinct question. Updating a record with `WHERE id=? AND owner=? AND version=?`, incrementing its version on success, refuses to apply an edit based on obsolete state. A retry token identifies the same requested operation; the expected version identifies the state the user edited. An identical already-committed retry can return its recorded result under the specified replay contract, while a new stale edit must be reviewed. Do not blindly retry a stale full replacement merely to remove a 409 banner.
An atomic database transaction does not include an external payment provider automatically. A crash after a provider commits but before the local receipt is stored leaves an ambiguous outcome. Use a durable workflow with a stable provider operation key and explicit reconciliation under that provider's contract. The existing synthetic action laboratory demonstrates a local model of those states; it does not send payments or establish a real provider's guarantees. Outbox patterns can atomically record local intent with local changes, but message delivery and recipient-side idempotence still need specifications.
Privileges, views and prepared execution
Database privileges constrain which roles may connect, use schemas or operate on particular objects. Separate a migration role from the application's ordinary role where the deployment supports that design. A least-privilege connection limits accidental or compromised operations; it does not fix a query that returns every customer's rows when the application role is permitted to read them. Row-level policies, views and application predicates can contribute to a design, but their interaction and any privileged bypass behavior must be reviewed for the actual database configuration.
A view names a query representation; it is not automatically a separately stored snapshot. Its permissions and execution semantics depend on its definition and engine/version. A materialized view stores results and introduces refresh/staleness policy. Neither word means “authorized for all visitors.” SQL PREPARE and driver-bound parameters also address different layers of execution. A prepared statement can reuse a parsed/planned statement structure; binding parameters keeps supplied values out of SQL syntax. Parameter binding does not permit a visitor to supply arbitrary table names or ORDER BY fragments. For a user-selectable sort, map a small public choice to a trusted query expression.
Indexes and query plans connect logical work to physical cost
An index retains a structure that helps locate rows under supported predicates and ordering. It costs storage and write maintenance. A B-tree index on customer_id can help locate a customer's orders, while a composite `(customer_id, created_at)` index can support a related filtered/ordered workload. Column order and predicate shape matter; there is no rule that every index speeds every query. A low-selectivity filter or a query returning most rows may be cheaper as a scan. Additional indexes can slow insert/update/delete operations and increase migration cost.
EXPLAIN describes the planner's chosen operations and estimated work. Its cost units are planner estimates, not directly milliseconds or a benchmark guarantee. EXPLAIN ANALYZE executes the statement and reports observations, so applying it casually to a mutation can change data. Use a disposable fixture or a carefully reviewed transaction policy when investigating side effects. Compare estimated versus observed row counts, loops, scan/join choices and actual workload. Refreshing statistics, changing data distribution or altering parameters can change the plan. A fast small synthetic fixture does not establish production latency or all parameter cases.
For a fictional dataset with 10,000 orders and 100 equally represented customers, an average customer has 100 orders. That arithmetic does not prove the query reads only 100 index entries or that a particular plan wins. Change the distribution so one customer owns 9,000 orders: the estimate based on uniformity is now unsuitable for that customer. Verify equivalent authorized outputs before comparing plans. An index chosen for speed must not remove a tenant predicate or a required validation step from the work being measured.
Optional integrated changed record and complete model
Aster's ordinary session submits order 10 with body fields `owner=Birch` and `role=admin`; the description contains an HTML event handler. The request carries a valid CSRF token. Stock is 5 and two independent requests each seek four units. A developer adds an index and declares the application secure because the query is faster. Identify the independent acceptance boundaries and observations, then change the operation to an identical replay after a lost response.
Compare the complete changed-record reasoning
**Model reasoning.** A valid CSRF token supports the intended-request check under its design but does not authorize the supplied owner/role. Resolve Aster from verified server state and check permission for order 10. Accept only permitted editable fields; reject or ignore privileged fields under an explicit schema rather than adopting them. Render the description as data through the correct output context; authorization and token validity do not sanitize HTML. Each stock operation must be conditionally accepted at the database boundary and coupled to its local sale/audit records. With capacity five and two requests for four, at most one may become a successful sale; inspect exact sale rows and stock, not merely one final number. The index affects a physical access path, not any permission or capacity proof. An identical replay uses the same operation ID and payload and returns the stored result without another decrement; changed content under that ID conflicts. A lost external-provider response requires reconciliation rather than assuming the local transaction rolled the provider back.
Evaluate on four equal criteria: identity/session/object authority; separate CSRF/XSS/form-schema mechanisms; transaction/isolation/version/replay reasoning and exact state evidence; and privilege/index/plan interpretation with resource and deployment limits. The original concurrency and audit-failure investigations remain the core applied cases.