Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
improved filename sanitization
Saurav Pandaa4380060b92e
diff --git a/browser_use/filesystem/file_system.py b/browser_use/filesystem/file_system.pyindex f3ea791f1..402c82872 100644--- a/browser_use/filesystem/file_system.py+++ b/browser_use/filesystem/file_system.py@@ -10,7 +10,6 @@ from typing import Anyfrom pydantic import BaseModel, Field-INVALID_FILENAME_ERROR_MESSAGE = 'Error: Invalid filename format. Must be alphanumeric with supported extension.'UNSUPPORTED_BINARY_EXTENSIONS = {'png',@@ -392,6 +391,22 @@ class FileSystem:return f'{name_part}.{ext.lower()}'+ def _resolve_filename(self, file_name: str) -> tuple[str, bool]:+ """Resolve a filename, attempting sanitization if the original is invalid.++ Returns:+ (resolved_name, was_sanitized): The resolved filename and whether sanitization was applied.+ If resolution fails, returns (original_name, False).+ """+ if self._is_valid_filename(file_name):+ return file_name, False++ sanitized = self.sanitize_filename(file_name)+ if sanitized != os.path.basename(file_name) and self._is_valid_filename(sanitized):+ return sanitized, True++ return file_name, False+def _parse_filename(self, filename: str) -> tuple[str, str]:"""Parse filename into name and extension. Always check _is_valid_filename first."""name, extension = filename.rsplit('.', 1)@@ -402,12 +417,13 @@ class FileSystem:return self.data_dirdef get_file(self, full_filename: str) -> BaseFile | None:- """Get a file object by full filename"""- if not self._is_valid_filename(full_filename):+ """Get a file object by full filename, trying sanitization if the name is invalid."""+ resolved, _ = self._resolve_filename(full_filename)+ if not self._is_valid_filename(resolved):return None- # Use full filename as key- return self.files.get(full_filename)+ # Use resolved filename as key+ return self.files.get(resolved)def list_files(self) -> list[str]:"""List all files in the system"""@@ -415,10 +431,11 @@ class FileSystem:def display_file(self, full_filename: str) -> str | None:"""Display file content using file-specific display method"""- if not self._is_valid_filename(full_filename):+ resolved, _ = self._resolve_filename(full_filename)+ if not self._is_valid_filename(resolved):return None- file_obj = self.get_file(full_filename)+ file_obj = self.files.get(resolved)if not file_obj:return None@@ -508,18 +525,26 @@ class FileSystem:return result# For internal files, only non-image types are supported- if not self._is_valid_filename(full_filename):- result['message'] = INVALID_FILENAME_ERROR_MESSAGE+ resolved, was_sanitized = self._resolve_filename(full_filename)+ if not self._is_valid_filename(resolved):+ result['message'] = _build_filename_error_message(full_filename, self.get_allowed_extensions())return result- file_obj = self.get_file(full_filename)+ file_obj = self.files.get(resolved)if not file_obj:- result['message'] = f"File '{full_filename}' not found."+ if was_sanitized:+ result['message'] = (+ f"File '{resolved}' not found. "+ f"(Filename was auto-corrected from '{full_filename}')"+ )+ else:+ result['message'] = f"File '{full_filename}' not found."return resulttry:content = file_obj.read()- result['message'] = f'Read from file {full_filename}.\n<content>\n{content}\n</content>'+ sanitize_note = f"Note: filename was auto-corrected from '{full_filename}' to '{resolved}'. " if was_sanitized else ''+ result['message'] = f'{sanitize_note}Read from file {resolved}.\n<content>\n{content}\n</content>'return resultexcept FileSystemError as e:result['message'] = str(e)@@ -538,13 +563,11 @@ class FileSystem:async def write_file(self, full_filename: str, content: str) -> str:"""Write content to file using file-specific write method"""- if not self._is_valid_filename(full_filename):- # Try sanitizing the filename before giving up- sanitized = self.sanitize_filename(full_filename)- if sanitized != os.path.basename(full_filename) and self._is_valid_filename(sanitized):- full_filename = sanitized- else:- return _build_filename_error_message(full_filename, self.get_allowed_extensions())+ original_filename = full_filename+ resolved, was_sanitized = self._resolve_filename(full_filename)+ if not self._is_valid_filename(resolved):+ return _build_filename_error_message(full_filename, self.get_allowed_extensions())+ full_filename = resolvedtry:name_without_ext, extension = self._parse_filename(full_filename)@@ -561,7 +584,8 @@ class FileSystem:# Use file-specific write methodawait file_obj.write(content, self.data_dir)- return f'Data written to file {full_filename} successfully.'+ sanitize_note = f" (auto-corrected from '{original_filename}')" if was_sanitized else ''+ return f'Data written to file {full_filename} successfully.{sanitize_note}'except FileSystemError as e:return str(e)except Exception as e:@@ -569,20 +593,22 @@ class FileSystem:async def append_file(self, full_filename: str, content: str) -> str:"""Append content to file using file-specific append method"""- if not self._is_valid_filename(full_filename):- sanitized = self.sanitize_filename(full_filename)- if sanitized != os.path.basename(full_filename) and self._is_valid_filename(sanitized):- full_filename = sanitized- else:- return _build_filename_error_message(full_filename, self.get_allowed_extensions())+ original_filename = full_filename+ resolved, was_sanitized = self._resolve_filename(full_filename)+ if not self._is_valid_filename(resolved):+ return _build_filename_error_message(full_filename, self.get_allowed_extensions())+ full_filename = resolved- file_obj = self.get_file(full_filename)+ file_obj = self.files.get(full_filename)if not file_obj:+ if was_sanitized:+ return f"File '{full_filename}' not found. (Filename was auto-corrected from '{original_filename}')"return f"File '{full_filename}' not found."try:await file_obj.append(content, self.data_dir)- return f'Data appended to file {full_filename} successfully.'+ sanitize_note = f" (auto-corrected from '{original_filename}')" if was_sanitized else ''+ return f'Data appended to file {full_filename} successfully.{sanitize_note}'except FileSystemError as e:return str(e)except Exception as e:@@ -590,25 +616,27 @@ class FileSystem:async def replace_file_str(self, full_filename: str, old_str: str, new_str: str) -> str:"""Replace old_str with new_str in file_name"""- if not self._is_valid_filename(full_filename):- sanitized = self.sanitize_filename(full_filename)- if sanitized != os.path.basename(full_filename) and self._is_valid_filename(sanitized):- full_filename = sanitized- else:- return _build_filename_error_message(full_filename, self.get_allowed_extensions())+ original_filename = full_filename+ resolved, was_sanitized = self._resolve_filename(full_filename)+ if not self._is_valid_filename(resolved):+ return _build_filename_error_message(full_filename, self.get_allowed_extensions())+ full_filename = resolvedif not old_str:return 'Error: Cannot replace empty string. Please provide a non-empty string to replace.'- file_obj = self.get_file(full_filename)+ file_obj = self.files.get(full_filename)if not file_obj:+ if was_sanitized:+ return f"File '{full_filename}' not found. (Filename was auto-corrected from '{original_filename}')"return f"File '{full_filename}' not found."try:content = file_obj.read()content = content.replace(old_str, new_str)await file_obj.write(content, self.data_dir)- return f'Successfully replaced all occurrences of "{old_str}" with "{new_str}" in file {full_filename}'+ sanitize_note = f" (auto-corrected from '{original_filename}')" if was_sanitized else ''+ return f'Successfully replaced all occurrences of "{old_str}" with "{new_str}" in file {full_filename}{sanitize_note}'except FileSystemError as e:return str(e)except Exception as e:diff --git a/browser_use/tools/service.py b/browser_use/tools/service.pyindex d612c2bbb..2fb68d4e0 100644--- a/browser_use/tools/service.py+++ b/browser_use/tools/service.py@@ -1076,8 +1076,9 @@ You will be given a query and the markdown of a webpage that has been filtered telse:result = await file_system.write_file(file_name, content)- # Log the full path where the file is stored- file_path = file_system.get_dir() / file_name+ # Log the full path where the file is stored (use resolved name)+ resolved_name, _ = file_system._resolve_filename(file_name)+ file_path = file_system.get_dir() / resolved_namelogger.info(f'💾 {result} File location: {file_path}')return ActionResult(extracted_content=result, long_term_memory=result)diff --git a/tests/ci/infrastructure/test_filesystem.py b/tests/ci/infrastructure/test_filesystem.pyindex b41405800..5b4e2d418 100644--- a/tests/ci/infrastructure/test_filesystem.py+++ b/tests/ci/infrastructure/test_filesystem.py@@ -8,7 +8,6 @@ import pytestfrom browser_use.filesystem.file_system import (DEFAULT_FILE_SYSTEM_PATH,- INVALID_FILENAME_ERROR_MESSAGE,CsvFile,FileSystem,FileSystemState,@@ -325,10 +324,14 @@ class TestFileSystem:non_existent = fs.get_file('nonexistent.md')assert non_existent is None- # Get file with invalid name+ # Get file with invalid name - sanitized to invalidname.md, still not foundinvalid = fs.get_file('[email protected]')assert invalid is None+ # Get default file via sanitized name should work+ todo = fs.get_file('todo.md')+ assert todo is not None+def test_list_files(self, temp_filesystem):"""Test listing files in the filesystem."""fs = temp_filesystem@@ -366,9 +369,11 @@ class TestFileSystem:result = await fs.read_file('nonexistent.md')assert result == "File 'nonexistent.md' not found."- # Read file with invalid name+ # Read file with invalid name - gets auto-sanitized to invalidname.md, but file doesn't existresult = await fs.read_file('[email protected]')- assert result == INVALID_FILENAME_ERROR_MESSAGE+ assert 'not found' in result+ assert 'invalidname.md' in result+ assert 'auto-corrected' in resultasync def test_write_file(self, temp_filesystem):"""Test writing content to files."""@@ -391,6 +396,8 @@ class TestFileSystem:# Write with special chars in filename - auto-sanitized to 'invalidname.md'result = await fs.write_file('[email protected]', 'content')assert 'successfully' in result+ assert 'auto-corrected' in result+ assert 'invalidname.md' in result# Write with unsupported extension - gives specific errorresult = await fs.write_file('test.doc', 'content')@@ -468,6 +475,7 @@ class TestFileSystem:# Append with special chars in filename - auto-sanitized but file doesn't existresult = await fs.append_file('[email protected]', 'content')assert 'not found' in result+ assert 'auto-corrected' in resultasync def test_append_json_file(self, temp_filesystem):"""Test appending content to JSON files."""@@ -967,18 +975,29 @@ class TestFilenameSanitization:assert FileSystem.sanitize_filename('@#$.md') == 'file.md'async def test_write_file_auto_sanitizes(self):- """Test that write_file auto-sanitizes invalid filenames when possible."""+ """Test that write_file auto-sanitizes invalid filenames and includes a notice."""with tempfile.TemporaryDirectory() as tmp_dir:fs = FileSystem(base_dir=tmp_dir, create_default_files=False)- # Filename with special chars should be auto-sanitized+ # Filename with special chars should be auto-sanitized with noticeresult = await fs.write_file('[email protected]', 'content')assert 'successfully' in result+ assert 'auto-corrected' in result+ assert 'testfile.md' in result- # Filename with spaces should be auto-sanitized+ # Filename with spaces - spaces are valid, so no sanitization neededresult = await fs.write_file('my file.txt', 'content')assert 'successfully' in result+ # Verify the sanitized file can be read back+ content = await fs.read_file('testfile.md')+ assert 'content' in content++ # Verify reading with the original invalid name also works (via sanitization)+ content = await fs.read_file('[email protected]')+ assert 'content' in content+ assert 'auto-corrected' in content+fs.nuke()async def test_write_file_binary_extension_error(self):@@ -1034,6 +1053,116 @@ class TestFilenameSanitization:fs.nuke()+ async def test_read_file_with_sanitized_name(self):+ """Test that read_file resolves sanitized filenames to find existing files."""+ with tempfile.TemporaryDirectory() as tmp_dir:+ fs = FileSystem(base_dir=tmp_dir, create_default_files=False)++ # Write with invalid name (gets sanitized)+ await fs.write_file('data#export.json', '{"key": "value"}')++ # Read with the sanitized name directly+ result = await fs.read_file('dataexport.json')+ assert '{"key": "value"}' in result++ # Read with the original invalid name (should resolve via sanitization)+ result = await fs.read_file('data#export.json')+ assert '{"key": "value"}' in result+ assert 'auto-corrected' in result++ fs.nuke()++ async def test_append_file_with_sanitized_name(self):+ """Test that append_file works with sanitized filenames."""+ with tempfile.TemporaryDirectory() as tmp_dir:+ fs = FileSystem(base_dir=tmp_dir, create_default_files=False)++ # Write with invalid name (gets sanitized to 'report.md')+ await fs.write_file('report!.md', '# Report')++ # Append using the original invalid name (should resolve via sanitization)+ result = await fs.append_file('report!.md', '\n## Section 2')+ assert 'successfully' in result+ assert 'auto-corrected' in result++ # Verify content was appended+ content = await fs.read_file('report.md')+ assert '# Report' in content+ assert '## Section 2' in content++ fs.nuke()++ async def test_replace_file_with_sanitized_name(self):+ """Test that replace_file_str works with sanitized filenames."""+ with tempfile.TemporaryDirectory() as tmp_dir:+ fs = FileSystem(base_dir=tmp_dir, create_default_files=False)++ # Write with invalid name (gets sanitized)+ await fs.write_file('my$notes.txt', 'old text here')++ # Replace using the original invalid name+ result = await fs.replace_file_str('my$notes.txt', 'old text', 'new text')+ assert 'Successfully replaced' in result+ assert 'auto-corrected' in result++ # Verify replacement worked+ content = await fs.read_file('mynotes.txt')+ assert 'new text here' in content++ fs.nuke()++ async def test_no_extension_gives_specific_error(self):+ """Test that filenames without extensions give a helpful error."""+ with tempfile.TemporaryDirectory() as tmp_dir:+ fs = FileSystem(base_dir=tmp_dir, create_default_files=False)++ result = await fs.write_file('justname', 'content')+ assert 'no extension' in result.lower()+ assert '.md' in result++ fs.nuke()++ async def test_read_unsanitizable_filename_gives_specific_error(self):+ """Test that truly unresolvable filenames get specific error messages."""+ with tempfile.TemporaryDirectory() as tmp_dir:+ fs = FileSystem(base_dir=tmp_dir, create_default_files=False)++ # No extension - can't be sanitized+ result = await fs.read_file('noextension')+ assert 'no extension' in result.lower()++ # Binary extension - specific error+ result = await fs.write_file('image.png', 'data')+ assert 'binary' in result.lower() or 'Cannot write' in result++ fs.nuke()++ def test_get_file_with_sanitized_name(self):+ """Test that get_file resolves sanitized filenames."""+ with tempfile.TemporaryDirectory() as tmp_dir:+ fs = FileSystem(base_dir=tmp_dir, create_default_files=True)++ # get_file with valid name+ assert fs.get_file('todo.md') is not None++ # get_file with invalid chars that sanitize to a non-existent file+ assert fs.get_file('[email protected]') is None++ fs.nuke()++ def test_display_file_with_sanitized_name(self):+ """Test that display_file resolves sanitized filenames."""+ with tempfile.TemporaryDirectory() as tmp_dir:+ fs = FileSystem(base_dir=tmp_dir, create_default_files=True)++ # Display with valid name+ assert fs.display_file('todo.md') is not None++ # Display with unsanitizable name+ assert fs.display_file('noext') is None++ fs.nuke()+class TestFileSystemIntegration:"""Integration tests for FileSystem with real file operations."""