From a871e9b5ee9380ad32b0d5cc17a0379ce659065d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 12:24:24 +0000 Subject: [PATCH 1/2] Harden query sandbox, add tests and CI, refresh docs - Run every player query in a fresh in-memory SQLite DB with a read-only authorizer, a 2s time limit and a 500-row cap - Surface real SQL errors to players (escaped) instead of silently returning no rows; give specific messages for rejected queries - Allow WITH/CTE queries, SQL comments and keywords inside string literals - Make verification answers case-insensitive - Remove dead timer code and unused tuple-result code paths - Drop Heroku Procfile/setup.sh and the duplicate requirements file; stop disabling XSRF protection in Streamlit config - Add pytest suite (sandbox, validation, stage rules, full UI playthrough via AppTest) and a GitHub Actions workflow for ruff + pytest on 3.10-3.13 - Rewrite README with live link, sandbox design and dev instructions Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WwKFojwA2s9TbXcrR6Mzqg --- .devcontainer/devcontainer.json | 2 +- .github/workflows/ci.yml | 27 ++++++ .streamlit/config.toml | 5 +- Procfile | 1 - README.md | 90 +++++++++++++++++++ Readme.md | 91 ------------------- app.py | 1 + backend/db.py | 133 ++++++++++++++++++---------- backend/game_logic.py | 147 ++++++++++++++----------------- backend/utils.py | 151 +++++++++----------------------- frontend/streamlit_app.py | 88 +++++++------------ init_database.py | 7 +- pyproject.toml | 14 +++ requirements-dev.txt | 3 + requirements-streamlit.txt | 3 - requirements.txt | 5 +- setup.sh | 27 ------ tests/__init__.py | 0 tests/test_app.py | 52 +++++++++++ tests/test_db.py | 67 ++++++++++++++ tests/test_game_logic.py | 101 +++++++++++++++++++++ 21 files changed, 588 insertions(+), 427 deletions(-) create mode 100644 .github/workflows/ci.yml delete mode 100644 Procfile create mode 100644 README.md delete mode 100644 Readme.md create mode 100644 pyproject.toml create mode 100644 requirements-dev.txt delete mode 100644 requirements-streamlit.txt delete mode 100644 setup.sh create mode 100644 tests/__init__.py create mode 100644 tests/test_app.py create mode 100644 tests/test_db.py create mode 100644 tests/test_game_logic.py diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 8491816..7b691f5 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -19,7 +19,7 @@ }, "updateContentCommand": "[ -f packages.txt ] && sudo apt update && sudo apt upgrade -y && sudo xargs apt install -y str: + return SCHEMA_FILE.read_text(encoding="utf-8") + "\n" + DATA_FILE.read_text(encoding="utf-8") + + +def _authorizer(action, arg1, arg2, db_name, trigger): # noqa: ARG001 - sqlite3 callback signature + if action in _ALLOWED_ACTIONS: + return sqlite3.SQLITE_OK + return sqlite3.SQLITE_DENY + + +def _new_connection() -> sqlite3.Connection: + conn = sqlite3.connect(":memory:") + conn.executescript(_seed_script()) + conn.set_authorizer(_authorizer) + return conn + + +def execute_query(query: str) -> list[dict]: + """Run a read-only query and return its rows as a list of dicts. + + Raises ``QueryError`` with a readable message on any failure. + """ + conn = _new_connection() + deadline = time.monotonic() + QUERY_TIMEOUT_SECONDS + conn.set_progress_handler(lambda: 1 if time.monotonic() > deadline else 0, _PROGRESS_INTERVAL) + try: + cur = conn.execute(query) + if cur.description is None: return [] + columns = [desc[0] for desc in cur.description] + rows = cur.fetchmany(MAX_ROWS) + return [dict(zip(columns, row, strict=True)) for row in rows] + except sqlite3.OperationalError as exc: + if "interrupted" in str(exc): + raise QueryError( + f"Query took longer than {QUERY_TIMEOUT_SECONDS:g} seconds and was stopped." + ) from exc + if "not authorized" in str(exc): + raise QueryError("That operation is not allowed. Only read-only SELECT queries are permitted.") from exc + raise QueryError(str(exc)) from exc + except sqlite3.ProgrammingError as exc: + # e.g. "You can only execute one statement at a time." + raise QueryError(str(exc)) from exc + except sqlite3.Error as exc: + raise QueryError(str(exc)) from exc + finally: + conn.close() diff --git a/backend/game_logic.py b/backend/game_logic.py index 37c7c01..1210329 100644 --- a/backend/game_logic.py +++ b/backend/game_logic.py @@ -1,90 +1,73 @@ +"""Query validation and game-state transitions.""" + +from __future__ import annotations + import re + from backend.utils import check_stage_completion -def start_timer(): - """Start a timer for the game - now just returns a placeholder value""" - return 1 # Placeholder value since we're removing the timer concept - -def validate_query(query): - """ - Validate SQL query for safety and game rules - - No DROP, DELETE, UPDATE, INSERT statements allowed - - No system table access - - Only SELECT statements allowed - - JOIN operations are allowed - """ - # Convert to lowercase for easier checking - query_lower = query.lower().strip() - - # Check if it's a SELECT statement - if not query_lower.startswith('select'): - return False +# Friendly pre-checks. The real enforcement is the read-only sandbox in backend/db.py; +# these exist so players get a clear message instead of a low-level SQLite error. +_FORBIDDEN_KEYWORDS = re.compile( + r"\b(drop|delete|update|insert|alter|create|truncate|attach|detach|pragma|vacuum|reindex)\b" +) +_SYSTEM_TABLES = re.compile(r"\bsqlite_\w+\b") +_STRING_LITERAL = re.compile(r"'(?:[^']|'')*'") +_LINE_COMMENT = re.compile(r"--[^\n]*") +_BLOCK_COMMENT = re.compile(r"/\*.*?\*/", re.DOTALL) + +MAX_QUERY_LENGTH = 5_000 + + +def _strip_literals_and_comments(query: str) -> str: + query = _BLOCK_COMMENT.sub(" ", query) + query = _LINE_COMMENT.sub(" ", query) + return _STRING_LITERAL.sub("''", query) - # Check for forbidden operations - using word boundaries to avoid false positives - forbidden_operations = [ - r'\bdrop\b', r'\bdelete\b', r'\bupdate\b', r'\binsert\b', - r'\balter\b', r'\bcreate\b', r'\btruncate\b', r'\bgrant\b', - r'\brevoke\b' - ] - - # Check for system tables - forbidden_tables = [ - r'\bpg_\w+\b', r'\binformation_schema\b', r'\bsqlite_\w+\b' - ] - - # Check for forbidden operations - for pattern in forbidden_operations: - if re.search(pattern, query_lower): - return False - - # Check for system tables - for pattern in forbidden_tables: - if re.search(pattern, query_lower): - return False - - # Basic SQL injection prevention - but allow semicolons in string literals - # This is a simplified check and not foolproof - if '--' in query: + +def check_query(query: str) -> tuple[bool, str]: + """Return ``(ok, message)``. ``message`` explains why a query was rejected.""" + if not query or not query.strip(): + return False, "Type a SQL query first." + if len(query) > MAX_QUERY_LENGTH: + return False, f"Queries are limited to {MAX_QUERY_LENGTH:,} characters." + + code = _strip_literals_and_comments(query).strip().lower() + if not (code.startswith("select") or code.startswith("with")): + return False, "Only SELECT queries (optionally starting with WITH) are allowed." + if ";" in code.rstrip(" ;\n\t"): + return False, "Run one statement at a time." + match = _FORBIDDEN_KEYWORDS.search(code) + if match: + return False, f"'{match.group(1).upper()}' is not allowed. This terminal is read-only." + if _SYSTEM_TABLES.search(code): + return False, "System tables are off limits. Stick to the game's tables." + return True, "" + + +def validate_query(query: str) -> bool: + """Backward-compatible boolean wrapper around :func:`check_query`.""" + return check_query(query)[0] + + +def update_game_state(current_stage: int, results: list[dict], game_state: dict) -> bool: + """Update ``game_state`` from a query result. Returns whether the stage was completed.""" + if not check_stage_completion(current_stage, results): return False - # Allow JOIN operations and other valid SQL constructs + if current_stage == 1: + for row in results: + if "Airport" in str(row.get("location", "")): + game_state["bomb_id"] = row.get("bomb_id") + break + game_state["clues_found"].append("Stage 1 complete: Bomb identified") + elif current_stage == 2: + game_state["clues_found"].append("Stage 2 complete: Defusal mechanism found") + elif current_stage == 3: + game_state["clues_found"].append("Stage 3 complete: Suspect identified") return True -def update_game_state(current_stage, results, game_state): - """ - Update game state based on query results and current stage - Returns: (bool) whether the stage was completed - """ - # Check if the current stage is completed - stage_completed = check_stage_completion(current_stage, results) - - if stage_completed: - if current_stage == 1: - # Found the real bomb - # Check if results are dictionaries or tuples - is_dict_results = isinstance(results[0], dict) if results else False - - if is_dict_results: - # For dictionary results - for row in results: - if 'Airport' in str(row.get('location', '')): - game_state['bomb_id'] = row.get('bomb_id') - game_state['clues_found'].append("Stage 1 complete: Bomb identified") - break - else: - # For tuple results (fallback) - for row in results: - if 'Airport' in str(row): - game_state['bomb_id'] = row[0] if len(row) > 0 else None - game_state['clues_found'].append("Stage 1 complete: Bomb identified") - break - - elif current_stage == 2: - # Found the defusal code - game_state['clues_found'].append("Stage 2 complete: Defusal mechanism found") - - elif current_stage == 3: - # Found the culprit - game_state['clues_found'].append("Stage 3 complete: Suspect identified") - - return stage_completed + +def is_correct_answer(given: str, expected: str) -> bool: + """Compare a verification answer, ignoring case and surrounding whitespace.""" + return given.strip().casefold() == expected.strip().casefold() diff --git a/backend/utils.py b/backend/utils.py index 0453213..3bf9181 100644 --- a/backend/utils.py +++ b/backend/utils.py @@ -1,124 +1,57 @@ -def start_timer(): - """Start a timer for the game - now just returns a placeholder value""" - return 1 # Placeholder value since we're removing the timer concept +"""Stage-completion rules. -def calculate_time_taken(start_time): - """Calculate the time taken since the timer started - now just returns a placeholder value""" - return 0 # Placeholder value since we're removing the timer concept +A stage is complete when the player's query result contains the row that proves +they found the answer, with the columns needed to show it. +""" -def format_time(seconds): - """Format seconds into minutes and seconds""" - mins, secs = divmod(seconds, 60) - return f"{mins:02}:{secs:02}" +from __future__ import annotations -def check_stage_completion(stage, results): - """Check if the current stage is completed based on query results""" - if not results: - return False - - # Check if results are dictionaries or tuples - is_dict_results = isinstance(results[0], dict) if results else False - - if stage == 1: - # Stage 1: Identify the real bomb (Airport) - # The real bomb has these characteristics: - # - High signal_strength (>95) - # - High battery_level (>90) - # - Consistent frequency_pattern (all values the same) - # - Device signature starting with 'B9Z' - # - Recently maintained (2025-03-08) - if is_dict_results: - # For dictionary results - for row in results: - location = str(row.get('location', '')) - signal = row.get('signal_strength', 0) - battery = row.get('battery_level', 0) - freq_pattern = str(row.get('frequency_pattern', '')) - signature = str(row.get('device_signature', '')) - maintained = str(row.get('last_maintained', '')) +def _num(value, default=0): + try: + return float(value) + except (TypeError, ValueError): + return default - # Check if this is the Airport bomb with the right characteristics - if ('Airport' in location and - signal > 95 and - battery > 90 and - '3.7,3.7,3.7' in freq_pattern and - signature.startswith('B9Z') and - '2025-03-08' in maintained): - return True - else: - # For tuple results - more complex check - for row in results: - row_str = str(row) - # This is a simplified check for tuple results - if ('Airport' in row_str and - 'B9Z31' in row_str and - '2025-03-08' in row_str and - '3.7,3.7,3.7' in row_str): - return True - return False +def _stage1(row: dict) -> bool: + # The real bomb: Airport, signal > 95, battery > 90, constant frequency pattern, + # signature starting with B9Z, maintained on 2025-03-08. + return ( + "Airport" in str(row.get("location", "")) + and _num(row.get("signal_strength")) > 95 + and _num(row.get("battery_level")) > 90 + and "3.7,3.7,3.7" in str(row.get("frequency_pattern", "")) + and str(row.get("device_signature", "")).startswith("B9Z") + and "2025-03-08" in str(row.get("last_maintained", "")) + ) - elif stage == 2: - # Stage 2: Find the defusal code - # The defusal code is 221, but we need to make sure they found it - # in the right context - it should be from bomb_id 2 (Airport) and - # specifically from the Detonator or Circuit component - if is_dict_results: - # For dictionary results - for row in results: - bomb_id = row.get('bomb_id', 0) - component = str(row.get('component_name', '')) - code = str(row.get('activation_code', '')) - material = str(row.get('material', '')) +def _stage2(row: dict) -> bool: + # The defusal code (221) on the Airport bomb's Titanium Detonator or Gold Circuit. + return ( + row.get("bomb_id") == 2 + and str(row.get("activation_code", "")) == "221" + and row.get("component_name") in ("Detonator", "Circuit") + and row.get("material") in ("Titanium", "Gold") + ) - # Check if this is the right component with the right code - if (bomb_id == 2 and - code == '221' and - (component == 'Detonator' or component == 'Circuit') and - (material == 'Titanium' or material == 'Gold')): - return True - else: - # For tuple results - for row in results: - row_str = str(row) - # This is a simplified check for tuple results - if ('221' in row_str and - ('Detonator' in row_str or 'Circuit' in row_str) and - ('Titanium' in row_str or 'Gold' in row_str)): - return True - return False +def _stage3(row: dict) -> bool: + # The suspect who performed the Installation on the Airport bomb. + return ( + row.get("name") == "Sarah Connor" + and row.get("action_performed") == "Installation" + and (row.get("bomb_id") == 2 or "Airport" in str(row.get("location", ""))) + ) - elif stage == 3: - # Stage 3: Identify the culprit (Sarah Connor) - # The culprit is Sarah Connor, but we need to make sure they found the connection - # to the Airport bomb (bomb_id 2) with an Installation action - if is_dict_results: - # For dictionary results - for row in results: - name = str(row.get('name', '')) - action = str(row.get('action_performed', '')) - bomb_id = row.get('bomb_id', 0) - location = str(row.get('location', '')) +_CHECKS = {1: _stage1, 2: _stage2, 3: _stage3} - # Check if this is Sarah Connor with the right action on the right bomb - if (name == 'Sarah Connor' and - action == 'Installation' and - (bomb_id == 2 or 'Airport' in location)): - return True - else: - # For tuple results - for row in results: - row_str = str(row) - # This is a simplified check for tuple results - if ('Sarah Connor' in row_str and - 'Installation' in row_str and - ('Airport' in row_str or 'bomb_id.*2' in row_str)): - return True +def check_stage_completion(stage: int, results: list[dict]) -> bool: + """Return True if ``results`` prove the player solved ``stage``.""" + check = _CHECKS.get(stage) + if check is None or not results: return False - - return False + return any(isinstance(row, dict) and check(row) for row in results) diff --git a/frontend/streamlit_app.py b/frontend/streamlit_app.py index a530b97..0009b57 100644 --- a/frontend/streamlit_app.py +++ b/frontend/streamlit_app.py @@ -1,8 +1,10 @@ +import html +import time + import streamlit as st -import time # Still needed for sleep function -from backend.db import execute_query -from backend.game_logic import validate_query, update_game_state -from backend.utils import format_time + +from backend.db import MAX_ROWS, QueryError, execute_query +from backend.game_logic import check_query, is_correct_answer, update_game_state # Game storyline with rich narrative STORYLINE = { @@ -475,7 +477,7 @@ def main_app(): col1, col2 = st.columns(2) with col1: - st.markdown(f""" + st.markdown("""
♣ @@ -490,7 +492,7 @@ def main_app(): """, unsafe_allow_html=True) with col2: - st.markdown(f""" + st.markdown("""
♦ @@ -595,9 +597,9 @@ def main_app(): # Verify button if st.button("VERIFY", key="verify_button", use_container_width=True): - if verification_answer.strip() == correct_answer: + if is_correct_answer(verification_answer, correct_answer): # Correct answer - st.success(f"✅ Correct! Moving to the next stage...") + st.success("✅ Correct! Moving to the next stage...") # Reset verification state st.session_state.verification_needed = False @@ -852,10 +854,12 @@ def main_app(): # Display results in a styled dataframe st.markdown("

Results:

", unsafe_allow_html=True) st.dataframe(data=results, use_container_width=True, height=400) + if len(results) >= MAX_ROWS: + st.caption(f"Showing the first {MAX_ROWS} rows.") except Exception as e: st.error(f"Error displaying results: {str(e)}") st.json(results) # Fallback to JSON display - else: + elif not st.session_state.game_state.get('last_query_error'): st.info("Query executed successfully, but returned no results.") # Display error if there was one @@ -864,61 +868,31 @@ def main_app():

Error: {}

- """.format(st.session_state.game_state['last_query_error']), unsafe_allow_html=True) + """.format(html.escape(st.session_state.game_state['last_query_error'])), unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) # Execute Query button logic if execute_btn: - try: - if validate_query(query): - # Store the query for display - st.session_state.game_state['last_query'] = query - st.session_state.game_state['last_query_error'] = None - - # Execute the query + game_state = st.session_state.game_state + ok, message = check_query(query) + if not ok: + st.error(message) + else: + game_state['last_query'] = query + game_state['last_query_error'] = None + try: results = execute_query(query) - - # Store the results in session state - st.session_state.game_state['last_query_results'] = results - - if results: - # Create a success message - st.markdown(""" -
-

