The Lawfare Academy

Lawfare Group → Knowledge Institute → Lawfare Academy

← Back to program

← CS 220 — Web Applications, SQL and Software Engineering

Weeks 9–11

Transactions, parameterization and authorization

Learning objectives

  • Explain and trace the mechanisms in transactions, parameterization and authorization.
  • Apply the method to the worked example and changed-condition exercise.
  • Identify assumptions, failure cases and the evidence needed to justify a result.
  • Test the added failure-mode fixture and explain which guarantee the evidence does and does not establish.

Current study directions: the original Academy lessons, preparation chapters, worked explanations and complete optional models on LawfareGroup.com provide the required conceptual preparation. Retained publisher/reference chapters, source exercises and their historical assignment directions are optional further study. Outside visits and assessments are optional. Independent subject review and observed learner testing remain pending. This current notice supersedes earlier textbook-supported study directions preserved below and in historical companion pages.

A transaction groups related changes into an operation with defined consistency behavior. If money is transferred, decrementing one account and incrementing the other must not leave a half-completed business operation. Transactions do not eliminate the need for constraints, isolation choices or correct application logic. A concurrency defect may appear only when two requests read the same old state before either writes.

Parameterized statements separate SQL structure from values. String concatenation lets submitted text change query syntax, creating injection risk. Parameters address values; dynamic column names and ordering still require allowlists or structured APIs. Parameterization does not decide who may access the resulting row. Authentication identifies a caller; authorization checks whether that caller may perform this operation on this object.

Never trust a customer_id submitted by the browser as proof of ownership. Bind requests to the authenticated identity and enforce object-level access on the server. A hidden admin button is presentation, not security. Test two fictional accounts and attempt to read or edit the other's order. Also examine logs and error messages: denying a write while revealing another person's confidential record is still a disclosure.

Worked reasoning The query constrains both identifier and verified owner. The caller identity must come from a trusted session verification process, not a body field. Parameters prevent values from becoming query syntax. The in-memory example demonstrates object-level filtering and intentionally omits production session and connection management.

Extended teaching and laboratory

Parameterization prevents submitted values from being interpreted as query syntax. It does not decide whether the requester may access the selected row. Constrain data operations by a trusted principal or by a verified permission relation. Prefer one bounded operation over a check followed by an unconstrained action that can race with changes.

A transaction groups database effects, but its isolation level and constraints determine which concurrent histories are allowed. A read-check-write sequence can oversell a resource if two workers both observe the same availability. Make the invariant enforceable at the update or constraint boundary.

Worked problem Inventory is 1. Two transactions each read 1, approve one sale, and write 0. Both report success. Give an update that makes the final remaining inventory meaningful.

Step-by-step reasoning 1. The application authorized two sales from one unit even though the stored count ends at zero. The final value conceals the lost coordination.

  1. Use an atomic conditional decrement such as UPDATE inventory SET quantity=quantity−1 WHERE id=? AND quantity>=1, within the sale transaction.
  1. Require exactly one affected row before recording success. If no row changes, report unavailability and do not create a successful sale.
  1. Rollback the decrement if the required local sale record cannot be committed. External payment still needs a separately coordinated workflow and retry policy.

Failure-oriented laboratory: Concurrent updates, authorization and transaction recovery

A browser's hidden button is a presentation choice, not an authorization boundary. The server must derive the acting identity from a verified session and check that identity against the specific record before reading or writing it. Never accept owner_id from the request as proof of ownership. Return only fields the caller is entitled to receive.

Concurrency creates a separate correctness problem. If two clients read version 4 and both write a full record, the later write can silently erase the earlier change. Optimistic concurrency attaches an expected version to the update and commits only if it still matches. A database transaction can combine the condition, update and audit record so that failure does not publish half an operation. The exact isolation behavior must be established for the chosen database.

Idempotency and version checks address different questions. A retry token identifies the same requested operation; a version controls whether the underlying state is still the one the user edited. Store a request fingerprint with the retry token so token reuse for a different operation is rejected. Test actual simultaneous requests as well as sequential examples.

