From 19e3bc557da21d525bc7942e50061daddb1ca7e3 Mon Sep 17 00:00:00 2001 From: Jerry Date: Tue, 10 Nov 2026 23:15:42 -0500 Subject: [PATCH] Fix stored XSS in uploads and compare, stop leaking password hashes - Uploaded images keep the client's Content-Type, so a ".png" posted as text/html or SVG was served inline from our origin (profile pictures and team logos). send_gridfs_file now serves only png/jpeg/gif with nosniff and falls back to the default image otherwise; team_logo goes through it instead of its own copy. This also neutralises payloads already stored. - SCOUTER_LOOKUP joined the scouter's whole user document, and /api/compare pushes $$ROOT to the browser, so every teammate's password_hash and email reached any team member. The lookup now projects only _id, username and teamNumber, for every pipeline that uses it. - /api/compare returned a bare string, so Flask served scouting notes as text/html. It now sends application/json like its sibling endpoints. Each fix has a regression test in tests/test_security.py that fails on the old code. Co-Authored-By: Claude Opus 5.5 --- app/scout/routes/lighthouse.py | 2 +- app/scout/scouting_utils.py | 9 ++++++-- app/team/routes.py | 13 +++--------- app/utils.py | 10 +++++++-- tests/test_security.py | 38 ++++++++++++++++++++++++++++++++++ 5 files changed, 57 insertions(+), 15 deletions(-) diff --git a/app/scout/routes/lighthouse.py b/app/scout/routes/lighthouse.py index b641fa7..ea86643 100644 --- a/app/scout/routes/lighthouse.py +++ b/app/scout/routes/lighthouse.py @@ -87,7 +87,7 @@ def compare_teams(): return jsonify({"error": "No data available for the selected teams"}), 404 current_app.logger.info(f"Compared teams {sorted(teams_data)} for user {actor_name(current_user)}") - return json_util.dumps(teams_data) + return json_util.dumps(teams_data), 200, {'Content-Type': 'application/json'} except Exception as e: current_app.logger.error(f"Error in compare_teams: {str(e)}", exc_info=True) diff --git a/app/scout/scouting_utils.py b/app/scout/scouting_utils.py index 254b82e..6e8c9d3 100644 --- a/app/scout/scouting_utils.py +++ b/app/scout/scouting_utils.py @@ -11,10 +11,15 @@ logger = logging.getLogger(__name__) +# Join only the scouter's public fields: results reach the browser (e.g. /api/compare pushes $$ROOT), +# so password_hash and email must never be in the joined document. SCOUTER_LOOKUP = {"$lookup": { "from": "users", - "localField": "scouter_id", - "foreignField": "_id", + "let": {"scouter_id": "$scouter_id"}, + "pipeline": [ + {"$match": {"$expr": {"$eq": ["$_id", "$$scouter_id"]}}}, + {"$project": {"_id": 1, "username": 1, "teamNumber": 1}}, + ], "as": "scouter" }} UNWIND_SCOUTER = {"$unwind": "$scouter"} diff --git a/app/team/routes.py b/app/team/routes.py index 8d6bb04..08a26c5 100644 --- a/app/team/routes.py +++ b/app/team/routes.py @@ -14,7 +14,7 @@ from app.team.team_utils import TeamManager from app.utils import (allowed_file, error_response, get_gridfs, handle_route_errors, limiter, save_file_to_gridfs, - success_response) + send_gridfs_file, success_response) from .forms import CreateTeamForm @@ -399,18 +399,11 @@ def delete_team(team_number): def team_logo(team_number): try: team = team_manager.db.teams.find_one({"team_number": team_number}) - if team and team.get("logo_id"): - logo_id = ObjectId(team["logo_id"]) if isinstance(team["logo_id"], str) else team["logo_id"] - logo = get_gridfs().get(logo_id) - return send_file( - BytesIO(logo.read()), - mimetype=logo.content_type, - download_name=logo.filename - ) + return send_gridfs_file(team["logo_id"], "static/images/default_logo.png") except Exception as e: current_app.logger.error(f"Error fetching team logo: {str(e)}", exc_info=True) - + # Return default logo on any error return send_file("static/images/default_logo.png") diff --git a/app/utils.py b/app/utils.py index 79242e3..03f6ff4 100644 --- a/app/utils.py +++ b/app/utils.py @@ -73,6 +73,8 @@ def setup_logger(): # File handling constants ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'} +# Uploads store the client's Content-Type, so only these are ever served inline. +SAFE_IMAGE_TYPES = {'image/png', 'image/jpeg', 'image/gif'} load_dotenv() @@ -239,16 +241,20 @@ def save_file_to_gridfs(file, prefix: str = '') -> str | None: return None def send_gridfs_file(file_id, default_path: str = None): - """Send file from GridFS or return default file""" + """Send an uploaded image from GridFS, or the default file if it is missing or not a safe image type""" try: if isinstance(file_id, str): file_id = ObjectId(file_id) file_data = get_gridfs().get(file_id) - return send_file( + if file_data.content_type not in SAFE_IMAGE_TYPES: + raise ValueError(f"Refusing to serve stored type {file_data.content_type!r}") + response = send_file( BytesIO(file_data.read()), mimetype=file_data.content_type, download_name=file_data.filename ) + response.headers['X-Content-Type-Options'] = 'nosniff' + return response except Exception as e: logger.error(f"Error retrieving file: {str(e)}") if default_path: diff --git a/tests/test_security.py b/tests/test_security.py index 2992814..c7278c1 100644 --- a/tests/test_security.py +++ b/tests/test_security.py @@ -1,6 +1,7 @@ """App-level security settings through create_app(); MongoDB and background services are mocked.""" import os import unittest +from types import SimpleNamespace from unittest.mock import patch from tests.app_harness import USER_ID, logged_in_client, start_app @@ -59,6 +60,43 @@ def test_session_cookies_are_same_site_and_no_wildcard_cors(self): response = self.app.test_client().get("/", headers={"Origin": "https://evil.test"}) self.assertNotIn("Access-Control-Allow-Origin", response.headers) + def test_uploaded_images_are_served_only_as_safe_image_types(self): + """Uploads keep the client's Content-Type; HTML or SVG must never be served inline from our origin.""" + client, _ = self.client() + payload = b"" + for content_type, served in (("text/html", False), ("image/svg+xml", False), ("image/png", True)): + stored = SimpleNamespace(content_type=content_type, filename="x.png", read=lambda: payload) + # Patch both lookups so the test still bites if team_logo ever serves GridFS files itself again. + with patch("app.team.routes.team_manager") as manager, patch("app.utils.get_gridfs") as gridfs, \ + patch("app.team.routes.get_gridfs", gridfs): + manager.db.teams.find_one.return_value = {"logo_id": USER_ID} + gridfs.return_value.get.return_value = stored + response = client.get("/team/team/334/logo") + self.assertNotIn(response.mimetype, ("text/html", "image/svg+xml"), content_type) + self.assertEqual(response.get_data() == payload, served, content_type) + if served: + self.assertEqual(response.headers["X-Content-Type-Options"], "nosniff") + + def test_scouter_join_exposes_only_public_fields(self): + """Aggregates push $$ROOT to the browser, so the joined user must never carry password_hash or email.""" + from app.scout.scouting_utils import SCOUTER_LOOKUP + self.assertEqual(SCOUTER_LOOKUP["$lookup"]["pipeline"][-1], + {"$project": {"_id": 1, "username": 1, "teamNumber": 1}}) + + def test_compare_api_is_served_as_json_not_html(self): + """Scouting notes in /api/compare must not render as HTML when the URL is opened directly.""" + client, _ = self.client() + stats = dict.fromkeys(["avg_auto_fuel", "avg_endgame_fuel", "avg_climb_level", "climb_success_rate", + "defense_rating", *(f"avg_teleop_shift_{n}_fuel" for n in range(1, 5))], 0) + stats["matches"] = [{"notes": ""}] + with patch("app.scout.routes.common.scouting_manager") as manager, \ + patch("app.scout.routes.lighthouse.TBAInterface") as tba: + manager.get_compare_stats.return_value = stats + tba.return_value.get_team.return_value = {"nickname": "Test"} + response = client.get("/api/compare?team1=1&team2=2") + self.assertEqual(response.status_code, 200) + self.assertEqual(response.mimetype, "application/json") + def test_missing_secret_key_refuses_to_start(self): from app.app import create_app with patch.dict(os.environ, {"SECRET_KEY": ""}), patch("app.app.load_dotenv"):