ODS V3 Pre-Release: Public testing and refinement ahead of the official V3 launch. Turn your PC, Mac, or Linux box into a private AI server.
Python ai-agentsamdcomfyuidockerllama-cppllmlocal-ain8nnvidiaopen-webuiragself-hostedspeech-to-textstrix-halotext-to-speechworkflow-automation
fix(installer): complete DGX reinstalls with private broker and workflow state (#8235)
Mike Bradleyf64908f1370b
diff --git a/ods/extensions/services/dashboard-api/config.py b/ods/extensions/services/dashboard-api/config.pyindex f31be6ef3..bce267a25 100644--- a/ods/extensions/services/dashboard-api/config.py+++ b/ods/extensions/services/dashboard-api/config.py@@ -671,7 +671,13 @@ def resolve_workflow_dir() -> Path:if env_dir:return Path(env_dir)canonical = Path(INSTALL_DIR) / "config" / "n8n"- if canonical.exists():+ try:+ if canonical.exists():+ return canonical+ except PermissionError:+ # Optional host configuration may belong to a different UID. Keep+ # the canonical path so the workflow endpoint can report unavailable+ # access, rather than crashing startup or selecting an empty fallback.return canonicalreturn Path(INSTALL_DIR) / "workflows"diff --git a/ods/extensions/services/dashboard-api/routers/workflows.py b/ods/extensions/services/dashboard-api/routers/workflows.pyindex fe1da8d91..4766f3b6e 100644--- a/ods/extensions/services/dashboard-api/routers/workflows.py+++ b/ods/extensions/services/dashboard-api/routers/workflows.py@@ -44,9 +44,9 @@ def _n8n_headers() -> dict[str, str]:def load_workflow_catalog() -> dict:"""Load workflow catalog from JSON file."""- if not WORKFLOW_CATALOG_FILE.exists():- return DEFAULT_WORKFLOW_CATALOGtry:+ if not WORKFLOW_CATALOG_FILE.exists():+ return DEFAULT_WORKFLOW_CATALOGwith open(WORKFLOW_CATALOG_FILE) as f:data = json.load(f)if not isinstance(data, dict):@@ -59,6 +59,12 @@ def load_workflow_catalog() -> dict:if not isinstance(categories, dict):categories = {}return {"workflows": workflows, "categories": categories}+ except PermissionError as e:+ logger.warning("Workflow catalog is not readable: %s", e)+ raise HTTPException(+ status_code=503,+ detail="Workflow catalog is unavailable. Check its access permissions.",+ ) from eexcept (json.JSONDecodeError, OSError, KeyError) as e:logger.warning("Failed to load workflow catalog from %s: %s", WORKFLOW_CATALOG_FILE, e)return DEFAULT_WORKFLOW_CATALOGdiff --git a/ods/extensions/services/dashboard-api/tests/test_workflows.py b/ods/extensions/services/dashboard-api/tests/test_workflows.pyindex c92ddcce3..fbbbf2ce4 100644--- a/ods/extensions/services/dashboard-api/tests/test_workflows.py+++ b/ods/extensions/services/dashboard-api/tests/test_workflows.py@@ -76,6 +76,78 @@ def test_workflow_executions_authenticated(test_client):# ---------------------------------------------------------------------------[email protected]("canonical_state", ["present", "missing", "denied"])+def test_resolve_workflow_dir_keeps_denied_canonical_path(monkeypatch, tmp_path, canonical_state):+ import config++ canonical = tmp_path / "config" / "n8n"+ monkeypatch.setattr(config, "INSTALL_DIR", str(tmp_path))+ monkeypatch.delenv("WORKFLOW_DIR", raising=False)+ original_exists = Path.exists++ def exists(path):+ if path == canonical:+ if canonical_state == "denied":+ raise PermissionError("private configuration directory")+ return canonical_state == "present"+ return original_exists(path)++ monkeypatch.setattr(Path, "exists", exists)+ expected = tmp_path / "workflows" if canonical_state == "missing" else canonical+ assert config.resolve_workflow_dir() == expected+++def test_resolve_workflow_dir_preserves_explicit_override(monkeypatch, tmp_path):+ import config++ override = tmp_path / "custom-workflows"+ monkeypatch.setenv("WORKFLOW_DIR", str(override))++ def unexpected_probe(_path):+ raise AssertionError("explicit workflow paths must not be probed at startup")++ monkeypatch.setattr(Path, "exists", unexpected_probe)+ assert config.resolve_workflow_dir() == override++[email protected]("failure", ["stat", "open"])[email protected]("method,path", [+ ("get", "/api/workflows"),+ ("get", "/api/workflows/categories"),+ ("post", "/api/workflows/example/enable"),+ ("post", "/api/workflows/example/disable"),+ ("delete", "/api/workflows/example"),+ ("get", "/api/workflows/example/executions"),+])+def test_workflow_catalog_denied_is_unavailable(test_client, monkeypatch, tmp_path, failure, method, path):+ import builtins+ import routers.workflows as workflows++ catalog = tmp_path / "private-catalog.json"+ catalog.write_text('{"workflows": [], "categories": {}}')+ monkeypatch.setattr(workflows, "WORKFLOW_CATALOG_FILE", catalog)+ original_exists = Path.exists+ original_open = builtins.open++ def exists(candidate):+ if candidate == catalog and failure == "stat":+ raise PermissionError(str(catalog))+ return original_exists(candidate)++ def open_file(candidate, *args, **kwargs):+ if candidate == catalog and failure == "open":+ raise PermissionError(str(catalog))+ return original_open(candidate, *args, **kwargs)++ monkeypatch.setattr(Path, "exists", exists)+ monkeypatch.setattr(builtins, "open", open_file)+ response = getattr(test_client, method)(path, headers=test_client.auth_headers)+ assert response.status_code == 503+ assert "unavailable" in response.json()["detail"]+ assert str(catalog) not in response.text+ assert "workflows" not in response.json()++def test_load_workflow_catalog_missing_file(monkeypatch):"""load_workflow_catalog returns DEFAULT_WORKFLOW_CATALOG when file does not exist."""import routers.workflows as wf_moddiff --git a/ods/get-ods.sh b/ods/get-ods.shindex 5da47d0e8..9e254ebff 100755--- a/ods/get-ods.sh+++ b/ods/get-ods.sh@@ -741,6 +741,11 @@ if [[ "$BOOTSTRAP_REINSTALL" == "true" || "$BOOTSTRAP_RECOVER_STRANDED" == "trueif [[ "$BOOTSTRAP_REINSTALL" == "true" ]]; thenlog "Removing the existing installation with the requested candidate uninstaller..."candidate_uninstall_args=(--install-dir "$INSTALL_DIR" --force)+ # A pinned older candidate can still use its strict cleanup contract.+ # New candidates retain unrecognized broker state in private custody.+ if grep -q -- '--preserve-broker-state)' "$candidate_uninstaller"; then+ candidate_uninstall_args+=(--preserve-broker-state)+ fiif [[ "$BOOTSTRAP_KEEP_MODELS" == true ]]; thencandidate_uninstall_args+=(--keep-models)fidiff --git a/ods/ods-uninstall.sh b/ods/ods-uninstall.shindex 26a83c2d2..5f6eec631 100755--- a/ods/ods-uninstall.sh+++ b/ods/ods-uninstall.sh@@ -132,6 +132,8 @@ KEEP_MODELS=falseKEEP_DATA=falseFORCE=falseNON_INTERACTIVE=false+PRESERVE_BROKER_STATE=false+PIXEL_BROKER_STATE_MODE=strictvalidate_requested_install_dir() {local target_dir="$1" target_real home_real script_real@@ -156,6 +158,7 @@ validate_requested_install_dir() {while [[ $# -gt 0 ]]; docase "$1" in--keep-models) KEEP_MODELS=true; shift ;;+ --preserve-broker-state) PRESERVE_BROKER_STATE=true; shift ;;--keep-data) KEEP_DATA=true; shift ;;--force) FORCE=true; shift ;;--non-interactive) NON_INTERACTIVE=true; shift ;;@@ -179,6 +182,8 @@ Options:--keep-models Keep models beside the install in <install>.models-backup--keep-data Keep user data (chat history, n8n workflows, etc.), backupsin .backups/, presets, and update snapshots in ~/.ods+ --preserve-broker-state With --force, retain unrecognized Linux Pixel broker+ state in private custody instead of deleting its contents--force Skip confirmation prompts--non-interactive Never prompt for sudo; require cached or passwordless sudo--install-dir Uninstall a separately located, fingerprinted ODS installation@@ -208,6 +213,17 @@ EOFesacdone+# Forced reinstalls can retain a legacy broker home instead of classifying+# unexpected distro skeleton files as safe to delete. This changes only the+# entry cleanup plan: root, parent, ownership and mount checks still apply.+if $PRESERVE_BROKER_STATE; then+ if ! $FORCE || $KEEP_DATA; then+ log_error "--preserve-broker-state requires --force without --keep-data; nothing was changed."+ exit 1+ fi+ PIXEL_BROKER_STATE_MODE=source-transition+fi+# The installer refuses root, so the install, its unit templates and Pixel# belong to the account that installed them. Under sudo, HOME and the user# become root's, and every ownership check then reports ODS's own files and@@ -395,7 +411,7 @@ if [[ "$(uname -s)" == "Linux" ]]; thenif [[ -f "$SCRIPT_DIR/lib/pixel-uninstall.sh" ]]; then# shellcheck source=lib/pixel-uninstall.sh. "$SCRIPT_DIR/lib/pixel-uninstall.sh"- if ! ODS_PIXEL_UNINSTALL_VALIDATE_ONLY=true ods_pixel_uninstall_managed "$INSTALL_DIR" "$HOME"; then+ if ! ODS_PIXEL_UNINSTALL_VALIDATE_ONLY=true ods_pixel_uninstall_managed "$INSTALL_DIR" "$HOME" "$PIXEL_BROKER_STATE_MODE"; thenlog_error "Pixel validation failed; nothing was changed"exit 1fi@@ -459,7 +475,7 @@ if [[ "$(uname -s)" == "Linux" ]]; thenif [[ -f "$SCRIPT_DIR/lib/pixel-uninstall.sh" ]]; then# shellcheck source=lib/pixel-uninstall.sh. "$SCRIPT_DIR/lib/pixel-uninstall.sh"- if ! ods_pixel_uninstall_managed "$INSTALL_DIR" "$HOME"; then+ if ! ods_pixel_uninstall_managed "$INSTALL_DIR" "$HOME" "$PIXEL_BROKER_STATE_MODE"; thenlog_error "Pixel cleanup failed; remaining installation retained"if [[ -n "${_ods_wsl_retire_helper:-}" ]]; thenlog_warn "Windows startup changes already applied for this uninstall remain in effect."diff --git a/ods/scripts/prepare-extension-manifests.py b/ods/scripts/prepare-extension-manifests.pyindex 70716e706..f16c40c2a 100644--- a/ods/scripts/prepare-extension-manifests.py+++ b/ods/scripts/prepare-extension-manifests.py@@ -10,6 +10,8 @@ This script only fixes the runtime manifest bind-mount surface:- services root: 0755- service child dirs: traversal only (add x, remove g/o w)- public manifest files (manifest.yaml/.yml/.json): 0644+ - config/: traversal only; the two bundled Dashboard catalogs: 0644+ - templates/: 0755 for enumeration; named bundled templates: 0644It validates the full scoped tree before any mutation, refuses symlinks,special files, hardlinked manifests, and wrong path types. It does not descend@@ -28,6 +30,16 @@ import sysfrom pathlib import PathMANIFEST_NAMES = ("manifest.yaml", "manifest.yml", "manifest.json")+PUBLIC_DASHBOARD_FILES = {+ "config": ("core-service-ids.json", "extensions-catalog.json"),+ "templates": (+ "ai-coding-workspace.yaml", "chat-playground.yaml", "creative-studio.yaml",+ "developer-homelab.yaml", "llm-platform.yaml", "ml-data-workshop.yaml",+ "multi-agent-laboratory.yaml", "no-code-ai-builder.yaml", "onboarding-agents.yaml",+ "onboarding-full-stack.yaml", "personal-knowledge-base.yaml",+ "private-research-hub.yaml", "voice-assistant.yaml",+ ),+}class ManifestPermissionError(Exception):@@ -173,6 +185,38 @@ def _build_plan(install_dir: Path, *, preserve_file_modes: bool = False) -> _Plaplan.add(manifest, mode)plan.manifest_count += 1+ # These source files are bundled public catalogs, not arbitrary config or+ # user templates. A single plan validates every scope before any chmod.+ for directory, names in PUBLIC_DASHBOARD_FILES.items():+ parent = install_dir / directory+ try:+ parent_stat = _require_dir(parent, f"public {directory} directory")+ except ManifestPermissionError as exc:+ if isinstance(exc.__cause__, FileNotFoundError):+ continue+ raise+ mode = 0o755 if directory == "templates" else _dir_traversal_mode(parent_stat.st_mode)+ plan.add(parent, mode)+ for name in names:+ leaf = parent / name+ try:+ leaf_stat = _require_regular_manifest(leaf)+ except ManifestPermissionError as exc:+ if isinstance(exc.__cause__, FileNotFoundError):+ continue+ raise+ mode = stat.S_IMODE(leaf_stat.st_mode)+ if preserve_file_modes:+ if mode & 0o444 != 0o444 or mode & 0o022:+ raise ManifestPermissionError(+ f"public Dashboard file is unreadable under a protected source "+ f"transaction: {leaf}; preserve the pending upgrade "+ "and resolve its source permissions before retrying"+ )+ else:+ mode = 0o644+ plan.add(leaf, mode)+return plandiff --git a/ods/tests/test-pixel-uninstall.sh b/ods/tests/test-pixel-uninstall.shindex b71d41793..8f8603c80 100755--- a/ods/tests/test-pixel-uninstall.sh+++ b/ods/tests/test-pixel-uninstall.sh@@ -1248,6 +1248,45 @@ elsefail "source rebind could not resume after custody"fi+# Stock DGX skeleton desktop entries are not ordinary private broker state.+# Strict uninstall refuses them before mutation. Forced reinstall uses the+# existing custody mode and must retain all their bytes and modes.+write_ops_fixture+mkdir -p "$OPS_STATE/.config/autostart" "$OPS_STATE/Desktop"+chmod 0755 "$OPS_STATE/.config" "$OPS_STATE/.config/autostart" "$OPS_STATE/Desktop"+printf '%s\n' '[Desktop Entry]' >"$OPS_STATE/.config/autostart/dgx-desktop-init.desktop"+printf '%s\n' 'DGX documentation shortcut' >"$OPS_STATE/Desktop/dgx-userguide.desktop"+chmod 0755 "$OPS_STATE/.config/autostart/dgx-desktop-init.desktop" "$OPS_STATE/Desktop/dgx-userguide.desktop"+if ods_pixel_uninstall_managed "$INSTALL_DIR" "$HOME_DIR"; then+ fail "strict uninstall accepted world-readable DGX skeleton state"+elif [[ -f "$OPS_STATE/.config/autostart/dgx-desktop-init.desktop" && ! -s "$SYSTEMCTL_LOG" && ! -s "$DOCKER_LOG" ]]; then+ pass "strict uninstall refuses DGX skeleton state before any service mutation"+else+ fail "strict DGX refusal changed the installation"+fi+if ODS_PIXEL_UNINSTALL_VALIDATE_ONLY=true ods_pixel_uninstall_managed "$INSTALL_DIR" "$HOME_DIR" source-transition \+ && [[ -f "$OPS_STATE/.config/autostart/dgx-desktop-init.desktop" && ! -s "$SYSTEMCTL_LOG" ]] \+ && ods_pixel_uninstall_managed "$INSTALL_DIR" "$HOME_DIR" source-transition; then+ if python3 - "$OPS_STATE" <<'PY'+import pathlib, stat, sys+root = pathlib.Path(sys.argv[1])+assert not root.exists()+holders = [p for p in root.parent.glob('.pixel-ops-broker-custody-*')+ if (p / 'state/.config/autostart/dgx-desktop-init.desktop').exists()]+assert len(holders) == 1+assert stat.S_IMODE(holders[0].stat().st_mode) == 0o700+saved = holders[0] / 'state'+desktop = saved / '.config/autostart/dgx-desktop-init.desktop'+assert desktop.read_text() == '[Desktop Entry]\n'+assert stat.S_IMODE(desktop.stat().st_mode) == 0o755+assert (saved / 'Desktop/dgx-userguide.desktop').read_text() == 'DGX documentation shortcut\n'+PY+ then pass "reinstall custody retains DGX skeleton bytes and modes after read-only validation"+ else fail "reinstall custody lost DGX skeleton state"; fi+else+ fail "reinstall custody could not retain DGX skeleton state"+fi+write_inspection_contract_fixture() {write_ops_fixturelocal file digestdiff --git a/ods/tests/test_bootstrap_reinstall_preflight.py b/ods/tests/test_bootstrap_reinstall_preflight.pyindex c43954b7d..f7861e0ad 100644--- a/ods/tests/test_bootstrap_reinstall_preflight.py+++ b/ods/tests/test_bootstrap_reinstall_preflight.py@@ -82,7 +82,7 @@ while [[ $# -gt 0 ]]; docase "$1" in--install-dir) INSTALL_DIR=$2; shift 2 ;;--keep-models) keep=true; shift ;;- --force|--non-interactive) shift ;;+ --force|--non-interactive|--preserve-broker-state) shift ;;*) exit 66 ;;esacdone@@ -94,6 +94,30 @@ rm -rf "$INSTALL_DIR"class ReinstallPreflightTests(unittest.TestCase):+ def test_older_candidate_keeps_its_strict_uninstall_contract(self):+ self.make_installed()+ older = self.root / 'older-uninstaller'+ shutil.copytree(self.repo, older)+ write(older / 'ods/ods-uninstall.sh', CANDIDATE_UNINSTALL.replace(+ '--force|--non-interactive|--preserve-broker-state)',+ '--force|--non-interactive)'), 0o755)+ self.env.update(ODS_REPO_URL=str(older), ODS_REF=self.commit(older, 'older uninstaller'))+ result, output = self.bootstrap()+ self.assertEqual(result.returncode, 0, output)+ self.assertNotIn('--preserve-broker-state', self.uninstall_args.read_text().split())+ self.assertEqual(json.loads(self.result.read_text())['model'], MODEL.hex())++ def test_broker_preservation_rejects_non_reinstall_invocations(self):+ for flags in ([], ['--force', '--keep-data']):+ with self.subTest(flags=flags):+ result = subprocess.run(+ [real('bash'), str(ROOT / 'ods-uninstall.sh'),+ '--preserve-broker-state', '--non-interactive', *flags],+ text=True, capture_output=True, timeout=15)+ self.assertNotEqual(result.returncode, 0)+ self.assertIn('requires --force without --keep-data; nothing was changed',+ result.stdout + result.stderr)+@classmethoddef setUpClass(cls):cls.fixture = tempfile.TemporaryDirectory()@@ -283,6 +307,7 @@ esacresult, output = self.bootstrap()self.assertEqual(result.returncode, 0, output)self.assertIn('--keep-models', self.uninstall_args.read_text().split())+ self.assertIn('--preserve-broker-state', self.uninstall_args.read_text().split())value = json.loads(self.result.read_text())self.assertEqual(value['args'], ['--non-interactive', '--force', '--recommended', '--pixel', '--no-bootstrap'])self.assertEqual(value['model'], MODEL.hex())diff --git a/ods/tests/test_public_extension_manifest_permissions.py b/ods/tests/test_public_extension_manifest_permissions.pyindex 68b546487..aa81e4ece 100644--- a/ods/tests/test_public_extension_manifest_permissions.py+++ b/ods/tests/test_public_extension_manifest_permissions.py@@ -109,7 +109,83 @@ def _snapshot_modes(paths: dict[str, Path]) -> dict[str, int]:return {k: _mode(v) for k, v in paths.items()}+def _make_dashboard_files(root: Path) -> dict[str, Path]:+ paths = {}+ with _Umask(0o077):+ for directory, names in _mod.PUBLIC_DASHBOARD_FILES.items():+ parent = root / directory+ parent.mkdir(exist_ok=True)+ paths[directory] = parent+ for name in names:+ leaf = parent / name+ leaf.write_text("{}", encoding="utf-8")+ paths[f"public_{directory}_{name}"] = leaf+ (root / "config/n8n").mkdir()+ for name in ("config/private.json", "config/n8n/catalog.json", "templates/custom-private.yaml"):+ leaf = root / name+ leaf.write_text("private fixture", encoding="utf-8")+ paths[f"private_{name}"] = leaf+ return paths++class PrepareExtensionManifestsTests(unittest.TestCase):+ def test_dashboard_public_scope_and_private_preservation(self) -> None:+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ paths = _make_tree(root, 0o077)+ paths.update(_make_dashboard_files(root))+ before = {key: path.read_bytes() for key, path in paths.items() if path.is_file()}+ self._run(root)+ self.assertEqual(_mode(paths["config"]), 0o711)+ self.assertEqual(_mode(paths["templates"]), 0o755)+ for key, path in paths.items():+ if key.startswith("public_"):+ self.assertEqual(_mode(path), 0o644)+ if key.startswith("private_") or key == "env":+ self.assertEqual(_mode(path), 0o600)+ self.assertEqual(_mode(root / "config/n8n"), 0o700)+ self.assertEqual({key: paths[key].read_bytes() for key in before}, before)+ self.assertEqual(self._run(root)[1], 0)++ def test_dashboard_unsafe_leaf_refused_before_any_mutation(self) -> None:+ for kind in ("symlink", "hardlink", "fifo"):+ with self.subTest(kind=kind), tempfile.TemporaryDirectory() as td:+ root = Path(td)+ paths = _make_tree(root, 0o077)+ paths.update(_make_dashboard_files(root))+ leaf = root / "config/core-service-ids.json"+ if kind == "hardlink":+ os.link(leaf, root / "linked-copy")+ else:+ leaf.unlink()+ if kind == "symlink":+ leaf.symlink_to(root / ".env")+ else:+ os.mkfifo(leaf)+ before = _snapshot_modes(paths)+ with self.assertRaises(_mod.ManifestPermissionError):+ self._run(root)+ self.assertEqual(_snapshot_modes(paths), before)++ def test_dashboard_private_protected_leaf_refused_before_mutation(self) -> None:+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ paths = _make_tree(root, 0o077)+ paths.update(_make_dashboard_files(root))+ for key, path in paths.items():+ if key.startswith("manifest_") or key.startswith("public_"):+ path.chmod(0o644)+ (root / "templates/voice-assistant.yaml").chmod(0o600)+ before = _snapshot_modes(paths)+ with self.assertRaisesRegex(_mod.ManifestPermissionError, "protected source"):+ _mod.prepare(root, preserve_file_modes=True)+ self.assertEqual(_snapshot_modes(paths), before)++ def test_dashboard_template_allowlist_matches_bundled_templates(self) -> None:+ templates = _HERE.parent.parent / "templates"+ self.assertEqual(set(_mod.PUBLIC_DASHBOARD_FILES["templates"]),+ {path.name for path in templates.glob("*.yaml")})+def test_protected_source_inventory_is_unchanged(self) -> None:spec = importlib.util.spec_from_file_location("pixel_source_upgrade", _HERE.parent.parent / "bin/pixel_source_upgrade.py"@@ -120,6 +196,10 @@ class PrepareExtensionManifestsTests(unittest.TestCase):root = Path(td) / "install"root.mkdir(mode=0o700)paths = _make_tree(root, 0o077)+ paths.update(_make_dashboard_files(root))+ for key, path in paths.items():+ if key.startswith("public_"):+ path.chmod(0o644)for name in upgrade.ROOTS:(root / name).mkdir(exist_ok=True)for key, mode in (("manifest_ape", 0o644), ("manifest_beta", 0o755),@@ -351,6 +431,7 @@ class PrepareExtensionManifestsTests(unittest.TestCase):root.mkdir()paths = _make_tree(root, 0o077)nobody = pwd.getpwnam("nobody")+ paths.update(_make_dashboard_files(root))def can_read(path):pid = os.fork()@@ -372,6 +453,11 @@ class PrepareExtensionManifestsTests(unittest.TestCase):for key in ("manifest_ape", "manifest_beta", "manifest_gamma"):self.assertTrue(can_read(paths[key]), key)self.assertFalse(can_read(paths["private_ape"]))+ for key, path in paths.items():+ if key.startswith("public_"):+ self.assertTrue(can_read(path), key)+ if key.startswith("private_") or key == "env":+ self.assertFalse(can_read(path), key)if __name__ == "__main__":