Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Preserve unrelated QNAP startup jobs during agent upgrades

pulse-triage[bot]89969b641882
diff --git a/docs/release-control/v6/internal/HIGH_RISK_RELEASE_VERIFICATION_MATRIX.md b/docs/release-control/v6/internal/HIGH_RISK_RELEASE_VERIFICATION_MATRIX.md
index 934e2aeb59..a4efa6fa66 100644
--- a/docs/release-control/v6/internal/HIGH_RISK_RELEASE_VERIFICATION_MATRIX.md
+++ b/docs/release-control/v6/internal/HIGH_RISK_RELEASE_VERIFICATION_MATRIX.md
@@ -1321,3 +1321,18 @@ as verification progresses:
- Exact-source race/vet/build and desktop/narrow consuming pixels are source qualification, not installed/native acceptance or release availability.
`TestClusterFirstUseConcurrentSelectionSharesConstruction` holds a real first-use TLS capture while eight ordinary readers join: one captured pin, one short/full login pair, independent returned readings and usable concurrent health inspection.
+
+### QNAP boot replacement preservation
+
+- `TestInstallSHQNAPBootReplacementPreservesUnrelatedJobs`: production boot
+ writer preserves unrelated tasks/comments; first/repeated writes and exact
+ legacy/current entries remain supported. Malformed/foreign/linked content,
+ pending recovery, partial rendering, copy/mode/rename failure and a source
+ change during staging leave the original intact. Boot text is parsed, never
+ executed, and credentials do not enter output.
+- The actual registration caller unmounts after a failed append and refuses
+ the persistence-success message when append or unmount fails. The existing
+ `TestInstallSHNASBootOwnersQuiesceBeforeRecoveryErasure` inventory exercises
+ removal against the production writer's output.
+- Confined source checks are not native NAS lifecycle or customer acceptance;
+ original QNAP installed-recovery dependencies remain independent.
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 37d8c32ae7..889a5599ef 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -10448,3 +10448,22 @@ agent report admission, enrollment, credential revocation and installed updater
contracts remain unchanged. The middleware exhaustion controls in
`rate_limit_journey_budget_test.go` prove bounded HTTP admission, not an agent
update, restart or recovery outcome.
+
+### QNAP upgrade boot-file ownership (27 October 2026)
+
+Agent installation and upgrade replace only complete, exact owned QNAP autorun
+entries, using the removal filter rather than substring/range deletion. Other
+startup lines and comments survive; malformed, foreign, incomplete, linked or
+unreadable content is not rewritten. The same-filesystem candidate is parsed
+without execution before replacement. Failed preparation or readback retains
+staging and recovery; a pending setup/removal recovery directory bars another
+write. Registration checks both replacement and flash unmount before claiming
+persistence, including when replacement failed after the agent was stopped.
+
+`TestInstallSHQNAPBootReplacementPreservesUnrelatedJobs` executes the production
+writer and registration caller in private ordinary-user fixtures. It covers
+first/repeated setup, exact legacy/current entries, unrelated jobs, malformed
+content, filesystem/write failures, concurrent source changes and unmount
+failure. The existing NAS removal inventory consumes the changed writer too.
+These checks establish boot-file preservation and truthful local completion,
+not a native QNAP install/reboot/update/removal or resolution of #2897/#1617.
diff --git a/docs/release-control/v6/internal/subsystems/deployment-installability.md b/docs/release-control/v6/internal/subsystems/deployment-installability.md
index 8e552d205e..e44868e8aa 100644
--- a/docs/release-control/v6/internal/subsystems/deployment-installability.md
+++ b/docs/release-control/v6/internal/subsystems/deployment-installability.md
@@ -4040,6 +4040,24 @@ artifact-selection behaviour.
## Current State
+### QNAP boot updates preserve unrelated startup work (27 October 2026)
+
+The agent installer stages a same-filesystem autorun replacement and admits
+only complete, exact Pulse entries through the existing NAS boot filter.
+Unrelated startup jobs/comments remain intact. Incomplete, foreign, linked or
+oversized input and pending setup/removal recovery stop replacement; boot text
+is syntax-checked without execution. Failed staging keeps the original and
+recovery rather than truncating the live file. Both append and flash unmount
+must succeed before persistence is reported; failure may follow an earlier
+agent stop and never triggers an automatic restart.
+
+`TestInstallSHQNAPBootReplacementPreservesUnrelatedJobs` runs the actual writer
+and registration caller with confined filesystem and manager controls. The
+existing `TestInstallSHNASBootOwnersQuiesceBeforeRecoveryErasure` also consumes
+its output. Native QNAP reboot/update/removal and #2897/#1617 recovery remain
+separate; source fixtures do not establish installed acceptance.
+
+
### Hosted chart verdict writer has no proposed executable
Build and Test's optional workload-chart evidence job retains a read-only
diff --git a/scripts/install.sh b/scripts/install.sh
index 1fe05fb7bf..49c1086f12 100755
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@ -4220,14 +4220,6 @@ write_unraid_go_entry() {
{ printf '# Pulse Agent\n'; render_unraid_go_launch "$wrapper_script"; } >> "$go_script"
}
-remove_qnap_autorun_block() {
- local autorun_path="$1"
-
- portable_sed_in_place '/^# Pulse Agent bootstrap begin$/,/^# Pulse Agent bootstrap end$/d' "$autorun_path"
- portable_sed_in_place '/^# Pulse Agent$/d' "$autorun_path"
- portable_sed_in_place '/start-pulse-agent\.sh/d' "$autorun_path"
-}
-
write_qnap_wrapper_script() {
local wrapper_script="$1"
local runtime_binary="$2"
@@ -4399,18 +4391,57 @@ EOF
append_qnap_autorun_block() {
local autorun_path="$1"
local wrapper_script="$2"
- local state_dir="$3"
-
- remove_qnap_autorun_block "$autorun_path"
- if [[ ! -f "$autorun_path" ]]; then
- echo "#!/bin/sh" > "$autorun_path"
+ local STATE_DIR="$3" parent="" staging="" prior="" observed="" existed=false
+
+ # Upgrade must use the same exact-entry admission as removal. Substring
+ # deletion also erased unrelated startup jobs and an unfinished marker
+ # erased every later line. Never evaluate the operator's boot text.
+ [[ "$STATE_DIR" == /* && "$wrapper_script" == "$STATE_DIR/start-pulse-agent.sh" &&
+ "$STATE_DIR" != *[\$\`\"\\]* && "$STATE_DIR" != *$'\n'* && "$STATE_DIR" != *$'\r'* &&
+ "$autorun_path" == /* ]] || return 1
+ parent=$(dirname "$autorun_path") || return 1
+ [[ -d "$parent" && ! -L "$parent" && "$(portable_path_uid "$parent")" == "$(id -u)" ]] || return 1
+ for prior in "$autorun_path".pulse-setup.* "$autorun_path".pulse-removal.*; do
+ [[ ! -e "$prior" && ! -L "$prior" ]] || return 1
+ done
+ if [[ -e "$autorun_path" || -L "$autorun_path" ]]; then
+ nas_agent_removal_file_safe "$autorun_path" || return 1
+ # Admit complete bounded content before copying onto small flash.
+ observed=$(filter_nas_agent_boot_file QNAP "$autorun_path" status) || return 1
+ [[ "$observed" == present || "$observed" == absent ]] || return 1
+ existed=true
+ fi
+
+ # Stage on the flash filesystem. Any failed read/filter/write/rename keeps
+ # the original and staging for reconciliation, not a blind overwrite.
+ staging=$(mktemp -d "$autorun_path.pulse-setup.XXXXXX") || return 1
+ chmod 700 "$staging" || return 1
+ if [[ "$existed" == true ]]; then
+ cp -p "$autorun_path" "$staging/original" || return 1
+ else
+ printf '#!/bin/sh\n' > "$staging/original" || return 1
+ chmod 755 "$staging/original" || return 1
+ fi
+ cp -p "$staging/original" "$staging/updated" || return 1
+ filter_nas_agent_boot_file QNAP "$staging/original" filter > "$staging/updated" || return 1
+ # Do not accumulate separator lines on every upgrade.
+ render_qnap_autorun_block "$wrapper_script" >> "$staging/updated" || return 1
+ sh -n "$staging/updated" >/dev/null 2>&1 || return 1
+ chmod +x "$staging/updated" || return 1
+ cp -p "$staging/updated" "$staging/ready" || return 1
+ if [[ "$existed" == true ]]; then
+ nas_agent_removal_file_safe "$autorun_path" && cmp -s "$autorun_path" "$staging/original" || return 1
+ mv -- "$staging/ready" "$autorun_path" || return 1
+ else
+ # FAT flash volumes need not support hard links or mv -n. Noclobber
+ # refuses a concurrent file or link; a partial first write stays visible
+ # with its complete staged copy and is never called configured.
+ (set -o noclobber; cat "$staging/ready" > "$autorun_path") || return 1
+ chmod 755 "$autorun_path" || return 1
fi
-
- printf '\n' >> "$autorun_path"
- render_qnap_autorun_block "$wrapper_script" >> "$autorun_path"
- printf '\n' >> "$autorun_path"
-
- chmod +x "$autorun_path"
+ nas_agent_removal_file_safe "$autorun_path" && cmp -s "$autorun_path" "$staging/updated" || return 1
+ rm -f -- "$staging/original" "$staging/updated" "$staging/ready" || return 1
+ rmdir -- "$staging"
}
# --- Auto-Detection Functions ---
@@ -7725,8 +7756,12 @@ if [[ -f /sbin/getcfg ]] || [[ -f /etc/config/qpkg.conf ]]; then
if [[ -x /etc/init.d/init_disk.sh ]]; then
if /etc/init.d/init_disk.sh mount_flash_config 2>/dev/null && [[ -d /tmp/nasconfig_tmp ]]; then
AUTORUN_PATH="/tmp/nasconfig_tmp/autorun.sh"
- append_qnap_autorun_block "$AUTORUN_PATH" "$WRAPPER_SCRIPT" "$STATE_DIR"
- /etc/init.d/init_disk.sh umount_flash_config 2>/dev/null || true
+ AUTORUN_RESULT=0
+ append_qnap_autorun_block "$AUTORUN_PATH" "$WRAPPER_SCRIPT" "$STATE_DIR" || AUTORUN_RESULT=1
+ /etc/init.d/init_disk.sh umount_flash_config 2>/dev/null || AUTORUN_RESULT=1
+ if [[ "$AUTORUN_RESULT" != 0 ]]; then
+ fail "QNAP boot setup was not confirmed; agent recovery files and any autorun.sh.pulse-setup staging were retained. The agent may already be stopped. Reconcile the boot file and flash mount before retrying; no automatic restart was attempted." "$EXIT_GENERAL"
+ fi
AUTORUN_CONFIGURED=true
log_info "Configured autorun.sh with a deferred Pulse Agent bootstrap."
else
diff --git a/scripts/installtests/agent_nas_teardown.py b/scripts/installtests/agent_nas_teardown.py
index 8633ef539c..3ddbe5c17f 100644
--- a/scripts/installtests/agent_nas_teardown.py
+++ b/scripts/installtests/agent_nas_teardown.py
@@ -25,7 +25,7 @@ FUNCTIONS = (
"filter_nas_agent_boot_file", "disable_nas_agent_boot_file", "nas_agent_boot_operation",
"read_nas_agent_removal_processes", "nas_agent_processes_absent", "quiesce_nas_agent_for_removal",
"confirm_nas_agent_removal_quiescent", "teardown_nas_agent_boot_owner",
- "remove_qnap_autorun_block", "render_qnap_autorun_block", "append_qnap_autorun_block",
+ "render_qnap_autorun_block", "append_qnap_autorun_block",
"render_unraid_go_launch", "write_unraid_go_entry",
)
@@ -229,10 +229,10 @@ class AgentNASTeardown(unittest.TestCase):
bootfile = root / "flash/autorun.sh" if platform == "QNAP" else root / "go"
unrelated = "#!/bin/sh\necho before\nbash /other/start-pulse-agent-prod.sh\necho pulse-agent-prod\n/boot/config/pulse/telegraf/start_telegraf.sh\n"
bootfile.write_text(unrelated)
- producer = definitions(self.source, ("portable_sed_in_place", "remove_qnap_autorun_block", "render_qnap_autorun_block", "append_qnap_autorun_block", "render_unraid_go_launch", "write_unraid_go_entry"))
+ producer = definitions(self.source, ("portable_path_uid", "nas_agent_removal_file_safe", "filter_nas_agent_boot_file", "render_qnap_autorun_block", "append_qnap_autorun_block", "render_unraid_go_launch", "write_unraid_go_entry"))
# Consume the real production boot emitters, not a second literal.
if platform == "QNAP":
- command = "AGENT_NAME=pulse-agent\nSTATE_DIR=" + shlex.quote(str(root / "state")) + "\n" + producer + "\nappend_qnap_autorun_block " + shlex.quote(str(bootfile)) + " " + shlex.quote(str(target)) + " " + shlex.quote(str(root / "state"))
+ command = "AGENT_NAME=pulse-agent BINARY_NAME=pulse-agent INSTALL_DIR=/usr/local/bin\nSTATE_DIR=" + shlex.quote(str(root / "state")) + "\n" + producer + "\nappend_qnap_autorun_block " + shlex.quote(str(bootfile)) + " " + shlex.quote(str(target)) + " " + shlex.quote(str(root / "state"))
else:
command = "AGENT_NAME=pulse-agent\n" + producer + "\nwrite_unraid_go_entry " + shlex.quote(str(bootfile)) + " " + shlex.quote(str(target)) + " " + shlex.quote(str(root / "bin/pulse-agent"))
subprocess.run(["bash", "-c", command], check=True, capture_output=True, text=True)
@@ -629,7 +629,7 @@ remove_safe_profile_state_dir() { rm -rf -- "$SAFE_PROFILE_STATE_DIR"; }
bootfile = root / 'flash/autorun.sh' if platform == 'QNAP' else root / 'go'
if platform == 'QNAP':
bootfile.write_text('#!/bin/sh\n')
- emitter = definitions(self.source, ('portable_sed_in_place', 'remove_qnap_autorun_block', 'render_qnap_autorun_block', 'append_qnap_autorun_block'))
+ emitter = definitions(self.source, ('portable_path_uid', 'nas_agent_removal_file_safe', 'filter_nas_agent_boot_file', 'render_qnap_autorun_block', 'append_qnap_autorun_block'))
render_file.write_text(setup + emitter + '\nappend_qnap_autorun_block ' + shlex.quote(str(bootfile)) + ' "$WRAPPER_SCRIPT" "$STATE_DIR"\n')
rendered = subprocess.run(['bash', str(render_file)], env=env, capture_output=True, text=True)
self.assertEqual(rendered.returncode, 0, rendered.stdout + rendered.stderr)
diff --git a/scripts/installtests/install_sh_test.go b/scripts/installtests/install_sh_test.go
index d91478a46b..acd527f5b7 100644
--- a/scripts/installtests/install_sh_test.go
+++ b/scripts/installtests/install_sh_test.go
@@ -1806,7 +1806,7 @@ func TestInstallSHUsesCanonicalQNAPBootstrapRenderer(t *testing.T) {
required := []string{
`detect_qnap_data_volume() {`,
`find_qnap_state_dir() {`,
- `remove_qnap_autorun_block() {`,
+ `filter_nas_agent_boot_file QNAP "$staging/original" filter`,
`write_qnap_wrapper_script() {`,
`append_qnap_autorun_block() {`,
`select_platform_state_dir "${QNAP_VOL}/.pulse-agent"`,
diff --git a/scripts/installtests/qnap_autorun_update.py b/scripts/installtests/qnap_autorun_update.py
new file mode 100644
index 0000000000..8d44124e99
--- /dev/null
+++ b/scripts/installtests/qnap_autorun_update.py
@@ -0,0 +1,219 @@
+#!/usr/bin/env python3
+"""Run production QNAP boot-file replacement only in private ordinary-user fixtures.
+
+No boot text, mount, service or NAS command runs. The caller test substitutes
+only the fixed flash paths and models its manager's result.
+"""
+from pathlib import Path
+import os
+import shlex
+import shutil
+import subprocess
+import tempfile
+import unittest
+
+ROOT = Path(__file__).resolve().parents[2]
+SOURCE = ROOT / 'scripts/install.sh'
+NAMES = ('portable_path_uid', 'portable_path_mode', 'nas_agent_removal_file_safe',
+ 'filter_nas_agent_boot_file', 'render_qnap_autorun_block', 'append_qnap_autorun_block')
+
+
+def definitions(source):
+ result = []
+ for name in NAMES:
+ marker = name + '() {'
+ if source.count(marker) != 1:
+ raise ValueError('missing or ambiguous production function: ' + name)
+ result.append(marker + source.split(marker, 1)[1].split('\n}\n', 1)[0] + '\n}\n')
+ return '\n'.join(result)
+
+
+class QNAPAutorunUpdate(unittest.TestCase):
+ source = SOURCE.read_text()
+
+ def setUp(self):
+ directory = tempfile.TemporaryDirectory(prefix='pulse-qnap-boot-')
+ self.addCleanup(directory.cleanup)
+ self.root = Path(directory.name)
+ for name in ('flash', 'state', 'tools'):
+ (self.root / name).mkdir(mode=0o700)
+ self.boot = self.root / 'flash/autorun.sh'
+ self.wrapper = self.root / 'state/start-pulse-agent.sh'
+ self.state = self.wrapper.parent
+ (self.state / 'token').write_text('synthetic-secret-not-for-logs')
+ self.functions = definitions(self.source)
+ self.environment = dict(os.environ, PATH=str(self.root / 'tools') + ':' + os.environ['PATH'])
+
+ def invoke(self, override=''):
+ setup = 'AGENT_NAME=pulse-agent BINARY_NAME=pulse-agent INSTALL_DIR=/usr/local/bin\n'
+ code = 'set -euo pipefail\n' + setup + self.functions + '\n' + override + '\nappend_qnap_autorun_block "$1" "$2" "$3"\n'
+ result = subprocess.run(['bash', '-c', code, '_', str(self.boot), str(self.wrapper), str(self.state)],
+ env=self.environment, capture_output=True, text=True, timeout=10)
+ self.assertNotIn('synthetic-secret-not-for-logs', result.stdout + result.stderr)
+ self.assertEqual((self.state / 'token').read_text(), 'synthetic-secret-not-for-logs')
+ self.assertFalse((self.root / 'executed').exists(), 'boot text must never execute')
+ return result
+
+ def write(self, content):
+ self.boot.write_bytes(content if isinstance(content, bytes) else content.encode())
+ self.boot.chmod(0o640)
+
+ def stub(self, name, code):
+ path = self.root / 'tools' / name
+ path.write_text('#!/bin/sh\n' + code + '\n')
+ path.chmod(0o700)
+
+ def test_first_install_then_replacement_is_idempotent(self):
+ self.assertEqual(self.invoke().returncode, 0)
+ first = self.boot.read_bytes()
+ self.assertEqual(first.count(b'# Pulse Agent bootstrap begin\n'), 1)
+ self.assertEqual(self.invoke().returncode, 0)
+ self.assertEqual(self.boot.read_bytes(), first)
+ self.assertTrue(os.access(self.boot, os.X_OK))
+ self.assertEqual(list(self.boot.parent.glob('*.pulse-setup.*')), [])
+
+ def test_unowned_comments_and_similarly_named_boot_jobs_survive(self):
+ original = '#!/bin/sh\n# Archive start-pulse-agent.sh before running other jobs\ncp /private/start-pulse-agent.sh.bak /backup/pulse-wrapper\nprintf synthetic-secret-not-for-logs\ntouch ' + shlex.quote(str(self.root / 'executed')) + '\n'
+ self.write(original)
+ result = self.invoke()
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertTrue(self.boot.read_text().startswith(original))
+ self.assertEqual(self.boot.stat().st_mode & 0o666, 0o640)
+ self.assertTrue(self.boot.stat().st_mode & 0o100)
+ self.assertEqual(self.invoke().returncode, 0)
+ self.assertTrue(self.boot.read_text().startswith(original))
+
+ def test_exact_legacy_and_duplicate_generated_entries_become_one(self):
+ self.write('#!/bin/sh\necho before\n# Pulse Agent\n"' + str(self.wrapper) + '" &\necho after\n')
+ self.assertEqual(self.invoke().returncode, 0)
+ emitted = self.boot.read_text()
+ block = '# Pulse Agent bootstrap begin' + emitted.split('# Pulse Agent bootstrap begin', 1)[1]
+ self.write(emitted + block)
+ self.assertEqual(self.invoke().returncode, 0)
+ self.assertEqual(self.boot.read_text().count('# Pulse Agent bootstrap begin\n'), 1)
+ self.assertIn('echo before\necho after\n', self.boot.read_text())
+
+ def test_malformed_unknown_and_incomplete_boot_content_is_not_rewritten(self):
+ cases = ('#!/bin/sh\n# Pulse Agent bootstrap begin\necho unrelated-nightly-job\n',
+ '#!/bin/sh\n# Pulse Agent\necho unrelated-job\n',
+ '#!/bin/sh\nsh /foreign/start-pulse-agent.sh &\n',
+ '#!/bin/sh\necho start-pulse-agent.sh\n',
+ '#!/bin/sh\necho no-final-newline',
+ '#!/bin/sh\nif true; then\n', b'#!/bin/sh\necho before\0\n',
+ '#!/bin/sh\n#' + 'x' * 1048577 + '\n')
+ for original in cases:
+ with self.subTest(size=len(original), prefix=repr(original[:50])):
+ # Retained stages deliberately bar a blind retry. Each case
+ # gets an independent path, not a removed recovery directory.
+ self.boot = self.boot.with_name('case-' + str(len(list(self.boot.parent.iterdir()))) + '.sh')
+ self.write(original)
+ before = self.boot.read_bytes()
+ result = self.invoke()
+ self.assertNotEqual(result.returncode, 0)
+ self.assertEqual(self.boot.read_bytes(), before)
+
+ def test_changed_generated_block_is_preserved_for_reconciliation(self):
+ self.assertEqual(self.invoke().returncode, 0)
+ before = self.boot.read_text().replace('_pulse_wait_max=1800', '_pulse_wait_max=999')
+ self.write(before)
+ self.assertNotEqual(self.invoke().returncode, 0)
+ self.assertEqual(self.boot.read_text(), before)
+
+ def test_linked_files_directories_and_parent_links_are_not_replaced(self):
+ other = self.root / 'other'; other.write_text('untouched\n')
+ self.boot.symlink_to(other)
+ self.assertNotEqual(self.invoke().returncode, 0)
+ self.assertTrue(self.boot.is_symlink()); self.assertEqual(other.read_text(), 'untouched\n')
+ self.boot.unlink(); self.boot.mkdir()
+ self.assertNotEqual(self.invoke().returncode, 0)
+ self.assertTrue(self.boot.is_dir())
+ self.boot.rmdir(); (self.root / 'flash').rmdir()
+ foreign = self.root / 'foreign'; foreign.mkdir()
+ (foreign / 'autorun.sh').write_text('untouched\n')
+ (self.root / 'flash').symlink_to(foreign)
+ self.assertNotEqual(self.invoke().returncode, 0)
+ self.assertEqual(self.boot.read_text(), 'untouched\n')
+
+ def test_existing_setup_or_removal_recovery_prevents_overwrite(self):
+ self.write('#!/bin/sh\necho kept\n')
+ for suffix in ('.pulse-setup.retained', '.pulse-removal.retained'):
+ with self.subTest(suffix=suffix):
+ recovery = Path(str(self.boot) + suffix); recovery.mkdir()
+ before = self.boot.read_bytes()
+ self.assertNotEqual(self.invoke().returncode, 0)
+ self.assertEqual(self.boot.read_bytes(), before)
+ recovery.rmdir()
+
+ def test_copy_mode_rename_and_validation_failures_leave_original_intact(self):
+ for command in ('cp', 'chmod', 'mv', 'sh'):
+ with self.subTest(command=command):
+ self.boot = self.boot.with_name(command + '.sh')
+ self.write('#!/bin/sh\necho kept\n'); before = self.boot.read_bytes()
+ self.stub(command, 'exit 1')
+ self.assertNotEqual(self.invoke().returncode, 0)
+ self.assertEqual(self.boot.read_bytes(), before)
+ (self.root / 'tools' / command).unlink()
+
+ def test_partial_renderer_cannot_truncate_active_boot_file(self):
+ self.write('#!/bin/sh\necho kept\n'); before = self.boot.read_bytes()
+ result = self.invoke("render_qnap_autorun_block() { if [[ -n \"${staging:-}\" && -s \"$staging/updated\" ]]; then printf partial; return 1; fi; return 0; }")
+ self.assertNotEqual(result.returncode, 0)
+ self.assertEqual(self.boot.read_bytes(), before)
+ self.assertTrue(list(self.boot.parent.glob('*.pulse-setup.*/original')))
+
+ def test_source_change_while_staging_is_not_clobbered(self):
+ self.write('#!/bin/sh\necho kept\n'); before = self.boot.read_bytes()
+ self.stub('cp', shlex.quote(shutil.which('cp')) + ' "$@" || exit $?\nif [ "$2" = ' + shlex.quote(str(self.boot)) + ' ]; then printf "# concurrent change\\n" >> "$2"; fi')
+ self.assertNotEqual(self.invoke().returncode, 0)
+ self.assertEqual(self.boot.read_bytes(), before + b'# concurrent change\n')
+
+ def test_concurrent_first_file_or_link_is_not_overwritten(self):
+ other = self.root / 'other'; other.write_text('foreign target\n')
+ for kind in ('file', 'link'):
+ with self.subTest(kind=kind):
+ self.boot = self.boot.with_name(kind + '.sh')
+ create = ('ln -s ' + shlex.quote(str(other)) + ' ' + shlex.quote(str(self.boot)) if kind == 'link'
+ else 'printf "foreign file\\n" > ' + shlex.quote(str(self.boot)))
+ self.stub('cp', shlex.quote(shutil.which('cp')) + ' "$@" || exit $?\ncase "$3" in */ready) ' + create + ';; esac')
+ self.assertNotEqual(self.invoke().returncode, 0)
+ if kind == 'link':
+ self.assertTrue(self.boot.is_symlink())
+ self.assertEqual(other.read_text(), 'foreign target\n')
+ else:
+ self.assertEqual(self.boot.read_text(), 'foreign file\n')
+ self.assertTrue(list(self.boot.parent.glob(self.boot.name + '.pulse-setup.*/updated')))
+
+ def test_unsafe_wrapper_interpolation_is_refused_without_execution(self):
+ self.write('#!/bin/sh\necho kept\n'); before = self.boot.read_bytes()
+ for name in ('dollar$dir', 'tick`dir', 'quote"dir', 'back\\dir', 'line\ndir'):
+ with self.subTest(name=name):
+ self.state = self.root / name
+ self.state.mkdir(); (self.state / 'token').write_text('synthetic-secret-not-for-logs')
+ self.wrapper = self.state / 'start-pulse-agent.sh'
+ self.assertNotEqual(self.invoke().returncode, 0)
+ self.assertEqual(self.boot.read_bytes(), before)
+
+ def test_real_registration_caller_checks_append_and_unmount_before_success(self):
+ entry = ' AUTORUN_CONFIGURED=false\n' + self.source.split(' AUTORUN_CONFIGURED=false\n', 1)[1].split(' if [[ "$AUTORUN_CONFIGURED" != true ]]; then', 1)[0]
+ mount = self.root / 'tools/init-disk'
+ entry = entry.replace('/etc/init.d/init_disk.sh', str(mount)).replace('/tmp/nasconfig_tmp', str(self.boot.parent))
+ events = self.root / 'events'
+ for fault, expected, failed in (
+ ('none', ['mount_flash_config', 'append', 'umount_flash_config', 'configured'], False),
+ ('append', ['mount_flash_config', 'append', 'umount_flash_config', 'failed'], True),
+ ('umount', ['mount_flash_config', 'append', 'umount_flash_config', 'failed'], True)):
+ with self.subTest(fault=fault):
+ events.write_text('')
+ mount.write_text('#!/bin/sh\nprintf "%s\\n" "$1" >> ' + shlex.quote(str(events)) + '\n' + ('[ "$1" != umount_flash_config ]\n' if fault == 'umount' else 'exit 0\n'))
+ mount.chmod(0o700)
+ setup = 'set -euo pipefail\nSTATE_DIR=' + shlex.quote(str(self.state)) + '\nWRAPPER_SCRIPT=' + shlex.quote(str(self.wrapper)) + '\nEXIT_GENERAL=1\n'
+ setup += 'event() { printf "%s\\n" "$1" >> ' + shlex.quote(str(events)) + '; }\n'
+ setup += 'append_qnap_autorun_block() { event append; ' + ('return 1' if fault == 'append' else 'return 0') + '; }\n'
+ setup += 'fail() { event failed; exit 1; }\nlog_info() { event configured; }\n'
+ result = subprocess.run(['bash', '-c', setup + entry], capture_output=True, text=True, timeout=5)
+ self.assertEqual(result.returncode != 0, failed, result.stderr)
+ self.assertEqual(events.read_text().splitlines(), expected)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/scripts/installtests/qnap_autorun_update_test.go b/scripts/installtests/qnap_autorun_update_test.go
new file mode 100644
index 0000000000..7719cb5700
--- /dev/null
+++ b/scripts/installtests/qnap_autorun_update_test.go
@@ -0,0 +1,27 @@
+package installtests
+
+import (
+ "context"
+ "os/exec"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestInstallSHQNAPBootReplacementPreservesUnrelatedJobs(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("Unix shell and filesystem fixture; native NAS acceptance remains separate")
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
+ defer cancel()
+ command := exec.CommandContext(ctx, "python3", repoFile("scripts", "installtests", "qnap_autorun_update.py"), "-v")
+ output, err := command.CombinedOutput()
+ if err != nil {
+ t.Fatalf("QNAP boot replacement controls: %v\n%s", err, output)
+ }
+ if !strings.Contains(string(output), "Ran 13 tests in ") ||
+ !strings.Contains(string(output), "\nOK\n") || strings.Contains(string(output), "skipped") {
+ t.Fatalf("incomplete QNAP boot replacement controls:\n%s", output)
+ }
+}