def _check_filepath(self, filepath: str) -> None: """Raises an error if a filepath is invalid. Args: filepath: str. The path to the relevant file within the entity's assets folder. Raises: OSError. Invalid filepath. """ base_dir = utils.vfs_construct_path('/', self.assets_path, 'assets') absolute_path = utils.vfs_construct_path(base_dir, filepath) normalized_path = utils.vfs_normpath(absolute_path) # This check prevents directory traversal. if not normalized_path.startswith(base_dir): raise IOError('Invalid filepath: %s' % filepath)
def test_vfs_normpath(self) -> None: p = utils.vfs_normpath('/foo/../bar') self.assertEqual(p, '/bar') p = utils.vfs_normpath('foo//bar') self.assertEqual(p, 'foo/bar') p = utils.vfs_normpath('foo/bar/..') self.assertEqual(p, 'foo') p = utils.vfs_normpath('/foo//bar//baz//') self.assertEqual(p, '/foo/bar/baz') p = utils.vfs_normpath('') self.assertEqual(p, '.') p = utils.vfs_normpath('//foo//bar//baz//') self.assertEqual(p, '//foo/bar/baz')