Validate file path to prevent directory traversal attacks. Args: file_path (str): Path to validate base_dir (str, optional): Base directory to restrict access to Returns: tuple: (is_valid, resolved_path)
(file_path, base_dir=None)
| 25 | # ============================================================================= |
| 26 | |
| 27 | def validate_file_path(file_path, base_dir=None): |
| 28 | """ |
| 29 | Validate file path to prevent directory traversal attacks. |
| 30 | |
| 31 | Args: |
| 32 | file_path (str): Path to validate |
| 33 | base_dir (str, optional): Base directory to restrict access to |
| 34 | |
| 35 | Returns: |
| 36 | tuple: (is_valid, resolved_path) |
| 37 | """ |
| 38 | try: |
| 39 | # Convert to Path object and resolve |
| 40 | path = Path(file_path).resolve() |
| 41 | |
| 42 | # Check for directory traversal attempts |
| 43 | if '..' in str(path) or str(path).startswith('/..'): |
| 44 | return False, None |
| 45 | |
| 46 | # If base_dir is specified, ensure path is within it |
| 47 | if base_dir: |
| 48 | base_path = Path(base_dir).resolve() |
| 49 | try: |
| 50 | path.relative_to(base_path) |
| 51 | except ValueError: |
| 52 | return False, None |
| 53 | |
| 54 | # Additional security checks |
| 55 | str_path = str(path) |
| 56 | dangerous_patterns = [ |
| 57 | '../', '..\\', '~/', '/etc/', '/proc/', '/sys/' |
| 58 | ] |
| 59 | if any(pattern in str_path for pattern in dangerous_patterns): |
| 60 | return False, None |
| 61 | |
| 62 | return True, str(path) |
| 63 | |
| 64 | except (OSError, ValueError): |
| 65 | return False, None |
| 66 | |
| 67 | def check_ksm_dependency(): |
| 68 | """Check if keeper_secrets_manager_core is installed. |
no test coverage detected