Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(sdk-python): publish immutable runtime generations safely
thinhlpgad3afa40fcf9
diff --git a/sdk/python/README.md b/sdk/python/README.mdindex 150981789..22e973ef2 100644--- a/sdk/python/README.md+++ b/sdk/python/README.md@@ -39,9 +39,17 @@ failed its digest, or that was interrupted mid-extract, is never visible as one:`find_runtime()` answers `None` for it. No Node and no third-party package areinvolved.-`version` and `sha256` pin. Both are checked against the manifest, and a-mismatch is an error rather than a substitution, so a run that has to reproduce-is never quietly moved to a newer runtime. `manifest_url` names another channel;+Each successful download gets an immutable generation directory. Only the small+lookup marker is atomically replaced, so concurrent installs and republished+versions cannot delete or change a binary path already returned to a caller.+Old generations remain until the cache is manually removed while no runtimes+are using it. Relative cache roots are resolved to absolute paths.+Tar extraction requires Python's safe data filter (Python 3.11.4+); an older+interpreter is refused rather than falling back to unsafe extraction.++`version` and `sha256` pin. A matching cached install is returned without network+access; otherwise both are checked against the manifest. A mismatch is an error+rather than a substitution. `manifest_url` names another channel;the default is the nightly one. The macOS artifact is notarized, and getting aruntime this way needs no Rust toolchain and no Jan Desktop.diff --git a/sdk/python/jan_agent_sdk/install.py b/sdk/python/jan_agent_sdk/install.pyindex cd89ded1d..0dcc47f08 100644--- a/sdk/python/jan_agent_sdk/install.py+++ b/sdk/python/jan_agent_sdk/install.py@@ -20,11 +20,12 @@ here needs Node or a third-party package.from __future__ import annotations-import errnoimport hashlibimport jsonimport osimport platform as _platform+import re+import tempfileimport shutilimport tarfileimport uuid@@ -147,6 +148,12 @@ def runtime_root(env: Optional[Dict[str, str]] = None) -> str:return str(Path(env.get("XDG_CACHE_HOME") or home / ".cache") / "jan-agent" / "runtimes")+def _valid_version(version: object) -> bool:+ return isinstance(version, str) and re.fullmatch(+ r"[A-Za-z0-9](?:[A-Za-z0-9._+-]*[A-Za-z0-9_+-])?", version+ ) is not None++def _install_dir(root: str, version: str, platform: str) -> Path:return Path(root) / version / platform@@ -157,17 +164,28 @@ def find_runtime(version: Optional[str] = None, root: Optional[str] = None) -> ONo network: a caller who already has one pays nothing to find it, and amissing one answers ``None`` rather than raising."""- if not version:+ if not _valid_version(version):return None- root = root or runtime_root()+ root = str(Path(root or runtime_root()).resolve())platform = platform_key()directory = _install_dir(root, version, platform)try:marker = json.loads((directory / "install.json").read_text())except (OSError, ValueError):return None+ if (+ not isinstance(marker, dict)+ or marker.get("version") != version+ or marker.get("platform") != platform+ or not isinstance(marker.get("sha256"), str)+ or re.fullmatch(r"[a-f0-9]{64}", marker["sha256"]) is None+ or not isinstance(marker.get("directory"), str)+ or re.fullmatch(rf"{platform}-[a-f0-9-]{{36}}", marker["directory"]) is None+ ):+ return None+ directory = Path(root) / version / marker["directory"]binary = directory / bin_name(platform)- if not binary.is_file():+ if binary.is_symlink() or not binary.is_file():# A marker whose binary is gone is not an install: it is the remains of one.return Nonereturn InstalledRuntime(@@ -201,7 +219,9 @@ def install_runtime(download; ``total`` is 0 when the server sends no length."""manifest_url = manifest_url or os.environ.get("JAN_AGENT_MANIFEST") or MANIFEST_URL- root = root or runtime_root()+ root = str(Path(root or runtime_root()).resolve())+ if version is not None and not _valid_version(version):+ raise JanInstallError("version must be a single safe path component")platform = platform_key()if version:@@ -243,8 +263,11 @@ def install_runtime(if existing is not None and existing.sha256 == expected:return existing- stage = Path(root) / published / f".{platform}.part-{os.getpid()}-{uuid.uuid4().hex[:8]}"- stage.mkdir(parents=True, exist_ok=True)+ directory.parent.mkdir(parents=True, exist_ok=True)+ stage = Path(tempfile.mkdtemp(prefix=f".{platform}.part-", dir=directory.parent))+ generation = f"{platform}-{uuid.uuid4()}"+ installed_directory = directory.parent / generation+ marker_temp = directory / f".{uuid.uuid4()}.json"try:archive = stage / (Path(urlparse(entry["url"]).path).name or "jan-runtime")actual = _download(entry["url"], archive, on_progress, timeout)@@ -262,7 +285,7 @@ def install_runtime(name = bin_name(platform)binary = stage / name- if not binary.is_file():+ if binary.is_symlink() or not binary.is_file():raise JanInstallError(f"the {platform} archive from {entry['url']} holds no {name} at its root",url=entry["url"],@@ -272,36 +295,29 @@ def install_runtime(binary.chmod(0o755)installed_at = _now()- (stage / "install.json").write_text(- json.dumps(- {- "version": published,- "pubDate": manifest.get("pub_date"),- "platform": platform,- "url": entry["url"],- "sha256": actual,- "bin": name,- "installedAt": installed_at,- },- indent=2,- )- + "\n"- )-- # Renamed into place last, and only now: until this line the install is- # invisible to every other process, and a crash anywhere above leaves no- # directory that `find_runtime` would trust. A rename that finds a- # directory already there is either a concurrent install of the same- # artifact or what an older one left behind; both are replaced, but only- # after asking.- directory.parent.mkdir(parents=True, exist_ok=True)- try:- os.rename(stage, directory)- except OSError as error:- if error.errno not in (errno.ENOTEMPTY, errno.EEXIST, errno.ENOTDIR):- raise- shutil.rmtree(directory, ignore_errors=True)- os.rename(stage, directory)+ marker = json.dumps(+ {+ "version": published,+ "directory": generation,+ "pubDate": manifest.get("pub_date"),+ "platform": platform,+ "url": entry["url"],+ "sha256": actual,+ "bin": name,+ "installedAt": installed_at,+ },+ indent=2,+ ).encode() + b"\n"++ # Published generations are never replaced: another process can still+ # be using the binary or holding its path under a digest pin. Only the+ # small lookup marker changes atomically; concurrent callers all keep+ # usable paths, regardless of which marker wins.+ os.rename(stage, installed_directory)+ directory.mkdir(parents=True, exist_ok=True)+ with marker_temp.open("xb") as target:+ target.write(marker)+ os.replace(marker_temp, directory / "install.json")return InstalledRuntime(version=published,pub_date=manifest.get("pub_date"),@@ -309,12 +325,13 @@ def install_runtime(url=entry["url"],sha256=actual,installed_at=installed_at,- bin=str(directory / name),- dir=str(directory),+ bin=str(installed_directory / name),+ dir=str(installed_directory),root=str(root),cached=False,)except BaseException:+ marker_temp.unlink(missing_ok=True)shutil.rmtree(stage, ignore_errors=True)raise@@ -333,7 +350,7 @@ def _read_manifest(url: str, timeout: float) -> Dict[str, object]:manifest = json.loads(body)except ValueError as error:raise JanInstallError(f"the runtime manifest at {url} is not JSON: {error}", url=url) from error- if not manifest.get("version") or not isinstance(manifest.get("platforms"), dict):+ if not isinstance(manifest, dict) or not _valid_version(manifest.get("version")) or not isinstance(manifest.get("platforms"), dict):raise JanInstallError(f"the runtime manifest at {url} names no version and no platforms", url=url)return manifest@@ -377,9 +394,6 @@ def _extract(archive: Path, into: Path) -> None:bundle.extractall(into)returnwith tarfile.open(archive) as bundle:- try:- bundle.extractall(into, filter="data")- except TypeError: # pragma: no cover - Python before 3.11.4 has no filter- bundle.extractall(into)- except (tarfile.TarError, zipfile.BadZipFile, OSError) as error:+ bundle.extractall(into, filter="data")+ except (tarfile.TarError, zipfile.BadZipFile, OSError, TypeError) as error:raise JanInstallError(f"could not extract {archive.name}: {error}", url=str(archive)) from errordiff --git a/sdk/python/tests/test_install.py b/sdk/python/tests/test_install.pyindex 6a135760b..2bbfdc40f 100644--- a/sdk/python/tests/test_install.py+++ b/sdk/python/tests/test_install.py@@ -18,6 +18,8 @@ import tarfileimport tempfileimport threadingimport unittest+from concurrent.futures import ThreadPoolExecutor+from unittest.mock import patchfrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom pathlib import Pathfrom typing import Any, Dict, List, Optional@@ -38,7 +40,7 @@ from jan_agent_sdk import ( # noqa: E402VERSION = "0.0.0-test"-def make_archive(directory: Path, *, member: Optional[str] = None) -> Path:+def make_archive(directory: Path, *, member: Optional[str] = None, content: str = VERSION) -> Path:"""A tarball holding a ``jan`` that is executable and does nothing.The installer only has to put a binary there; whether it runs is the@@ -48,7 +50,7 @@ def make_archive(directory: Path, *, member: Optional[str] = None) -> Path:staged = directory / "staged"staged.mkdir(parents=True, exist_ok=True)name = bin_name()- (staged / name).write_text(f"#!/bin/sh\necho {VERSION}\n")+ (staged / name).write_text(f"#!/bin/sh\necho {content}\n")archive = directory / "jan-runtime.tar.gz"with tarfile.open(archive, "w:gz") as bundle:bundle.add(staged / name, arcname=member or name)@@ -215,13 +217,15 @@ class InstallTests(unittest.TestCase):# two apart, so this is a re-install rather than a cache hit.rebuilt = self.source / "second"rebuilt.mkdir(parents=True, exist_ok=True)- second = _Channel(make_archive(rebuilt))+ second = _Channel(make_archive(rebuilt, content="replacement"))try:again = install_runtime(manifest_url=second.url, root=str(self.root))self.assertEqual(again.version, VERSION)self.assertFalse(again.cached, "a republished digest is not the install on disk")self.assertNotEqual(again.sha256, installed.sha256)self.assertEqual(again.sha256, sha256((rebuilt / "jan-runtime.tar.gz").read_bytes()))+ self.assertEqual(Path(installed.bin).read_text(), f"#!/bin/sh\necho {VERSION}\n")+ self.assertEqual(Path(again.bin).read_text(), "#!/bin/sh\necho replacement\n")finally:second.close()@@ -265,6 +269,41 @@ class InstallTests(unittest.TestCase):self.assertIsNone(find_runtime(None, str(self.root)))self.assertIsNone(find_runtime(VERSION, str(self.root / "elsewhere")))+ def test_concurrent_installs_preserve_every_returned_binary(self) -> None:+ published = _Channel(make_archive(self.source))+ self.addCleanup(published.close)+ barrier = threading.Barrier(4)++ def install():+ barrier.wait(timeout=10)+ return install_runtime(root=str(self.root), manifest_url=published.url)++ with ThreadPoolExecutor(max_workers=4) as pool:+ installs = list(pool.map(lambda _: install(), range(4)))+ for installed in installs:+ self.assertEqual(Path(installed.bin).read_text(), f"#!/bin/sh\necho {VERSION}\n")++ def test_relative_root_returns_an_absolute_binary(self) -> None:+ published = _Channel(make_archive(self.source))+ self.addCleanup(published.close)+ installed = install_runtime(root=os.path.relpath(self.root), manifest_url=published.url)+ self.assertTrue(Path(installed.bin).is_absolute())++ def test_untrusted_version_path_is_refused_before_download(self) -> None:+ published = _Channel(make_archive(self.source), version="../escaped")+ self.addCleanup(published.close)+ with self.assertRaises(JanInstallError):+ install_runtime(root=str(self.root / "cache"), manifest_url=published.url)+ self.assertEqual(published.artifacts, 0)++ def test_unsupported_safe_extraction_never_falls_back(self) -> None:+ published = _Channel(make_archive(self.source))+ self.addCleanup(published.close)+ with patch.object(tarfile.TarFile, "extractall", side_effect=TypeError("no filter")) as extract:+ with self.assertRaises(JanInstallError):+ install_runtime(root=str(self.root), manifest_url=published.url)+ self.assertEqual(extract.call_count, 1)+# -- the archive ---------------------------------------------------------def test_an_archive_that_escapes_the_staging_directory_is_refused(self) -> None: