diff --git a/README.md b/README.md index 448f167..96e8ba5 100644 --- a/README.md +++ b/README.md @@ -91,22 +91,34 @@ make test ```text .venv/bin/python -m pytest -q -........................................ [100%] -40 passed in 13.30s +....................................................... [100%] +55 passed in 16.70s ``` The suite is end to end and needs the container: before every test `tests/conftest.py` recreates the `public` schema through the same helper the Makefile uses, and the tests then call the real functions of `database.py` - the ones `main.py` calls - against PostgreSQL. Nothing is mocked except the keyboard. It checks the column order and the keys against `information_schema`, then walks the flows: sign up and log in (including the two rejected cases), catalogue search and detail view, ordering, a rent with its balance and end date, the refused rent, current and expired rentals, a message that is read, a broadcast to everybody except the sender, adding an article with a reused actor, a price change with its history, the two removal paths, and the statistics. Three tests guard the credentials: `database.py` must refuse to import without `NETFLOX_DB_PASSWORD`, no connection string may contain a password literal, and no tracked file may contain the value of that variable. -The tests at the end of `tests/test_netflox.py` are the regression suite: each one fails against the code before the fix and passes after it - there is no `xfail` and no `test_known_bug_*` left. "Known limitations" below lists what was deliberately left alone. +The tests at the end of `tests/test_netflox.py` are the regression suite: each one fails against the code before the fix and passes after it - there is no `xfail` and no `test_known_bug_*` left. `tests/test_injection.py` is the same kind of suite for the SQL: every statement in `database.py` is parameterized now, so a stacked `DROP TABLE`, an apostrophe in `O'Brien` and quotes inside a stored message are all just text. "Known limitations" below lists what was deliberately left alone. ### Known limitations Not fixed, and not covered by the suite, because they are the shape of the interface -rather than a defect with a single right answer: every statement is built by string -concatenation, so the input is interpolated into the SQL; the menus index the list they -just printed without checking the range (`article[x - 1]` past the end raises -`IndexError`); and `database.my_articles()` / `database.my_history()` read from the -keyboard, which puts the menu inside the data layer. +rather than a defect with a single right answer: + +- the menus index the list they just printed without checking the range, so + `article[x - 1]` past the end raises `IndexError`; +- `database.my_articles()` / `database.my_history()` read from the keyboard with + `input()`, which puts the menu inside the data layer; +- `database.message_all()` sizes its `while` loop with + `Sum(pg_column_size(userid))/4` instead of `count(*)`, so it stays tied to + `users.userid` being a 4-byte `int4` numbered from 1 without gaps; +- the client menu in `main.py` keeps its own copy of `USERID` + (`USERID = database.USERID`) while the administrator menu reads + `database.USERID`, so the two can drift apart. + +The SQL injection that used to be listed here is gone: the 48 statements that +interpolated a value are parameterized (`%s` with the value in a tuple), and no +identifier comes from input - every table and column name is a literal. The tests in +`tests/test_injection.py` fail against the previous version and pass against this one. ## Structure @@ -115,7 +127,8 @@ database.py every SQL statement and the connection; reads NETFLOX_DB_ main.py the menus: menu() -> client() or admin() schema.sql the relational schema (7 tables, primary and foreign keys) and the minimal seed scripts/db.py applies schema.sql and loads the demo rows; used by make schema/seed and the tests -tests/conftest.py recreates the schema before every test; tests/test_netflox.py is the suite +tests/conftest.py recreates the schema before every test; tests/*.py are the suites + (test_netflox.py the flows, test_injection.py the SQL) docker-compose.yml throwaway PostgreSQL (NetfloxFinal, postgres, 127.0.0.1:5432) Makefile up, schema, seed, run, test, down (plus venv, clean, help) requirements.txt psycopg2-binary; requirements-dev.txt adds pytest diff --git a/database.py b/database.py index 68f2476..f0e6c86 100644 --- a/database.py +++ b/database.py @@ -52,7 +52,11 @@ def create_user(name, email, password): print("\n\tCan't create accounts under netflox domain") else: - c.execute("INSERT INTO users (nome, email, password, balance) VALUES ('" + name + "','" + email + "','" + password + "',20)") + c.execute( + "INSERT INTO users (nome, email, password, balance)" + " VALUES (%s, %s, %s, 20)", + (name, email, password), + ) conn.commit() conn.close() @@ -60,7 +64,10 @@ def log_in(email, password): with _connection() as conn: c = conn.cursor() - c.execute("SELECT * FROM users WHERE email = '" + email + "' AND password = '" + password + "'") + c.execute( + "SELECT * FROM users WHERE email = %s AND password = %s", + (email, password), + ) results = c.fetchall() global USERID @@ -94,7 +101,10 @@ def show_unread_messages(userid): with _connection() as conn: c = conn.cursor() - c.execute("SELECT * FROM messages WHERE users_userid = " + str(userid) + " AND bolread = FALSE") + c.execute( + "SELECT * FROM messages WHERE users_userid = %s AND bolread = FALSE", + (userid,), + ) results = c.fetchall() if results: @@ -103,7 +113,7 @@ def show_unread_messages(userid): for i in results: # i[4] is the recipient, i[5] is the sender: the list used to name # every message after the account that received it. - c.execute("SELECT * FROM users WHERE userid = " + str(i[5])) + c.execute("SELECT * FROM users WHERE userid = %s", (i[5],)) sender = c.fetchall() for x in sender: y += 1 @@ -121,13 +131,16 @@ def show_read_messages(userid): with _connection() as conn: c = conn.cursor() - c.execute("SELECT * FROM messages WHERE users_userid = " + str(userid) + " AND bolread = TRUE") + c.execute( + "SELECT * FROM messages WHERE users_userid = %s AND bolread = TRUE", + (userid,), + ) messages = c.fetchall() y = 0 print("\r") for i in messages: - c.execute("SELECT * FROM users WHERE userid = " + str(i[5])) + c.execute("SELECT * FROM users WHERE userid = %s", (i[5],)) sender = c.fetchall() for x in sender: y += 1 @@ -141,7 +154,7 @@ def read_message(msgid): with _connection() as conn: c = conn.cursor() - c.execute("UPDATE messages SET bolread = TRUE WHERE msgid='" + str(msgid) + "'") + c.execute("UPDATE messages SET bolread = TRUE WHERE msgid = %s", (msgid,)) conn.commit() conn.close() @@ -160,8 +173,11 @@ def message_all(msg, senderid): while i < size: if results[i][0] != senderid: c.execute( - "INSERT INTO messages (message, bolread, users_userid, senderid, data) VALUES ('" + msg + "', FALSE, '" + str( - results[i][0]) + "', '" + str(senderid) + "', CURRENT_DATE)") + "INSERT INTO messages" + " (message, bolread, users_userid, senderid, data)" + " VALUES (%s, FALSE, %s, %s, CURRENT_DATE)", + (msg, results[i][0], senderid), + ) i += 1 print("\n\tMessage sent to all") @@ -173,8 +189,11 @@ def message_client(msg, recieverid, senderid): c = conn.cursor() c.execute( - "INSERT INTO messages (message, bolread, users_userid, senderid, data) VALUES ('" + msg + "', FALSE, '" + - str(recieverid) + "', '" + str(senderid) + "', CURRENT_DATE)") + "INSERT INTO messages" + " (message, bolread, users_userid, senderid, data)" + " VALUES (%s, FALSE, %s, %s, CURRENT_DATE)", + (msg, recieverid, senderid), + ) print("\n\tMessage sent successfully") @@ -185,7 +204,7 @@ def message_client(msg, recieverid, senderid): def findby_name(name): with _connection() as conn: c = conn.cursor() - c.execute("SELECT * FROM articles WHERE name like '%" + name + "%'") + c.execute("SELECT * FROM articles WHERE name like %s", ("%" + name + "%",)) movies = c.fetchall() y = 0 for x in movies: @@ -203,7 +222,10 @@ def findby_director(director): with _connection() as conn: y = 0 c = conn.cursor() - c.execute("SELECT * FROM articles WHERE director like '%" + director + "%'") + c.execute( + "SELECT * FROM articles WHERE director like %s", + ("%" + director + "%",), + ) movies = c.fetchall() for x in movies: y = y + 1 @@ -220,7 +242,7 @@ def findby_type(type): with _connection() as conn: y = 0 c = conn.cursor() - c.execute("SELECT * FROM articles WHERE type like '%" + type + "%'") + c.execute("SELECT * FROM articles WHERE type like %s", ("%" + type + "%",)) movies = c.fetchall() for x in movies: y = y + 1 @@ -237,17 +259,20 @@ def findby_actor(actor): with _connection() as conn: j = 0 c = conn.cursor() - c.execute("SELECT * FROM actors WHERE name like('%" + actor + "%')") + c.execute("SELECT * FROM actors WHERE name like %s", ("%" + actor + "%",)) actors = c.fetchall() print("\r") articles = [] for x in actors: actorid = x[0] - c.execute("SELECT * FROM articles_actors WHERE actors_actorid = '" + str(actorid) + "' ") + c.execute( + "SELECT * FROM articles_actors WHERE actors_actorid = %s", + (actorid,), + ) articles_actors = c.fetchall() for y in articles_actors: j = j + 1 - c.execute("SELECT * FROM articles WHERE itemid = '" + str(y[0]) + "' ") + c.execute("SELECT * FROM articles WHERE itemid = %s", (y[0],)) matched = c.fetchall() if matched: articles.append(matched[0]) @@ -278,7 +303,7 @@ def list_all(): def view_details(itemid): with _connection() as conn: c = conn.cursor() - c.execute("SELECT * FROM articles WHERE itemid = '"+str(itemid)+"'") + c.execute("SELECT * FROM articles WHERE itemid = %s", (itemid,)) article = c.fetchall()[0] print("\n\tTitle: "+str(article[1])) print("\tDirector: " + str(article[2])) @@ -290,11 +315,13 @@ def view_details(itemid): print("\tTime available: " + str(article[8]) + " days") print("\tActors: ") - c.execute("SELECT * FROM articles_actors WHERE articles_itemid = '" + str(itemid) + "'") + c.execute( + "SELECT * FROM articles_actors WHERE articles_itemid = %s", (itemid,) + ) actors = c.fetchall() for i in actors: - c.execute("SELECT * FROM actors WHERE actorid = '" + str(i[1]) + "'") + c.execute("SELECT * FROM actors WHERE actorid = %s", (i[1],)) actors_name = c.fetchall()[0][1] print("\t\t"+str(actors_name)) @@ -304,10 +331,10 @@ def purchase(itemid, userid): with _connection() as conn: c = conn.cursor() - c.execute("SELECT balance FROM users WHERE userid = '" + str(userid) + "'") + c.execute("SELECT balance FROM users WHERE userid = %s", (userid,)) balance = c.fetchall()[0][0] - c.execute("SELECT price FROM articles WHERE itemid = '" + str(itemid) + "'") + c.execute("SELECT price FROM articles WHERE itemid = %s", (itemid,)) cost = c.fetchall()[0][0] if balance >= cost: @@ -315,12 +342,21 @@ def purchase(itemid, userid): # The debit follows the userid argument, not USERID (the account of # the last log_in): buying for somebody else used to charge the # logged-in account while the rent went to the argument. - c.execute("UPDATE users SET balance= '" + str(new_balance) + "' WHERE userid='" + str(userid) + "'") + c.execute( + "UPDATE users SET balance = %s WHERE userid = %s", + (new_balance, userid), + ) - c.execute("SELECT time_available FROM articles WHERE itemid = '" + str(itemid) + "'") + c.execute( + "SELECT time_available FROM articles WHERE itemid = %s", (itemid,) + ) time_available = c.fetchall()[0][0] - c.execute("INSERT INTO rents (purchased_date, end_date, articles_itemid, users_userid) VALUES (CURRENT_DATE, CURRENT_DATE +" + str(int(time_available)) + ",'" + str(itemid) + "','" + str(userid) + "')") + c.execute( + "INSERT INTO rents (purchased_date, end_date, articles_itemid," + " users_userid) VALUES (CURRENT_DATE, CURRENT_DATE + %s, %s, %s)", + (int(time_available), itemid, userid), + ) print("\n\tPurchase successful!") print("\tNew balance: " + str(new_balance) + "€") @@ -440,7 +476,11 @@ def my_articles(userid): with _connection() as conn: c = conn.cursor() - c.execute("SELECT * FROM rents WHERE end_date >= CURRENT_DATE AND users_userid = '" + str(userid) + "' ORDER BY articles_itemid") + c.execute( + "SELECT * FROM rents WHERE end_date >= CURRENT_DATE" + " AND users_userid = %s ORDER BY articles_itemid", + (userid,), + ) rents = c.fetchall() if rents: @@ -448,7 +488,10 @@ def my_articles(userid): print("\n\tMy articles:\n") for i in rents: y += 1 - c.execute("SELECT * FROM articles WHERE itemid = '" + str(i[3]) + "' ORDER BY itemid") + c.execute( + "SELECT * FROM articles WHERE itemid = %s ORDER BY itemid", + (i[3],), + ) articles = c.fetchall() print("\t"+str(articles[0][0])+") "+str(articles[0][1])) @@ -463,7 +506,11 @@ def my_history(userid): with _connection() as conn: c = conn.cursor() - c.execute("SELECT * FROM rents WHERE end_date < CURRENT_DATE AND users_userid = '" + str(userid) + "' ORDER BY articles_itemid") + c.execute( + "SELECT * FROM rents WHERE end_date < CURRENT_DATE" + " AND users_userid = %s ORDER BY articles_itemid", + (userid,), + ) rents = c.fetchall() if rents: @@ -471,7 +518,10 @@ def my_history(userid): print("\n\tMy old articles:\n") for i in rents: y += 1 - c.execute("SELECT * FROM articles WHERE itemid = '" + str(i[3]) + "' ORDER BY itemid") + c.execute( + "SELECT * FROM articles WHERE itemid = %s ORDER BY itemid", + (i[3],), + ) articles = c.fetchall() print("\t" + str(articles[0][1])) @@ -486,7 +536,10 @@ def time_left(itemid, userid): with _connection() as conn: c = conn.cursor() - c.execute("SELECT * FROM rents WHERE articles_itemid = "+str(itemid)+" AND users_userid = '"+str(userid)+"'") + c.execute( + "SELECT * FROM rents WHERE articles_itemid = %s AND users_userid = %s", + (itemid, userid), + ) time = c.fetchall()[0][2] print("\n\tItem available until "+str(time)) @@ -499,8 +552,13 @@ def add_article(name, director, imbd_rating, genre, price, year, time_available, with _connection() as conn: c = conn.cursor() - c.execute("INSERT INTO articles(name, director, release_year, imbd_rating, genre, price, type, time_available) VALUES('" + name + "','" + director + "', '" + year + "','" + imbd_rating + "','" + genre + "','" + price + "','" + type + "','" + time_available + "')") - c.execute("SELECT * FROM articles WHERE name = '" + name + "'") + c.execute( + "INSERT INTO articles(name, director, release_year, imbd_rating," + " genre, price, type, time_available)" + " VALUES (%s, %s, %s, %s, %s, %s, %s, %s)", + (name, director, year, imbd_rating, genre, price, type, time_available), + ) + c.execute("SELECT * FROM articles WHERE name = %s", (name,)) item_id = c.fetchall()[0][0] n_actors = int(input("\n\tNumber of actors: ")) @@ -509,16 +567,24 @@ def add_article(name, director, imbd_rating, genre, price, year, time_available, x += 1 name_actor = str(input("\n\tActor name: ")) - c.execute("SELECT * FROM actors WHERE name ='" + name_actor + "'") + c.execute("SELECT * FROM actors WHERE name = %s", (name_actor,)) actor = c.fetchall() if actor: - c.execute("INSERT INTO articles_actors(articles_itemid, actors_actorid) VALUES ('" + str(item_id) + "', '" + str(actor[0][0]) + "' )") + c.execute( + "INSERT INTO articles_actors (articles_itemid, actors_actorid)" + " VALUES (%s, %s)", + (item_id, actor[0][0]), + ) else: - c.execute("INSERT INTO actors (name) VALUES ('" + name_actor + "')") - c.execute("SELECT * FROM actors WHERE name ='" + name_actor + "'") + c.execute("INSERT INTO actors (name) VALUES (%s)", (name_actor,)) + c.execute("SELECT * FROM actors WHERE name = %s", (name_actor,)) actor_id = c.fetchall()[0][0] - c.execute("INSERT INTO articles_actors(articles_itemid, actors_actorid) VALUES ('" + str(item_id) + "', '" + str(actor_id) + "')") + c.execute( + "INSERT INTO articles_actors (articles_itemid, actors_actorid)" + " VALUES (%s, %s)", + (item_id, actor_id), + ) print("\n\tSuccess!") @@ -530,21 +596,25 @@ def change_price(n_id, newprice): itemid = n_id if isinstance(n_id, str): - c.execute("SELECT itemid FROM articles WHERE name = '" + n_id + "'") + c.execute("SELECT itemid FROM articles WHERE name = %s", (n_id,)) n_id = c.fetchall() for i in n_id: itemid = i[0] - c.execute("SELECT price FROM articles WHERE itemid = '" + str(itemid) + "'") + c.execute("SELECT price FROM articles WHERE itemid = %s", (itemid,)) result = c.fetchall() oldprice = 0 for i in result: oldprice = i[0] - c.execute("UPDATE articles SET price = '" + str(newprice) + "' WHERE itemid = '" + str(itemid) + "'") c.execute( - "INSERT INTO pricehistory(old_price, change_date, articles_itemid) VALUES('" + str(oldprice) + "', CURRENT_DATE,'" + str( - itemid) + "')") + "UPDATE articles SET price = %s WHERE itemid = %s", (newprice, itemid) + ) + c.execute( + "INSERT INTO pricehistory(old_price, change_date, articles_itemid)" + " VALUES(%s, CURRENT_DATE, %s)", + (oldprice, itemid), + ) print("\n\tPrice updated successfully") print("\tOld price saved to history") @@ -557,12 +627,16 @@ def remove_article(n_id): itemid = n_id if isinstance(n_id, str): - c.execute("SELECT itemid FROM articles WHERE name = '" + n_id + "'") + c.execute("SELECT itemid FROM articles WHERE name = %s", (n_id,)) n_id = c.fetchall() for i in n_id: itemid = i[0] - c.execute("SELECT * FROM rents WHERE articles_itemid = '" + str(itemid) + "' AND CURRENT_DATE < end_date") + c.execute( + "SELECT * FROM rents WHERE articles_itemid = %s" + " AND CURRENT_DATE < end_date", + (itemid,), + ) result = c.fetchall() if result: print("\n\tCan't remove article because there are user(s) renting it") @@ -571,9 +645,13 @@ def remove_article(n_id): # The foreign keys block the article through the rents that already ended # and through its price history too; checking only the open rents turned # the refusal into a ForeignKeyViolation traceback. - c.execute("SELECT count(*) FROM rents WHERE articles_itemid = '" + str(itemid) + "'") + c.execute( + "SELECT count(*) FROM rents WHERE articles_itemid = %s", (itemid,) + ) old_rents = c.fetchall()[0][0] - c.execute("SELECT count(*) FROM pricehistory WHERE articles_itemid = '" + str(itemid) + "'") + c.execute( + "SELECT count(*) FROM pricehistory WHERE articles_itemid = %s", (itemid,) + ) price_changes = c.fetchall()[0][0] if old_rents or price_changes: kept_by = [] @@ -586,8 +664,10 @@ def remove_article(n_id): return try: - c.execute("DELETE FROM articles_actors WHERE articles_itemid = '" + str(itemid) + "'") - c.execute("DELETE FROM articles WHERE itemid = '" + str(itemid) + "'") + c.execute( + "DELETE FROM articles_actors WHERE articles_itemid = %s", (itemid,) + ) + c.execute("DELETE FROM articles WHERE itemid = %s", (itemid,)) except psycopg2.errors.ForeignKeyViolation: conn.rollback() print("\n\tCan't remove article because another table still refers to it") @@ -600,7 +680,9 @@ def alter_balance(userid, balance): with _connection() as conn: c = conn.cursor() - c.execute("UPDATE users SET balance = '" + str(balance) + "' WHERE userid='" + str(userid) + "'") + c.execute( + "UPDATE users SET balance = %s WHERE userid = %s", (balance, userid) + ) print("\n\tBalance updated successfully") @@ -613,7 +695,7 @@ def statistics(): c.execute("SELECT articles_itemid FROM rents") rents = c.fetchall() for x in rents: - c.execute("SELECT * FROM articles WHERE itemid= '"+str(x[0])+"' ") + c.execute("SELECT * FROM articles WHERE itemid = %s", (x[0],)) price=c.fetchall() for y in price: total=total+y[6] @@ -659,7 +741,7 @@ def statistics(): c.execute("SELECT * FROM rents WHERE end_date > CURRENT_DATE ") rents2 = c.fetchall() for e in rents2: - c.execute("SELECT * FROM articles WHERE itemid= '"+str(e[3])+"' ") + c.execute("SELECT * FROM articles WHERE itemid = %s", (e[3],)) price2=c.fetchall() for d in price2: total2=total2+d[6] diff --git a/tests/test_injection.py b/tests/test_injection.py new file mode 100644 index 0000000..fb46420 --- /dev/null +++ b/tests/test_injection.py @@ -0,0 +1,282 @@ +"""Regression tests for the SQL injection that used to be in database.py. + +Every statement in database.py was built by concatenating the value into the +SQL text, so anything that reached a search box, a sign-up form or a message +body was interpreted as SQL. Every statement is parameterized now (the value +travels as a psycopg2 parameter, never as part of the statement) and these tests +pin that. + +Each test here fails against the previous, concatenating version of +database.py - see README, "Known limitations" and "Tests". The payloads are the +usual ones: a stacked `DROP TABLE`, a legitimate apostrophe, and quotes inside +the text that is stored and read back. +""" +from __future__ import annotations + +import ast +import builtins +import contextlib +import os +import pathlib + +import pytest + +import database +from scripts import db as dbctl + +ROOT = pathlib.Path(__file__).resolve().parent.parent +ADMIN_EMAIL = dbctl.ADMIN[1] + +# Two statements in one call, and then a comment that swallows the trailing +# quote: `LIKE '%'; DROP TABLE users; --%'`. +DROP_PAYLOAD = "'; DROP TABLE users; --" + + +# -------------------------------------------------------------------------- +# helpers (same shape as the ones in test_netflox.py) +# -------------------------------------------------------------------------- +def demo_password() -> str: + return os.environ["NETFLOX_DEMO_PASSWORD"] + + +@contextlib.contextmanager +def raw_cursor(): + """A plain connection to the throwaway database, for assertions.""" + conn = dbctl.connect() + try: + with conn.cursor() as cur: + yield cur + conn.commit() + finally: + conn.close() + + +def scalar(sql, params=None): + with raw_cursor() as cur: + cur.execute(sql, params) + row = cur.fetchone() + return row[0] if row else None + + +def user_id(email: str) -> int: + return scalar("SELECT userid FROM users WHERE email = %s", (email,)) + + +def make_client(name="Ana", email="ana@exemplo.pt") -> int: + database.create_user(name, email, demo_password()) + assert database.log_in(email, demo_password()) == 1 + return database.USERID + + +def feed_inputs(monkeypatch, values): + queue = list(values) + + def fake_input(prompt=""): + if not queue: + raise AssertionError(f"unexpected input() call: {prompt!r}") + return queue.pop(0) + + monkeypatch.setattr(builtins, "input", fake_input) + + +def insert_article(name, director, actors=(), **overrides): + """Insert one article (and its cast) with parameterized SQL, for fixtures.""" + fields = { + "release_year": 1995, + "imbd_rating": 7.0, + "genre": "drama", + "price": 1.50, + "type": "movie", + "time_available": 7, + } + fields.update(overrides) + with raw_cursor() as cur: + cur.execute( + "INSERT INTO articles (name, director, release_year, imbd_rating," + " genre, price, type, time_available)" + " VALUES (%s, %s, %s, %s, %s, %s, %s, %s) RETURNING itemid", + (name, director, fields["release_year"], fields["imbd_rating"], + fields["genre"], fields["price"], fields["type"], + fields["time_available"]), + ) + itemid = cur.fetchone()[0] + for actor in actors: + cur.execute("INSERT INTO actors (name) VALUES (%s) RETURNING actorid", + (actor,)) + cur.execute( + "INSERT INTO articles_actors (articles_itemid, actors_actorid)" + " VALUES (%s, %s)", + (itemid, cur.fetchone()[0]), + ) + return itemid + + +# -------------------------------------------------------------------------- +# (a) a stacked DROP TABLE is searched as text and changes nothing +# -------------------------------------------------------------------------- +@pytest.mark.parametrize("search", [ + "findby_name", "findby_director", "findby_type", "findby_actor", +]) +def test_a_drop_table_payload_is_searched_as_text(capsys, search): + """The payload used to be pasted into the statement, which turned the search + into two statements: the SELECT, and `DROP TABLE users`. The SELECT matching + `LIKE '%'` also returned every article as if it were a search result. + + Now it is one parameter, the pattern matches nothing (there is no article + with that name), and the statement is a search like any other. + """ + result = getattr(database, search)(DROP_PAYLOAD) + capsys.readouterr() + + # findby_actor returns None when nothing matches; the other three return []. + assert result in ([], None) + + # The table is still there, and still has its rows, after the search. + assert scalar("SELECT to_regclass('public.users') IS NOT NULL") is True + assert scalar("SELECT count(*) FROM users") >= 2 + assert scalar("SELECT count(*) FROM articles") == 6 + + +# -------------------------------------------------------------------------- +# (b) a legitimate apostrophe is a character, not the end of a literal +# -------------------------------------------------------------------------- +def test_an_apostrophe_in_a_search_term_is_text(capsys): + """`LIKE '%O'Brien%'` used to be a syntax error (unterminated string).""" + insert_article("O'Brien's Ghost", "Ana O'Brien", actors=["Sean O'Brien"]) + capsys.readouterr() + + assert [row[1] for row in database.findby_name("O'Brien")] == ["O'Brien's Ghost"] + assert [row[1] for row in database.findby_director("O'Brien")] == ["O'Brien's Ghost"] + assert [row[1] for row in database.findby_actor("O'Brien")] == ["O'Brien's Ghost"] + # findby_type() searches the movie/series column, where an apostrophe can + # only appear as a fragment that matches nothing - and it is still a + # fragment, not the end of a string literal. + assert database.findby_type("movie'") == [] + capsys.readouterr() + + +def test_an_apostrophe_in_an_admin_lookup_is_text(capsys): + """change_price()/remove_article() look the article up by name first.""" + insert_article("O'Brien's Ghost", "Ana O'Brien") + capsys.readouterr() + + database.change_price("O'Brien's Ghost", "2.00") + capsys.readouterr() + assert scalar("SELECT price FROM articles WHERE name = %s", + ("O'Brien's Ghost",)) == 2 + assert scalar("SELECT count(*) FROM pricehistory") == 1 + + +# -------------------------------------------------------------------------- +# (c) quotes in stored text survive a write and a read, unchanged +# -------------------------------------------------------------------------- +def test_create_user_stores_quotes_exactly(capsys): + """`VALUES ('Ana 'Aspas' Silva', ...)` used to be a syntax error.""" + name = "Ana 'Aspas' Silva" + password = demo_password() + + database.create_user(name, "anasilva@exemplo.pt", password) + capsys.readouterr() + + assert scalar("SELECT nome FROM users WHERE email = %s", + ("anasilva@exemplo.pt",)) == name + assert scalar("SELECT password FROM users WHERE email = %s", + ("anasilva@exemplo.pt",)) == password + # And the account is usable: the same quotes go through log_in(). + assert database.log_in("anasilva@exemplo.pt", password) == 1 + capsys.readouterr() + + +def test_a_message_with_quotes_is_stored_exactly(capsys): + client = make_client() + admin = user_id(ADMIN_EMAIL) + text = "Ele disse 'olá' e \"adeus\" 'a'" + capsys.readouterr() + + database.message_client(text, str(client), str(admin)) + capsys.readouterr() + + assert scalar("SELECT message FROM messages WHERE users_userid = %s", + (client,)) == text + assert scalar("SELECT count(*) FROM messages WHERE senderid = %s", + (admin,)) == 1 + + +def test_a_broadcast_with_quotes_is_stored_exactly(capsys): + admin = user_id(ADMIN_EMAIL) + total_users = scalar("SELECT count(*) FROM users") + text = "Aviso: 'manutenção' \"; DROP TABLE messages; --" + + database.message_all(text, admin) + capsys.readouterr() + + assert scalar("SELECT count(*) FROM messages WHERE message = %s", + (text,)) == total_users - 1 + assert scalar("SELECT count(*) FROM messages") == total_users - 1 + + +def test_add_article_stores_quotes_exactly(monkeypatch, capsys): + feed_inputs(monkeypatch, ["1", "Sean O'Brien"]) + + database.add_article("O'Brien's Ghost", "Ana O'Brien", "7.0", "drama", + "1.50", "1995", "7", "movie") + capsys.readouterr() + + itemid = scalar("SELECT itemid FROM articles WHERE name = %s", + ("O'Brien's Ghost",)) + assert itemid is not None + assert scalar("SELECT director FROM articles WHERE itemid = %s", + (itemid,)) == "Ana O'Brien" + assert scalar("SELECT count(*) FROM actors WHERE name = %s", + ("Sean O'Brien",)) == 1 + assert scalar("SELECT count(*) FROM articles_actors WHERE articles_itemid = %s", + (itemid,)) == 1 + + +# -------------------------------------------------------------------------- +# the password cannot be commented out or short-circuited +# -------------------------------------------------------------------------- +@pytest.mark.parametrize("payload", ["' OR '1'='1", "' OR 1=1 --", "x' OR 'a'='a"]) +def test_the_password_cannot_be_bypassed(capsys, payload): + """`password = '' OR '1'='1'` used to be true for every row, so log_in() + handed out the administrator session for any password.""" + before = database.USERID # a failed login must not move the session + assert database.log_in(ADMIN_EMAIL, payload) == 0 + capsys.readouterr() + assert database.USERID == before + + +def test_the_email_cannot_comment_out_the_password(capsys): + """`email = 'admin@netflox.com' --' AND password = '...'` used to match.""" + before = database.USERID + assert database.log_in("admin@netflox.com' --", "not-the-password") == 0 + capsys.readouterr() + assert database.USERID == before + + +# -------------------------------------------------------------------------- +# structural guard: no statement may be assembled from parts again +# -------------------------------------------------------------------------- +def test_no_statement_is_built_by_string_concatenation(): + """Every execute() must receive a constant string (plus its parameters). + + This is what the previous version looked like in all 48 interpolated + statements: `c.execute("... = '" + value + "'")`, an ast.BinOp as the first + argument. + """ + source = (ROOT / "database.py").read_text(encoding="utf-8") + tree = ast.parse(source) + + offenders = [] + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + func = node.func + name = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", "") + if name != "execute" or not node.args: + continue + statement = node.args[0] + if not (isinstance(statement, ast.Constant) and isinstance(statement.value, str)): + offenders.append(ast.get_source_segment(source, statement)) + + assert offenders == [], f"statements assembled at runtime: {offenders}"