Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions backend/tests/mocks/hosts/host_mocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,13 @@ class _Handler(http.server.BaseHTTPRequestHandler):
def log_message(self, *args):
pass

def parse_request(self): # noqa: D401 - record a verb that has no do_<VERB> handler (TRACE, CONNECT, extensions)
parsed = super().parse_request()
if parsed and not hasattr(self, "do_" + self.command):
server: MockHost = self.server # type: ignore[assignment]
server.requests.append({"method": self.command, "path": self.path.split("?", 1)[0], "headers": {}})
return parsed

def _send(self, status: int, body: bytes = b"", extra: dict | None = None):
self.send_response(status)
self.send_header("Content-Type", "application/json")
Expand All @@ -82,12 +89,12 @@ def do_GET(self): # noqa: N802
status, body = hit
self._send(status, json.dumps(body).encode("utf-8"))

def do_POST(self): # noqa: N802 - mocks never accept writes; a POST is recorded and refused
def do_POST(self): # noqa: N802 - mocks never accept writes; any other verb is recorded as sent and refused
server: MockHost = self.server # type: ignore[assignment]
server.requests.append({"method": "POST", "path": self.path.split("?", 1)[0], "headers": {}})
server.requests.append({"method": self.command, "path": self.path.split("?", 1)[0], "headers": {}})
self._send(405, b"{}")

do_PUT = do_DELETE = do_PATCH = do_POST
do_PUT = do_DELETE = do_PATCH = do_HEAD = do_OPTIONS = do_POST


def make_moonraker(fixture_bundle: dict, *, octoprint_compat: bool = True) -> MockHost:
Expand Down
17 changes: 17 additions & 0 deletions backend/tests/recovery/test_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,23 @@ def test_monitoring_route_refuses_public_host_and_bad_input(api):
assert api("/monitoring/history", {})[0] == 400


@pytest.mark.parametrize("port", [0, 65536, -1, 7125.5, True, "not-a-port"])
def test_monitoring_routes_reject_invalid_ports(api, port):
assert api("/monitoring/read", {"host": "127.0.0.1", "port": port})[0] == 400
assert api("/monitoring/history", {"host": "127.0.0.1", "port": port})[0] == 400


def test_monitoring_custom_loopback_port_stays_within_the_read_only_boundary(api):
mock = MockHost({"/printer/objects/query": (200, STATUS)}).start()
try:
code, _ = api("/monitoring/read", {"host": "127.0.0.1", "port": mock.server_address[1]})
requests = list(mock.requests)
finally:
mock.stop()
assert code == 200
assert [(request["method"], request["path"]) for request in requests] == [("GET", "/printer/objects/query")]


def test_malformed_monitoring_host_is_a_400_not_a_500(api):
for host in ("evil.com/path", "user@host", "http://x"):
code, _ = api("/monitoring/read", {"host": host})
Expand Down
193 changes: 193 additions & 0 deletions backend/tests/test_crosstrack_journey.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
"""Test 11: synthetic cross-track journey through route dispatch, the Prepare service and the real passport CLI.

Not covered: the HTTP transport and token, the HTTP /convert handler, /creative/prepare, the desktop UI, and a process crash or restart.
"""
from __future__ import annotations

import json
import os
import subprocess
import sys
import http.client
import socket
import struct
from pathlib import Path
import zipfile

CRLF = chr(13) + chr(10)

from snapstudio_api import ext_routes
from snapstudio_api import service
from snapstudio_core.stl_wrap import wrap_stl
from tests.mocks.hosts.host_mocks import MockHost


class _Dispatch:
def __init__(self):
self.result = None

def _send(self, status, body):
self.result = status, body


def _post(path: str, data: dict) -> tuple[int, dict]:
handler = _Dispatch()
assert ext_routes.dispatch(handler, path, data)
assert handler.result is not None
return handler.result


def _forca_project(path: Path) -> Path:
"""Add a published FOrca key to a synthetic project archive used by Prepare."""
staged = path.with_suffix(".staged.3mf")
with zipfile.ZipFile(path) as src, zipfile.ZipFile(staged, "w", zipfile.ZIP_DEFLATED) as dst:
for item in src.infolist():
data = src.read(item.filename)
if item.filename == "Metadata/project_settings.config":
settings = json.loads(data)
settings["fos_physical_nozzle_diameter"] = [0.4]
data = json.dumps(settings).encode()
dst.writestr(item, data)
staged.replace(path)
return path


def _synthetic_project(path: Path) -> Path:
"""Build a tiny geometry archive entirely from synthetic tetrahedron bytes."""
stl = path.with_suffix(".stl")
head = b"\0" * 80 + struct.pack("<I", 2)
for v1, v2, v3 in [((0, 0, 0), (10, 0, 0), (0, 10, 0)),
((0, 0, 0), (0, 10, 0), (0, 0, 10))]:
head += struct.pack("<12fH", 0, 0, 0, *v1, *v2, *v3, 0)
stl.write_bytes(head)
wrap_stl(str(stl)).save(path)
stl.unlink()
return _forca_project(path)


