The Lawfare Academy

Lawfare Group → Knowledge Institute → Lawfare Academy

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

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.

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.

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.

Check understanding

What does parameterization fail to establish by itself?

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

    Authorization requires an independent access-control decision.

  2. Separation of SQL values from syntax
    Feedback

    Value separation is exactly what parameterized statements provide.

  3. Correct handling of quoted value text
    Feedback

    Proper parameter binding handles quotes without manual concatenation.

Further reading

Study the complete on-site source sections below, then work the original example, changed-condition problem and transfer laboratory. Complete CS50 SQL Writing, Viewing, Optimizing and Scaling. Study CS50 Web SQL, Models and Migrations and Scalability and Security. Explain atomicity and access policy separately.

My learning →