strata components install-file: install an engine package the person downloaded (signature, every file, fit, test start, switch; no network); the engine switch is shared with the download path

This commit is contained in:
Niko1221 committed 2026-10-24 13:42:41 +02:00
1 parent 13a4153be4
commit 31adebc8b7
4 files changed
+182 -3

No files matched your search

+1 -1
View File
@@ -2132,7 +2132,7 @@ def _run(a: argparse.Namespace) -> int:
return _components_backends(a)
if a.command == "components" and a.components_command == "engine":
return _components_engine(a)
if a.command == "update" or (a.command == "components" and a.components_command in ("update", "rollback")):
if a.command == "update" or (a.command == "components" and a.components_command in ("update", "rollback", "install-file")):
from strata_cli import update_cmd
return update_cmd.run(a)
if a.command in ("doctor", "components"):
+14 -1
View File
@@ -56,7 +56,10 @@ def add_parsers(sp, components_sp) -> list:
comp_update.add_argument("--no-control", action="store_true")
rollback = components_sp.add_parser("rollback", help="return to the previous engine version the last update kept")
_common(rollback)
return [update, comp_update, rollback]
install_file = components_sp.add_parser("install-file", help="install an engine package you downloaded yourself (no network; the package's signature is checked)")
install_file.add_argument("file", help="the engine package (.tar.gz or .zip) from the release page")
_common(install_file)
return [update, comp_update, rollback, install_file]
def _emit_factory(a, lines: list):
@@ -201,6 +204,16 @@ def run(a) -> int:
"Saved tuning presets are unchanged.")
print("Run `strata update --force` to try the newer version again.")
return 0
if getattr(a, "components_command", None) == "install-file":
ctx.trusted = signing.load_trusted_keys()
ctx.serving = updater.serving_now
_maybe_wait(a, ctx, machine)
out = updater.install_engine_file(ctx, Path(a.file))
if machine:
print(json.dumps({"schema_version": 1, "ok": True, **out}, ensure_ascii=False))
else:
print(out.get("note") or _line("Engine", out))
return 0
acquisition.require("the update", "`strata update` from a terminal")
trusted = signing.load_trusted_keys()
ctx.trusted = trusted
+81 -1
View File
@@ -950,6 +950,14 @@ def update_engine(ctx: Context, feed: feedmod.Feed, state: State) -> dict:
if exc.exit_code == 5:
archive.unlink(missing_ok=True) # a refused package is not kept for a retry
raise
return _finish_engine_install(ctx, state, pkg, stage_root, staged, archive, result, delete_archive=True)
def _finish_engine_install(ctx: Context, state: State, pkg: feedmod.EnginePackage, stage_root: Path, staged: ec.EngineComponent,
archive: Path, result: dict, *, delete_archive: bool) -> dict:
"""The part of an engine install both ways share (a download from the feed, a file the person chose): test-start the staged engine,
switch to it, keep the previous one, remove the staging folder. ``archive`` is only deleted when Strata downloaded it."""
root = ctx.components
before_installed, _ = installed_engine(root, ctx.hardware)
before_identity = preset_marks.identity_of(before_installed, _manifest_sha(before_installed.root)) if before_installed else None
try:
@@ -1021,7 +1029,8 @@ def update_engine(ctx: Context, feed: feedmod.Feed, state: State) -> dict:
"from": before_installed.version if before_installed else None, "to": pkg.version, "ok": True,
"detail": smoke.get("mode")})
state.save()
archive.unlink(missing_ok=True)
if delete_archive:
archive.unlink(missing_ok=True)
result.update({"changed": True, "status": "updated", "installed_after": _engine_view(chosen), "test_start": smoke,
"previous": previous, "removed": removed, "presets_marked": bool(mark)})
ctx.say("done", f"Engine {pkg.version} is installed and will be used on the next start", component="engine")
@@ -1030,6 +1039,77 @@ def update_engine(ctx: Context, feed: feedmod.Feed, state: State) -> dict:
shutil.rmtree(longpath.long_path(stage_root), ignore_errors=True)
def _archive_format(archive: Path) -> str:
name = archive.name.lower()
for suffix, fmt in ((".tar.gz", "tar.gz"), (".tgz", "tar.gz"), (".tar.xz", "tar.xz"), (".zip", "zip")):
if name.endswith(suffix):
return fmt
raise UpdateError("this is not a Strata engine package (it should be a .tar.gz or .zip file from the release page)", 5)
def install_engine_file(ctx: Context, archive: Path) -> dict:
"""Install an engine package the person downloaded themselves (the offline path of the first-run card). No feed and no network:
the package must carry the feed key's signature on its manifest, every file must match the manifest, and the package must fit this
PC. After that it goes through the same test start and switch as a downloaded one. The file the person chose is left where it is."""
archive = Path(archive)
if not archive.is_file():
raise UpdateError(f"{archive} is not a file", 5)
fmt = _archive_format(archive)
state_root = ctx.components
with update_lock(state_root):
state = State(state_root)
stage_root = new_stage(state_root)
keep_stage = False
try:
try:
total = _archive_size(archive, fmt)
except (tarfile.TarError, zipfile.BadZipFile, OSError, EOFError) as exc:
raise UpdateError(f"this file cannot be read as a package ({type(exc).__name__}); download it again", 5) from None
_free_space_check(state_root, total * 2, ctx, "", "engine")
folder = stage_root / "engine" / "incoming"
longpath.long_path(folder.parent).mkdir(parents=True, exist_ok=True)
ctx.say("verify", "Unpacking the engine file", component="engine")
extract(archive, folder, fmt, total)
try:
component = ec.read_manifest(folder)
except ec.ComponentProblem as exc:
raise UpdateError(f"this file is not a Strata engine package: {exc}", 5) from None
ctx.say("verify", "Checking the package signature and every file", component="engine")
outer = ec._verifier
signing.install_component_verifier(ctx.trusted)
try:
ec.verify_signature(component, {**ctx.environ, ec.ENV_REQUIRE_SIGNED: "1"})
ec.verify(component, full=True)
except ec.ComponentProblem as exc:
raise UpdateError(f"this file did not pass the security check, so it was not used ({exc})", 5) from None
finally:
ec.register_signature_verifier(outer)
pkg = feedmod.EnginePackage(
version=component.version, platform=component.platform, backend=component.backend, variant=component.variant or "",
archs=tuple(component.archs), min_driver=dict(component.min_driver or {}), min_runtime=component.min_runtime,
build_id=component.build_id, url="", format=fmt, size=archive.stat().st_size, sha256=transfer.sha256_file(archive),
manifest_sha256=transfer.sha256_file(folder / ec.MANIFEST), installed_bytes=total)
why = feedmod.engine_fit_reasons(pkg, ctx.hardware)
if why:
raise UpdateError("this file is not a Strata engine for this PC: " + "; ".join(why), 5)
# the staged folder gets the name an installed package has
final_stage = stage_root / "engine" / folder_name(pkg)
if final_stage != folder:
_move_dir(folder, final_stage)
staged = ec.read_manifest(final_stage)
before, _ = installed_engine(state_root, ctx.hardware)
if before is not None and feedmod.version_key(before.version) > feedmod.version_key(pkg.version) and not ctx.force:
return {"component": "engine", "status": "current", "changed": False, "installed_before": _engine_view(before),
"note": f"Engine {before.version} is already installed and is newer than this file ({pkg.version}); nothing was changed."}
result = {"component": "engine", "status": "install" if before is None else "available",
"installed_before": _engine_view(before), "changed": False, "source": "file"}
keep_stage = True
return _finish_engine_install(ctx, state, pkg, stage_root, staged, archive, result, delete_archive=False)
finally:
if not keep_stage:
shutil.rmtree(longpath.long_path(stage_root), ignore_errors=True)
def rollback_engine(ctx: Context) -> dict:
"""Return to the previous engine version, which the last update kept. Nothing is downloaded. A pin makes the older
package the one a start picks even though a newer one is installed; the next successful update clears it."""
@@ -0,0 +1,86 @@
"""The offline path of the first-run card: an engine package the person downloaded and chose is checked (signature, every file, fit for
this PC), test-started and switched to, with no feed and no network. The file they chose stays where it is."""
import tarfile
from pathlib import Path
from unittest import mock
from strata_control import updater
from tests.terminal import update_fixture as fx
from feed_tool import pack_engine # noqa: E402 (update_fixture puts packaging/ on the path)
from tests.terminal.test_updater import PLATFORM, UpdaterCase
class InstallEngineFile(UpdaterCase):
def package(self, version="0.1.46", key="default", **options):
folder = fx.build_package(self.root / f"file-{version}", version, key=self.key if key == "default" else key, **options)
out = self.root / f"file-out-{version}"
out.mkdir(exist_ok=True)
pack_engine(folder, out)
return next(p for p in sorted(out.iterdir()) if p.name.endswith((".tar.gz", ".zip")))
def install(self, archive, **over):
with mock.patch.object(updater, "discover_run_config", return_value=None):
return updater.install_engine_file(self.ctx(run_config=None, **over), archive)
def test_a_signed_package_is_installed_without_any_network(self):
archive = self.package()
out = self.install(archive)
self.assertEqual((out["status"], out["changed"]), ("updated", True), out)
self.assertEqual(self.resolved(), "0.1.46")
self.assertTrue(archive.is_file(), "the person's file is not deleted")
self.assertEqual(self.server.requests, [], "nothing was fetched")
self.assertEqual(sorted(p.name for p in (self.components / ".s").iterdir()), [], "staging is cleaned")
def test_an_unsigned_package_is_refused(self):
archive = self.package(key=None)
with self.assertRaises(updater.UpdateError) as caught:
self.install(archive)
self.assertIn("security check", str(caught.exception))
self.assertEqual(self.engine_folders(), [])
def test_a_package_signed_by_another_key_is_refused(self):
archive = self.package(key=fx.make_key())
with self.assertRaises(updater.UpdateError):
self.install(archive)
self.assertEqual(self.engine_folders(), [])
def test_a_package_that_does_not_fit_this_card_says_so(self):
archive = self.package(archs=("sm_100",))
with self.assertRaises(updater.UpdateError) as caught:
self.install(archive)
self.assertIn("not a Strata engine for this PC", str(caught.exception))
self.assertEqual(self.engine_folders(), [])
def test_something_that_is_not_a_package_is_refused_in_plain_words(self):
junk = self.root / "notes.txt"
junk.write_text("hello")
with self.assertRaises(updater.UpdateError) as caught:
self.install(junk)
self.assertIn("not a Strata engine package", str(caught.exception))
bad = self.root / "bad.tar.gz"
bad.write_bytes(b"this is not gzip")
with self.assertRaises(updater.UpdateError):
self.install(bad)
def test_an_older_package_does_not_replace_a_newer_engine(self):
self.install_current("0.1.47")
out = self.install(self.package("0.1.46"))
self.assertEqual((out["status"], out["changed"]), ("current", False))
self.assertEqual(self.resolved(), "0.1.47")
def test_a_package_with_a_changed_file_is_refused(self):
archive = self.package()
tampered = self.root / "tampered.tar.gz"
with tarfile.open(archive) as src, tarfile.open(tampered, "w:gz") as dst:
for member in src.getmembers():
data = src.extractfile(member) if member.isfile() else None
if member.isfile() and member.name.endswith("engine_main.py"):
import io
payload = b"print('changed')\n"
member.size = len(payload)
data = io.BytesIO(payload)
dst.addfile(member, data)
with self.assertRaises(updater.UpdateError):
self.install(tampered)
self.assertEqual(self.engine_folders(), [])