def test_11_cross_track_prepare_passport_checkpoint_mutation_and_read_only_restore(tmp_path, monkeypatch):
"""Exercise inspect -> Prepare -> passport CLI -> checkpoint -> mutation -> preview."""
monkeypatch.setenv("SNAPSTUDIO_DATA_DIR", str(tmp_path / "studio-data"))
monkeypatch.setenv("LOCALAPPDATA", str(tmp_path / "local"))
monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path / "xdg"))
monkeypatch.setenv("HOME", str(tmp_path / "home"))

# (a) A synthetic FOrca-tagged creative project enters via the real route dispatch.
original = _synthetic_project(tmp_path / "synthetic-project.3mf")
before = original.read_bytes()
code, inspected = _post("/creative/inspect", {"path": str(original), "format": "forcaslicer"})
assert code == 200 and inspected["origin"]["generator"] == "forcaslicer"
assert inspected["source"]["unchanged"] is True and original.read_bytes() == before

# (b) Prepare calls the same service entry used by the HTTP /convert handler.
result = service.convert(str(original), str(tmp_path))
prepared = Path(result["output_path"])
assert result["validated_ok"] is True and prepared != original and prepared.is_file()
assert original.read_bytes() == before

# (c) Build a declared original -> prepared chain and verify through the real CLI module.
code, built = _post("/passport/build", {"entries": [
{"path": str(original), "role": "original"},
{"path": str(prepared), "role": "prepared", "parents": [0]},
]})
assert code == 200 and built["passport"]
passport_file = tmp_path / "job.passport.json"
passport_file.write_text(json.dumps(built["passport"]), encoding="utf-8")
cli = subprocess.run(
[sys.executable, "-m", "u1convert.cli", "passport", "verify", str(passport_file),
"--base-dir", str(tmp_path)], cwd=Path(__file__).resolve().parents[1],
env={**os.environ, "PYTHONPATH": str(Path(__file__).resolve().parents[1])},
capture_output=True, text=True, timeout=120, check=False,
)
initial_verification = json.loads(cli.stdout)
assert cli.returncode == 0 and initial_verification["ok"] is True
assert initial_verification["verification"]["summary"]["all_intact"] is True

# (d) Checkpoint the original, the prepared copy and an additional synthetic tracked file (three files).
extra = tmp_path / "synthetic-sliced.gcode"
extra.write_text("synthetic sliced stand-in", encoding="utf-8")
code, checkpoint = _post("/recovery/checkpoint", {"workspace": {"name": "Synthetic demo"},
"files": [{"name": p.name, "path": str(p)} for p in (original, prepared, extra)],
"jobs": [{"job_id": "synthetic-job", "state": "running"}]})
assert code == 200 and checkpoint["file_count"] == 3

# (e) Mutate prepared bytes, delete an extra file, then replace the original by the same name.
prepared.write_bytes(prepared.read_bytes() + b"synthetic post-checkpoint mutation")
extra.unlink()
original.unlink()
original.write_bytes(b"different synthetic file with the same name")
cli = subprocess.run(
[sys.executable, "-m", "u1convert.cli", "passport", "verify", str(passport_file),
"--base-dir", str(tmp_path)], cwd=Path(__file__).resolve().parents[1],
env={**os.environ, "PYTHONPATH": str(Path(__file__).resolve().parents[1])},
capture_output=True, text=True, timeout=120, check=False,
)
changed_verification = json.loads(cli.stdout)
summary = changed_verification["verification"]["summary"]
assert cli.returncode == 1 and changed_verification["ok"] is False
assert summary["all_intact"] is False and summary["invalidated"]
assert all(item["bytes"] != "same" for item in changed_verification["verification"]["artifacts"])

# Monitoring is the sole network capability used here. The sentinel records every verb/path.
mock = MockHost({
"/printer/objects/query": (200, {"result": {"status": {"print_stats": {"state": "standby"}}}}),
"/server/history/list": (200, {"result": {"jobs": []}}),
}).start()
try:
for endpoint in ("/monitoring/read", "/monitoring/history"):
code, _ = _post(endpoint, {"host": "127.0.0.1", "port": mock.server_address[1]})
assert code == 200
before_restore_requests = len(mock.requests)
code, preview = _post("/recovery/restore", {})
after_restore_requests = len(mock.requests)
assert code == 200 and after_restore_requests == before_restore_requests
finally:
mock.stop()

