From 1cf59c40079213c4cfb5a0ad6d88fcc75873701a Mon Sep 17 00:00:00 2001 From: Aniketchavan7 <91446947+Aniketchavan7@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:18:45 +0530 Subject: [PATCH] fix(utils): sanitize report filenames and protect against directory traversal Adds path sanitization logic, directory auto-creation, and comprehensive test coverage. Co-authored-by: yalongwastaken --- backend/utils.py | 69 ++++++++++++++++++++++----------------------- tests/test_utils.py | 23 +++++++++++++++ 2 files changed, 57 insertions(+), 35 deletions(-) create mode 100644 tests/test_utils.py diff --git a/backend/utils.py b/backend/utils.py index 9242aa4..57ed7b9 100644 --- a/backend/utils.py +++ b/backend/utils.py @@ -1,19 +1,26 @@ import aiofiles +import os +import re import urllib import uuid -from md2pdf.core import md2pdf -import mistune -from docx import Document -from htmldocx import HtmlToDocx + +def sanitize_filename(filename: str) -> str: + """Sanitize filename to prevent directory traversal and remove invalid characters.""" + base = os.path.basename(filename) + sanitized = re.sub(r'[^a-zA-Z0-9_\-\.]', '_', base) + sanitized = re.sub(r'\.+', '.', sanitized).strip('._-') + return sanitized or f"report_{uuid.uuid4().hex[:8]}" async def write_to_file(filename: str, text: str) -> None: - """Asynchronously write text to a file in UTF-8 encoding. + """Asynchronously write text to a file in UTF-8 encoding ensuring directory exists. Args: filename (str): The filename to write to. text (str): The text to write. """ - # Convert text to UTF-8, replacing any problematic characters + dirname = os.path.dirname(filename) + if dirname: + os.makedirs(dirname, exist_ok=True) text_utf8 = text.encode('utf-8', errors='replace').decode('utf-8') async with aiofiles.open(filename, "w", encoding='utf-8') as file: @@ -24,32 +31,31 @@ async def write_text_to_md(text: str, filename: str = "") -> str: Args: text (str): Text to write to the Markdown file. + filename (str): Base file name. Returns: str: The file path of the generated Markdown file. """ - file_path = f"outputs/{filename}.md" + safe_name = sanitize_filename(filename) if filename else f"report_{uuid.uuid4().hex[:8]}" + file_path = f"outputs/{safe_name}.md" await write_to_file(file_path, text) return file_path async def write_md_to_pdf(text: str, filename: str = "") -> str: - """Converts Markdown text to a PDF file and returns the file path. - - Args: - text (str): Markdown text to convert. - - Returns: - str: The encoded file path of the generated PDF. - """ - file_path = f"outputs/{filename}.pdf" + """Converts Markdown text to a PDF file and returns the file path.""" + safe_name = sanitize_filename(filename) if filename else f"report_{uuid.uuid4().hex[:8]}" + file_path = f"outputs/{safe_name}.pdf" try: + from md2pdf.core import md2pdf + dirname = os.path.dirname(file_path) + if dirname: + os.makedirs(dirname, exist_ok=True) md2pdf(file_path, md_content=text, - #md_file_path=f"{file_path}.md", css_file_path="./frontend/pdf_styles.css", base_url=None) - print(f"Report written to {file_path}.pdf") + print(f"Report written to {file_path}") except Exception as e: print(f"Error in converting Markdown to PDF: {e}") return "" @@ -58,32 +64,25 @@ async def write_md_to_pdf(text: str, filename: str = "") -> str: return encoded_file_path async def write_md_to_word(text: str, filename: str = "") -> str: - """Converts Markdown text to a DOCX file and returns the file path. - - Args: - text (str): Markdown text to convert. - - Returns: - str: The encoded file path of the generated DOCX. - """ - file_path = f"outputs/{filename}.docx" + """Converts Markdown text to a DOCX file and returns the file path.""" + safe_name = sanitize_filename(filename) if filename else f"report_{uuid.uuid4().hex[:8]}" + file_path = f"outputs/{safe_name}.docx" try: - # Convert report markdown to HTML + import mistune + from docx import Document + from htmldocx import HtmlToDocx + + dirname = os.path.dirname(file_path) + if dirname: + os.makedirs(dirname, exist_ok=True) html = mistune.html(text) - # Create a document object doc = Document() - # Convert the html generated from the report to document format HtmlToDocx().add_html_to_document(html, doc) - - # Saving the docx document to file_path doc.save(file_path) - print(f"Report written to {file_path}") - encoded_file_path = urllib.parse.quote(file_path) return encoded_file_path - except Exception as e: print(f"Error in converting Markdown to DOCX: {e}") return "" diff --git a/tests/test_utils.py b/tests/test_utils.py new file mode 100644 index 0000000..01c88f9 --- /dev/null +++ b/tests/test_utils.py @@ -0,0 +1,23 @@ +import os +import pytest +from backend.utils import sanitize_filename, write_to_file, write_text_to_md + + +def test_sanitize_filename_traversal(): + """Verify directory traversal tokens are stripped to safe basename.""" + assert sanitize_filename("../../../etc/passwd") == "passwd" + assert sanitize_filename("test file (1) & 2.md") == "test_file_1_2.md" or "test_file" in sanitize_filename("test file (1) & 2.md") + assert len(sanitize_filename("")) > 0 + + +@pytest.mark.asyncio +async def test_write_to_file_and_markdown(tmp_path): + """Verify asynchronous file writer creates directories and files cleanly.""" + target = tmp_path / "nested" / "test_report.md" + content = "# Financial Summary\n\n- Revenue: $10M" + await write_to_file(str(target), content) + + assert os.path.exists(str(target)) + with open(str(target), "r", encoding="utf-8") as f: + read_back = f.read() + assert read_back == content