def verify_file_path(path: str) -> None: """Check if path can be accessed.""" restricted_paths = [ "/bin", "/boot", "/dev", "/etc", "/lib", "/media", "/proc", "/root", "/run", "/sbin", "/snap", "/srv", "/swapfile", "/usr", "/var", ] real_path = os.path.realpath(path) if not os.path.exists(real_path): raise NotFoundException("File not found.") if os.stat(real_path).st_uid == 0: raise AccessDeniedException("Access denied.") for path_element in real_path.split(os.sep): if path_element.startswith("."): raise AccessDeniedException("Access denied.") for restricted_path in restricted_paths: if real_path.startswith(restricted_path): raise AccessDeniedException("Access denied.")
def test_from_exception_for_access_denied_exception(self) -> None: """Test from_exception for AccessDeniedException.""" message = "You can't enter here!" response = ResponseGenerator.from_exception( AccessDeniedException(message)) self.assertEqual(403, response.status_code) self.assertEqual(message, response.data.decode("utf-8"))
def get_directory_entries(data: Dict[str, Any], ) -> Dict[str, Any]: """Get directory entries.""" try: path = get_requested_path(data) verify_file_path(path) contents = get_non_hidden_directory_entries(path) contents = filter_requested_entries(contents, get_filter_value(data)) return { "path": path, "contents": sort_entries(contents), } except PermissionError as err: raise AccessDeniedException(err) except FileNotFoundError as err: raise NotFoundException(err) except NotADirectoryError as err: raise ClientErrorException(err)