Compare commits

..
57 Commits
Author SHA1 Message Date
Andre Neto 0a2e4d9468 licenca: nomeia o co-autor no copyright — a linha passa a André Neto and Alexandre Cavadas de Almeida, os dois autores do relatorio docs/relatorio-BD.pdf. So a atribuicao; a licenca MIT ja aplicada nao muda. 2026-10-08 15:01:27 +01:00
Andre Neto 3d14aadbb5 Parameterize every SQL statement: the injection is gone
All 48 statements that pasted a value into the SQL text now send it as a
psycopg2 parameter, so a search term, an account name or a message body is data
and nothing else. Before this, `findby_name("'; DROP TABLE users; --")` ran two
statements, `log_in(admin, "' OR '1'='1")` handed out an administrator session
for a wrong password, and a legitimate apostrophe in `O'Brien` was a syntax
error.

No semantics changed: same statements, same column order and types (SELECT *
read by position, users.userid still a 4-byte int4), and every table/column name
is a literal - no identifier comes from input, so no whitelist was needed. The
connection string keeps `password={DB_PASSWORD}` from the environment, and the
LIKE fragments keep their wildcards in the parameter.

tests/test_injection.py adds 15 tests: the stacked DROP TABLE (no exception, and
the table is still there, checked with a SELECT), the legitimate apostrophe, the
quotes written and read back byte for byte through create_user/message_client/
message_all/add_article, the password bypass, and a structural guard that every
execute() receives a constant string. All 15 fail against the previous
database.py; `make test` is 55 passed, 0 failed.

README: SQL injection leaves "Known limitations"; what stays is listed (the
article[x - 1] IndexError, input() in the data layer, message_all()'s
Sum(pg_column_size(userid))/4, and the global USERID copy in main.py).
2026-10-08 14:56:39 +01:00
Andre Neto bfd711271b Add MIT LICENSE (first commit year 2020) and point the README section to it
O repo era publico e espelhado sem licenca: sem LICENSE os direitos ficam
reservados e ninguem pode reutilizar o codigo. MIT foi a licenca decidida para
o catalogo; o ano do copyright e o do primeiro commit, nao o de hoje.
2026-10-08 14:53:34 +01:00
Andre Neto db490b0354 Fix the defects the suite pinned; turn xfail/known_bug into regressions
The suite documented every defect with two `xfail` and four `test_known_bug_*`
tests. With the tests as the specification, all of them are fixed and those
tests are now regression tests that fail against the previous code:

- findby_director() returned None on the success path (it printed the matches
  and fell off the end); it returns the rows now.
- findby_actor() raised UnboundLocalError when no actor matched, and returned
  only the last article of an actor with several; it returns the list, or None.
- findby_name() and findby_type() returned the integer 0 on no match, which
  main.py indexed into; they return an empty list and the menus skip it.
- purchase() debited USERID (the account of the last log_in) instead of the
  userid argument, while the rent went to the argument.
- the message list looked the author up with row[4] (the recipient) instead of
  row[5] (the sender), in the unread and in the read list.
- remove_article() checked only the open rents, so the foreign keys on the
  older rents and on pricehistory turned the refusal into a traceback; it now
  explains which records keep the article and rolls back as a backstop.
- show_unread_messages() returned None when there was nothing; it returns an
  empty list like the read side, and the messages menu skips an empty list.
- database.USERID did not exist before a login, so leaving the menu with 0
  raised AttributeError; it starts as None and the menu code handles 0.
- every connection is opened and closed by one context manager:
  findby_director(), findby_actor() and findby_type() returned before
  conn.close() and statistics() never closed, leaving sessions
  `idle in transaction`.

