Start learning free

LESSON 34 OF 56 · SECURITY: ACCESS CONTROL

Reports on a Read-Only Connection in Python

Practice

The shop has a report endpoint for admins: POST /reports takes the SQL an admin types, runs it and answers with the rows as JSON. But SQL can write as well as read. If reports run on the shop's normal read-write connection, anyone who holds the admin key, or an admin who pastes a query from a chat, can delete every order with one request: {"sql": "DELETE FROM orders"}.

Let the database refuse. A list of forbidden words always misses one: block DELETE and DROP, and UPDATE products SET price = 1 still gets through. Instead, open the file read-only: give connect an address like file:name.db?mode=ro together with uri=True, and SQLite itself refuses every write on that connection.

archive = sqlite3.connect("file:archive.db?mode=ro", uri=True)
archive.execute("SELECT COUNT(*) FROM old_orders").fetchone()   # works
archive.execute("DELETE FROM old_orders")
# sqlite3.OperationalError: attempt to write a readonly database
archive.close()

Three more details. A new connection doesn't copy the settings of db, so set its row_factory to sqlite3.Row, or dict(row) fails. Each report opens its own connection, so close it in a finally: block, which runs whether the query worked or the except part returned 400. And SQL's ATTACH can open the same file a second time with mode=rw: setting the connection's limit sqlite3.SQLITE_LIMIT_ATTACHED to 0 with setlimit shuts that side door.

Every request below carries the header X-Admin-Key: admin-key-6d2e, except the last one:

POST /reports  {"sql": "SELECT status, COUNT(*) AS orders FROM orders GROUP BY status ORDER BY status"}
  →  200  [{"orders": 1, "status": "cancelled"}, {"orders": 5, "status": "paid"}, {"orders": 1, "status": "shipped"}]
POST /reports  {"sql": "DELETE FROM orders"}
  →  400  {"error": "attempt to write a readonly database"}
POST /reports  {"sql": "UPDATE products SET price = 1"}
  →  400  {"error": "attempt to write a readonly database"}
POST /reports  {"sql": "DROP TABLE customers"}
  →  400  {"error": "attempt to write a readonly database"}
POST /reports  {"sql": "ATTACH DATABASE 'file:shop.db?mode=rw' AS w"}
  →  400  {"error": "too many attached databases - max 0"}
POST /reports  {"sql": "SELECT COUNT(*) AS orders FROM orders"}
  →  200  [{"orders": 7}]
POST /orders/7/cancel
  →  200  {"id": 7, "status": "cancelled"}
POST /reports  {"sql": "SELECT id, status FROM orders WHERE id = 7"}
  →  200  [{"id": 7, "status": "cancelled"}]
POST /reports  {"sql": "SELECT name, email FROM customers"}   (no X-Admin-Key)
  →  403  {"error": "Admins only"}

Your task: the starting code checks the admin key, runs the report's SQL inside try and turns a sqlite3.Error into 400. But it runs the SQL on reports_db, which doesn't exist yet, so every report answers 500. In run_report, open reports_db read-only, give it sqlite3.Row rows, close it in finally, and set its limit of attached databases to 0. The cancel route keeps using the read-write db.


Assignment
Follow the Coding Tutorial to run every report on its own read-only connection, closed after each report, that can't attach a writable copy of the file.


Hint
uri=True is what makes connect read ?mode=ro as an option instead of part of a file name. The finally: line sits at the level of try, and the setlimit line goes right below the connect line, even though you type it last.


STEP 1 OF 5
    Ctrl + Enter to check

    Secx Read Only Db in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free