✅ Query Successful!

-
- """, unsafe_allow_html=True) - - # Update game state based on query results - stage_completed = update_game_state( - current_stage, - results, - st.session_state.game_state - ) - - # Handle stage completion with verification step - if stage_completed: - # Set verification needed flag - st.session_state.verification_needed = True - st.session_state.verification_stage = current_stage - - # Show verification form - st.success(f"🎯 You've found something important! Please verify your findings to proceed.") - st.rerun() - else: - st.info("Query executed successfully, but returned no results.") + except QueryError as e: + game_state['last_query_results'] = [] + game_state['last_query_error'] = str(e) else: - st.error("Invalid query. Only SELECT statements are allowed, and certain operations are restricted for security.") - except Exception as e: - error_msg = str(e) - st.error(f"Error executing query: {error_msg}") - # Store the error in session state - st.session_state.game_state['last_query_results'] = [] - st.session_state.game_state['last_query_error'] = error_msg - - # Force a rerun to update the display - st.rerun() + game_state['last_query_results'] = results + if results and update_game_state(current_stage, results, game_state): + st.session_state.verification_needed = True + st.session_state.verification_stage = current_stage + # Rerun so the results panel above reflects the new query + st.rerun() # No game over condition needed since we removed the timer diff --git a/init_database.py b/init_database.py index 9bef4c4..59cfff2 100644 --- a/init_database.py +++ b/init_database.py @@ -1,7 +1,8 @@ -import sqlite3 import os +import sqlite3 import sys + def init_database(): """Initialize the SQLite database with schema and sample data""" print("Initializing the SQL Bomb Defusal Game database...") @@ -43,7 +44,7 @@ def init_database(): # Read and execute schema.sql try: - with open(os.path.join(db_dir, "schema.sql"), "r") as schema_file: + with open(os.path.join(db_dir, "schema.sql")) as schema_file: schema_sql = schema_file.read() cursor.executescript(schema_sql) conn.commit() @@ -54,7 +55,7 @@ def init_database(): # Read and execute sample_data.sql try: - with open(os.path.join(db_dir, "sample_data.sql"), "r") as data_file: + with open(os.path.join(db_dir, "sample_data.sql")) as data_file: data_sql = data_file.read() cursor.executescript(data_sql) conn.commit() diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..b9a7740 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,14 @@ +[tool.pytest.ini_options] +testpaths = ["tests"] +pythonpath = ["."] + +[tool.ruff] +line-length = 120 +target-version = "py310" + +[tool.ruff.lint] +select = ["E", "F", "W", "I", "B", "UP"] + +[tool.ruff.lint.per-file-ignores] +# Long narrative strings and inline HTML/CSS for the UI. +"frontend/streamlit_app.py" = ["E501"] diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..98ed3d1 --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,3 @@ +-r requirements.txt +pytest>=8 +ruff>=0.6 diff --git a/requirements-streamlit.txt b/requirements-streamlit.txt deleted file mode 100644 index 8d560a8..0000000 --- a/requirements-streamlit.txt +++ /dev/null @@ -1,3 +0,0 @@ -streamlit>=1.30.0 -pandas>=2.0.0 -python-dateutil>=2.8.0 diff --git a/requirements.txt b/requirements.txt index 8d560a8..f932372 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,2 @@ -streamlit>=1.30.0 -pandas>=2.0.0 -python-dateutil>=2.8.0 +streamlit>=1.30,<2 +pandas>=2.0,<3 diff --git a/setup.sh b/setup.sh deleted file mode 100644 index dbeb17b..0000000 --- a/setup.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/bin/bash - -mkdir -p ~/.streamlit/ - -echo "\ -[general]\n\ -email = \"\"\n\ -" > ~/.streamlit/credentials.toml - -echo "\ -[server]\n\ -headless = true\n\ -enableCORS = false\n\ -enableXsrfProtection = false\n\ -port = $PORT\n\ -" > ~/.streamlit/config.toml - -echo "\ -[theme]\n\ -primaryColor = \"#4dabf7\"\n\ -backgroundColor = \"#212529\"\n\ -secondaryBackgroundColor = \"#343a40\"\n\ -textColor = \"#f8f9fa\"\n\ -" >> ~/.streamlit/config.toml - -# Initialize the database -python init_database.py diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_app.py b/tests/test_app.py new file mode 100644 index 0000000..aa6e92a --- /dev/null +++ b/tests/test_app.py @@ -0,0 +1,52 @@ +"""End-to-end playthrough of the Streamlit UI using Streamlit's AppTest harness.""" + +from pathlib import Path + +from streamlit.testing.v1 import AppTest + +from tests.test_game_logic import STAGE_SOLUTIONS + +APP = str(Path(__file__).resolve().parent.parent / "app.py") +ANSWERS = {1: "Airport", 2: "221", 3: "sarah connor"} # answers are case-insensitive + + +def _run_query(at: AppTest, query: str) -> AppTest: + at.text_area(key="sql_query_input").input(query) + at.button(key="execute_query_button").click() + return at.run() + + +def test_full_playthrough(): + at = AppTest.from_file(APP, default_timeout=30).run() + assert not at.exception + + at.button(key="start_mission").click() + at.run() + assert at.session_state.game_state["game_started"] + + for stage in (1, 2, 3): + assert at.session_state.game_state["current_stage"] == stage + _run_query(at, STAGE_SOLUTIONS[stage]) + assert not at.exception + assert at.session_state.verification_needed + + at.text_input(key="verification_input").input(ANSWERS[stage]) + at.button(key="verify_button").click() + at.run() + assert not at.exception + + assert at.session_state.game_state["game_completed"] + + +def test_rejected_and_failing_queries_show_errors(): + at = AppTest.from_file(APP, default_timeout=30).run() + at.button(key="start_mission").click() + at.run() + + _run_query(at, "DROP TABLE bombs") + assert any("Only SELECT" in e.value for e in at.error) + + _run_query(at, "SELECT nope FROM bombs") + assert at.session_state.game_state["last_query_error"] + assert "no such column" in at.session_state.game_state["last_query_error"] + assert not at.exception diff --git a/tests/test_db.py b/tests/test_db.py new file mode 100644 index 0000000..6a82147 --- /dev/null +++ b/tests/test_db.py @@ -0,0 +1,67 @@ +import pytest + +from backend import db +from backend.db import QueryError, execute_query + + +def test_select_returns_rows_as_dicts(): + rows = execute_query("SELECT bomb_id, location FROM bombs ORDER BY bomb_id") + assert len(rows) == 8 + assert rows[1] == {"bomb_id": 2, "location": "Airport"} + + +def test_joins_and_ctes_work(): + rows = execute_query( + "WITH airport AS (SELECT bomb_id FROM bombs WHERE location = 'Airport') " + "SELECT COUNT(*) AS n FROM bomb_components bc JOIN airport a ON bc.bomb_id = a.bomb_id" + ) + assert rows == [{"n": 4}] + + +@pytest.mark.parametrize( + "query", + [ + "DELETE FROM bombs", + "UPDATE bombs SET location = 'x'", + "INSERT INTO suspects (name) VALUES ('x')", + "DROP TABLE bombs", + "CREATE TABLE t (x)", + "ATTACH DATABASE '/tmp/evil.db' AS evil", + "PRAGMA table_info(bombs)", + ], +) +def test_writes_and_admin_statements_are_blocked(query): + with pytest.raises(QueryError): + execute_query(query) + + +def test_each_query_gets_a_fresh_database(): + # Even if a write somehow got through, it could not leak into the next query. + before = execute_query("SELECT COUNT(*) AS n FROM bombs") + with pytest.raises(QueryError): + execute_query("DELETE FROM bombs") + assert execute_query("SELECT COUNT(*) AS n FROM bombs") == before + + +def test_multiple_statements_are_rejected(): + with pytest.raises(QueryError): + execute_query("SELECT 1; SELECT 2") + + +def test_runaway_query_times_out(monkeypatch): + monkeypatch.setattr(db, "QUERY_TIMEOUT_SECONDS", 0.2) + with pytest.raises(QueryError, match="longer than"): + execute_query( + "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c) SELECT COUNT(*) FROM c" + ) + + +def test_row_limit(monkeypatch): + monkeypatch.setattr(db, "MAX_ROWS", 10) + rows = execute_query("SELECT * FROM bombs, suspects") + assert len(rows) == 10 + + +def test_syntax_errors_are_reported(): + with pytest.raises(QueryError, match="syntax error"): + execute_query("SELEC * FROM bombs") diff --git a/tests/test_game_logic.py b/tests/test_game_logic.py new file mode 100644 index 0000000..7db6cf4 --- /dev/null +++ b/tests/test_game_logic.py @@ -0,0 +1,101 @@ +import pytest + +from backend.db import execute_query +from backend.game_logic import check_query, is_correct_answer, update_game_state +from backend.utils import check_stage_completion + +STAGE_SOLUTIONS = { + 1: """ + SELECT bomb_id, location, signal_strength, battery_level, frequency_pattern, + device_signature, last_maintained + FROM bombs + WHERE signal_strength > 95 AND battery_level > 90 AND device_signature LIKE 'B9Z%' + """, + 2: """ + SELECT bc.bomb_id, bc.component_name, bc.material, bc.activation_code + FROM bomb_components bc + JOIN bombs b ON bc.bomb_id = b.bomb_id + WHERE b.location = 'Airport' AND bc.material IN ('Titanium', 'Gold') + """, + 3: """ + SELECT s.name, a.action_performed, a.bomb_id, b.location + FROM access_logs a + JOIN suspects s ON s.suspect_id = a.suspect_id + JOIN bombs b ON b.bomb_id = a.bomb_id + WHERE b.location = 'Airport' AND a.action_performed = 'Installation' + """, +} + + +@pytest.mark.parametrize("stage", [1, 2, 3]) +def test_solution_queries_pass_validation_and_complete_stage(stage): + query = STAGE_SOLUTIONS[stage] + assert check_query(query) == (True, "") + assert check_stage_completion(stage, execute_query(query)) + + +@pytest.mark.parametrize( + "stage, query", + [ + (1, "SELECT bomb_id, location FROM bombs WHERE location = 'Airport'"), # missing evidence columns + (1, "SELECT * FROM bombs WHERE location = 'Stadium'"), # decoy + (2, "SELECT * FROM bomb_components WHERE bomb_id = 7"), # decoy with a Gold 221 circuit + (3, "SELECT s.name, a.action_performed, a.bomb_id FROM access_logs a " + "JOIN suspects s USING (suspect_id) WHERE a.bomb_id = 1"), + ], +) +def test_wrong_queries_do_not_complete_stage(stage, query): + assert not check_stage_completion(stage, execute_query(query)) + + +def test_stage_queries_do_not_cross_complete(): + assert not check_stage_completion(2, execute_query(STAGE_SOLUTIONS[1])) + assert not check_stage_completion(4, execute_query(STAGE_SOLUTIONS[1])) + assert not check_stage_completion(1, []) + + +def test_update_game_state_records_bomb_and_clue(): + state = {"bomb_id": None, "clues_found": []} + assert update_game_state(1, execute_query(STAGE_SOLUTIONS[1]), state) + assert state["bomb_id"] == 2 + assert state["clues_found"] == ["Stage 1 complete: Bomb identified"] + + +@pytest.mark.parametrize( + "query", + [ + "SELECT * FROM bombs", + " select location from bombs; ", + "WITH x AS (SELECT 1) SELECT * FROM x", + "-- find the airport\nSELECT * FROM bombs WHERE location = 'Airport'", + "SELECT * FROM suspects WHERE name = 'Drop Table'", # keyword inside a string literal + "SELECT replace(location, 'a', 'b') FROM bombs", + ], +) +def test_check_query_accepts(query): + ok, msg = check_query(query) + assert ok, msg + + +@pytest.mark.parametrize( + "query", + [ + "", + " ", + "DELETE FROM bombs", + "SELECT 1; DROP TABLE bombs", + "SELECT * FROM sqlite_master", + "PRAGMA table_info(bombs)", + "SELECT 1 " + "x" * 6000, + ], +) +def test_check_query_rejects(query): + ok, msg = check_query(query) + assert not ok + assert msg + + +def test_is_correct_answer_is_case_and_space_insensitive(): + assert is_correct_answer(" airport ", "Airport") + assert is_correct_answer("SARAH CONNOR", "Sarah Connor") + assert not is_correct_answer("Stadium", "Airport") From 72c36a29a14d75bc84afdd7acaf4aa2c72fea68d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 12:26:17 +0000 Subject: [PATCH 2/2] Handle multi-statement error on Python 3.10, where sqlite3 raises Warning Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WwKFojwA2s9TbXcrR6Mzqg --- backend/db.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/backend/db.py b/backend/db.py index 3303798..4ca5fe2 100644 --- a/backend/db.py +++ b/backend/db.py @@ -78,8 +78,9 @@ def execute_query(query: str) -> list[dict]: if "not authorized" in str(exc): raise QueryError("That operation is not allowed. Only read-only SELECT queries are permitted.") from exc raise QueryError(str(exc)) from exc - except sqlite3.ProgrammingError as exc: - # e.g. "You can only execute one statement at a time." + except (sqlite3.ProgrammingError, sqlite3.Warning) as exc: + # "You can only execute one statement at a time." is a ProgrammingError on + # Python 3.11+ but a sqlite3.Warning (not an sqlite3.Error) on 3.10. raise QueryError(str(exc)) from exc except sqlite3.Error as exc: raise QueryError(str(exc)) from exc