make test: 40 passed, 0 xfailed (was 30 passed, 2 xfailed). No xfail and no
test_known_bug_* is left. The README's previous "what is broken" paragraph and
its test output are updated, and a "Known limitations" section lists what was
deliberately not touched: SQL built by string concatenation, menu selections
past the end of the list, and input() inside the data layer.
2026-10-08 14:38:11 +01:00
Andre Neto 4ef5a67343 Add the schema, the dependencies and an end-to-end test suite
The schema existed only inside the queries, so a clean clone could not run:
nothing created the tables that database.py and main.py expect, and there was
no declaration of what to install.

- schema.sql: the seven tables, their primary and foreign keys, and the
  administrator the code requires. Reconstructed from the SQL the code issues
  and typed for it: the code reads rows by position (SELECT *), so the column
  order is part of the contract, and users.userid has to be a 4-byte integer
  because message_all() counts rows with pg_column_size(userid)/4.
- scripts/db.py, Makefile, docker-compose.yml: a throwaway PostgreSQL and the
  targets up/schema/seed/run/test/down. Both passwords come from the
  environment (NETFLOX_DB_PASSWORD, NETFLOX_DEMO_PASSWORD); nothing is stored
  in the repository, and schema.sql receives the administrator password
  through a session setting.
- requirements.txt and requirements-dev.txt: psycopg2-binary, plus pytest for
  the suite.
- tests/: 30 end-to-end tests that recreate the schema and drive the real
  functions of database.py. They check the column order and the keys against
  information_schema and walk every main flow. The defects found while mapping
  the code are pinned by test_known_bug_* and xfail instead of fixed, since
  fixing the application was not part of this change. The suite also guards the
  credential fix: database.py must refuse to import without its variable and no
  tracked file may contain the value.
- README.md: the sections shared with the other repositories, with a real
  session.
- The report moved to docs/relatorio-BD.pdf: it had accents and spaces in the
  filename.
2026-10-08 14:26:47 +01:00
Andre Neto c2a253071e Netflox: read DB password from env; stop tracking archive with old password
database.py had the PostgreSQL password in plain text (inline literal repeated
in every psycopg2.connect call). It now reads NETFLOX_DB_PASSWORD once at
import time and raises RuntimeError if it is unset, so there is no default.

The committed Projeto_Netflox_*.zip embeds the same database.py and therefore
still carries the old password, so it is removed from the index
(git rm --cached; the file stays on disk outside the working tree). README.md
documents the env var and the archive removal.

