Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/scout/routes/lighthouse.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
9 changes: 7 additions & 2 deletions app/scout/scouting_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"}
Expand Down
13 changes: 3 additions & 10 deletions app/team/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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")

Expand Down
10 changes: 8 additions & 2 deletions app/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down Expand Up @@ -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:
Expand Down
38 changes: 38 additions & 0 deletions tests/test_security.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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"<script>alert(document.domain)</script>"
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": "<img src=x onerror=alert(1)>"}]
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"):
Expand Down
Loading