# (f) The original path now resolves to different bytes; the prepared file changed; extra is missing.
states = {item["name"]: item["state"] for item in preview["files"]}
assert states == {original.name: "changed", prepared.name: "changed", extra.name: "missing"}
assert preview["jobs"][0] == {"job_id": "synthetic-job", "state": "interrupted", "replayed": False}
observed = [(request["method"], request["path"]) for request in mock.requests]
# Sentinel: any non-GET or unapproved GET reaches this assertion and fails the journey.
assert observed == [("GET", "/printer/objects/query"), ("GET", "/server/history/list")]



def test_11_sentinel_records_verbs_that_have_no_handler_too():
"""TRACE, CONNECT and an extension verb are unsupported by the server and must still be recorded."""
mock = MockHost({}).start()
try:
port = mock.server_address[1]
for method in ("TRACE", "CONNECT", "BREW"):
raw = socket.create_connection(("127.0.0.1", port), timeout=5)
raw.sendall(CRLF.join([f"{method} /printer/gcode/script HTTP/1.1", "Host: x",
"Connection: close", "", ""]).encode())
raw.recv(4096)
raw.close()
observed = [(request["method"], request["path"]) for request in mock.requests]
finally:
mock.stop()
assert observed == [("TRACE", "/printer/gcode/script"), ("CONNECT", "/printer/gcode/script"),
("BREW", "/printer/gcode/script")]


def test_11_sentinel_records_every_verb_it_would_have_to_reject():
"""The request sentinel used by test 11 must see HEAD, OPTIONS, write verbs and unapproved paths."""
mock = MockHost({"/printer/objects/query": (200, {"result": {}})}).start()
try:
port = mock.server_address[1]
for method, path in (("HEAD", "/printer/objects/query"), ("OPTIONS", "/printer/objects/query"),
("PUT", "/printer/objects/query"), ("DELETE", "/x"), ("POST", "/printer/print/start"),
("GET", "/printer/gcode/script")):
connection = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
connection.request(method, path)
connection.getresponse().read()
connection.close()
observed = [(request["method"], request["path"]) for request in mock.requests]
finally:
mock.stop()
assert observed == [("HEAD", "/printer/objects/query"), ("OPTIONS", "/printer/objects/query"),
("PUT", "/printer/objects/query"), ("DELETE", "/x"), ("POST", "/printer/print/start"),
("GET", "/printer/gcode/script")]
assert observed != [("GET", "/printer/objects/query"), ("GET", "/server/history/list")]
10 changes: 10 additions & 0 deletions desktop/src/lib/recovery/RecoveryPanel.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { MonitorSummary, RestorePreview } from "./RecoveryPanel";
import { isValidPort } from "./api";
import type { RestoreResult } from "./api";

const base: RestoreResult = {
Expand Down Expand Up @@ -45,3 +46,12 @@ describe("MonitorSummary", () => {
expect(renderToStaticMarkup(<MonitorSummary read={null} />)).toBe("");
});
});

describe("monitor port validation", () => {
it("accepts only whole-number ports in the TCP range", () => {
for (const value of ["1", "7125", "65535"]) expect(isValidPort(value)).toBe(true);
for (const value of ["", "0", "65536", "7125.5", "1e3", " 7125", "port"]) {
expect(isValidPort(value)).toBe(false);
}
});
});
14 changes: 14 additions & 0 deletions desktop/src/lib/recovery/RecoveryView.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { describe, expect, it } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { RecoveryView } from "./RecoveryView";

describe("RecoveryView monitoring port", () => {
it("renders a configured port field with the default and browser range", () => {
const html = renderToStaticMarkup(<RecoveryView />);
expect(html).toContain('aria-label="Configured printer port"');
expect(html).toContain('type="number"');
expect(html).toContain('min="1"');
expect(html).toContain('max="65535"');
expect(html).toContain('value="7125"');
});
});
15 changes: 11 additions & 4 deletions desktop/src/lib/recovery/RecoveryView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useEffect, useState, useSyncExternalStore } from "react";
import { RotateCcw } from "lucide-react";
import { Button } from "@/components/ui/button";
import { PageHeader } from "@/components/ui/layout";
import { legacyJobSnapshot, readMonitoring, saveCheckpoint, type MonitoringRead } from "@/lib/recovery/api";
import { isValidPort, legacyJobSnapshot, readMonitoring, saveCheckpoint, type MonitoringRead } from "@/lib/recovery/api";
import { MonitorSummary, RestorePreview } from "@/lib/recovery/RecoveryPanel";
import { getPreview, refreshPreview, registerRecoverySubscriber, subscribePreview } from "@/lib/recovery/subscriber";