Worked fixture

Two authorized clients read a synthetic record at version 4. Client A saves a title change with expected version 4. Client B then saves an old full record with expected version 4.

Explain the fixture

A commits version 5. B must receive a conflict rather than overwrite A, because its expected version no longer matches. The server should return enough authorized state for B to review and deliberately merge. Automatic retrying of the stale full replacement can recreate the lost-update bug.

Integrated application: implementation, debugging and local deployment

The complete service-company project is now part of this unit’s applied work. It supplies an inspectable browser interface, HTTP server, persistent SQLite ledger, transaction tests, export recovery, permission-scoped retrieval and a separate synthetic logistic evaluation pipeline. Begin with its actual test suite, then trace one user request from UI to storage and back. The README distinguishes the local teaching environment from a production deployment.

Course-specific investigation

Run the actual simultaneous HTTP-write test. Trace verified demo identity to the tenant SQL condition, the BEGIN IMMEDIATE transaction, version check and audit insertion. Add a UI conflict-review flow and test recovery after a stale save.

What the evidence must establish

Exactly one of two conflicting fresh writes should commit. A retry of the identical event is a distinct case. A changed event using the same ID must fail, and an audit insertion failure must roll back the ledger and version together.

Keep a reproducibility log with Python version, launch command, fixture, expected result, observed result and explanation of any discrepancy. Introduce one deliberate defect and show the corresponding failing test before restoring the implementation. Passing an existing test without explaining its boundary is insufficient. The integration project remains optional practice rather than a mandatory capstone submission.

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:

```sql 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.

**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.

Apply the idea

Inventory is 1. Two transactions each read 1, approve one sale, and write 0. Both report success. Give an update that makes the final remaining inventory meaningful.

A parameterized order lookup filters only id. A user guesses another customer’s valid id. What additional condition is needed?

Additional laboratory — Run concurrent requests from two sessions, an unauthorized session and a retry using the same token with changed contents. Inject failure before the audit insert.

Complete-application investigation: Run the actual simultaneous HTTP-write test. Trace verified demo identity to the tenant SQL condition, the BEGIN IMMEDIATE transaction, version check and audit insertion. Add a UI conflict-review flow and test recovery after a stale save.

Read the worked reasoning

Scope the lookup or update to the verified customer, such as id=? AND customer_id=?, or a verified role/permission join. Derive the identity from trusted authentication, not a client field. Parameterization remains necessary but does not supply object-level authorization.

Additional laboratory model — Exactly one conflicting version-4 update should commit. Unauthorized access must fail at the server even if the UI is bypassed. Reusing an idempotency token with different contents must fail. Under the documented transaction boundary, audit failure must roll back the state change. Record actual results rather than assuming the database isolation level.

Application reasoning model: Exactly one of two conflicting fresh writes should commit. A retry of the identical event is a distinct case. A changed event using the same ID must fail, and an audit insertion failure must roll back the ledger and version together.

Check understanding

What does parameterization fail to establish by itself?

  1. Separation of SQL values from syntax
    Feedback

    Value separation is exactly what parameterized statements provide.

  2. Correct handling of quoted value text
    Feedback

    Proper parameter binding handles quotes without manual concatenation.

  3. Whether the caller is allowed to access the selected row
    Feedback

    Authorization requires an independent access-control decision.

Further reading

Current study directions: the original Academy lessons, preparation chapters, worked explanations and complete optional models on LawfareGroup.com provide the required conceptual preparation. Retained publisher/reference chapters, source exercises and their historical assignment directions are optional further study. Outside visits and assessments are optional. Independent subject review and observed learner testing remain pending. This current notice supersedes earlier textbook-supported study directions preserved below and in historical companion pages.

Use the complete original preparation chapter, preserved investigation and optional changed-record reasoning for this unit. Earlier source directions remain in immutable edition 4.

My learning →