Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(sdk): the Python client installs the pinned runtime from the published manifest

thinhlpgde6aefe272a3
diff --git a/sdk/python/README.md b/sdk/python/README.md
index 2c9d3e2b8..150981789 100644
--- a/sdk/python/README.md
+++ b/sdk/python/README.md
@@ -17,10 +17,47 @@ process serving many addressable sessions.
pip install jan-agent-sdk
```
-The runtime binary is separate: `jan` must be on `PATH`, or named by
-`$JAN_BIN` (the `bin` argument overrides both). A package that ships the runtime
-is the distribution half of the same protocol; until then, build it with
-`make agent` in the Jan repository.
+The runtime binary is separate, and there are three ways to have one: on `PATH`,
+named by `$JAN_BIN` (the `bin` argument overrides both), or installed by this
+package from the channel Jan publishes. That channel is a manifest naming, per
+platform, the artifact and its SHA-256, so an install is reproducible rather
+than whatever the URL serves today:
+
+```python
+from jan_agent_sdk import JanRuntime, install_runtime
+
+runtime_bin = install_runtime() # downloaded once, then cached
+with JanRuntime.start(bin=runtime_bin.bin) as runtime:
+ ...
+```
+
+`install_runtime()` maps this platform to its artifact (`darwin-universal`,
+`linux-x86_64`, `linux-aarch64`, `windows-x86_64`, `windows-aarch64`), verifies
+the published digest before extracting anything, and only then renames the
+install into `JAN_AGENT_HOME` or the per-user cache directory. An install that
+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 are
+involved.
+
+`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;
+the default is the nightly one. The macOS artifact is notarized, and getting a
+runtime this way needs no Rust toolchain and no Jan Desktop.
+
+```python
+pinned = install_runtime(version="0.8.4-50") # must be what the manifest publishes
+found = find_runtime("0.8.4-50") # reads the cache, no network
+```
+
+The nightly channel also publishes a shell installer, which is what the
+[jan.ai SDK pages](https://jan.ai/docs/agent/sdk) use:
+
+```bash
+curl -fsSL https://delta.jan.ai/jan-cli/install-jan-agent.sh | bash
+```
+
+To build your own instead, `make agent` in the Jan repository.
## Quickstart
diff --git a/sdk/python/jan_agent_sdk/__init__.py b/sdk/python/jan_agent_sdk/__init__.py
index 8261e7e8a..45e84bd3c 100644
--- a/sdk/python/jan_agent_sdk/__init__.py
+++ b/sdk/python/jan_agent_sdk/__init__.py
@@ -18,6 +18,17 @@ See ``README.md`` for host tools, images and process ownership.
from ._generated import EVENT_TAGS, PROTOCOL_VERSION
from .errors import JanRpcError, JanRuntimeError
+from .install import (
+ MANIFEST_URL,
+ PLATFORM_KEYS,
+ InstalledRuntime,
+ JanInstallError,
+ bin_name,
+ find_runtime,
+ install_runtime,
+ platform_key,
+ runtime_root,
+)
from .runtime import CLIENT_NAME, CLIENT_VERSION, JanRuntime
from .session import HostTool, HostToolCall, JanSession, JanTurn, TurnResult
@@ -27,9 +38,13 @@ __all__ = [
"CLIENT_NAME",
"CLIENT_VERSION",
"EVENT_TAGS",
+ "MANIFEST_URL",
+ "PLATFORM_KEYS",
"PROTOCOL_VERSION",
"HostTool",
"HostToolCall",
+ "InstalledRuntime",
+ "JanInstallError",
"JanRpcError",
"JanRuntime",
"JanRuntimeError",
@@ -37,4 +52,9 @@ __all__ = [
"JanTurn",
"TurnResult",
"__version__",
+ "bin_name",
+ "find_runtime",
+ "install_runtime",
+ "platform_key",
+ "runtime_root",
]
diff --git a/sdk/python/jan_agent_sdk/install.py b/sdk/python/jan_agent_sdk/install.py
new file mode 100644
index 000000000..cd89ded1d
--- /dev/null
+++ b/sdk/python/jan_agent_sdk/install.py
@@ -0,0 +1,385 @@
+"""Installing a pinned Jan runtime, without a Rust toolchain and without Jan Desktop.
+
+:class:`JanRuntime` spawns and owns a ``jan`` process, and where that process
+comes from is the caller's business: a PATH install, a build of their own, or
+this - the runtime Jan publishes, downloaded for this platform and checked
+against the digest the manifest carries.
+
+The manifest is the only source of truth, deliberately. It names, per platform,
+the artifact and its SHA-256; an install therefore reproduces the bytes that were
+advertised rather than whatever the URL serves today. A caller who names a
+``version`` or a ``sha256`` is pinning: the install fails closed when the
+published manifest has moved on, which is the same rule the protocol applies to a
+session's model.
+
+An install is atomic: everything happens in a staging directory that is renamed
+into place only after the digest matches and the binary is there, so an
+interrupted or corrupt install never leaves something that looks usable. Nothing
+here needs Node or a third-party package.
+"""
+
+from __future__ import annotations
+
+import errno
+import hashlib
+import json
+import os
+import platform as _platform
+import shutil
+import tarfile
+import uuid
+import zipfile
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Callable, Dict, Optional, Tuple
+from urllib.parse import urlparse
+from urllib.request import Request, urlopen
+
+# The channel the runtime is published on today. A release channel is the same
+# shape at another URL, which is why the URL is an argument and this is only a
+# default.
+MANIFEST_URL = "https://delta.jan.ai/agent-nightly/manifest.json"
+
+# Every platform key the current manifest publishes. macOS is one universal
+# artifact, so both of its architectures map to ``darwin-universal``.
+PLATFORM_KEYS: Tuple[str, ...] = (
+ "darwin-universal",
+ "linux-x86_64",
+ "linux-aarch64",
+ "windows-x86_64",
+ "windows-aarch64",
+)
+
+ARCH_ALIASES = {
+ "x86_64": "x86_64",
+ "amd64": "x86_64",
+ "arm64": "aarch64",
+ "aarch64": "aarch64",
+}
+
+
+class JanInstallError(RuntimeError):
+ """A runtime could not be installed.
+
+ No artifact for this platform, a manifest that does not name what was asked
+ for, a digest that does not match, or an archive that holds no binary.
+ Distinct from :class:`~jan_agent_sdk.JanRuntimeError`, which is a runtime
+ that will not run - this is a runtime that could not be fetched.
+ """
+
+ def __init__(
+ self,
+ message: str,
+ *,
+ url: Optional[str] = None,
+ expected: Optional[str] = None,
+ actual: Optional[str] = None,
+ platform: Optional[str] = None,
+ ) -> None:
+ super().__init__(message)
+ self.url = url
+ self.expected = expected
+ self.actual = actual
+ self.platform = platform
+
+
+@dataclass(frozen=True)
+class InstalledRuntime:
+ """An installed runtime and what it was installed from."""
+
+ version: str
+ pub_date: Optional[str]
+ platform: str
+ url: str
+ sha256: str
+ installed_at: str
+ #: Absolute path to the runtime binary, for ``JanRuntime(bin=...)``.
+ bin: str
+ dir: str
+ root: str
+ #: True when the install was already on disk and nothing was downloaded.
+ cached: bool
+
+
+def platform_key(system: Optional[str] = None, machine: Optional[str] = None) -> str:
+ """The manifest key for a system/machine pair.
+
+ Raises rather than guessing: an artifact for another architecture extracts
+ fine and then fails at exec.
+ """
+ system = (system or _platform.system()).lower()
+ raw_machine = machine or _platform.machine()
+ machine = ARCH_ALIASES.get((raw_machine or "").lower())
+ if system == "darwin":
+ return "darwin-universal"
+ if system == "linux" and machine in ("x86_64", "aarch64"):
+ return f"linux-{machine}"
+ if system == "windows" and machine in ("x86_64", "aarch64"):
+ return f"windows-{machine}"
+ raise JanInstallError(
+ f"the Jan runtime publishes no artifact for {system}/{raw_machine or 'unknown'}; "
+ f"it publishes {', '.join(PLATFORM_KEYS)}",
+ platform=f"{system}/{raw_machine or 'unknown'}",
+ )
+
+
+def bin_name(platform: Optional[str] = None) -> str:
+ """The binary's name inside an installed runtime."""
+ return "jan.exe" if (platform or platform_key()).startswith("windows-") else "jan"
+
+
+def runtime_root(env: Optional[Dict[str, str]] = None) -> str:
+ """Where installed runtimes live.
+
+ ``JAN_AGENT_HOME`` when set, otherwise the per-user cache directory each OS
+ already has a convention for.
+ """
+ env = os.environ if env is None else env
+ if env.get("JAN_AGENT_HOME"):
+ return env["JAN_AGENT_HOME"]
+ home = Path.home()
+ if os.name == "nt":
+ base = Path(env.get("LOCALAPPDATA") or home / "AppData" / "Local")
+ return str(base / "jan-agent" / "runtimes")
+ if _platform.system().lower() == "darwin":
+ return str(home / "Library" / "Caches" / "jan-agent" / "runtimes")
+ return str(Path(env.get("XDG_CACHE_HOME") or home / ".cache") / "jan-agent" / "runtimes")
+
+
+def _install_dir(root: str, version: str, platform: str) -> Path:
+ return Path(root) / version / platform
+
+
+def find_runtime(version: Optional[str] = None, root: Optional[str] = None) -> Optional[InstalledRuntime]:
+ """An installed runtime for ``version``, read from the marker an install writes.
+
+ No network: a caller who already has one pays nothing to find it, and a
+ missing one answers ``None`` rather than raising.
+ """
+ if not version:
+ return None
+ root = root or runtime_root()
+ platform = platform_key()
+ directory = _install_dir(root, version, platform)
+ try:
+ marker = json.loads((directory / "install.json").read_text())
+ except (OSError, ValueError):
+ return None
+ binary = directory / bin_name(platform)
+ if not binary.is_file():
+ # A marker whose binary is gone is not an install: it is the remains of one.
+ return None
+ return InstalledRuntime(
+ version=marker["version"],
+ pub_date=marker.get("pubDate"),
+ platform=marker.get("platform", platform),
+ url=marker.get("url", ""),
+ sha256=marker["sha256"],
+ installed_at=marker.get("installedAt", ""),
+ bin=str(binary),
+ dir=str(directory),
+ root=str(root),
+ cached=True,
+ )
+
+
+def install_runtime(
+ version: Optional[str] = None,
+ *,
+ sha256: Optional[str] = None,
+ manifest_url: Optional[str] = None,
+ root: Optional[str] = None,
+ on_progress: Optional[Callable[[int, int], None]] = None,
+ timeout: float = 120.0,
+) -> InstalledRuntime:
+ """Install the runtime for this platform and return it.
+
+ ``manifest_url`` names the channel (default: the one above). ``version`` and
+ ``sha256`` pin: either is checked against the manifest and a mismatch is an
+ error, never a silent fallback. ``on_progress(received, total)`` reports the
+ 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()
+
+ platform = platform_key()
+ if version:
+ hit = find_runtime(version, root)
+ if hit is not None and (not sha256 or hit.sha256 == sha256):
+ return hit
+
+ manifest = _read_manifest(manifest_url, timeout)
+ published = manifest.get("version")
+ if version and published != version:
+ raise JanInstallError(
+ f"the manifest at {manifest_url} publishes {published}, not {version}: "
+ "point `manifest_url` at the manifest that names the version you are pinning, or drop it",
+ url=manifest_url,
+ )
+ entry = (manifest.get("platforms") or {}).get(platform)
+ if not entry or not entry.get("url") or not entry.get("sha256"):
+ raise JanInstallError(
+ f"the manifest at {manifest_url} (version {published}) has no entry for {platform}",
+ url=manifest_url,
+ platform=platform,
+ )
+ expected = entry["sha256"]
+ if sha256 and sha256 != expected:
+ raise JanInstallError(
+ f"the manifest publishes {expected} for {platform}, not the {sha256} this install pins",
+ url=entry["url"],
+ expected=sha256,
+ actual=expected,
+ platform=platform,
+ )
+
+ directory = _install_dir(root, published, platform)
+ # An install of the version the manifest names, whose digest is still the one
+ # the manifest publishes, is the artifact this call would fetch. A channel
+ # that republished the same version with different bytes fails this check and
+ # is downloaded again, which is the point of recording the digest.
+ existing = find_runtime(published, root)
+ 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)
+ try:
+ archive = stage / (Path(urlparse(entry["url"]).path).name or "jan-runtime")
+ actual = _download(entry["url"], archive, on_progress, timeout)
+ if actual != expected:
+ raise JanInstallError(
+ f"the artifact downloaded from {entry['url']} hashes to {actual}, "
+ f"not the {expected} the manifest publishes",
+ url=entry["url"],
+ expected=expected,
+ actual=actual,
+ platform=platform,
+ )
+ _extract(archive, stage)
+ archive.unlink()
+
+ name = bin_name(platform)
+ binary = stage / name
+ if not binary.is_file():
+ raise JanInstallError(
+ f"the {platform} archive from {entry['url']} holds no {name} at its root",
+ url=entry["url"],
+ platform=platform,
+ )
+ if os.name != "nt":
+ 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)
+ return InstalledRuntime(
+ version=published,
+ pub_date=manifest.get("pub_date"),
+ platform=platform,
+ url=entry["url"],
+ sha256=actual,
+ installed_at=installed_at,
+ bin=str(directory / name),
+ dir=str(directory),
+ root=str(root),
+ cached=False,
+ )
+ except BaseException:
+ shutil.rmtree(stage, ignore_errors=True)
+ raise
+
+
+def _now() -> str:
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+
+
+def _read_manifest(url: str, timeout: float) -> Dict[str, object]:
+ try:
+ with urlopen(Request(url, headers={"accept": "application/json"}), timeout=timeout) as response:
+ body = response.read()
+ except OSError as error:
+ raise JanInstallError(f"could not read the runtime manifest at {url}: {error}", url=url) from error
+ try:
+ 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):
+ raise JanInstallError(f"the runtime manifest at {url} names no version and no platforms", url=url)
+ return manifest
+
+
+def _download(
+ url: str,
+ target: Path,
+ on_progress: Optional[Callable[[int, int], None]],
+ timeout: float,
+) -> str:
+ """Stream the artifact to ``target``, hashing as it arrives, and answer the digest."""
+ digest = hashlib.sha256()
+ received = 0
+ try:
+ with urlopen(Request(url), timeout=timeout) as response, open(target, "wb") as sink:
+ total = int(response.headers.get("content-length") or 0)
+ while True:
+ chunk = response.read(1 << 16)
+ if not chunk:
+ break
+ digest.update(chunk)
+ received += len(chunk)
+ sink.write(chunk)
+ if on_progress is not None:
+ on_progress(received, total)
+ except OSError as error:
+ raise JanInstallError(f"could not download the artifact at {url}: {error}", url=url) from error
+ return digest.hexdigest()
+
+
+def _extract(archive: Path, into: Path) -> None:
+ """Unpack the artifact into the staging directory.
+
+ ``filter="data"`` refuses members that would land outside ``into`` (a
+ traversal, an absolute path, a link out), so a compromised channel cannot
+ write anywhere but the staging directory this caller removes on any error.
+ """
+ try:
+ if zipfile.is_zipfile(archive):
+ with zipfile.ZipFile(archive) as bundle:
+ bundle.extractall(into)
+ return
+ with 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:
+ raise JanInstallError(f"could not extract {archive.name}: {error}", url=str(archive)) from error
diff --git a/sdk/python/tests/test_install.py b/sdk/python/tests/test_install.py
new file mode 100644
index 000000000..6a135760b
--- /dev/null
+++ b/sdk/python/tests/test_install.py
@@ -0,0 +1,289 @@
+"""Installing a runtime, against a manifest this test serves itself.
+
+Nothing here touches the network: an HTTP server in this process publishes a
+manifest and a tarball this test builds with :mod:`tarfile`, so the whole path -
+manifest, platform key, download, digest, extract, rename - runs for real. What
+is faked is only the channel. No runtime and no ``JAN_BIN`` are needed, which is
+the point: getting a runtime is what is under test.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import shutil
+import sys
+import tarfile
+import tempfile
+import threading
+import unittest
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from typing import Any, Dict, List, Optional
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from jan_agent_sdk import ( # noqa: E402
+ MANIFEST_URL,
+ PLATFORM_KEYS,
+ JanInstallError,
+ bin_name,
+ find_runtime,
+ install_runtime,
+ platform_key,
+ runtime_root,
+)
+
+VERSION = "0.0.0-test"
+
+
+def make_archive(directory: Path, *, member: Optional[str] = None) -> 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
+ runtime's business. ``member`` overrides the name inside the archive, which
+ is how the traversal case below gets built.
+ """
+ staged = directory / "staged"
+ staged.mkdir(parents=True, exist_ok=True)
+ name = bin_name()
+ (staged / name).write_text(f"#!/bin/sh\necho {VERSION}\n")
+ archive = directory / "jan-runtime.tar.gz"
+ with tarfile.open(archive, "w:gz") as bundle:
+ bundle.add(staged / name, arcname=member or name)
+ return archive
+
+
+def sha256(data: bytes) -> str:
+ return hashlib.sha256(data).hexdigest()
+
+
+class _Channel:
+ """A channel: ``/manifest.json`` and the artifact, counted.
+
+ The count is what proves a cached install downloaded nothing, and what
+ proves a refused pin downloaded nothing at all.
+ """
+
+ def __init__(self, archive: Path, *, version: str = VERSION, digest: Optional[str] = None,
+ omit_platform: bool = False) -> None:
+ self.bytes = archive.read_bytes()
+ self.version = version
+ self.digest = digest or sha256(self.bytes)
+ self.omit_platform = omit_platform
+ self.requests: List[str] = []
+ self.artifacts = 0
+
+ channel = self
+
+ class Handler(BaseHTTPRequestHandler):
+ def log_message(self, *args: Any) -> None: # keep the test output clean
+ pass
+
+ def do_GET(self) -> None: # noqa: N802 - the name http.server wants
+ channel.requests.append(self.path)
+ if self.path == "/manifest.json":
+ platforms: Dict[str, Dict[str, str]] = {
+ platform_key(): {
+ "url": f"http://127.0.0.1:{self.server.server_port}/jan-runtime.tar.gz",
+ "sha256": channel.digest,
+ }
+ }
+ if channel.omit_platform:
+ platforms.pop(platform_key(), None)
+ body = json.dumps(
+ {"version": channel.version, "pub_date": "2026-01-01T00:00:00.000Z", "platforms": platforms}
+ ).encode()
+ self.send_response(200)
+ self.send_header("content-type", "application/json")
+ self.send_header("content-length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+ return
+ channel.artifacts += 1
+ self.send_response(200)
+ self.send_header("content-type", "application/gzip")
+ self.send_header("content-length", str(len(channel.bytes)))
+ self.end_headers()
+ self.wfile.write(channel.bytes)
+
+ self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
+ self.thread.start()
+
+ @property
+ def url(self) -> str:
+ return f"http://127.0.0.1:{self.server.server_port}/manifest.json"
+
+ def close(self) -> None:
+ self.server.shutdown()
+ self.server.server_close()
+ self.thread.join(timeout=5)
+
+
+class InstallTests(unittest.TestCase):
+ def setUp(self) -> None:
+ self.root = Path(tempfile.mkdtemp(prefix="jan-install-"))
+ self.source = Path(tempfile.mkdtemp(prefix="jan-install-src-"))
+
+ def tearDown(self) -> None:
+ shutil.rmtree(self.root, ignore_errors=True)
+ shutil.rmtree(self.source, ignore_errors=True)
+
+ # -- the platform table -------------------------------------------------
+
+ def test_a_platform_maps_to_the_artifact_the_manifest_publishes(self) -> None:
+ self.assertEqual(platform_key("Darwin", "arm64"), "darwin-universal")
+ self.assertEqual(platform_key("Darwin", "x86_64"), "darwin-universal")
+ self.assertEqual(platform_key("Linux", "x86_64"), "linux-x86_64")
+ self.assertEqual(platform_key("Linux", "AMD64"), "linux-x86_64")
+ self.assertEqual(platform_key("Linux", "aarch64"), "linux-aarch64")
+ self.assertEqual(platform_key("Windows", "AMD64"), "windows-x86_64")
+ self.assertEqual(platform_key("Windows", "ARM64"), "windows-aarch64")
+ with self.assertRaises(JanInstallError) as caught:
+ platform_key("SunOS", "sparc")
+ self.assertIn("sunos/sparc", str(caught.exception))
+ self.assertIn("darwin-universal", str(caught.exception))
+ for key in PLATFORM_KEYS:
+ self.assertIn(bin_name(key), ("jan", "jan.exe"))
+
+ def test_the_runtime_root_follows_jan_agent_home(self) -> None:
+ self.assertEqual(runtime_root({"JAN_AGENT_HOME": str(self.root)}), str(self.root))
+ default = runtime_root({})
+ self.assertNotEqual(default, str(self.root))
+ self.assertTrue(default.endswith(os.path.join("jan-agent", "runtimes")), default)
+ self.assertEqual(MANIFEST_URL, "https://delta.jan.ai/agent-nightly/manifest.json")
+
+ # -- install, cache, verify ---------------------------------------------
+
+ def test_an_install_lands_a_verified_executable_binary_and_is_cached_after_that(self) -> None:
+ archive = make_archive(self.source)
+ published = _Channel(archive)
+ try:
+ progress: List[int] = []
+ installed = install_runtime(
+ manifest_url=published.url, root=str(self.root), on_progress=lambda got, _total: progress.append(got)
+ )
+
+ self.assertEqual(installed.version, VERSION)
+ self.assertEqual(installed.platform, platform_key())
+ self.assertFalse(installed.cached)
+ # The digest is the archive's, which is what the manifest pins and
+ # what a caller recomputes from the published artifact.
+ self.assertEqual(installed.sha256, sha256(archive.read_bytes()))
+ self.assertTrue(os.access(installed.bin, os.X_OK), "the binary is executable")
+ self.assertTrue(progress, "progress was reported")
+
+ # The marker is what makes it findable without the network, and what
+ # the next install reads instead of downloading again.
+ found = find_runtime(VERSION, str(self.root))
+ self.assertIsNotNone(found)
+ assert found is not None
+ self.assertEqual(found.bin, installed.bin)
+ self.assertTrue(found.cached)
+ self.assertEqual(found.sha256, installed.sha256)
+
+ before = len(published.requests)
+ again = install_runtime(version=VERSION, manifest_url=published.url, root=str(self.root))
+ self.assertTrue(again.cached)
+ self.assertEqual(len(published.requests), before, "a cached install fetches nothing")
+ self.assertEqual(published.artifacts, 1, "the artifact was downloaded once")
+
+ # Pinned to what the manifest publishes, an install is a cache read.
+ pinned = install_runtime(
+ version=VERSION, sha256=found.sha256, manifest_url=published.url, root=str(self.root)
+ )
+ self.assertTrue(pinned.cached)
+
+ # And so is one that pins nothing: the manifest names the version
+ # already installed, with the digest it was installed under.
+ unpinned = install_runtime(manifest_url=published.url, root=str(self.root))
+ self.assertTrue(unpinned.cached)
+ self.assertEqual(unpinned.version, VERSION)
+ self.assertEqual(published.artifacts, 1, "still one download for the whole test")
+ finally:
+ published.close()
+
+ def test_a_channel_that_republishes_a_version_under_a_new_digest_installs_again(self) -> None:
+ first = _Channel(make_archive(self.source))
+ self.addCleanup(first.close)
+ installed = install_runtime(manifest_url=first.url, root=str(self.root))
+ self.assertFalse(installed.cached)
+
+ # Same version, different bytes: the recorded digest is what tells the
+ # 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))
+ 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()))
+ finally:
+ second.close()
+
+ def test_a_digest_that_does_not_match_is_an_error_and_leaves_nothing_behind(self) -> None:
+ published = _Channel(make_archive(self.source), digest="f" * 64)
+ self.addCleanup(published.close)
+ with self.assertRaises(JanInstallError) as caught:
+ install_runtime(manifest_url=published.url, root=str(self.root))
+ error = caught.exception
+ self.assertEqual(error.expected, "f" * 64)
+ self.assertNotEqual(error.actual, error.expected)
+ self.assertIn("hashes to", str(error))
+ self.assertIsNone(find_runtime(VERSION, str(self.root)))
+ self.assertFalse((self.root / VERSION / platform_key()).exists(), "no directory survives a bad digest")
+ self.assertEqual(list((self.root / VERSION).iterdir()), [], "no staging directory survives")
+
+ def test_a_version_or_digest_the_manifest_does_not_publish_is_refused_not_substituted(self) -> None:
+ published = _Channel(make_archive(self.source))
+ self.addCleanup(published.close)
+ with self.assertRaises(JanInstallError) as caught:
+ install_runtime(version="0.0.0-other", manifest_url=published.url, root=str(self.root))
+ self.assertIn("publishes 0.0.0-test, not 0.0.0-other", str(caught.exception))
+ with self.assertRaises(JanInstallError) as caught:
+ install_runtime(sha256="a" * 64, manifest_url=published.url, root=str(self.root))
+ self.assertIn(f"not the {'a' * 64} this install pins", str(caught.exception))
+ self.assertEqual(published.artifacts, 0, "nothing was downloaded for a refused pin")
+
+ def test_a_manifest_without_this_platform_is_an_error_naming_what_it_has(self) -> None:
+ published = _Channel(make_archive(self.source), omit_platform=True)
+ self.addCleanup(published.close)
+ with self.assertRaises(JanInstallError) as caught:
+ install_runtime(manifest_url=published.url, root=str(self.root))
+ self.assertIn(f"no entry for {platform_key()}", str(caught.exception))
+ self.assertEqual(caught.exception.platform, platform_key())
+
+ def test_a_marker_without_a_binary_is_not_an_install(self) -> None:
+ directory = self.root / VERSION / platform_key()
+ directory.mkdir(parents=True)
+ (directory / "install.json").write_text(json.dumps({"version": VERSION, "bin": bin_name()}))
+ self.assertIsNone(find_runtime(VERSION, str(self.root)))
+ self.assertIsNone(find_runtime(None, str(self.root)))
+ self.assertIsNone(find_runtime(VERSION, str(self.root / "elsewhere")))
+
+ # -- the archive ---------------------------------------------------------
+
+ def test_an_archive_that_escapes_the_staging_directory_is_refused(self) -> None:
+ """A member outside the staging directory is refused, not followed.
+
+ The install directory is the caller's, so an archive that can write
+ anywhere else is the one thing an installer must not accept - including
+ from a channel whose digest matched, because the next publish is not the
+ one that was reviewed.
+ """
+ archive = make_archive(self.source, member="../escaped")
+ published = _Channel(archive)
+ self.addCleanup(published.close)
+ with self.assertRaises(JanInstallError) as caught:
+ install_runtime(manifest_url=published.url, root=str(self.root))
+ self.assertIn("could not extract", str(caught.exception))
+ self.assertFalse((self.root / VERSION / "escaped").exists())
+ self.assertFalse((self.source / "escaped").exists())
+
+
+if __name__ == "__main__":
+ unittest.main()