diff --git a/backend/snapstudio_api/routes_engines.py b/backend/snapstudio_api/routes_engines.py new file mode 100644 index 00000000..c941002e --- /dev/null +++ b/backend/snapstudio_api/routes_engines.py @@ -0,0 +1,254 @@ +"""Routes of the Engines track: an optional, user-configured local Lumina-compatible service. + + POST /engines/lumina/formats {} -> {formats, ...} + POST /engines/lumina/status {service_url} -> {status, ...} + POST /engines/lumina/generate {service_url, image_path, lut_name, format, out_dir?} -> {generated, ...} + +Studio does not slice and does not control anything here. The service is whatever local address the user +typed; it is reached only through `foundation.netguard` (loopback / LAN, no redirects, bounded). The +generated artifact is written as a NEW file in a Studio-owned folder (or a local folder the user chose), +never over or next to the input image. No response carries a filesystem path or a service response body. +Progress and cancel are `unknown`: the saved Lumina research publishes neither, so none is invented. + +Evidence: mock-service-tested. No real Lumina installation has been exercised. +""" +from __future__ import annotations + +import os +import re + +from snapstudio_core import paths +from snapstudio_core.engines import local_input +from snapstudio_core.engines.lumina import MAX_INPUT_BYTES, LuminaClient, LuminaError +from snapstudio_core.foundation.netguard import NetguardRefused + +from . import ext_routes +from . import request_validation as rv + +EVIDENCE = "mock-service-tested" +GENERATED_BY = "a user-configured local Lumina-compatible service (not verified)" +ADVISORY = ("Studio did not watch this file being made. It came from a service you configured, which " + "Studio has not verified. Inspect it before you use it; Studio does not slice or print it.") +DEFAULT_OUT_FOLDER = "lumina-output" +MAX_PATH_CHARS = 4096 +MAX_URL_CHARS = 512 + +#: The explicit list. A format is never inferred; anything else is refused. +SUPPORTED_FORMATS: tuple[dict, ...] = ( + {"kind": "3mf", "meaning": "A 3MF model file returned by the service.", "evidence": EVIDENCE}, + {"kind": "png", "meaning": "A PNG preview image returned by the service.", "evidence": EVIDENCE}, + {"kind": "glb", "meaning": "A binary glTF (GLB) preview model returned by the service.", "evidence": EVIDENCE}, +) +FORMAT_KINDS = tuple(f["kind"] for f in SUPPORTED_FORMATS) + +_FILE_URL = re.compile(r"\A/api/files/([A-Za-z0-9_-]{1,128})\Z") +_EXT = re.compile(r"\A\.[A-Za-z0-9]{1,8}\Z") + +#: Plain explanations per adapter error code. Never a service body, URL or path. +LUMINA_MESSAGES = { + "invalid_service_url": "Enter only the service address, for example http://192.168.1.20:8000, with no path.", + "discovery_failed": "The service did not answer its description request. Check the address and that it is running.", + "malformed_discovery": "The service described itself in a shape Studio does not recognise.", + "malformed_json": "The service answered with something Studio could not read.", + "unknown_version": "The service did not say which API version it speaks, so Studio will not use it.", + "unsupported_version": "The service speaks an API version Studio has not been tested with.", + "health_failed": "The service did not pass its identity check, so Studio did not send anything to it.", + "malformed_health": "The service identity check answered in a shape Studio does not recognise.", + "route_unavailable": "The service does not offer a route Studio needs.", + "identity_not_confirmed": "The service identity was not confirmed, so Studio did not send anything to it.", + "preview_failed": "The service refused or failed the request.", + "malformed_preview": "The service answered in a shape Studio does not recognise.", + "unknown_preview_locator": "The service pointed at a file location Studio does not recognise.", + "artifact_unavailable": "The service did not provide the file it announced.", + "invalid_file_id": "The service named a file in a form Studio will not fetch.", + "invalid_input": "The image is empty or larger than Studio will send.", + "invalid_lut": "Enter a LUT name of up to 256 characters.", + "progress_unknown": "Progress is unknown: the service does not publish a progress route Studio can rely on.", + "cancel_unknown": "Cancel is unknown: the service does not publish a cancel route Studio can rely on.", +} +_GENERIC_ENGINE = "The service could not be used." + + +def _refusal(code: str, message: str) -> tuple[int, dict]: + return 422, {"error": "refusal", "code": code, "message": message} + + +def _lumina_refusal(exc: LuminaError) -> tuple[int, dict]: + return _refusal(exc.code, LUMINA_MESSAGES.get(exc.code, _GENERIC_ENGINE)) + + +def _netguard_refusal(exc: NetguardRefused) -> tuple[int, dict]: + return _refusal(f"network_{exc.code}", str(exc)) + + +def _service_url(data: dict) -> str: + return rv.require_bounded_str(data, "service_url", MAX_URL_CHARS).strip() + + +def _format_list_text() -> str: + return ", ".join(FORMAT_KINDS) + + +@ext_routes.route("/engines/lumina/formats") +def formats(data: dict) -> tuple[int, dict]: + return 200, { + "formats": [dict(f) for f in SUPPORTED_FORMATS], + "evidence": EVIDENCE, + "progress": "unknown", + "cancel": "unknown", + "note": ("Formats are listed explicitly and chosen by you; Studio never infers one. " + "Evidence is a synthetic loopback mock: no real Lumina installation was exercised."), + } + + +@ext_routes.route("/engines/lumina/status") +def status(data: dict) -> tuple[int, dict]: + url = _service_url(data) + client = None + try: + client = LuminaClient(url) + discovery = client.discover() + client.health_check() + return 200, { + "status": "ok", + "api_version": discovery.api_version, + "can_generate": {"/api/convert/preview", "/api/files/{file_id}"} <= set(discovery.paths), + "progress": "unknown", + "cancel": "unknown", + "evidence": EVIDENCE, + "note": ("That answer is not proof of what the service is or " + "that it will produce a good result."), + } + except NetguardRefused as exc: + if exc.code in ("syntax", "off_network", "public_address", "unresolvable"): + return _netguard_refusal(exc) + return 200, {"status": "unknown", "code": f"network_{exc.code}", "message": str(exc), + "progress": "unknown", "cancel": "unknown", "evidence": EVIDENCE} + except LuminaError as exc: + if exc.code == "invalid_service_url": + return _lumina_refusal(exc) + return 200, {"status": "unknown", "code": exc.code, + "message": LUMINA_MESSAGES.get(exc.code, _GENERIC_ENGINE), + "progress": "unknown", "cancel": "unknown", "evidence": EVIDENCE} + finally: + if client is not None: + client.close() + + +def _image_path(data: dict) -> str: + raw = rv.require_bounded_str(data, "image_path", MAX_PATH_CHARS) + if "\x00" in raw: + raise rv.ValidationError("Invalid 'image_path'") + if local_input.is_network_or_device_path(raw) or local_input.reaches_network(raw): + raise rv.ValidationError("That image path is a network or device location. Choose a file on this computer.") + if not os.path.exists(raw): + raise rv.ValidationError("That image file was not found.") + if not local_input.is_local_regular_file(raw, max_bytes=MAX_INPUT_BYTES): + raise rv.ValidationError("That is not a regular image file Studio can send " + f"(it must be a file of at most {MAX_INPUT_BYTES // (1024 * 1024)} MB).") + return raw + + +def _out_dir(data: dict, image_path: str) -> tuple[str, str]: + """(directory, location label). The folder must be Studio's own or an existing local one.""" + raw = data.get("out_dir") + if raw is None or raw == "": + target = os.path.join(paths.data_dir(), DEFAULT_OUT_FOLDER) + os.makedirs(target, exist_ok=True) + label = "Studio's lumina-output folder" + else: + if not isinstance(raw, str) or len(raw) > MAX_PATH_CHARS or "\x00" in raw: + raise rv.ValidationError("Invalid 'out_dir'") + if not local_input.is_local_directory(raw): + raise rv.ValidationError("That output folder is not an existing local folder Studio can write to.") + target = raw + label = "the folder you chose" + try: + if os.path.samefile(target, os.path.dirname(os.path.abspath(image_path))): + raise rv.ValidationError("Choose an output folder other than the image's own folder, so the " + "original is never written next to.") + except OSError: + raise rv.ValidationError("That output folder is not an existing local folder Studio can write to.") from None + return target, label + + +def _write_new(directory: str, kind: str, sha256: str, data: bytes) -> str: + """Create a new file, never replacing one. Returns the file name only.""" + for n in range(1, 1000): + name = f"lumina-{sha256[:12]}.{kind}" if n == 1 else f"lumina-{sha256[:12]}-{n}.{kind}" + try: + fd = os.open(os.path.join(directory, name), os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0), 0o600) + except FileExistsError: + continue + with os.fdopen(fd, "wb") as handle: + handle.write(data) + return name + raise rv.ValidationError("The output folder already holds too many files with this name.") + + +def _read_input(path: str) -> bytes: + with open(path, "rb") as handle: + blob = handle.read(MAX_INPUT_BYTES + 1) + if not blob or len(blob) > MAX_INPUT_BYTES: + raise rv.ValidationError("The image is empty or larger than Studio will send.") + return blob + + +@ext_routes.route("/engines/lumina/generate") +def generate(data: dict) -> tuple[int, dict]: + url = _service_url(data) + fmt = data.get("format") + if not isinstance(fmt, str) or fmt not in FORMAT_KINDS: + raise rv.ValidationError(f"Choose one of the supported formats: {_format_list_text()}. " + "Studio does not guess a format.") + lut = rv.require_bounded_str(data, "lut_name", 256) + image_path = _image_path(data) + out_dir, location = _out_dir(data, image_path) + image = _read_input(image_path) + suffix = os.path.splitext(image_path)[1] + upload_name = "input" + (suffix if _EXT.match(suffix) else "") + + client = None + try: + client = LuminaClient(url) + client.discover() + client.health_check() + preview = client.preview(image, upload_name, lut_name=lut) + locators = [preview.get("preview_url"), preview.get("preview_glb_url")] + seen: list[str] = [] + artifact = None + for locator in locators: + match = _FILE_URL.match(locator) if isinstance(locator, str) else None + if match is None: + continue + candidate = client.fetch_artifact(match.group(1)) + seen.append(candidate.kind) + if candidate.kind == fmt: + artifact = candidate + break + if artifact is None: + produced = ", ".join(sorted(set(seen))) if seen else "no file" + return _refusal("format_not_produced", + f"You asked for {fmt}, but the service returned {produced}. Nothing was saved. " + f"Choose a format the service produced, from: {_format_list_text()}.") + name = _write_new(out_dir, artifact.kind, artifact.sha256, artifact.data) + return 200, { + "generated": True, + "file_name": name, + "sha256": artifact.sha256, + "size_bytes": artifact.size_bytes, + "kind": artifact.kind, + "generated_by": GENERATED_BY, + "location_label": location, + "advisory": ADVISORY, + "progress": "unknown", + "cancel": "unknown", + "evidence": EVIDENCE, + } + except NetguardRefused as exc: + return _netguard_refusal(exc) + except LuminaError as exc: + return _lumina_refusal(exc) + finally: + if client is not None: + client.close() diff --git a/backend/snapstudio_core/engines/cli_runner.py b/backend/snapstudio_core/engines/cli_runner.py index b8df74c0..ef3b5ec5 100644 --- a/backend/snapstudio_core/engines/cli_runner.py +++ b/backend/snapstudio_core/engines/cli_runner.py @@ -2,11 +2,14 @@ from __future__ import annotations import hashlib +import json import os import re +import signal import shutil import stat import subprocess +import sys import threading import time import uuid @@ -28,6 +31,106 @@ def _template_ok(arg: object) -> bool: _MAX_SCAN_ENTRIES = 10000 _MAX_SCAN_DEPTH = 32 _REPARSE_POINT = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400) +_SLICER_NAMES = {"orca", "snapmaker-orca", "bambu", "prusa", "slic3r", "superslicer", "cura", "kiri"} +_WINDOWS_LAUNCHER = ( + "import json,subprocess,sys; command=json.loads(sys.argv[1]); " + "sys.exit(subprocess.call(command, stdin=subprocess.DEVNULL, shell=False)) " + "if sys.stdin.buffer.read(1) == b'\\x01' else sys.exit(125)" +) + + +def _is_own_interpreter(path: Path) -> bool: + try: + return path == Path(sys.executable).resolve(strict=True) + except OSError: + return False + + +def _hash_approved(path: Path, approved: Sequence[str]) -> bool: + """True when the file's SHA-256 is one the caller pinned. Hash comparison is done on the bytes read now.""" + pins = {item.lower() for item in approved if isinstance(item, str) and re.fullmatch(r"[0-9a-fA-F]{64}", item)} + if not pins: + return False + digest = hashlib.sha256() + try: + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(chunk) + except OSError: + return False + return digest.hexdigest() in pins + + +def _executable_policy_refused(path: Path) -> bool: + name = path.name.lower() + if name.endswith(".exe"): + name = name[:-4] + tokens = [token for token in re.split(r"[-_. ]+", name) if token] + return name in _SLICER_NAMES or "slicer" in name or any(token in _SLICER_NAMES for token in tokens) + + +class _WindowsJob: + """A kill-on-close Job Object containing this runner's child process tree.""" + + def __init__(self, process: subprocess.Popen[bytes]) -> None: + import ctypes + + from ctypes import wintypes + + class IO_COUNTERS(ctypes.Structure): + _fields_ = [(name, ctypes.c_ulonglong) for name in ( + "ReadOperationCount", "WriteOperationCount", "OtherOperationCount", + "ReadTransferCount", "WriteTransferCount", "OtherTransferCount")] + + class BASIC_LIMIT(ctypes.Structure): + _fields_ = [ + ("PerProcessUserTimeLimit", ctypes.c_longlong), + ("PerJobUserTimeLimit", ctypes.c_longlong), + ("LimitFlags", wintypes.DWORD), + ("MinimumWorkingSetSize", ctypes.c_size_t), + ("MaximumWorkingSetSize", ctypes.c_size_t), + ("ActiveProcessLimit", wintypes.DWORD), + ("Affinity", ctypes.c_size_t), + ("PriorityClass", wintypes.DWORD), + ("SchedulingClass", wintypes.DWORD), + ] + + class EXTENDED_LIMIT(ctypes.Structure): + _fields_ = [ + ("BasicLimitInformation", BASIC_LIMIT), + ("IoInfo", IO_COUNTERS), + ("ProcessMemoryLimit", ctypes.c_size_t), + ("JobMemoryLimit", ctypes.c_size_t), + ("PeakProcessMemoryUsed", ctypes.c_size_t), + ("PeakJobMemoryUsed", ctypes.c_size_t), + ] + + self._kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32 = self._kernel32 + kernel32.CreateJobObjectW.restype = wintypes.HANDLE + kernel32.CreateJobObjectW.argtypes = (ctypes.c_void_p, wintypes.LPCWSTR) + kernel32.SetInformationJobObject.argtypes = (wintypes.HANDLE, ctypes.c_int, + ctypes.c_void_p, wintypes.DWORD) + kernel32.AssignProcessToJobObject.argtypes = (wintypes.HANDLE, wintypes.HANDLE) + kernel32.CloseHandle.argtypes = (wintypes.HANDLE,) + self.handle = kernel32.CreateJobObjectW(None, None) + if not self.handle: + raise OSError(ctypes.get_last_error(), "CreateJobObjectW failed") + limits = EXTENDED_LIMIT() + limits.BasicLimitInformation.LimitFlags = 0x00002000 # JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE + if not kernel32.SetInformationJobObject(self.handle, 9, ctypes.byref(limits), ctypes.sizeof(limits)): + error = ctypes.get_last_error() + self.close() + raise OSError(error, "SetInformationJobObject failed") + if not kernel32.AssignProcessToJobObject(self.handle, wintypes.HANDLE(process._handle)): + error = ctypes.get_last_error() + self.close() + raise OSError(error, "AssignProcessToJobObject failed") + + def close(self) -> None: + if self.handle: + self._kernel32.CloseHandle(self.handle) + self.handle = None class RunnerError(Exception): @@ -78,19 +181,29 @@ def drain(self, stream: object) -> None: class CliRunner: """Run a fixed executable and argument template without a shell. - Every run gets a fresh directory created beneath `job_root`; process cancellation - targets only the exact Popen object created by this runner. + Every run gets a fresh directory created beneath `job_root`. Processes run in a + private process group (POSIX) or kill-on-close Job Object (Windows), so stop + operations only affect the tree this runner started. The executable-name policy + is a safety rail, not a sandbox or a guarantee. """ def __init__(self, executable: str | os.PathLike[str], job_root: str | os.PathLike[str], argument_template: Sequence[str], *, timeout_s: float = 300.0, output_limit: int = 1024 * 1024, - artifact_limit: int = 512 * 1024 * 1024) -> None: + artifact_limit: int = 512 * 1024 * 1024, + approved_sha256: Sequence[str] = ()) -> None: self.executable = Path(executable).expanduser().resolve(strict=True) if not self.executable.is_file(): raise RunnerError("executable_invalid") if self.executable.suffix.lower() in {".bat", ".cmd"}: raise RunnerError("executable_script_refused") + if _executable_policy_refused(self.executable): + raise RunnerError("executable_policy_refused") + # Admission is by identity, not by name: the caller pins the SHA-256 of the one executable it approves. + # Only the interpreter running Studio is admitted without a pin. A renamed copy of anything else has a + # different path and, unless its bytes were pinned, no approval. + if not _is_own_interpreter(self.executable) and not _hash_approved(self.executable, approved_sha256): + raise RunnerError("executable_not_approved") self.job_root = Path(job_root).expanduser().resolve(strict=True) if not self.job_root.is_dir(): raise RunnerError("job_root_invalid") @@ -109,7 +222,7 @@ def __init__(self, executable: str | os.PathLike[str], job_root: str | os.PathLi self.output_limit = output_limit self.artifact_limit = artifact_limit self._lock = threading.Lock() - self._active: dict[int, subprocess.Popen[bytes]] = {} + self._active: dict[int, tuple[subprocess.Popen[bytes], _WindowsJob | None]] = {} def run(self, *, inputs: Mapping[str, str] | None = None, cancel_event: threading.Event | None = None) -> RunnerResult: @@ -121,6 +234,14 @@ def run(self, *, inputs: Mapping[str, str] | None = None, job_dir = (self.job_root / run_id).resolve() if not job_dir.is_relative_to(self.job_root): raise RunnerError("job_path_invalid") + try: + return self._run_job(job_dir, inputs, cancel_event) + except BaseException: + self._remove_job_dir(job_dir) + raise + + def _run_job(self, job_dir: Path, inputs: Mapping[str, str], + cancel_event: threading.Event | None) -> RunnerResult: job_dir.mkdir(mode=0o700) output_dir = job_dir / "output" output_dir.mkdir() @@ -142,15 +263,42 @@ def run(self, *, inputs: Mapping[str, str] | None = None, lambda match: values[match.group(1)], arg) for arg in self.argument_template] command = [str(self.executable), *rendered] + windows_job: _WindowsJob | None = None try: - process = subprocess.Popen(command, cwd=str(job_dir), shell=False, - stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, - stderr=subprocess.PIPE) + launch_command = command + launch_stdin = subprocess.DEVNULL + if os.name == "nt": + # The helper waits before starting the configured engine. This lets + # the runner assign the helper to its Job Object first, so even a + # fast engine cannot spawn a descendant outside that job. + if getattr(sys, "frozen", False): + # The launcher needs a plain interpreter; a packaged sidecar would start itself instead. + raise RunnerError("windows_launcher_unavailable_in_packaged_app") + launch_command = [sys.executable, "-I", "-c", _WINDOWS_LAUNCHER, json.dumps(command)] + launch_stdin = subprocess.PIPE + process = subprocess.Popen(launch_command, cwd=str(job_dir), shell=False, + stdin=launch_stdin, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + start_new_session=(os.name != "nt")) + if os.name == "nt": + try: + windows_job = _WindowsJob(process) + except OSError: + self._stop_owned(process, windows_job) + raise RunnerError("process_job_assignment_failed") from None + try: + assert process.stdin is not None + process.stdin.write(b"\x01") + process.stdin.flush() + process.stdin.close() + except OSError: + self._stop_owned(process, windows_job) + raise RunnerError("process_start_failed") from None except OSError: raise RunnerError("process_start_failed") from None try: with self._lock: - self._active[process.pid] = process + self._active[process.pid] = (process, windows_job) overflow = threading.Event() budget_lock = threading.Lock() output_total = [0] @@ -163,23 +311,26 @@ def run(self, *, inputs: Mapping[str, str] | None = None, deadline = time.monotonic() + self.timeout_s while process.poll() is None: if cancel_event is not None and cancel_event.is_set(): - self._stop_owned(process) + self._stop_owned(process, windows_job) raise RunnerError("cancelled", stdout=bytes(stdout.data)) if overflow.is_set(): - self._stop_owned(process) + self._stop_owned(process, windows_job) raise RunnerError("output_limit_exceeded", stdout=bytes(stdout.data)) try: output_size = self._output_size(output_dir) except RunnerError: - self._stop_owned(process) + self._stop_owned(process, windows_job) raise if output_size > self.artifact_limit: - self._stop_owned(process) + self._stop_owned(process, windows_job) raise RunnerError("artifact_output_limit_exceeded", stdout=bytes(stdout.data)) if time.monotonic() >= deadline: - self._stop_owned(process) + self._stop_owned(process, windows_job) raise RunnerError("timeout", stdout=bytes(stdout.data)) time.sleep(0.02) + # The direct process can exit while a descendant still holds inherited + # pipes or continues writing. Close the runner-owned tree before scanning. + self._stop_owned(process, windows_job) for reader in readers: reader.join(timeout=0.1) if overflow.is_set(): @@ -189,8 +340,9 @@ def run(self, *, inputs: Mapping[str, str] | None = None, raise RunnerError("process_failed", stdout=bytes(stdout.data)) return RunnerResult(job_dir, int(code), bytes(stdout.data), self._manifest(output_dir)) finally: - if process.poll() is None: - self._stop_owned(process) + self._stop_owned(process, windows_job) + if windows_job is not None: + windows_job.close() with self._lock: self._active.pop(process.pid, None) # A descendant may still hold an inherited pipe. Closing its BufferedReader @@ -200,34 +352,72 @@ def run(self, *, inputs: Mapping[str, str] | None = None, def cancel(self, pid: int) -> bool: """Terminate a process only when its PID maps to this runner's live Popen handle.""" with self._lock: - process = self._active.get(pid) - if process is None or process.poll() is not None: + active = self._active.get(pid) + if active is None: return False - self._stop_owned(process) + self._stop_owned(*active) return True @staticmethod - def _stop_owned(process: subprocess.Popen[bytes]) -> None: - if process.poll() is None: - try: + def _stop_owned(process: subprocess.Popen[bytes], windows_job: _WindowsJob | None = None) -> None: + if os.name == "nt": + if windows_job is not None: + windows_job.close() + if process.poll() is None: + if windows_job is None: + try: + process.terminate() + except OSError: + pass + try: + process.wait(timeout=1.0) + except (OSError, subprocess.TimeoutExpired): + try: + process.kill() + except OSError: + pass + try: + process.wait(timeout=1.0) + except subprocess.TimeoutExpired: + pass + return + try: + os.killpg(process.pid, signal.SIGTERM) + except ProcessLookupError: + pass + except OSError: + if process.poll() is None: process.terminate() - except OSError: - if process.poll() is not None: - return + try: + process.wait(timeout=1.0) + except subprocess.TimeoutExpired: + pass + try: + os.killpg(process.pid, signal.SIGKILL) + except (ProcessLookupError, OSError): + pass + if process.poll() is None: try: process.wait(timeout=1.0) except subprocess.TimeoutExpired: - try: - process.kill() - except OSError: - if process.poll() is not None: - return - try: - process.wait(timeout=1.0) - except subprocess.TimeoutExpired: - # The runner has made a bounded terminate/kill attempt. Never let - # cleanup itself turn the configured deadline into an unbounded wait. - return + # Cleanup remains bounded even if the OS cannot stop the child. + pass + + def cleanup(self, result: RunnerResult) -> None: + """Remove a successful run's job directory after its caller has read artifacts.""" + if not isinstance(result, RunnerResult): + raise RunnerError("result_invalid") + self._remove_job_dir(result.job_dir) + + def _remove_job_dir(self, job_dir: Path) -> None: + try: + resolved = job_dir.resolve(strict=False) + if resolved.parent != self.job_root or not re.fullmatch(r"[0-9a-f]{32}", resolved.name): + return + shutil.rmtree(resolved, ignore_errors=True) + except OSError: + # Cleanup is best effort and must not mask the original engine outcome. + pass @staticmethod def _iter_output_files(output_dir: Path): diff --git a/backend/snapstudio_core/engines/local_input.py b/backend/snapstudio_core/engines/local_input.py new file mode 100644 index 00000000..073fa7d1 --- /dev/null +++ b/backend/snapstudio_core/engines/local_input.py @@ -0,0 +1,95 @@ +"""Best-effort guard for a user-supplied local input file or output folder. + +Interim private helper for the engines track. The shared guard lives in the #140 work +(`snapstudio_core.localpath`); this module should be replaced by it once both land. + +It refuses a network (UNC) path in any slash style, a Windows device path, a symlink or +junction chain that reaches one of those, anything that is not a regular file, and a file +over the caller's size cap. The checks are lexical first; the link walk then `lstat`s each +component (never following the one being examined) and reads a link's target text with +`readlink`, so a link to a network share is rejected without connecting to it. + +This is best-effort, not a sandbox: the check and the later open are separate steps, so a +process that can change the path in between can redirect the operation. A mapped network +drive letter looks like a local volume and is allowed; it is the user's own storage. +""" +from __future__ import annotations + +import os +import stat + +_MAX_LINK_DEPTH = 8 +_REDIRECTING_REPARSE_TAGS = {0xA000000C, 0xA0000003} # symlink, junction + + +def is_network_or_device_path(path: object) -> bool: + """UNC shares and the device namespaces, in any mix of slash styles.""" + if not isinstance(path, str): + return False + normal = path.replace("/", "\\") + # `\\host\share`, `\\?\...`, `\\.\...` and the NT passthrough prefix `\??\...` (one leading backslash). + return normal.startswith("\\\\") or normal.startswith("\\??\\") + + +def _plain_drive_target(target: str) -> str: + # Windows readlink returns a link to C:\x as \\?\C:\x: a local drive, not a device namespace. + if len(target) >= 7 and target[:4] == "\\\\?\\" and "A" <= target[4].upper() <= "Z" and target[5:7] == ":\\": + return target[4:] + return target + + +def _is_redirect(info: os.stat_result) -> bool: + return stat.S_ISLNK(info.st_mode) or getattr(info, "st_reparse_tag", 0) in _REDIRECTING_REPARSE_TAGS + + +def reaches_network(path: str, depth: int = 0) -> bool: + """True when the path, or any link on the way to it, names a network or device location.""" + if is_network_or_device_path(path): + return True + if depth > _MAX_LINK_DEPTH: + return True + absolute = os.path.abspath(path) + if is_network_or_device_path(absolute): + return True + drive, rest = os.path.splitdrive(absolute) + current = drive + os.sep + for part in [piece for piece in rest.split(os.sep) if piece]: + current = os.path.join(current, part) + try: + info = os.lstat(current) + except FileNotFoundError: + return False + except (OSError, ValueError): + return True + if _is_redirect(info): + try: + target = os.readlink(current) + except (OSError, ValueError): + return True + target = _plain_drive_target(target) + if not os.path.isabs(target) and not is_network_or_device_path(target): + target = os.path.join(os.path.dirname(current), target) + if reaches_network(target, depth + 1): + return True + return False + + +def is_local_regular_file(path: object, *, max_bytes: int) -> bool: + """True only for a regular local file no larger than `max_bytes`. Never raises.""" + if not isinstance(path, str) or not path or "\x00" in path or reaches_network(path): + return False + try: + info = os.stat(path) + except (OSError, ValueError): + return False + return stat.S_ISREG(info.st_mode) and info.st_size <= max_bytes + + +def is_local_directory(path: object) -> bool: + """True only for an existing local directory. Never raises.""" + if not isinstance(path, str) or not path or "\x00" in path or reaches_network(path): + return False + try: + return stat.S_ISDIR(os.stat(path).st_mode) + except (OSError, ValueError): + return False diff --git a/backend/tests/engines/test_lumina_adapter_slice1.py b/backend/tests/engines/test_lumina_adapter_slice1.py index ba2f6685..26b489cc 100644 --- a/backend/tests/engines/test_lumina_adapter_slice1.py +++ b/backend/tests/engines/test_lumina_adapter_slice1.py @@ -260,6 +260,151 @@ def test_cli_runner_timeout_returns_when_grandchild_keeps_pipes_open(tmp_path): os.kill(grandchild_pid, signal.SIGTERM) +@pytest.mark.parametrize("stop_kind", ["timeout", "cancel"]) +def test_cli_runner_timeout_or_cancel_stops_descendant_writer(tmp_path, stop_kind): + root = tmp_path / "jobs" + root.mkdir() + pid_file = tmp_path / "writer.pid" + marker = tmp_path / "writes.log" + child_script = tmp_path / "writer.py" + script = tmp_path / "engine.py" + child_script.write_text( + "import sys,time\n" + "from pathlib import Path\n" + "path=Path(sys.argv[1])\n" + "while True:\n" + " with path.open('a', encoding='utf-8') as handle: handle.write('x')\n" + " time.sleep(0.02)\n", + encoding="utf-8", + ) + script.write_text( + "import subprocess,sys,time\n" + "from pathlib import Path\n" + "pid_file,marker=sys.argv[1:]\n" + f"child=subprocess.Popen([sys.executable,{str(child_script)!r},marker])\n" + "Path(pid_file).write_text(str(child.pid))\n" + "time.sleep(30)\n", + encoding="utf-8", + ) + runner = CliRunner(sys.executable, root, (str(script), str(pid_file), str(marker)), timeout_s=0.25) + cancel = threading.Event() if stop_kind == "cancel" else None + outcome: list[object] = [] + + def run(): + try: + outcome.append(runner.run(cancel_event=cancel)) + except Exception as exc: # noqa: BLE001 - asserted below + outcome.append(exc) + + worker = threading.Thread(target=run) + worker.start() + if cancel is not None: + deadline = time.monotonic() + 3 + while not pid_file.exists() and time.monotonic() < deadline: + time.sleep(0.005) + cancel.set() + worker.join(timeout=3) + assert not worker.is_alive() + assert isinstance(outcome[0], RunnerError), repr(outcome) + assert outcome[0].code == ("cancelled" if stop_kind == "cancel" else "timeout") + grandchild_pid = int(pid_file.read_text(encoding="utf-8")) + first_size = marker.stat().st_size if marker.exists() else 0 + time.sleep(0.12) + second_size = marker.stat().st_size if marker.exists() else 0 + try: + assert not _pid_alive(grandchild_pid), "runner left its descendant alive" + assert second_size == first_size, "descendant kept writing after the runner returned" + finally: + if _pid_alive(grandchild_pid): + os.kill(grandchild_pid, signal.SIGTERM) + + +def test_cli_runner_failed_run_leaves_no_job_directory(tmp_path): + root = tmp_path / "jobs" + root.mkdir() + runner = CliRunner(sys.executable, root, ("-c", "raise SystemExit(7)"), timeout_s=2) + with pytest.raises(RunnerError, match="process_failed"): + runner.run() + assert list(root.iterdir()) == [] + + +def test_cli_runner_keeps_successful_job_until_explicit_cleanup(tmp_path): + root = tmp_path / "jobs" + root.mkdir() + runner = CliRunner(sys.executable, root, ("-c", "pass"), timeout_s=2) + result = runner.run() + assert result.job_dir.is_dir() + runner.cleanup(result) + assert not result.job_dir.exists() + + +@pytest.mark.skipif(os.name != "nt", reason="the launcher is the Windows path") +def test_cli_runner_refuses_windows_launch_when_frozen(monkeypatch, tmp_path): + root = tmp_path / "jobs" + root.mkdir() + runner = CliRunner(sys.executable, root, ("-c", "pass"), timeout_s=2) + monkeypatch.setattr(sys, "frozen", True, raising=False) + with pytest.raises(RunnerError, match="windows_launcher_unavailable_in_packaged_app"): + runner.run() + assert list(root.iterdir()) == [] + + +@pytest.mark.parametrize("name", ["orca", "Snapmaker-Orca.EXE", "Snapmaker_Orca.exe", "bambu-studio.exe", "UltiMaker-Cura", "Snapmaker_Orca_Linux_2.AppImage", "bambu", "PrusaSlicer", "SuperSlicer", "cura", "kiri", "custom-slicer-engine"]) +def test_cli_runner_refuses_slicer_named_executable(tmp_path, name): + root = tmp_path / "jobs" + root.mkdir() + executable = tmp_path / name + executable.write_bytes(b"synthetic executable placeholder") + with pytest.raises(RunnerError, match="executable_policy_refused"): + CliRunner(executable, root, ()) + + +def _copy_interpreter_as(tmp_path, name): + import shutil + copy = tmp_path / name + shutil.copy2(sys.executable, copy) + return copy + + +def _sha256_of(path): + import hashlib + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def test_cli_runner_refuses_unpinned_renamed_copy(tmp_path): + root = tmp_path / "jobs" + root.mkdir() + copy = _copy_interpreter_as(tmp_path, "engine.exe" if os.name == "nt" else "engine") + with pytest.raises(RunnerError, match="executable_not_approved"): + CliRunner(copy, root, ()) + + +def test_cli_runner_admits_renamed_copy_with_matching_pin(tmp_path): + root = tmp_path / "jobs" + root.mkdir() + copy = _copy_interpreter_as(tmp_path, "engine.exe" if os.name == "nt" else "engine") + # Admission only: a copied interpreter may not start outside its install directory, so it is not run here. + runner = CliRunner(copy, root, ("-c", "pass"), timeout_s=5, approved_sha256=[_sha256_of(copy).upper()]) + assert runner.executable == copy.resolve() + + +@pytest.mark.parametrize("pin", ["0" * 64, "not-a-hash", ""]) +def test_cli_runner_refuses_wrong_or_malformed_pin(tmp_path, pin): + root = tmp_path / "jobs" + root.mkdir() + copy = _copy_interpreter_as(tmp_path, "engine.exe" if os.name == "nt" else "engine") + with pytest.raises(RunnerError, match="executable_not_approved"): + CliRunner(copy, root, (), approved_sha256=[pin]) + + +def test_cli_runner_name_rail_still_wins_over_a_matching_pin(tmp_path): + root = tmp_path / "jobs" + root.mkdir() + copy = _copy_interpreter_as(tmp_path, "orca.exe" if os.name == "nt" else "orca") + with pytest.raises(RunnerError, match="executable_policy_refused"): + CliRunner(copy, root, (), approved_sha256=[_sha256_of(copy)]) + + def test_cli_runner_stops_child_after_unexpected_poll_exception(monkeypatch, tmp_path): root = tmp_path / "jobs" root.mkdir() diff --git a/backend/tests/mocks/lumina_server.py b/backend/tests/mocks/lumina_server.py index 1ded6532..6e60d81a 100644 --- a/backend/tests/mocks/lumina_server.py +++ b/backend/tests/mocks/lumina_server.py @@ -46,3 +46,87 @@ def __enter__(self): def __exit__(self, *_): return None + + +#: Synthetic artifact bytes. They are labelled bytes, not real 3MF/PNG/GLB documents. +HTTP_ARTIFACTS: dict[str, tuple[str, bytes]] = { + "mfile": ("model/3mf", b"synthetic-mock-3mf-bytes"), + "pngfile": ("image/png", b"\x89PNG\r\n\x1a\nsynthetic-mock-png-bytes"), + "glbfile": ("model/gltf-binary", b"glTFsynthetic-mock-glb-bytes"), +} + + +class LuminaHttpMock: + """A synthetic Lumina-shaped HTTP service on loopback, for route tests and screenshots. + + It is NOT Lumina. It answers only the shapes in the saved research, with fixed synthetic bytes. + `preview_id` / `glb_id` pick which artifact the preview response points at. + """ + + def __init__(self, *, preview_id: str = "pngfile", glb_id: str | None = "glbfile", + version: str = "2.0", artifacts: dict | None = None, host: str = "127.0.0.1", + port: int = 0) -> None: + import threading + from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + + self.artifacts = dict(artifacts if artifacts is not None else HTTP_ARTIFACTS) + self.requests: list[tuple[str, str]] = [] + self.uploads: list[dict] = [] + mock = self + + class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *_): + return None + + def _send(self, status: int, ctype: str, body: bytes) -> None: + self.send_response(status) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + path = urlsplit(self.path).path + mock.requests.append(("GET", path)) + if path == "/openapi.json": + doc = {"info": {"version": version}, "paths": { + "/api/health": {}, "/api/convert/preview": {}, "/api/files/{file_id}": {}}} + return self._send(200, "application/json", json.dumps(doc).encode()) + if path == "/api/health": + return self._send(200, "application/json", b"{}") + if path.startswith("/api/files/"): + item = mock.artifacts.get(path[len("/api/files/"):]) + if item is not None: + return self._send(200, item[0], item[1]) + return self._send(404, "application/json", b"{}") + + def do_POST(self): + path = urlsplit(self.path).path + mock.requests.append(("POST", path)) + length = int(self.headers.get("Content-Length") or 0) + body = self.rfile.read(length) + if path != "/api/convert/preview": + return self._send(404, "application/json", b"{}") + mock.uploads.append({"bytes": body, "type": self.headers.get("Content-Type", "")}) + payload = {"session_id": "session1", "status": "ok", "message": "Preview generated", + "preview_url": f"/api/files/{preview_id}", + "preview_glb_url": f"/api/files/{glb_id}" if glb_id else None, + "palette": [], "dimensions": {}, "contours": None} + self._send(200, "application/json", json.dumps(payload).encode()) + + self._server = ThreadingHTTPServer((host, port), Handler) + self._server.daemon_threads = True + self._thread = threading.Thread(target=self._server.serve_forever, daemon=True) + self.url = f"http://{host}:{self._server.server_port}" + + def __enter__(self): + self._thread.start() + return self + + def __exit__(self, *_): + self._server.shutdown() + self._server.server_close() + self._thread.join(timeout=5) + return None diff --git a/backend/tests/test_routes_engines_lumina.py b/backend/tests/test_routes_engines_lumina.py new file mode 100644 index 00000000..c5345903 --- /dev/null +++ b/backend/tests/test_routes_engines_lumina.py @@ -0,0 +1,350 @@ +"""Engines track routes for a user-configured Lumina-compatible service. + +The service in every test is the synthetic loopback `LuminaHttpMock`, not Lumina: evidence is +mock-service-tested and no real Lumina installation is exercised. +""" +from __future__ import annotations + +import hashlib +import json +import os +import sys + +import pytest + +from snapstudio_api import ext_routes, routes_engines +from snapstudio_core.foundation.netguard import clear_write_origins +from tests.mocks.lumina_server import HTTP_ARTIFACTS, LuminaHttpMock + +IMAGE_BYTES = b"synthetic-image-bytes-not-a-real-picture" + + +class FakeHandler: + def __init__(self): + self.sent = [] + + def _send(self, code, obj): + self.sent.append((code, obj)) + + +def call(path, data): + handler = FakeHandler() + assert ext_routes.dispatch(handler, path, data) is True + assert len(handler.sent) == 1 + return handler.sent[0] + + +@pytest.fixture +def data_dir(tmp_path, monkeypatch): + target = tmp_path / "studio-data" + target.mkdir() + monkeypatch.setenv("SNAPSTUDIO_DATA_DIR", str(target)) + return target + + +@pytest.fixture +def image(tmp_path): + folder = tmp_path / "inputs" + folder.mkdir() + path = folder / "synthetic.png" + path.write_bytes(IMAGE_BYTES) + return path + + +@pytest.fixture +def service(): + with LuminaHttpMock() as mock: + yield mock + clear_write_origins() + + +def assert_no_path(body, *roots): + text = json.dumps(body) + for root in roots: + for form in (str(root), str(root).replace("\\", "\\\\"), root.as_posix()): + assert form not in text + assert "\\Users\\" not in text and "\\\\Users\\\\" not in text and "/Users/" not in text + + +def request(service, image, fmt, **extra): + return {"service_url": service.url, "image_path": str(image), "lut_name": "Default", "format": fmt, **extra} + + +# -- registration ---------------------------------------------------------------- + +def test_routes_are_registered_under_engines_through_dispatch(): + for suffix in ("formats", "status", "generate"): + assert f"/engines/lumina/{suffix}" in ext_routes.ROUTES + assert ext_routes.ROUTES[f"/engines/lumina/{suffix}"].__module__.endswith("routes_engines") + handled = ext_routes.dispatch(FakeHandler(), "/engines/lumina/nothing", {}) + assert handled is False + + +def test_dispatch_rejects_a_non_object_body(): + handler = FakeHandler() + ext_routes.dispatch(handler, "/engines/lumina/formats", []) + assert handler.sent[0][0] == 400 + + +# -- formats --------------------------------------------------------------------- + +def test_formats_list_is_explicit_and_labelled(): + status, body = call("/engines/lumina/formats", {}) + assert status == 200 + assert [f["kind"] for f in body["formats"]] == ["3mf", "png", "glb"] + assert all(f["evidence"] == "mock-service-tested" and f["meaning"] for f in body["formats"]) + assert body["progress"] == "unknown" and body["cancel"] == "unknown" + assert "no real Lumina" in body["note"] + + +# -- status ---------------------------------------------------------------------- + +def test_status_ok_reports_only_what_was_read(service): + status, body = call("/engines/lumina/status", {"service_url": service.url}) + assert status == 200 + assert body["status"] == "ok" and body["api_version"] == "2.0" and body["can_generate"] is True + assert body["progress"] == "unknown" and body["cancel"] == "unknown" + assert "not proof" in body["note"] + + +def test_status_unknown_for_unsupported_version_without_body_echo(): + with LuminaHttpMock(version="9.9") as mock: + status, body = call("/engines/lumina/status", {"service_url": mock.url}) + clear_write_origins() + assert status == 200 and body["status"] == "unknown" and body["code"] == "unsupported_version" + assert "9.9" not in json.dumps(body) + + +def test_status_unknown_when_nothing_is_listening(): + with LuminaHttpMock() as mock: + url = mock.url + status, body = call("/engines/lumina/status", {"service_url": url}) + assert status == 200 and body["status"] == "unknown" + assert body["code"].startswith("network_") + + +def test_status_refuses_a_non_local_address(): + status, body = call("/engines/lumina/status", {"service_url": "http://8.8.8.8:8000"}) + assert status == 422 and body["error"] == "refusal" and body["code"] == "network_off_network" + + +def test_status_rejects_a_service_url_with_a_path(service): + status, body = call("/engines/lumina/status", {"service_url": service.url + "/x"}) + assert status == 422 and body["code"] == "invalid_service_url" + + +def test_status_requires_a_service_url(): + status, body = call("/engines/lumina/status", {}) + assert status == 400 and body["error"] == "invalid" + + +# -- generate: success ----------------------------------------------------------- + +@pytest.mark.parametrize("fmt,preview_id,glb_id,artifact", [ + ("3mf", "mfile", None, "mfile"), + ("png", "pngfile", "glbfile", "pngfile"), + ("glb", "pngfile", "glbfile", "glbfile"), +]) +def test_generate_writes_the_exact_bytes_as_a_new_file(tmp_path, data_dir, image, fmt, preview_id, glb_id, artifact): + before = hashlib.sha256(image.read_bytes()).hexdigest() + with LuminaHttpMock(preview_id=preview_id, glb_id=glb_id) as mock: + status, body = call("/engines/lumina/generate", request(mock, image, fmt)) + uploaded = mock.uploads[0]["bytes"] + clear_write_origins() + expected = HTTP_ARTIFACTS[artifact][1] + assert status == 200 and body["generated"] is True + assert body["kind"] == fmt + assert body["sha256"] == hashlib.sha256(expected).hexdigest() and body["size_bytes"] == len(expected) + written = data_dir / "lumina-output" / body["file_name"] + assert written.read_bytes() == expected + assert os.path.dirname(body["file_name"]) == "" + assert body["generated_by"] == "a user-configured local Lumina-compatible service (not verified)" + assert body["location_label"] == "Studio's lumina-output folder" + assert "did not watch" in body["advisory"] + assert body["progress"] == "unknown" and body["cancel"] == "unknown" + assert hashlib.sha256(image.read_bytes()).hexdigest() == before + assert sorted(p.name for p in image.parent.iterdir()) == ["synthetic.png"] + assert IMAGE_BYTES in uploaded + assert_no_path(body, tmp_path, data_dir) + + +def test_generate_into_a_chosen_folder_and_never_overwrites(tmp_path, data_dir, image): + chosen = tmp_path / "chosen" + chosen.mkdir() + with LuminaHttpMock() as mock: + s1, b1 = call("/engines/lumina/generate", request(mock, image, "png", out_dir=str(chosen))) + s2, b2 = call("/engines/lumina/generate", request(mock, image, "png", out_dir=str(chosen))) + clear_write_origins() + assert s1 == s2 == 200 + assert b1["location_label"] == "the folder you chose" + assert b1["file_name"] != b2["file_name"] + assert len(list(chosen.iterdir())) == 2 + assert_no_path(b1, tmp_path, data_dir) + assert_no_path(b2, tmp_path, data_dir) + + +def test_generate_refuses_the_images_own_folder_as_output(tmp_path, data_dir, service, image): + status, body = call("/engines/lumina/generate", request(service, image, "png", out_dir=str(image.parent))) + assert status == 400 and "other than the image's own folder" in body["message"] + assert service.requests == [] + assert_no_path(body, tmp_path, data_dir) + + +# -- generate: refusals ---------------------------------------------------------- + +@pytest.mark.parametrize("fmt", ["", "stl", "PNG", "obj", None, 3, ["png"]]) +def test_generate_refuses_an_unlisted_format_before_any_request(data_dir, service, image, fmt): + status, body = call("/engines/lumina/generate", request(service, image, fmt)) + assert status == 400 and body["error"] == "invalid" + assert "3mf, png, glb" in body["message"] + assert service.requests == [] + assert not (data_dir / "lumina-output").exists() or not list((data_dir / "lumina-output").iterdir()) + + +def test_generate_requires_a_format(data_dir, service, image): + payload = request(service, image, "png") + del payload["format"] + status, body = call("/engines/lumina/generate", payload) + assert status == 400 and "3mf, png, glb" in body["message"] + assert service.requests == [] + + +def test_generate_refuses_a_non_local_service_url(tmp_path, data_dir, image): + payload = {"service_url": "http://8.8.8.8:8000", "image_path": str(image), "lut_name": "Default", "format": "png"} + status, body = call("/engines/lumina/generate", payload) + assert status == 422 and body["code"] == "network_off_network" + assert "local network" in body["message"] or "own network" in body["message"] + assert_no_path(body, tmp_path, data_dir) + assert not (data_dir / "lumina-output").exists() or not list((data_dir / "lumina-output").iterdir()) + + +@pytest.mark.parametrize("path", [ + "\\\\server\\share\\a.png", "//server/share/a.png", "\\/server/share/a.png", + "\\\\?\\UNC\\server\\share\\a.png", "\\\\?\\C:\\a.png", "\\\\.\\pipe\\a", + "\\??\\UNC\\server\\share\\a.png", "/??/UNC/server/share/a.png", +]) +def test_generate_refuses_unc_and_device_paths_in_any_slash_style(data_dir, service, path): + status, body = call("/engines/lumina/generate", { + "service_url": service.url, "image_path": path, "lut_name": "Default", "format": "png"}) + assert status == 400 and "network or device" in body["message"] + assert service.requests == [] + + +def test_generate_refuses_a_directory_and_a_missing_file(tmp_path, data_dir, service): + for target in (tmp_path, tmp_path / "missing.png"): + status, body = call("/engines/lumina/generate", { + "service_url": service.url, "image_path": str(target), "lut_name": "Default", "format": "png"}) + assert status == 400 + assert_no_path(body, tmp_path) + assert service.requests == [] + + +def test_generate_refuses_an_oversize_image(tmp_path, data_dir, service, image, monkeypatch): + monkeypatch.setattr(routes_engines, "MAX_INPUT_BYTES", 8) + status, body = call("/engines/lumina/generate", request(service, image, "png")) + assert status == 400 and "at most" in body["message"] + assert service.requests == [] + assert_no_path(body, tmp_path, data_dir) + + +def test_generate_refuses_a_link_to_a_network_target(tmp_path, data_dir, service): + link = tmp_path / "linked.png" + try: + os.symlink("\\\\server\\share\\a.png", link) + except (OSError, NotImplementedError): + pytest.skip("symlink creation is not permitted here") + status, body = call("/engines/lumina/generate", { + "service_url": service.url, "image_path": str(link), "lut_name": "Default", "format": "png"}) + assert status == 400 and "network or device" in body["message"] + assert service.requests == [] + + +def test_generate_refuses_a_missing_or_overlong_lut(data_dir, service, image): + payload = request(service, image, "png") + del payload["lut_name"] + assert call("/engines/lumina/generate", payload)[0] == 400 + payload["lut_name"] = "x" * 257 + assert call("/engines/lumina/generate", payload)[0] == 400 + assert service.requests == [] + + +def test_generate_refuses_an_out_dir_that_is_not_a_local_folder(tmp_path, data_dir, service, image): + for target in ("\\\\server\\share", str(tmp_path / "nope"), str(image)): + status, body = call("/engines/lumina/generate", request(service, image, "png", out_dir=target)) + assert status == 400 and "output folder" in body["message"] + assert_no_path(body, tmp_path) + assert service.requests == [] + + +# -- generate: engine behaviour -------------------------------------------------- + +def test_generate_names_what_the_service_returned_when_the_format_differs(tmp_path, data_dir, image): + with LuminaHttpMock(preview_id="pngfile", glb_id=None) as mock: + status, body = call("/engines/lumina/generate", request(mock, image, "3mf")) + clear_write_origins() + assert status == 422 and body["code"] == "format_not_produced" + assert "png" in body["message"] and "Nothing was saved" in body["message"] + assert not (data_dir / "lumina-output").exists() or not list((data_dir / "lumina-output").iterdir()) + + +def test_generate_maps_engine_error_codes_without_body_echo(tmp_path, data_dir, image): + with LuminaHttpMock(version="9.9") as mock: + status, body = call("/engines/lumina/generate", request(mock, image, "png")) + clear_write_origins() + assert status == 422 and body["code"] == "unsupported_version" + assert "9.9" not in json.dumps(body) + with LuminaHttpMock(artifacts={}) as mock: + status, body = call("/engines/lumina/generate", request(mock, image, "png")) + clear_write_origins() + assert status == 422 and body["code"] == "artifact_unavailable" + assert_no_path(body, tmp_path, data_dir) + + +@pytest.mark.parametrize("locator", ["bad.id", "..%2Fx", "a b", "x" * 129]) +def test_generate_never_fetches_an_invalid_file_id(data_dir, image, locator): + with LuminaHttpMock(preview_id=locator, glb_id=None) as mock: + status, body = call("/engines/lumina/generate", request(mock, image, "png")) + fetched = [r for r in mock.requests if r[1].startswith("/api/files/")] + clear_write_origins() + assert status == 422 and body["code"] == "format_not_produced" + assert fetched == [] + + +def test_write_origin_is_revoked_after_generate(data_dir, image): + from snapstudio_core.foundation import netguard + + with LuminaHttpMock() as mock: + call("/engines/lumina/generate", request(mock, image, "png")) + assert netguard._WRITE_ORIGINS == set() + clear_write_origins() + + +@pytest.mark.skipif(sys.platform != "win32", reason="Windows path styles") +def test_generate_response_never_holds_a_windows_path(tmp_path, data_dir, image): + with LuminaHttpMock() as mock: + status, body = call("/engines/lumina/generate", request(mock, image, "png")) + clear_write_origins() + assert status == 200 + assert ":\\" not in json.dumps(body).replace("\\\\", "\\") + + +def test_link_walk_refuses_a_link_whose_target_is_a_network_path(tmp_path, monkeypatch): + """Exercised with a faked link so it runs where symlinks cannot be created.""" + import stat as stat_module + + from snapstudio_core.engines import local_input + + fake = str(tmp_path / "linked.png") + real_lstat = os.lstat + + def fake_lstat(path, *a, **k): + if os.fspath(path) == fake: + info = real_lstat(tmp_path) + return os.stat_result((stat_module.S_IFLNK | 0o777,) + tuple(info)[1:]) + return real_lstat(path, *a, **k) + + monkeypatch.setattr(os, "lstat", fake_lstat) + monkeypatch.setattr(os, "readlink", lambda p: r"\\server\share\a.png") + assert local_input.reaches_network(fake) is True + monkeypatch.setattr(os, "readlink", lambda p: str(tmp_path)) + assert local_input.reaches_network(fake) is False diff --git a/desktop/src/lib/lumina/LuminaResultCard.tsx b/desktop/src/lib/lumina/LuminaResultCard.tsx new file mode 100644 index 00000000..9cc834d9 --- /dev/null +++ b/desktop/src/lib/lumina/LuminaResultCard.tsx @@ -0,0 +1,41 @@ +import type { LuminaGenerateResponse, LuminaStatusResponse } from "./luminaApi"; + +/** The generated file, by name only. Studio shows no folder path: the label says which folder. */ +export function LuminaResultCard({ result }: { result: LuminaGenerateResponse }) { + return ( +
A new {result.kind} file was saved
+{result.advisory}
+Your original image was not changed. Studio does not slice this file; open it in your slicer to review it.
+The service answered Studio's identity check (API version {status.api_version ?? "unknown"}).
++ {status.can_generate ? "It offers the routes Studio uses." : "It does not offer every route Studio uses."} {status.note} +
+Unknown: Studio could not confirm this service.
+{status.message}
+{formatsError}
} + {chosen + ?{chosen.kind}: {chosen.meaning} Tested against: {chosen.evidence}.
+ :Studio does not guess the format: pick one from the list ({formats.map((f) => f.kind).join(", ") || "loading"}).
} +Tested only against a synthetic stand-in service. No real Lumina installation has been exercised, and Studio has not verified the service you point it at.
+{error}
} + {status &&