Why: the credential must not live in the repository. The value is still in the
history and in any clone/cache, so it must be rotated.
2026-10-08 14:03:21 +01:00
alexalmeida2001 9177ffb7e9 Add files via upload 2020-12-12 21:58:55 +00:00
alexalmeida2001 8074252074 Add files via upload 2020-12-12 21:56:44 +00:00
agsNeto20 22dd6968d9 Add files via upload 2020-12-12 13:40:18 +00:00
agsNeto20 b19b0f3fdb Delete main.py 2020-12-12 13:40:07 +00:00
agsNeto20 32877ad278 Delete database.py 2020-12-12 13:36:46 +00:00
agsNeto20 dced1e0d7e Add files via upload 2020-12-12 06:31:39 +00:00
agsNeto20 64ab222151 Delete ernetflox.json 2020-12-12 06:28:21 +00:00
agsNeto20 40155dd2b3 Delete sqlfinal.sql 2020-12-12 06:25:19 +00:00
agsNeto20 566c211785 Delete main.py 2020-12-12 06:25:12 +00:00
agsNeto20 b76cce566c Delete database.py 2020-12-12 06:25:04 +00:00
agsNeto20 303e1b2fc7 Update database.py 2020-12-11 22:09:10 +00:00
agsNeto20 7af6b46ed4 Update main.py 2020-12-11 22:00:54 +00:00
agsNeto20 baecf5a0c5 Update database.py 2020-12-11 22:00:32 +00:00
agsNeto20 022436c7b3 Add files via upload 2020-12-10 20:02:08 +00:00
agsNeto20 2e7a798c59 Add files via upload 2020-12-10 20:01:58 +00:00
agsNeto20 cc61339385 Delete projetodatabase_alex_UPDATED.sql 2020-12-10 20:01:19 +00:00
agsNeto20 cd4eb4a6dd Delete main_CODIGO_TOTAL 2020-12-10 20:01:09 +00:00
agsNeto20 d3fe512121 Delete database_TOTAL 2020-12-10 20:01:01 +00:00
agsNeto20 2cff69bdae Delete databaseUPDATED-alex.py 2020-12-10 20:00:55 +00:00
agsNeto20 9b11d10792 Delete database.py 2020-12-10 20:00:49 +00:00
agsNeto20 cfe71e66bd Delete appUPDATED-alex.py 2020-12-10 20:00:37 +00:00
agsNeto20 a67fc2c8fe Delete app.py 2020-12-10 20:00:29 +00:00
agsNeto20 21fb445d03 Delete DATABASE_SQL 2020-12-10 20:00:18 +00:00
alexalmeida2001 d2709b2a3c Add files via upload 2020-12-10 12:01:36 +00:00
alexalmeida2001 eb12a528c9 Update main_CODIGO_TOTAL 2020-12-10 11:56:48 +00:00
alexalmeida2001 96911c6f1f Add files via upload 2020-12-10 01:20:21 +00:00
alexalmeida2001 2854c36929 Create database_TOTAL 2020-12-09 10:50:09 +00:00
alexalmeida2001 734b48fa6e Create main_CODIGO_TOTAL 2020-12-09 10:49:37 +00:00
alexalmeida2001 88b6ca0ea8 Update databaseUPDATED-alex.py 2020-12-07 17:29:39 +00:00
alexalmeida2001 95e361c167 Update app.py 2020-12-07 17:29:19 +00:00
alexalmeida2001 cf57033a75 Update databaseUPDATED-alex.py 2020-12-07 16:23:15 +00:00
alexalmeida2001 916beb4905 Update appUPDATED-alex.py 2020-12-07 16:22:46 +00:00
alexalmeida2001 d21f4ced94 Update database.py 2020-12-06 12:30:47 +00:00
alexalmeida2001 77ca634bed Update app.py 2020-12-06 12:30:20 +00:00
alexalmeida2001 6a461c8fa7 Add files via upload 2020-12-06 12:29:40 +00:00
alexalmeida2001 0be5531afd Update appUPDATED-alex.py 2020-12-05 19:22:27 +00:00
alexalmeida2001 2861446546 Update databaseUPDATED-alex.py 2020-12-05 19:22:07 +00:00
alexalmeida2001 1847513760 Update databaseUPDATED-alex.py 2020-12-05 19:16:30 +00:00
alexalmeida2001 7c40fd0596 Update and rename databaseUPDATED.py to databaseUPDATED-alex.py 2020-12-05 18:27:51 +00:00
alexalmeida2001 6e1e2665fe Update and rename appUPDATED.py to appUPDATED-alex.py 2020-12-05 18:26:57 +00:00
alexalmeida2001 fdf9b678d9 Create appUPDATED.py 2020-12-03 16:49:21 +00:00
alexalmeida2001 751e14904b Create databaseUPDATED.py 2020-12-03 16:48:53 +00:00
alexalmeida2001 5f363e78d8 Update database.py 2020-12-03 11:45:35 +00:00
alexalmeida2001 7741501c18 Update app.py 2020-12-03 11:45:02 +00:00
alexalmeida2001 1b3e45308d Update database.py 2020-12-02 16:24:43 +00:00
alexalmeida2001 8edbdb3fb5 Add files via upload
new stuff
2020-11-28 12:05:12 +00:00
agsNeto20 ba494d9c66 Update app.py 2020-11-27 11:31:30 +00:00
agsNeto20 64bbeafb4f Update app.py 2020-11-27 11:09:32 +00:00
agsNeto20 ee858f8bc5 Update database.py 2020-11-27 11:07:28 +00:00
agsNeto20 9d7cb39be9 Add files via upload 2020-11-26 12:50:54 +00:00
agsNeto20 d0d8203a61 Add files via upload 2020-11-26 12:50:21 +00:00
6 changed files with 1112 additions and 516 deletions
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 André Neto and Alexandre Cavadas de Almeida
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+30 -6
View File
@@ -11,7 +11,7 @@
The data model has seven tables - `users`, `articles`, `actors`, `articles_actors`, `rents`, `messages`, `pricehistory` - and it exists only in `schema.sql`: it was reconstructed from the queries, and no table or column was invented. The code reads rows by position (`SELECT *` followed by `row[1]`, `row[4]`, ...), so the column order in that file is part of the contract.
Some behaviour is broken and was left as it is, because fixing the application was not part of reconstructing its database. The suite pins each case with a test named `test_known_bug_*` or marked `xfail`: `findby_director()` returns nothing when it finds a match; `findby_actor()` raises `UnboundLocalError` when nothing matches; a search with no results returns the integer `0`, which `main.py` then indexes into; `purchase()` deducts the money from the account of the last login instead of the account in its argument; the message list shows the recipient's name as the author; `remove_article()` checks only the rentals that are still open, while the foreign keys also block the older ones; and a few paths never close their connection.
The defects the tests used to pin are fixed. `findby_director()` printed its matches and returned nothing; `findby_actor()` raised `UnboundLocalError` when no actor matched, and returned only the last article of an actor that had several; a search with no results returned the integer `0`, which `main.py` then indexed into; `purchase()` debited the account of the last login instead of the account in its argument; the message list showed the recipient's name as the author; `remove_article()` checked only the rentals that were still open, so the foreign keys on the older ones and on `pricehistory` turned the refusal into a traceback; `show_unread_messages()` returned `None` instead of an empty list; `database.USERID` was created by `log_in()`, so leaving the menu with `0` raised `AttributeError`; and several functions returned before closing their connection, leaving `idle in transaction` sessions behind. Every connection is opened and closed in one context manager now, and each of these defects has a regression test.
The archive `Projeto_Netflox_Alexandre_Almeida_Andre_Neto.zip` is not tracked any more (it was removed in commit `17f75ec`) because it contained a copy of `database.py` with the database password in clear. If that password was ever used for anything other than a local test database, it has to be rotated. The passwords used now are chosen locally and are not in the repository.
@@ -91,13 +91,34 @@ make test
```text
.venv/bin/python -m pytest -q
...........................xx... [100%]
30 passed, 2 xfailed in 8.87s
....................................................... [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.
Two tests are marked `xfail` and four are named `test_known_bug_*`: they document the defects listed under "What it is" instead of hiding them. When one of those bugs is fixed, the corresponding test has to change.
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:
- 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
@@ -106,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
@@ -117,4 +139,6 @@ encript.jpg image from the original upload; no code or schema reads i
## License
Not decided yet: the repository carries no license file, so no license is granted. The author has to choose one before this section can state anything.
MIT — see [LICENSE](LICENSE). Copyright (c) 2020 **André Neto and
Alexandre Cavadas de Almeida**, both named as authors in the course report
(`docs/relatorio-BD.pdf`).
+606 -480
View File
File diff suppressed because it is too large Load Diff
+25 -3
View File
@@ -67,6 +67,9 @@ def client():
if client_search == '1':
client_search_typo=input("\tInsert movie name: ")
article=database.findby_name(client_search_typo)
if not article:
print("\n\tNo article matches that search")
continue
while (x := int(input("\tYour Selection: "))) != 0:
print("\n\t" + article[x - 1][1])
while (client_in := input(article_interface)) != '0':
@@ -83,6 +86,9 @@ def client():
if client_search == '2':
client_search_typo=input("\tInsert movie director: ")
article=database.findby_director(client_search_typo)
if not article:
print("\n\tNo article matches that search")
continue
while (x := int(input("\tYour Selection: "))) != 0:
print("\n\t" + article[x - 1][1])
while (client_in := input(article_interface)) != '0':
@@ -99,6 +105,9 @@ def client():
if client_search == '3':
client_search_typo=input("\tInsert movie type: ")
article=database.findby_type(client_search_typo)
if not article:
print("\n\tNo article matches that search")
continue
while (x := int(input("\tYour Selection: "))) != 0:
print("\n\t" + article[x - 1][1])
while (client_in := input(article_interface)) != '0':
@@ -114,6 +123,9 @@ def client():
if client_search == '4':
client_search_typo=input("\tInsert movie actor: ")
article=database.findby_actor(client_search_typo)
if not article:
print("\n\tNo article matches that search")
continue
while (x := int(input("\tYour Selection: "))) != 0:
print("\n\t" + article[x - 1][1])
while (client_in := input(article_interface)) != '0':
@@ -268,6 +280,8 @@ def client():
while (client_input := input(message_interface)) != '0':
if client_input == '1':
y = database.show_unread_messages(USERID)
if not y:
continue
while (x := int(input("\tYour Selection: "))) != 0:
database.read_message(y[x - 1][0])
print("\n\t" + y[x - 1][1])
@@ -357,9 +371,17 @@ def admin():
database.statistics()
if menu() != -1:
# menu() returns 1 for a client, -1 for an administrator and None when the
# user leaves with 0. That last case used to be tested with `!= -1`, so it
# went into the client branch and read database.USERID, which did not exist
# until somebody logged in (AttributeError). Nobody is logged in there, so
# neither menu is opened.
role = menu()
if role == -1:
USERID = database.USERID
admin()
elif role == 1:
USERID = database.USERID
client()
else:
USERID = database.USERID
admin()
print("\n\tGoodbye")
+282
View File
@@ -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}"
+148 -27
View File
@@ -6,12 +6,13 @@ real functions of database.py - the same ones main.py calls. Nothing is mocked
except keyboard input: if the schema does not match what the code expects, these
tests fail.
Tests named `test_known_bug_*` and the ones marked `xfail` pin down behaviour
that is wrong in database.py / main.py; they are documentation, not approval
(see README, "Known limitations").
Every defect that used to be pinned here by an `xfail` or a `test_known_bug_*`
name now has a regression test that fails against the previous code; the last
section of this file is that regression suite (see README, "What it is").
"""
from __future__ import annotations
import ast
import builtins
import contextlib
import datetime
@@ -318,7 +319,7 @@ def test_message_to_one_client_then_mark_it_read(capsys):
assert scalar("SELECT bolread FROM messages") is True
read = database.show_read_messages(client)
assert len(read) == 1 and read[0][1] == "Bem-vindo"
assert database.show_unread_messages(client) is None # documented quirk
assert database.show_unread_messages(client) == [] # an empty list, not None
def test_message_all_reaches_every_user_except_the_sender(capsys):
@@ -472,47 +473,167 @@ def test_schema_sql_does_not_carry_the_demo_password():
# --------------------------------------------------------------------------
# known bugs, pinned so that they are visible instead of silent
# regressions: every test below used to be an xfail or a `test_known_bug_*`
# --------------------------------------------------------------------------
@pytest.mark.xfail(reason="findby_director() has no return on the success path")
def test_known_bug_findby_director_returns_nothing_on_a_match():
assert database.findby_director("Christopher Nolan") is not None
def test_findby_director_returns_the_rows_it_printed(capsys):
"""It printed the matches and fell off the end of the function (None)."""
movies = database.findby_director("Christopher Nolan")
assert movies is not None
assert [row[1] for row in movies] == ["Interstellar"]
assert movies[0][2] == "Christopher Nolan" # column order kept
assert "Interstellar" in capsys.readouterr().out
assert database.findby_director("zzz-nao-existe") == []
@pytest.mark.xfail(reason="findby_actor() raises UnboundLocalError when no actor matches")
def test_known_bug_findby_actor_without_a_match():
def test_findby_actor_without_a_match_returns_none():
"""It used to raise UnboundLocalError: `articles` was never bound."""
assert database.findby_actor("Ninguem Com Este Nome") is None
def test_known_bug_search_without_matches_breaks_main_py():
"""findby_name() returns 0, and main.py immediately does article[x - 1][1]."""
assert database.findby_name("zzz-nao-existe") == 0
def test_findby_actor_returns_every_article_of_the_actor():
"""It used to return whatever `articles` held after the last iteration: only
the last article of the actor, out of a list that could have several."""
with raw_cursor() as cur:
cur.execute("INSERT INTO articles (name, director, release_year, imbd_rating,"
" genre, price, type, time_available) VALUES ('John Wick',"
" 'Chad Stahelski', 2014, 7.4, 'action', 2.00, 'movie', 7)"
" RETURNING itemid")
second = cur.fetchone()[0]
cur.execute("INSERT INTO articles_actors (articles_itemid, actors_actorid)"
" SELECT %s, actorid FROM actors WHERE name = 'Keanu Reeves'",
(second,))
movies = database.findby_actor("Keanu Reeves")
assert sorted(row[1] for row in movies) == ["John Wick", "The Matrix"]
assert movies[0] == database.findby_name("The Matrix")[0]
def test_known_bug_message_list_labels_a_message_with_the_recipient(capsys):
"""show_unread_messages() looks the author up with row[4], which is the
recipient (users_userid); the sender is row[5]. A client therefore sees their
own name as the author of every message."""
def test_search_without_matches_returns_an_empty_list():
"""It used to return the integer 0, which main.py then indexed into."""
assert database.findby_name("zzz-nao-existe") == []
assert database.findby_type("zzz-nao-existe") == []
def test_message_list_shows_the_sender_not_the_recipient(capsys):
"""The author was looked up with row[4] (the recipient) instead of row[5]."""
client = make_client()
admin = user_id(ADMIN_EMAIL)
database.message_client("Ola", str(client), str(admin))
capsys.readouterr()
database.show_unread_messages(client)
unread = database.show_unread_messages(client)
out = capsys.readouterr().out
assert "Message from Ana" in out # the recipient, not the admin
assert "Message from Admin" not in out
assert "Message from Admin" in out
assert "Message from Ana" not in out
database.read_message(unread[0][0]) # the read list had it too
capsys.readouterr()
database.show_read_messages(client)
out = capsys.readouterr().out
assert "Message from Admin" in out
assert "Message from Ana" not in out
def test_known_bug_purchase_debits_the_last_logged_in_account():
"""database.py:294 updates the balance WHERE userid = USERID (the global set by
the last log_in), while the rent is inserted for the userid argument."""
def test_purchase_debits_the_account_it_was_given(capsys):
"""It debited USERID (the account of the last log_in), not its argument."""
ana = make_client("Ana", "ana@exemplo.pt")
bruno = make_client("Bruno", "bruno@exemplo.pt")
assert database.log_in("ana@exemplo.pt", demo_password()) == 1 # Ana is the last login
assert database.log_in("ana@exemplo.pt", demo_password()) == 1
database.purchase(article_id("Pulp Fiction"), bruno)
assert "Purchase successful!" in capsys.readouterr().out
assert balance_of(ana) == Decimal("17.50") # Ana paid
assert balance_of(bruno) == Decimal("20.00")
assert scalar("SELECT users_userid FROM rents") == bruno
assert balance_of(bruno) == Decimal("17.50") # 20.00 - 2.50, the buyer
assert balance_of(ana) == Decimal("20.00") # the last login, untouched
assert scalar("SELECT count(*) FROM rents WHERE users_userid = %s", (bruno,)) == 1
def test_remove_article_is_refused_with_rent_history_and_it_says_why(capsys):
"""Only the *current* rents were checked, so the older ones - which the
foreign key also protects - turned the removal into a traceback."""
client = make_client()
itemid = article_id("The Matrix")
database.purchase(itemid, client)
with raw_cursor() as cur:
cur.execute("UPDATE rents SET end_date = CURRENT_DATE - 1"
" WHERE articles_itemid = %s", (itemid,))
database.remove_article(str(itemid)) # main.py always passes a string
out = capsys.readouterr().out
assert "Can't remove article" in out
assert "rental history" in out # explained, not a traceback
assert scalar("SELECT count(*) FROM articles WHERE itemid = %s", (itemid,)) == 1
def test_remove_article_is_refused_while_the_price_history_keeps_it(capsys):
"""pricehistory carries a foreign key to the article as well."""
itemid = article_id("The Matrix")
database.change_price("The Matrix", "9.99") # writes one pricehistory row
capsys.readouterr()
database.remove_article(str(itemid))
out = capsys.readouterr().out
assert "Can't remove article" in out
assert "price history" in out
assert scalar("SELECT count(*) FROM articles WHERE itemid = %s", (itemid,)) == 1
assert scalar("SELECT count(*) FROM pricehistory") == 1
def test_a_failing_call_does_not_leave_its_session_idle_in_transaction():
"""A traceback keeps its frame alive, and the frame held the connection:
findby_type()/findby_actor()/findby_director() returned before conn.close()
and statistics() never closed at all, so the session stayed open."""
try:
database.view_details(999999) # no such article: IndexError
except IndexError as exc:
held = exc.__traceback__ # keeps the frame, and its connection
assert held is not None
assert scalar("SELECT count(*) FROM pg_stat_activity"
" WHERE datname = current_database()"
" AND state = 'idle in transaction'") == 0
def test_no_function_opens_a_connection_outside_the_managed_helper():
"""Structural guard: one place opens and closes, so no early return can leave
an `idle in transaction` session behind again."""
source = (ROOT / "database.py").read_text(encoding="utf-8")
assert source.count("psycopg2.connect(") == 1
tree = ast.parse(source)
openers = sorted(
node.name for node in ast.walk(tree)
if isinstance(node, ast.FunctionDef)
and "psycopg2.connect(" in (ast.get_source_segment(source, node) or "")
)
assert openers == ["_connection"]
def test_userid_exists_and_is_none_before_any_login():
"""database.USERID was created by log_in(), so the code that runs before a
login read an attribute that did not exist (AttributeError)."""
proc = subprocess.run([sys.executable, "-c", "import database; print(database.USERID)"],
cwd=ROOT, capture_output=True, text=True, env=os.environ.copy())
assert proc.returncode == 0, proc.stderr
assert proc.stdout.strip() == "None"
def test_leaving_the_menu_with_zero_exits_without_a_traceback():
"""`0` at the first menu used to be compared with -1, fall into the client
branch and read database.USERID before anybody had logged in."""
proc = subprocess.run([sys.executable, "main.py"], cwd=ROOT, input="0\n",
capture_output=True, text=True, env=os.environ.copy())
assert proc.returncode == 0, proc.stderr
assert "Traceback" not in proc.stderr
assert "Goodbye" in proc.stdout
def test_an_administrator_login_opens_the_administrator_menu():
proc = subprocess.run([sys.executable, "main.py"], cwd=ROOT,
input=f"2\n{ADMIN_EMAIL}\n{demo_password()}\n0\n",
capture_output=True, text=True, env=os.environ.copy())
assert proc.returncode == 0, proc.stderr
assert "Welcome Admin" in proc.stdout
assert "Change price" in proc.stdout # the administrator menu