From c7b8fb1d62a7e0563f72c0ffb88a3cda345a108e Mon Sep 17 00:00:00 2001 From: karthik-0306 Date: Sun, 22 Nov 2026 23:20:37 +0530 Subject: [PATCH 1/2] [Feature][Client] Add per-user cache location and distribution URL to Python SDK --- .../seatunnel/distribution.py | 126 ++++++++++++ .../tests/test_distribution.py | 185 ++++++++++++++++++ 2 files changed, 311 insertions(+) create mode 100644 tools/seatunnel-python-sdk/seatunnel/distribution.py create mode 100644 tools/seatunnel-python-sdk/tests/test_distribution.py diff --git a/tools/seatunnel-python-sdk/seatunnel/distribution.py b/tools/seatunnel-python-sdk/seatunnel/distribution.py new file mode 100644 index 000000000000..1da754e095fc --- /dev/null +++ b/tools/seatunnel-python-sdk/seatunnel/distribution.py @@ -0,0 +1,126 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Locate the per-user cache of a SeaTunnel distribution and build its download URL. + +Ownership boundary: :func:`cache_dir` is the per-user, per-version directory that the +launcher owns. Later launcher steps (download, extraction, plugin installation) may modify +this directory and nothing else. It is never inside a source checkout, a shared +installation or the Python package directory (``site-packages``), so installing or +upgrading the Python package neither touches nor loses a downloaded distribution. + +This module only computes locations. It creates no directory, opens no connection and +downloads nothing; those belong to later steps of +https://github.com/apache/seatunnel/issues/12707. +""" + +import os +import re +import sys +from urllib.parse import urlsplit + +DEFAULT_BASE_URL = "https://downloads.apache.org/seatunnel" + +_CACHE_DIR_NAME = "seatunnel" + +# A release version is used as a URL path segment and as a directory name, so it must start +# and end with a letter or digit. Starting with one rules out "." and "..", which would let a +# version name a directory outside the cache. Ending with one keeps "3.0." and "3.0" apart on +# Windows, which drops a trailing dot from directory names. +_VERSION_RE = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?") + + +class DistributionError(Exception): + """Raised when a distribution location cannot be determined.""" + + +def _validate_version(version: str) -> str: + if not isinstance(version, str) or not _VERSION_RE.fullmatch(version.strip()): + raise DistributionError( + f"Invalid SeaTunnel version {version!r}: it must start and end with a letter or " + f"digit and may only contain letters, digits, '.', '_' and '-'." + ) + return version.strip() + + +def distribution_url(version: str, base_url: str = DEFAULT_BASE_URL) -> str: + """Return the URL of the binary distribution archive of a SeaTunnel release. + + The result is deterministic and needs no network access. For ``3.0.0`` it is + ``https://downloads.apache.org/seatunnel/3.0.0/apache-seatunnel-3.0.0-bin.tar.gz``. The + checksum and signature published next to the archive are at the same URL with a + ``.sha512`` or ``.asc`` suffix. + + Note that downloads.apache.org only keeps current releases; the ASF moves older ones to + archive.apache.org, which can be passed as *base_url* by the caller. + + :param version: Release version such as ``"3.0.0"``. It may only contain + ``A-Z a-z 0-9 . _ -`` and must start and end with a letter or digit. + :param base_url: Root of the release repository, such as + ``https://archive.apache.org/dist/seatunnel``. It must be an ``https://`` URL with a + host and no query or fragment, so the archive, checksum and signature cannot be + altered in transit. + :raises DistributionError: If the version or base URL is invalid. + """ + version = _validate_version(version) + parts = urlsplit(base_url) if isinstance(base_url, str) else None + if ( + parts is None + or parts.scheme != "https" + or not parts.netloc + or parts.query + or parts.fragment + ): + raise DistributionError( + f"The distribution base URL must be an 'https://' URL with a host and no query " + f"or fragment, got {base_url!r}." + ) + return f"{base_url.rstrip('/')}/{version}/apache-seatunnel-{version}-bin.tar.gz" + + +def _cache_root() -> str: + """Return the per-user cache root of the current platform.""" + home = os.path.expanduser("~") + if sys.platform == "win32": + base = os.environ.get("LOCALAPPDATA") or os.path.join(home, "AppData", "Local") + elif sys.platform == "darwin": + base = os.path.join(home, "Library", "Caches") + else: + # The XDG specification says to ignore a relative XDG_CACHE_HOME. + base = os.environ.get("XDG_CACHE_HOME", "") + if not os.path.isabs(base): + base = os.path.join(home, ".cache") + if not os.path.isabs(base): + raise DistributionError( + f"Cannot determine a per-user cache location: '{base}' is not an absolute path." + ) + return os.path.join(base, _CACHE_DIR_NAME) + + +def cache_dir(version: str) -> str: + """Return the per-user directory that holds the distribution of *version*. + + Each user and each version gets a separate directory, so two versions or two users never + share or overwrite files. The location is ``seatunnel/`` under the platform's + per-user cache directory: ``$XDG_CACHE_HOME`` or ``~/.cache`` on Linux, + ``~/Library/Caches`` on macOS and ``%LOCALAPPDATA%`` on Windows. The directory is not + created and may not exist. + + :param version: Release version such as ``"3.0.0"``; see :func:`distribution_url`. + :returns: An absolute path. + :raises DistributionError: If the version is invalid or no absolute per-user cache + location can be determined. + """ + return os.path.join(_cache_root(), _validate_version(version)) diff --git a/tools/seatunnel-python-sdk/tests/test_distribution.py b/tools/seatunnel-python-sdk/tests/test_distribution.py new file mode 100644 index 000000000000..5afb79466aaa --- /dev/null +++ b/tools/seatunnel-python-sdk/tests/test_distribution.py @@ -0,0 +1,185 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import contextlib +import os +import tempfile +import unittest +from unittest import mock + +from seatunnel import distribution +from seatunnel.distribution import DistributionError, cache_dir, distribution_url + + +class TestDistributionUrl(unittest.TestCase): + def test_release_url_follows_the_apache_layout(self): + self.assertEqual( + "https://downloads.apache.org/seatunnel/3.0.0/apache-seatunnel-3.0.0-bin.tar.gz", + distribution_url("3.0.0"), + ) + + def test_url_is_deterministic(self): + self.assertEqual(distribution_url("3.0.0"), distribution_url("3.0.0")) + + def test_each_version_gets_its_own_url(self): + self.assertNotEqual(distribution_url("3.0.0"), distribution_url("3.0.1")) + + def test_surrounding_whitespace_in_version_is_dropped(self): + self.assertEqual(distribution_url("3.0.0"), distribution_url(" 3.0.0\n")) + + def test_custom_base_url_is_used_and_trailing_slash_is_ignored(self): + expected = ( + "https://archive.apache.org/dist/seatunnel/2.3.9/apache-seatunnel-2.3.9-bin.tar.gz" + ) + self.assertEqual( + expected, distribution_url("2.3.9", "https://archive.apache.org/dist/seatunnel") + ) + self.assertEqual( + expected, distribution_url("2.3.9", "https://archive.apache.org/dist/seatunnel/") + ) + + def test_invalid_versions_raise(self): + for version in ("", " ", ".", "..", "../x", "-3.0.0", "3.0.", "3.0-", "3.0/1", + "3.0\\1", "3.0 beta", "3.0;rm", "3.0?x=1", "3.0#frag", None, 3): + with self.subTest(version=version): + with self.assertRaises(DistributionError): + distribution_url(version) + + def test_single_character_version_is_accepted(self): + self.assertTrue(distribution_url("3").endswith("/3/apache-seatunnel-3-bin.tar.gz")) + + def test_invalid_base_url_raises(self): + for base_url in ("http://downloads.apache.org/seatunnel", "ftp://x/y", "https://", + "https:///seatunnel", "https://x/seatunnel?mirror=1", + "https://x/seatunnel#top", "downloads.apache.org/seatunnel", "", + None): + with self.subTest(base_url=base_url): + with self.assertRaises(DistributionError) as ctx: + distribution_url("3.0.0", base_url) + self.assertIn("https://", str(ctx.exception)) + + +class TestCacheDir(unittest.TestCase): + def setUp(self): + # Absolute paths of the host OS, so the tests behave the same on Linux, macOS and + # Windows while sys.platform is faked. + self.root = os.path.join(tempfile.gettempdir(), "seatunnel-cache-test") + self.home = os.path.join(self.root, "alice") + + @contextlib.contextmanager + def _environment(self, platform, home=None, **env): + """Fake the platform, the home directory and the cache related environment.""" + home = home or self.home + with contextlib.ExitStack() as stack: + stack.enter_context(mock.patch.object(distribution.sys, "platform", platform)) + stack.enter_context(mock.patch("os.path.expanduser", return_value=home)) + stack.enter_context( + mock.patch.dict(os.environ, {"XDG_CACHE_HOME": "", "LOCALAPPDATA": ""}) + ) + stack.enter_context(mock.patch.dict(os.environ, env)) + yield + + def test_linux_uses_the_default_cache_directory(self): + with self._environment("linux"): + self.assertEqual( + os.path.join(self.home, ".cache", "seatunnel", "3.0.0"), cache_dir("3.0.0") + ) + + def test_linux_honors_xdg_cache_home(self): + xdg = os.path.join(self.root, "xdg") + with self._environment("linux", XDG_CACHE_HOME=xdg): + self.assertEqual(os.path.join(xdg, "seatunnel", "3.0.0"), cache_dir("3.0.0")) + + def test_linux_ignores_a_relative_xdg_cache_home(self): + with self._environment("linux", XDG_CACHE_HOME="relative/cache"): + self.assertEqual( + os.path.join(self.home, ".cache", "seatunnel", "3.0.0"), cache_dir("3.0.0") + ) + + def test_macos_uses_the_library_caches_directory(self): + with self._environment("darwin"): + self.assertEqual( + os.path.join(self.home, "Library", "Caches", "seatunnel", "3.0.0"), + cache_dir("3.0.0"), + ) + + def test_windows_uses_localappdata(self): + local = os.path.join(self.root, "local") + with self._environment("win32", LOCALAPPDATA=local): + self.assertEqual(os.path.join(local, "seatunnel", "3.0.0"), cache_dir("3.0.0")) + + def test_windows_without_localappdata_falls_back_to_the_home_directory(self): + with self._environment("win32"): + self.assertEqual( + os.path.join(self.home, "AppData", "Local", "seatunnel", "3.0.0"), + cache_dir("3.0.0"), + ) + + def test_relative_cache_location_raises(self): + with self._environment("win32", LOCALAPPDATA="relative"): + with self.assertRaises(DistributionError) as ctx: + cache_dir("3.0.0") + self.assertIn("absolute", str(ctx.exception)) + + def test_versions_are_isolated_from_each_other(self): + with self._environment("linux"): + first, second = cache_dir("3.0.0"), cache_dir("3.0.1") + self.assertNotEqual(first, second) + self.assertEqual(os.path.dirname(first), os.path.dirname(second)) + + def test_users_are_isolated_from_each_other(self): + with self._environment("linux", home=os.path.join(self.root, "alice")): + alice = cache_dir("3.0.0") + with self._environment("linux", home=os.path.join(self.root, "bob")): + bob = cache_dir("3.0.0") + self.assertNotEqual(alice, bob) + self.assertTrue(alice.startswith(os.path.join(self.root, "alice") + os.sep)) + self.assertTrue(bob.startswith(os.path.join(self.root, "bob") + os.sep)) + + def test_version_cannot_name_a_directory_outside_the_cache(self): + with self._environment("linux"): + cache_root = os.path.dirname(cache_dir("3.0.0")) + for version in ("..", ".", "../../etc", "3.0/../..", "/abs", "a/b"): + with self.subTest(version=version): + with self.assertRaises(DistributionError): + cache_dir(version) + self.assertEqual(cache_root, os.path.dirname(cache_dir("3.0.0"))) + + def test_invalid_version_raises(self): + with self._environment("linux"): + for version in ("", None, 3, "3.0 beta"): + with self.subTest(version=version): + with self.assertRaises(DistributionError): + cache_dir(version) + + def test_cache_dir_is_absolute_and_not_created(self): + with tempfile.TemporaryDirectory() as tmp: + with self._environment("linux", home=tmp): + path = cache_dir("3.0.0") + self.assertTrue(os.path.isabs(path)) + self.assertFalse(os.path.exists(path)) + self.assertEqual([], os.listdir(tmp)) + + def test_cache_dir_is_not_inside_the_installed_package(self): + # Uses the real platform and environment, not the fakes above. + package_dir = os.path.dirname(os.path.dirname(os.path.abspath(distribution.__file__))) + path = cache_dir("3.0.0") + self.assertTrue(os.path.isabs(path)) + self.assertFalse(path.startswith(package_dir + os.sep)) + + +if __name__ == "__main__": + unittest.main() From 1cfe3e9fe8204a4f970e4251a8990303c5d61373 Mon Sep 17 00:00:00 2001 From: karthik-0306 Date: Mon, 23 Nov 2026 14:08:45 +0530 Subject: [PATCH 2/2] [Feature][Client] Address review: strict base URL validation, home directory checks, digit-first versions --- .../seatunnel/distribution.py | 161 +++++++++++----- .../tests/test_distribution.py | 178 ++++++++++++++---- 2 files changed, 256 insertions(+), 83 deletions(-) diff --git a/tools/seatunnel-python-sdk/seatunnel/distribution.py b/tools/seatunnel-python-sdk/seatunnel/distribution.py index 1da754e095fc..29d21e9c4d96 100644 --- a/tools/seatunnel-python-sdk/seatunnel/distribution.py +++ b/tools/seatunnel-python-sdk/seatunnel/distribution.py @@ -17,9 +17,13 @@ Ownership boundary: :func:`cache_dir` is the per-user, per-version directory that the launcher owns. Later launcher steps (download, extraction, plugin installation) may modify -this directory and nothing else. It is never inside a source checkout, a shared -installation or the Python package directory (``site-packages``), so installing or -upgrading the Python package neither touches nor loses a downloaded distribution. +this directory and nothing else. By default it is under the user's own cache directory, +outside any source checkout, shared installation or the Python package directory +(``site-packages``), so installing or upgrading the Python package neither touches nor loses +a downloaded distribution. The location follows the user's home directory and +``XDG_CACHE_HOME`` (Linux) or ``LOCALAPPDATA`` (Windows); a relative value or one that +resolves to the filesystem root is not used, but the location is not otherwise checked, so +pointing those at a shared directory makes the cache shared too. This module only computes locations. It creates no directory, opens no connection and downloads nothing; those belong to later steps of @@ -29,17 +33,30 @@ import os import re import sys +from typing import Optional from urllib.parse import urlsplit DEFAULT_BASE_URL = "https://downloads.apache.org/seatunnel" _CACHE_DIR_NAME = "seatunnel" -# A release version is used as a URL path segment and as a directory name, so it must start -# and end with a letter or digit. Starting with one rules out "." and "..", which would let a -# version name a directory outside the cache. Ending with one keeps "3.0." and "3.0" apart on -# Windows, which drops a trailing dot from directory names. -_VERSION_RE = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?") +# A release version is used as a URL path segment and as a directory name. It must start with +# a digit, as every SeaTunnel release does: that rules out "." and "..", which would let a +# version name a directory outside the cache, and the Windows device names such as "nul", +# "con" or "com1", which are not directories. It must end with a letter or digit, because +# Windows drops a trailing dot from directory names and "3.0." would share "3.0"'s directory. +_VERSION_RE = re.compile(r"[0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?") + +# Characters allowed in a base URL: the RFC 3986 unreserved and reserved characters and "%", +# without "?" and "#". That excludes spaces, control characters, non-ASCII characters and "\", +# and keeps a query or fragment from swallowing the version and file name appended to it. +_BASE_URL_RE = re.compile(r"[A-Za-z0-9._~:/@!$&'()*+,;=%\[\]-]+") + +# A "%" that does not start a two-digit hexadecimal escape such as "%20". +_BAD_PERCENT_RE = re.compile(r"%(?![0-9A-Fa-f]{2})") + +# The user information ("user:password@") of a URL, hidden in error messages. +_USERINFO_RE = re.compile(r"(//)[^/]*@") class DistributionError(Exception): @@ -49,12 +66,46 @@ class DistributionError(Exception): def _validate_version(version: str) -> str: if not isinstance(version, str) or not _VERSION_RE.fullmatch(version.strip()): raise DistributionError( - f"Invalid SeaTunnel version {version!r}: it must start and end with a letter or " - f"digit and may only contain letters, digits, '.', '_' and '-'." + f"Invalid SeaTunnel version {version!r}: it must start with a digit, end with a " + f"letter or digit, and may only contain letters, digits, '.', '_' and '-'." ) return version.strip() +def _validate_base_url(base_url: str) -> str: + """Return *base_url* without surrounding whitespace and trailing slashes, if it is valid.""" + if not isinstance(base_url, str): + raise DistributionError(f"The distribution base URL must be a string, got {base_url!r}.") + url = base_url.strip() + shown = _USERINFO_RE.sub(r"\1***@", url) + if not _BASE_URL_RE.fullmatch(url): + problem = ( + "it may only contain characters allowed in a URL path, without spaces, control " + "characters, '\\', '?' or '#'" + ) + elif _BAD_PERCENT_RE.search(url): + problem = "'%' must start a two-digit hexadecimal escape such as '%20'" + else: + try: + parts = urlsplit(url) + hostname, port = parts.hostname, parts.port + except ValueError as exc: + raise DistributionError(f"Invalid distribution base URL {shown!r}: {exc}.") from exc + if parts.scheme != "https": + problem = "it must start with 'https://'" + elif not hostname: + problem = "it has no host" + elif parts.username is not None or parts.password is not None: + problem = "it must not contain credentials" + elif "[" in parts.path or "]" in parts.path: + problem = "'[' and ']' are only allowed around an IPv6 host" + elif port == 0: + problem = "port 0 is not a valid port" + else: + return url.rstrip("/") + raise DistributionError(f"Invalid distribution base URL {shown!r}: {problem}.") + + def distribution_url(version: str, base_url: str = DEFAULT_BASE_URL) -> str: """Return the URL of the binary distribution archive of a SeaTunnel release. @@ -66,61 +117,83 @@ def distribution_url(version: str, base_url: str = DEFAULT_BASE_URL) -> str: Note that downloads.apache.org only keeps current releases; the ASF moves older ones to archive.apache.org, which can be passed as *base_url* by the caller. - :param version: Release version such as ``"3.0.0"``. It may only contain - ``A-Z a-z 0-9 . _ -`` and must start and end with a letter or digit. + :param version: Release version such as ``"3.0.0"``. It must start with a digit, end with + a letter or digit, and may only contain ``A-Z a-z 0-9 . _ -``. Surrounding whitespace + is dropped. :param base_url: Root of the release repository, such as ``https://archive.apache.org/dist/seatunnel``. It must be an ``https://`` URL with a - host and no query or fragment, so the archive, checksum and signature cannot be - altered in transit. + host, so the archive, checksum and signature cannot be altered in transit. It must not + contain credentials, a query (``?``), a fragment (``#``), or characters that are not + valid in a URL path, such as spaces, control characters, non-ASCII characters, ``\\``, + a malformed ``%`` escape or ``[`` / ``]`` outside an IPv6 host. Surrounding + whitespace and trailing slashes are dropped. :raises DistributionError: If the version or base URL is invalid. """ version = _validate_version(version) - parts = urlsplit(base_url) if isinstance(base_url, str) else None - if ( - parts is None - or parts.scheme != "https" - or not parts.netloc - or parts.query - or parts.fragment - ): - raise DistributionError( - f"The distribution base URL must be an 'https://' URL with a host and no query " - f"or fragment, got {base_url!r}." - ) - return f"{base_url.rstrip('/')}/{version}/apache-seatunnel-{version}-bin.tar.gz" + url = _validate_base_url(base_url) + return f"{url}/{version}/apache-seatunnel-{version}-bin.tar.gz" + + +def _usable_dir(path: Optional[str]) -> Optional[str]: + """Return *path* if it is an absolute path other than the filesystem root, else ``None``. + + The filesystem root is refused because every user whose home or cache variable resolves to + it (for example ``HOME=/`` in a container) would share the same cache. + """ + if not path or not os.path.isabs(path): + return None + normalized = os.path.normpath(path) + if os.path.dirname(normalized) == normalized: + return None + return path def _cache_root() -> str: """Return the per-user cache root of the current platform.""" - home = os.path.expanduser("~") if sys.platform == "win32": - base = os.environ.get("LOCALAPPDATA") or os.path.join(home, "AppData", "Local") + base = _usable_dir(os.environ.get("LOCALAPPDATA")) + fallback = ("AppData", "Local") + variables = "LOCALAPPDATA or USERPROFILE" elif sys.platform == "darwin": - base = os.path.join(home, "Library", "Caches") + base = None + fallback = ("Library", "Caches") + variables = "HOME" else: # The XDG specification says to ignore a relative XDG_CACHE_HOME. - base = os.environ.get("XDG_CACHE_HOME", "") - if not os.path.isabs(base): - base = os.path.join(home, ".cache") - if not os.path.isabs(base): - raise DistributionError( - f"Cannot determine a per-user cache location: '{base}' is not an absolute path." - ) + base = _usable_dir(os.environ.get("XDG_CACHE_HOME")) + fallback = (".cache",) + variables = "XDG_CACHE_HOME or HOME" + + if base is None: + # expanduser returns "~" unchanged when the home directory is unknown, and "/" when + # HOME is empty or "/". + home = os.path.expanduser("~") + if _usable_dir(home) is None: + raise DistributionError( + f"Cannot determine a per-user cache location: the home directory resolves to " + f"{home!r}, which is not an absolute path or is the filesystem root. Set " + f"{variables} to a directory owned by the current user." + ) + base = os.path.join(home, *fallback) return os.path.join(base, _CACHE_DIR_NAME) def cache_dir(version: str) -> str: """Return the per-user directory that holds the distribution of *version*. - Each user and each version gets a separate directory, so two versions or two users never - share or overwrite files. The location is ``seatunnel/`` under the platform's - per-user cache directory: ``$XDG_CACHE_HOME`` or ``~/.cache`` on Linux, - ``~/Library/Caches`` on macOS and ``%LOCALAPPDATA%`` on Windows. The directory is not - created and may not exist. + The location is ``seatunnel/`` under the platform's per-user cache directory: + ``$XDG_CACHE_HOME`` or ``~/.cache`` on Linux, ``~/Library/Caches`` on macOS and + ``%LOCALAPPDATA%`` (or ``~\\AppData\\Local``) on Windows. A relative value or the + filesystem root in one of those variables is ignored. By default each user and each + version gets a separate directory; see the module docstring for what is not checked. + The directory is not created and may not exist. + + Versions are case-sensitive in the download URL, but Windows and macOS file systems are + usually not, so ``3.0.0-SNAPSHOT`` and ``3.0.0-snapshot`` share one directory there. :param version: Release version such as ``"3.0.0"``; see :func:`distribution_url`. :returns: An absolute path. - :raises DistributionError: If the version is invalid or no absolute per-user cache - location can be determined. + :raises DistributionError: If the version is invalid or no per-user cache location can be + determined; the message names the variable to set. """ return os.path.join(_cache_root(), _validate_version(version)) diff --git a/tools/seatunnel-python-sdk/tests/test_distribution.py b/tools/seatunnel-python-sdk/tests/test_distribution.py index 5afb79466aaa..fb892510902d 100644 --- a/tools/seatunnel-python-sdk/tests/test_distribution.py +++ b/tools/seatunnel-python-sdk/tests/test_distribution.py @@ -23,6 +23,8 @@ from seatunnel import distribution from seatunnel.distribution import DistributionError, cache_dir, distribution_url +ARCHIVE_2_3_9 = "https://archive.apache.org/dist/seatunnel/2.3.9/apache-seatunnel-2.3.9-bin.tar.gz" + class TestDistributionUrl(unittest.TestCase): def test_release_url_follows_the_apache_layout(self): @@ -40,44 +42,116 @@ def test_each_version_gets_its_own_url(self): def test_surrounding_whitespace_in_version_is_dropped(self): self.assertEqual(distribution_url("3.0.0"), distribution_url(" 3.0.0\n")) - def test_custom_base_url_is_used_and_trailing_slash_is_ignored(self): - expected = ( - "https://archive.apache.org/dist/seatunnel/2.3.9/apache-seatunnel-2.3.9-bin.tar.gz" - ) - self.assertEqual( - expected, distribution_url("2.3.9", "https://archive.apache.org/dist/seatunnel") - ) - self.assertEqual( - expected, distribution_url("2.3.9", "https://archive.apache.org/dist/seatunnel/") - ) + def test_valid_versions_are_accepted(self): + for version in ("3", "2.3.9", "3.0.0", "3.0.0-SNAPSHOT", "3.0.0-RC1", "3.0.0_beta"): + with self.subTest(version=version): + self.assertTrue( + distribution_url(version).endswith( + f"/{version}/apache-seatunnel-{version}-bin.tar.gz" + ) + ) def test_invalid_versions_raise(self): for version in ("", " ", ".", "..", "../x", "-3.0.0", "3.0.", "3.0-", "3.0/1", - "3.0\\1", "3.0 beta", "3.0;rm", "3.0?x=1", "3.0#frag", None, 3): + "3.0\\1", "3.0 beta", "3.0;rm", "3.0?x=1", "3.0#frag", "v3.0.0", + "nul", "con", "aux", "prn", "com1", "lpt1", None, 3): with self.subTest(version=version): with self.assertRaises(DistributionError): distribution_url(version) - def test_single_character_version_is_accepted(self): - self.assertTrue(distribution_url("3").endswith("/3/apache-seatunnel-3-bin.tar.gz")) + def test_custom_base_url_is_used_and_trailing_slash_is_ignored(self): + for base_url in ("https://archive.apache.org/dist/seatunnel", + "https://archive.apache.org/dist/seatunnel/", + "https://archive.apache.org/dist/seatunnel//"): + with self.subTest(base_url=base_url): + self.assertEqual(ARCHIVE_2_3_9, distribution_url("2.3.9", base_url)) + + def test_surrounding_whitespace_in_base_url_is_dropped(self): + for base_url in ("https://archive.apache.org/dist/seatunnel/ ", + "https://archive.apache.org/dist/seatunnel\n", + " https://archive.apache.org/dist/seatunnel\t"): + with self.subTest(base_url=base_url): + self.assertEqual(ARCHIVE_2_3_9, distribution_url("2.3.9", base_url)) + + def test_valid_hosts_and_ports_are_accepted(self): + for base_url in ("https://mirror.example.org:8443/seatunnel", + "https://127.0.0.1/seatunnel", "https://[::1]/seatunnel", + "https://mirror.example.org", "https://x/apache%20seatunnel"): + with self.subTest(base_url=base_url): + self.assertEqual( + f"{base_url}/3.0.0/apache-seatunnel-3.0.0-bin.tar.gz", + distribution_url("3.0.0", base_url), + ) def test_invalid_base_url_raises(self): - for base_url in ("http://downloads.apache.org/seatunnel", "ftp://x/y", "https://", - "https:///seatunnel", "https://x/seatunnel?mirror=1", - "https://x/seatunnel#top", "downloads.apache.org/seatunnel", "", - None): + for base_url in ( + # Not HTTPS, or not a URL. + "http://downloads.apache.org/seatunnel", "ftp://x/y", "downloads.apache.org/x", "", + " ", + # No host, or an authority urlsplit cannot parse. + "https://", "https:///seatunnel", "https://:443/seatunnel", "https://user@/seatunnel", + "https://[::1/seatunnel", "https://host:abc/seatunnel", "https://host:99999/seatunnel", + "https://host:0/seatunnel", + # Credentials. + "https://user@host/seatunnel", "https://user:secret@host/seatunnel", + # A query or fragment, also with nothing after the delimiter. + "https://x/seatunnel?mirror=1", "https://x/seatunnel#top", "https://x/seatunnel?", + "https://x/seatunnel#", "https://x/seatunnel/?", + # Whitespace, control or non-ASCII characters, and backslashes inside the URL. + "https://x/sea tunnel", "https://x/sea\ntunnel", "https://x/sea\ttunnel", + "https://x/sea\rtunnel", "https://x/sea\x00tunnel", "https://x\\seatunnel", + "https://x/séatunnel", + # Broken percent escapes, and brackets outside an IPv6 host. + "https://x/sea%zztunnel", "https://x/seatunnel%", "https://x/seatunnel%2", + "https://x/sea[tunnel]", + ): + with self.subTest(base_url=base_url): + with self.assertRaises(DistributionError): + distribution_url("3.0.0", base_url) + + def test_non_string_base_url_raises(self): + for base_url in (None, 3, b"https://x/seatunnel"): + with self.subTest(base_url=base_url): + with self.assertRaises(DistributionError): + distribution_url("3.0.0", base_url) + + def test_errors_explain_the_problem(self): + cases = { + "http://x/seatunnel": "https://", + "https://:443/seatunnel": "no host", + "https://x/seatunnel#": "'#'", + "https://x/sea tunnel": "spaces", + "https://host:abc/seatunnel": "Invalid distribution base URL", + "https://user@host/seatunnel": "credentials", + } + for base_url, expected in cases.items(): with self.subTest(base_url=base_url): with self.assertRaises(DistributionError) as ctx: distribution_url("3.0.0", base_url) - self.assertIn("https://", str(ctx.exception)) + self.assertIn(expected, str(ctx.exception)) + + def test_credentials_are_not_shown_in_errors(self): + for base_url in ("https://alice:secret@host/seatunnel", + "https://alice:secret@host/sea tunnel", + "http://alice:secret@host/seatunnel"): + with self.subTest(base_url=base_url): + with self.assertRaises(DistributionError) as ctx: + distribution_url("3.0.0", base_url) + self.assertNotIn("secret", str(ctx.exception)) + self.assertNotIn("alice", str(ctx.exception)) class TestCacheDir(unittest.TestCase): + # The platform, the home directory and the environment are faked, so every platform branch + # runs on any OS. CI runs on Linux, so there it checks which branch is taken and how the + # path is built, with Linux path rules; Windows path rules are covered by running this + # suite on Windows. + def setUp(self): - # Absolute paths of the host OS, so the tests behave the same on Linux, macOS and - # Windows while sys.platform is faked. + # Absolute paths of the host OS, so the tests behave the same on every OS. self.root = os.path.join(tempfile.gettempdir(), "seatunnel-cache-test") self.home = os.path.join(self.root, "alice") + self.filesystem_root = os.path.abspath(os.sep) @contextlib.contextmanager def _environment(self, platform, home=None, **env): @@ -103,12 +177,6 @@ def test_linux_honors_xdg_cache_home(self): with self._environment("linux", XDG_CACHE_HOME=xdg): self.assertEqual(os.path.join(xdg, "seatunnel", "3.0.0"), cache_dir("3.0.0")) - def test_linux_ignores_a_relative_xdg_cache_home(self): - with self._environment("linux", XDG_CACHE_HOME="relative/cache"): - self.assertEqual( - os.path.join(self.home, ".cache", "seatunnel", "3.0.0"), cache_dir("3.0.0") - ) - def test_macos_uses_the_library_caches_directory(self): with self._environment("darwin"): self.assertEqual( @@ -128,11 +196,50 @@ def test_windows_without_localappdata_falls_back_to_the_home_directory(self): cache_dir("3.0.0"), ) - def test_relative_cache_location_raises(self): - with self._environment("win32", LOCALAPPDATA="relative"): - with self.assertRaises(DistributionError) as ctx: - cache_dir("3.0.0") - self.assertIn("absolute", str(ctx.exception)) + def test_relative_or_root_cache_variable_is_ignored(self): + cases = ( + ("linux", "XDG_CACHE_HOME", (".cache",)), + ("win32", "LOCALAPPDATA", ("AppData", "Local")), + ) + for platform, variable, fallback in cases: + for value in ("relative/cache", self.filesystem_root): + with self.subTest(platform=platform, value=value): + with self._environment(platform, **{variable: value}): + self.assertEqual( + os.path.join(self.home, *fallback, "seatunnel", "3.0.0"), + cache_dir("3.0.0"), + ) + + def test_home_at_the_filesystem_root_raises(self): + # HOME=/ or HOME="" (expanduser returns "/" for both) would give every such user the + # same /.cache/seatunnel directory. + for platform, variable in (("linux", "HOME"), ("darwin", "HOME"), + ("win32", "LOCALAPPDATA")): + with self.subTest(platform=platform): + with self._environment(platform, home=self.filesystem_root): + with self.assertRaises(DistributionError) as ctx: + cache_dir("3.0.0") + self.assertIn("filesystem root", str(ctx.exception)) + self.assertIn(variable, str(ctx.exception)) + + def test_unresolved_home_raises_and_names_the_variable_to_set(self): + # expanduser returns "~" unchanged when HOME is unset and the user has no passwd entry. + for platform, variable in (("linux", "XDG_CACHE_HOME or HOME"), ("darwin", "HOME"), + ("win32", "LOCALAPPDATA or USERPROFILE")): + with self.subTest(platform=platform): + with self._environment(platform, home="~"): + with self.assertRaises(DistributionError) as ctx: + cache_dir("3.0.0") + self.assertIn(f"Set {variable}", str(ctx.exception)) + + def test_cache_variable_works_without_a_home_directory(self): + cache = os.path.join(self.root, "cache") + for platform, variable in (("linux", "XDG_CACHE_HOME"), ("win32", "LOCALAPPDATA")): + with self.subTest(platform=platform): + with self._environment(platform, home="~", **{variable: cache}): + self.assertEqual( + os.path.join(cache, "seatunnel", "3.0.0"), cache_dir("3.0.0") + ) def test_versions_are_isolated_from_each_other(self): with self._environment("linux"): @@ -152,7 +259,7 @@ def test_users_are_isolated_from_each_other(self): def test_version_cannot_name_a_directory_outside_the_cache(self): with self._environment("linux"): cache_root = os.path.dirname(cache_dir("3.0.0")) - for version in ("..", ".", "../../etc", "3.0/../..", "/abs", "a/b"): + for version in ("..", ".", "../../etc", "3.0/../..", "/abs", "a/b", "nul"): with self.subTest(version=version): with self.assertRaises(DistributionError): cache_dir(version) @@ -173,13 +280,6 @@ def test_cache_dir_is_absolute_and_not_created(self): self.assertFalse(os.path.exists(path)) self.assertEqual([], os.listdir(tmp)) - def test_cache_dir_is_not_inside_the_installed_package(self): - # Uses the real platform and environment, not the fakes above. - package_dir = os.path.dirname(os.path.dirname(os.path.abspath(distribution.__file__))) - path = cache_dir("3.0.0") - self.assertTrue(os.path.isabs(path)) - self.assertFalse(path.startswith(package_dir + os.sep)) - if __name__ == "__main__": unittest.main()