Expand All @@ -13,6 +13,7 @@ export function RecoveryView() {
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState("");
const [host, setHost] = useState("");
const [port, setPort] = useState("7125");
const [monitor, setMonitor] = useState<MonitoringRead | null>(null);

// Registered through the lifecycle seam (extLifecycle), not App.tsx; app start only reads the checkpoint.
Expand All @@ -31,8 +32,9 @@ export function RecoveryView() {
finally { setBusy(false); }
};
const monitorRead = async () => {
if (!isValidPort(port)) { setMonitor(null); setMessage("Enter a port from 1 to 65535."); return; }
setBusy(true); setMessage("");
try { setMonitor(await readMonitoring(host, "7125")); }
try { setMonitor(await readMonitoring(host, port)); }
catch (error) { setMonitor(null); setMessage(error instanceof Error ? error.message : "Monitoring read failed"); }
finally { setBusy(false); }
};
Expand All @@ -52,10 +54,15 @@ export function RecoveryView() {
<section className="space-y-3 rounded-lg border border-border bg-card p-4">
<h2 className="font-semibold">Read monitoring context</h2>
<p className="text-sm text-muted-foreground">One bounded, read-only request to your configured printer host. A filename match stays unverified.</p>
<div className="flex gap-2">
<div className="flex flex-wrap gap-2">
<input aria-label="Configured printer host" className="h-9 w-64 rounded-md border border-border bg-background px-3 text-sm" placeholder="printer.local" value={host} onChange={(e) => setHost(e.target.value)} />
<Button variant="secondary" disabled={busy || !host.trim()} onClick={() => void monitorRead()}>Read status</Button>
<label className="flex items-center gap-2 text-sm" htmlFor="monitor-port">
Port
<input id="monitor-port" aria-label="Configured printer port" className="h-9 w-24 rounded-md border border-border bg-background px-3 text-sm" type="number" inputMode="numeric" min={1} max={65535} step={1} required value={port} onChange={(e) => setPort(e.target.value)} />
</label>
<Button variant="secondary" disabled={busy || !host.trim() || !isValidPort(port)} onClick={() => void monitorRead()}>Read status</Button>
</div>
{!isValidPort(port) && <p className="text-sm text-destructive" role="status">Enter a whole-number port from 1 to 65535.</p>}
<MonitorSummary read={monitor} />
</section>
</div>;
Expand Down
7 changes: 7 additions & 0 deletions desktop/src/lib/recovery/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,13 @@ export type HistoryRead = {
last_job: { filename: string | null; outcome: string } | null;
};

/** Accept only an integer port in the range the backend monitoring route allows. */
export function isValidPort(value: string): boolean {
if (!/^\d+$/.test(value)) return false;
const port = Number(value);
return Number.isInteger(port) && port >= 1 && port <= 65535;
}

export const saveCheckpoint = (body: unknown) => callExt<{ revision: number; checkpointed_at: string; file_count: number }>(
"/recovery/checkpoint", body, "Could not save the checkpoint");
export const restoreCheckpoint = () => callExt<RestoreResult>("/recovery/restore", {}, "Could not read the checkpoint");
Expand Down
4 changes: 3 additions & 1 deletion docs/internal/RECOVERY.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,6 @@ Monitoring uses two bounded, read-only GETs through `foundation.netguard.local_r

Evidence: **fixture-tested** and **mock-service-tested** (in-process loopback mock that counts requests). All names and values are synthetic. No real printer or local monitoring service was queried.

Roadmap, not a capability: the end-to-end chain (generate, inspect, compare, passport, checkpoint, terminate, restore; test 11) is not built or tested. Camera context and websocket event streams are not implemented.
Test 11 is DONE for a deterministic synthetic cross-track journey: `/creative/inspect` reads a synthetic FOrca-tagged project, Prepare writes a new file through `service.convert`, `/passport/build` records the declared original-to-prepared chain, `python -m u1convert.cli passport verify` verifies it, and `/recovery/checkpoint` records the original, the prepared copy and a stand-in third file. After mutating the prepared bytes, deleting a third tracked file, and replacing the original at the same path with different bytes, CLI verification reports the chain invalidated and restore preview reports changed/missing files. A loopback Moonraker sentinel confirms monitoring uses only its two allowed GET endpoints and restore preview adds no request. The original archive is checked unchanged after inspection and Prepare; recovery records interrupted work and does not replay it.

Test 11 does **not** cover real hardware, real generators, or generated archive formats from third-party software. It also does not cover the HTTP transport and token (routes are dispatched in-process), the HTTP `/convert` handler (it calls `service.convert` directly), `/creative/prepare`, the desktop UI, or a process crash and restart. The request sentinel observes only the one loopback mock host it was given, and a separate test shows it records HEAD, OPTIONS, write verbs and unapproved paths; a request sent to any other host would not be seen by it. All archive contents and names in the journey are synthetic. Camera context and websocket event streams are not implemented.
Loading
Loading