mirror of
https://github.com/kevinveenbirkenbach/computer-playbook.git
synced 2026-11-30 06:46:31 +00:00
fix(backup): make the DR-drill pull survive rsync version drift and stalls
The backup pull ssh forced-command wrapper exact-matched a fixed rsync --server flag string. rsync 3.4.x renegotiates that flag block (and our own --numeric-ids was added), so the match fell through to the reject echo, which polluted the rsync protocol stream and failed every pull with 'protocol incompatibility (code 2)'. Glob the version-dependent flags while pinning mode and destination, and reject shell metacharacters so the relaxation cannot be abused. The pull script carried no ssh/rsync timeouts and the oneshot unit inherits the 24h default start timeout, so a stalled provider hung the whole job budget. Add ssh BatchMode/ConnectTimeout/ServerAlive and rsync --timeout so a dead provider fails in seconds and the retry loop reports it. Add an integration test that routes a real rsync client through the rendered wrapper (the --numeric-ids path) and asserts the pull works and injection is rejected, so future rsync version drift fails in the suite. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d37520bb69
commit
a786c8fcd7
5 files changed
+208
-28
No files matched your search
@@ -1,4 +1,12 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Pull the newest backup generations from a remote provider via rsync.
|
||||
|
||||
Every network operation is bounded (ssh ConnectTimeout/ServerAlive, rsync
|
||||
--timeout): the systemd unit is Type=oneshot and would otherwise inherit the
|
||||
24h default start timeout, so a stalled provider must fail fast instead of
|
||||
eating the whole job budget.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import subprocess
|
||||
@@ -6,6 +14,11 @@ import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
SSH_OPTS = (
|
||||
"-o BatchMode=yes -o ConnectTimeout=30 "
|
||||
"-o ServerAliveInterval=15 -o ServerAliveCountMax=4"
|
||||
)
|
||||
|
||||
|
||||
def run_command(
|
||||
command: str,
|
||||
@@ -45,20 +58,18 @@ def pull_backups(hostname: str, backups_dir: str) -> None:
|
||||
remote_host = f"backup@{hostname}"
|
||||
print(f"host address: {remote_host}")
|
||||
|
||||
# required: machine id
|
||||
remote_machine_id = run_command(f'ssh "{remote_host}" sha256sum /etc/machine-id')[
|
||||
:64
|
||||
]
|
||||
remote_machine_id = run_command(
|
||||
f'ssh {SSH_OPTS} "{remote_host}" sha256sum /etc/machine-id'
|
||||
)[:64]
|
||||
print(f"remote machine id: {remote_machine_id}")
|
||||
|
||||
general_backup_machine_dir = f"{backups_dir}/{remote_machine_id}/"
|
||||
print(f"backup root: {backups_dir}")
|
||||
print(f"backup dir: {general_backup_machine_dir}")
|
||||
|
||||
# IMPORTANT:
|
||||
# This command MUST stay exactly like this to match ssh-wrapper.sh
|
||||
# Exception: the remote command must byte-match the ssh-wrapper.sh allowlist arm; any drift falls through to its reject echo and corrupts the session.
|
||||
remote_backup_types = run_command(
|
||||
f'ssh "{remote_host}" '
|
||||
f'ssh {SSH_OPTS} "{remote_host}" '
|
||||
f'"find {general_backup_machine_dir} -maxdepth 1 -type d -execdir basename {{}} ;"'
|
||||
).splitlines()
|
||||
print(f"backup types: {' '.join(remote_backup_types)}")
|
||||
@@ -72,7 +83,6 @@ def pull_backups(hostname: str, backups_dir: str) -> None:
|
||||
general_backup_type_dir = f"{general_backup_machine_dir}{backup_type}/"
|
||||
general_versions_dir = general_backup_type_dir
|
||||
|
||||
# Optional: local previous version (may not exist)
|
||||
local_previous_version_dir = ""
|
||||
try:
|
||||
local_previous_version_dir = run_command(
|
||||
@@ -83,9 +93,8 @@ def pull_backups(hostname: str, backups_dir: str) -> None:
|
||||
local_previous_version_dir = ""
|
||||
print(f"last local backup: {local_previous_version_dir}")
|
||||
|
||||
# Required: remote versions
|
||||
remote_backup_versions = run_command(
|
||||
f'ssh "{remote_host}" '
|
||||
f'ssh {SSH_OPTS} "{remote_host}" '
|
||||
f'"ls -d {backups_dir}/{remote_machine_id}/{backup_type}/*"'
|
||||
).splitlines()
|
||||
print(f"remote backup versions: {' '.join(remote_backup_versions)}")
|
||||
@@ -111,7 +120,8 @@ def pull_backups(hostname: str, backups_dir: str) -> None:
|
||||
Path(local_backup_destination_path).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
rsync_command = (
|
||||
f"rsync -abP --numeric-ids --delete --delete-excluded "
|
||||
f"rsync -abP --numeric-ids --delete --delete-excluded --timeout=300 "
|
||||
f'-e "ssh {SSH_OPTS}" '
|
||||
f'--rsync-path="sudo rsync" '
|
||||
f'--link-dest="{local_previous_version_dir}" '
|
||||
f'"{remote_source_path}" "{local_backup_destination_path}"'
|
||||
@@ -122,9 +132,9 @@ def pull_backups(hostname: str, backups_dir: str) -> None:
|
||||
|
||||
retry_count = 0
|
||||
max_retries = 12
|
||||
retry_delay = 300 # 5 minutes
|
||||
retry_delay = 300
|
||||
last_retry_start = 0
|
||||
max_retry_duration = 43200 # 12 hours
|
||||
max_retry_duration = 43200
|
||||
|
||||
rsync_exit_code = 1
|
||||
while retry_count < max_retries:
|
||||
@@ -134,14 +144,12 @@ def pull_backups(hostname: str, backups_dir: str) -> None:
|
||||
current_time = int(time.time())
|
||||
last_retry_duration = current_time - last_retry_start
|
||||
if last_retry_duration >= max_retry_duration:
|
||||
# keep original semantics
|
||||
print(
|
||||
"Last retry took more than 12 hours, increasing max retries to 12."
|
||||
)
|
||||
max_retries = 12
|
||||
|
||||
last_retry_start = int(time.time())
|
||||
# rsync_command is built from Ansible-templated config (host-trusted), not user input.
|
||||
rsync_exit_code = os.system(rsync_command) # noqa: S605
|
||||
|
||||
if rsync_exit_code == 0:
|
||||
|
||||
@@ -15,14 +15,18 @@ backup_types="{{ BACKUP_REPOSITORIES | join(' ') }}"
|
||||
for backup_type in $backup_types; do
|
||||
get_version_directories="ls -d {{ DIR_BACKUPS }}/$hashed_machine_id/$backup_type/*"
|
||||
last_version_directory="$($get_version_directories 2>/dev/null | tail -1)"
|
||||
rsync_command="sudo rsync --server --sender -blogDtpre.iLsfxCIvu . $last_version_directory/"
|
||||
case "$SSH_ORIGINAL_COMMAND" in
|
||||
"$get_version_directories")
|
||||
$get_version_directories
|
||||
exit $?
|
||||
;;
|
||||
"$rsync_command")
|
||||
$rsync_command
|
||||
"sudo rsync --server --sender "*" . $last_version_directory/")
|
||||
# Exception: rsync negotiates version-dependent server flags (3.4.x differs and adds --numeric-ids), so glob them instead of exact-matching a fixed string; allowlist-guard the chars so no shell metacharacter can be injected before running the client's path-constrained command.
|
||||
if printf '%s' "$SSH_ORIGINAL_COMMAND" | grep -q '[^ A-Za-z0-9./_=+:-]'; then
|
||||
echo "This command is not supported."
|
||||
exit 1
|
||||
fi
|
||||
$SSH_ORIGINAL_COMMAND
|
||||
exit $?
|
||||
;;
|
||||
esac
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
from pathlib import Path
|
||||
|
||||
PROJECT_ROOT: Path = Path(__file__).resolve().parents[4]
|
||||
@@ -0,0 +1,164 @@
|
||||
"""End-to-end guard for the backup pull ssh forced-command wrapper.
|
||||
|
||||
A real rsync client is routed through the rendered
|
||||
``roles/user-backup/templates/ssh-wrapper.sh.j2`` via a fake-ssh transport,
|
||||
reproducing the DR-drill pull path (``--server --sender`` + ``--numeric-ids``).
|
||||
|
||||
Trip-wire this test exists for: the wrapper used to exact-match a fixed rsync
|
||||
flag string, so an rsync version bump (3.4.x renegotiated the flag block) made
|
||||
the match fall through to the reject echo, which polluted the rsync protocol
|
||||
stream and killed every pull with ``protocol incompatibility (code 2)``. This
|
||||
runs against the host's actual rsync so a future version drift fails here
|
||||
instead of only in a swarm deploy.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from jinja2 import Template
|
||||
|
||||
from utils.cache.files import read_text
|
||||
|
||||
from . import PROJECT_ROOT
|
||||
|
||||
WRAPPER_TEMPLATE = (
|
||||
PROJECT_ROOT / "roles" / "user-backup" / "templates" / "ssh-wrapper.sh.j2"
|
||||
)
|
||||
BACKUP_TYPE = "backup-docker-to-local"
|
||||
VERSION = "20260101000000"
|
||||
|
||||
|
||||
def _executable(path: Path) -> None:
|
||||
path.chmod(path.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
|
||||
|
||||
|
||||
@unittest.skipUnless(
|
||||
shutil.which("rsync") and shutil.which("ssh") and shutil.which("sha256sum"),
|
||||
"rsync, ssh and sha256sum are required for the wrapper e2e test",
|
||||
)
|
||||
class TestSshWrapperRsyncE2E(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.work = Path(tempfile.mkdtemp(prefix="ssh-wrapper-e2e-"))
|
||||
self.backups = self.work / "backups"
|
||||
self.mid = self.work / "machine-id"
|
||||
self.mid.write_text("integration-test-machine-id\n")
|
||||
self.hashed = subprocess.run(
|
||||
["sha256sum", str(self.mid)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
).stdout[:64]
|
||||
|
||||
self.version_dir = self.backups / self.hashed / BACKUP_TYPE / VERSION
|
||||
(self.version_dir / "data").mkdir(parents=True)
|
||||
(self.version_dir / "data" / "file1.txt").write_text("hello-backup")
|
||||
(self.version_dir / "data" / "file2.txt").write_text("second")
|
||||
|
||||
self.wrapper = self.work / "wrapper.sh"
|
||||
rendered = Template(read_text(str(WRAPPER_TEMPLATE))).render(
|
||||
DIR_BACKUPS=str(self.backups),
|
||||
BACKUP_REPOSITORIES=[BACKUP_TYPE],
|
||||
)
|
||||
rendered = rendered.replace(
|
||||
"sha256sum /etc/machine-id", f"sha256sum {self.mid}"
|
||||
)
|
||||
self.wrapper.write_text(rendered)
|
||||
|
||||
bindir = self.work / "bin"
|
||||
bindir.mkdir()
|
||||
self.sudo_shim = bindir / "sudo"
|
||||
self.sudo_shim.write_text('#!/bin/sh\nexec "$@"\n')
|
||||
_executable(self.sudo_shim)
|
||||
self.bindir = bindir
|
||||
|
||||
self.fake_ssh = self.work / "fake-ssh"
|
||||
self.fake_ssh.write_text(
|
||||
"#!/bin/sh\n"
|
||||
"shift\n"
|
||||
f'export PATH="{bindir}:$PATH"\n'
|
||||
f'SSH_ORIGINAL_COMMAND="$*" exec sh "{self.wrapper}"\n'
|
||||
)
|
||||
_executable(self.fake_ssh)
|
||||
|
||||
def tearDown(self) -> None:
|
||||
shutil.rmtree(self.work, ignore_errors=True)
|
||||
|
||||
def _run_wrapper(self, original_command: str) -> subprocess.CompletedProcess:
|
||||
env = dict(os.environ)
|
||||
env["PATH"] = f"{self.bindir}:{env['PATH']}"
|
||||
env["SSH_ORIGINAL_COMMAND"] = original_command
|
||||
return subprocess.run(
|
||||
["sh", str(self.wrapper)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
env=env,
|
||||
check=False,
|
||||
)
|
||||
|
||||
def test_real_rsync_pull_through_wrapper(self) -> None:
|
||||
dest = self.work / "dest"
|
||||
dest.mkdir()
|
||||
result = subprocess.run(
|
||||
[
|
||||
"rsync",
|
||||
"-abP",
|
||||
"--numeric-ids",
|
||||
"--delete",
|
||||
"--delete-excluded",
|
||||
"--timeout=300",
|
||||
"-e",
|
||||
str(self.fake_ssh),
|
||||
"--rsync-path=sudo rsync",
|
||||
f"fakehost:{self.version_dir}/",
|
||||
f"{dest}/",
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
self.assertEqual(
|
||||
result.returncode,
|
||||
0,
|
||||
f"rsync pull through wrapper failed (rsync {shutil.which('rsync')}):\n"
|
||||
f"{result.stdout}\n{result.stderr}",
|
||||
)
|
||||
f1 = dest / "data" / "file1.txt"
|
||||
f2 = dest / "data" / "file2.txt"
|
||||
self.assertEqual(f1.read_text(), "hello-backup") # nocheck: cache-read
|
||||
self.assertEqual(f2.read_text(), "second") # nocheck: cache-read
|
||||
|
||||
def test_version_directory_listing(self) -> None:
|
||||
listing = self._run_wrapper(
|
||||
f"ls -d {self.backups}/{self.hashed}/{BACKUP_TYPE}/*"
|
||||
)
|
||||
self.assertEqual(listing.returncode, 0, listing.stderr)
|
||||
self.assertIn(VERSION, listing.stdout)
|
||||
|
||||
def test_injection_attempts_are_rejected(self) -> None:
|
||||
pwned = self.work / "pwned"
|
||||
cases = [
|
||||
f"sudo rsync --server --sender -x ; touch {pwned} . {self.version_dir}/",
|
||||
f"sudo rsync --server --sender -x $(touch {pwned}) . {self.version_dir}/",
|
||||
f"sudo rsync --server --sender -x `touch {pwned}` . {self.version_dir}/",
|
||||
"sudo rsync --server --sender -x . /etc/",
|
||||
]
|
||||
for cmd in cases:
|
||||
with self.subTest(command=cmd):
|
||||
result = self._run_wrapper(cmd)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("not supported", result.stdout + result.stderr)
|
||||
self.assertFalse(
|
||||
pwned.exists(),
|
||||
f"guard let a metacharacter execute: {cmd}",
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -36,6 +36,7 @@ class PullSpecificHostTests(unittest.TestCase):
|
||||
self.hash64 = "a" * 64
|
||||
self.host = "1.2.3.4"
|
||||
self.remote = f"backup@{self.host}"
|
||||
self.ssh = f'ssh {self.mod.SSH_OPTS} "{self.remote}"'
|
||||
|
||||
self.backups_dir = os.environ["INFINITO_DIR_BACKUPS"]
|
||||
self.base = f"{self.backups_dir}/{self.hash64}/"
|
||||
@@ -56,11 +57,11 @@ class PullSpecificHostTests(unittest.TestCase):
|
||||
):
|
||||
cmd = command if isinstance(command, str) else " ".join(command)
|
||||
|
||||
if cmd.startswith(f'ssh "{self.remote}" sha256sum /etc/machine-id'):
|
||||
if cmd.startswith(f"{self.ssh} sha256sum /etc/machine-id"):
|
||||
return self._completed(stdout=f"{self.hash64} /etc/machine-id\n")
|
||||
|
||||
if cmd.startswith(
|
||||
f'ssh "{self.remote}" "find {self.base} -maxdepth 1 -type d -execdir basename {{}} ;"'
|
||||
f'{self.ssh} "find {self.base} -maxdepth 1 -type d -execdir basename {{}} ;"'
|
||||
):
|
||||
return self._completed(stdout=f"{self.hash64}\n{self.backup_type}\n")
|
||||
|
||||
@@ -68,7 +69,7 @@ class PullSpecificHostTests(unittest.TestCase):
|
||||
return self._completed(stdout=self.last_local)
|
||||
|
||||
if cmd.startswith(
|
||||
f'ssh "{self.remote}" "ls -d {self.backups_dir}/{self.hash64}/{self.backup_type}/*"'
|
||||
f'{self.ssh} "ls -d {self.backups_dir}/{self.hash64}/{self.backup_type}/*"'
|
||||
):
|
||||
return self._completed(stdout=f"{self.last_remote}\n")
|
||||
|
||||
@@ -80,13 +81,13 @@ class PullSpecificHostTests(unittest.TestCase):
|
||||
cmd = command if isinstance(command, str) else " ".join(command)
|
||||
|
||||
if cmd.startswith(
|
||||
f'ssh "{self.remote}" "find {self.base} -maxdepth 1 -type d -execdir basename {{}} ;"'
|
||||
f'{self.ssh} "find {self.base} -maxdepth 1 -type d -execdir basename {{}} ;"'
|
||||
):
|
||||
raise subprocess.CalledProcessError(
|
||||
returncode=1, cmd=cmd, output="", stderr="find: error"
|
||||
)
|
||||
|
||||
if cmd.startswith(f'ssh "{self.remote}" sha256sum /etc/machine-id'):
|
||||
if cmd.startswith(f"{self.ssh} sha256sum /etc/machine-id"):
|
||||
return self._completed(stdout=f"{self.hash64} /etc/machine-id\n")
|
||||
|
||||
return self._completed(stdout="")
|
||||
@@ -96,11 +97,11 @@ class PullSpecificHostTests(unittest.TestCase):
|
||||
):
|
||||
cmd = command if isinstance(command, str) else " ".join(command)
|
||||
|
||||
if cmd.startswith(f'ssh "{self.remote}" sha256sum /etc/machine-id'):
|
||||
if cmd.startswith(f"{self.ssh} sha256sum /etc/machine-id"):
|
||||
return self._completed(stdout=f"{self.hash64} /etc/machine-id\n")
|
||||
|
||||
if cmd.startswith(
|
||||
f'ssh "{self.remote}" "find {self.base} -maxdepth 1 -type d -execdir basename {{}} ;"'
|
||||
f'{self.ssh} "find {self.base} -maxdepth 1 -type d -execdir basename {{}} ;"'
|
||||
):
|
||||
return self._completed(stdout="")
|
||||
|
||||
@@ -114,11 +115,11 @@ class PullSpecificHostTests(unittest.TestCase):
|
||||
"""
|
||||
cmd = command if isinstance(command, str) else " ".join(command)
|
||||
|
||||
if cmd.startswith(f'ssh "{self.remote}" sha256sum /etc/machine-id'):
|
||||
if cmd.startswith(f"{self.ssh} sha256sum /etc/machine-id"):
|
||||
return self._completed(stdout=f"{self.hash64} /etc/machine-id\n")
|
||||
|
||||
if cmd.startswith(
|
||||
f'ssh "{self.remote}" "find {self.base} -maxdepth 1 -type d -execdir basename {{}} ;"'
|
||||
f'{self.ssh} "find {self.base} -maxdepth 1 -type d -execdir basename {{}} ;"'
|
||||
):
|
||||
return self._completed(stdout=f"{self.hash64}\n{self.backup_type}\n")
|
||||
|
||||
@@ -126,7 +127,7 @@ class PullSpecificHostTests(unittest.TestCase):
|
||||
return self._completed(stdout=self.last_local)
|
||||
|
||||
if cmd.startswith(
|
||||
f'ssh "{self.remote}" "ls -d {self.backups_dir}/{self.hash64}/{self.backup_type}/*"'
|
||||
f'{self.ssh} "ls -d {self.backups_dir}/{self.hash64}/{self.backup_type}/*"'
|
||||
):
|
||||
return self._completed(stdout="")
|
||||
|
||||
|
||||
Reference in new issue
Block a user