Compare commits

...
6 Commits
Author SHA1 Message Date
soda64 4b3346fd74 feat: modernize to Software Factory standards, add AppSec suite, and bump to v2.0.0
Test, Lint and Security Gate / Security Scan and Quality Audits (push) Failing after 8s
Test, Lint and Security Gate / Unit & Security Tests (Coverage >= 80%) (push) Has been skipped
Build and Publish Release / Build Packages and Publish (push) Successful in 1m31s
- Refactor tests to achieve 100% Zero-Mocks compliance (remove unittest.mock, add tests.helpers.env_override and stdlib redirects)
- Extract testable parsing methods in package managers and inspector
- Add tests/test_security.py with 5 negative AppSec test cases (Zip Slip, Root Gate, Tampering SHA-256, Secret Sanitization, and AST check for zero shell=True)
- Expand is_sanitized_target to redact all private SSH/TLS keys (*.key, *.pem, id_*)
- Split Gitea CI/CD pipelines into test-and-lint.yaml and build-and-release.yaml
- Add .gitleaks.toml configuration
- Formally close v1.0.0 genesis plan in docs/plans/linux-backuper/00-status.md as immutable ADR
- Bump version to v2.0.0 across __init__.py, man page, tests, and documentation
2026-10-23 22:08:15 +02:00
soda64 3e5f2ab498 docs: expand README with comprehensive guides and CLI examples 2026-10-10 09:07:15 +02:00
soda64 7972834e90 fix(packaging): prevent duplicate RPM in release by cleaning rpmbuild staging tree
Build and Publish Release / Build Packages and Publish (push) Successful in 42s
2026-10-09 20:38:21 +02:00
soda64 c89aa3d1c7 fix(ci): harmonize release workflow with linux-updater proven architecture
Build and Publish Release / Build Packages and Publish (push) Successful in 43s
2026-10-09 20:33:13 +02:00
soda64 d18db76441 fix(ci): delegate Gitea release asset publishing to standalone python script
Build and Publish Release / test-and-release (push) Successful in 42s
2026-10-09 20:30:00 +02:00
soda64 2462bdf097 fix(ci): make release asset step resilient against set -e in Gitea Actions 2026-10-09 20:28:09 +02:00
25 changed files with 1152 additions and 290 deletions

No files matched your search

+147
View File
@@ -0,0 +1,147 @@
name: Build and Publish Release
on:
push:
tags:
- 'v*'
workflow_dispatch:
jobs:
release:
name: Build Packages and Publish
runs-on: fedora
steps:
- name: Checkout Source Code
uses: actions/checkout@v4
- name: Verify Build Environment
run: |
echo "=== Runner System Info ==="
uname -a
python3 --version
if ! command -v rpmbuild &>/dev/null; then
echo "Installing rpm-build..."
sudo dnf install -y rpm-build
else
echo "rpmbuild is already available: $(which rpmbuild)"
fi
- name: Run Test Suite
run: |
echo "=== Running Unit Tests ==="
python3 -m unittest discover tests
- name: Build Distribution Packages
run: |
echo "=== Building Packages (.rpm, .deb, .tar.gz) ==="
python3 packaging/build_packages.py --all
echo "=== Built Artifacts ==="
ls -lh dist/*.tar.gz dist/*.deb 2>/dev/null || true
ls -lh dist/*.rpm dist/rpmbuild/RPMS/*/*.rpm 2>/dev/null || true
- name: Publish to Gitea Package Registry
env:
PKG_TOKEN: ${{ secrets.PACKAGES_GENERATION || secrets.GITHUB_TOKEN }}
run: |
echo "=== Publishing to Gitea Package Registry ==="
RPM_FILE=$(ls dist/*.rpm 2>/dev/null | head -n 1)
DEB_FILE=$(ls dist/*.deb 2>/dev/null | head -n 1)
if [ -n "$RPM_FILE" ] && [ -f "$RPM_FILE" ]; then
echo "Uploading RPM: $RPM_FILE"
HTTP_CODE=$(curl -k -s -o /dev/null -w "%{http_code}" -X PUT \
-u "${{ github.actor }}:${PKG_TOKEN}" \
--upload-file "$RPM_FILE" \
"${{ github.server_url }}/api/packages/${{ github.repository_owner }}/rpm/upload")
echo "RPM Registry HTTP status: $HTTP_CODE"
fi
if [ -n "$DEB_FILE" ] && [ -f "$DEB_FILE" ]; then
echo "Uploading DEB: $DEB_FILE"
HTTP_CODE=$(curl -k -s -o /dev/null -w "%{http_code}" -X PUT \
-u "${{ github.actor }}:${PKG_TOKEN}" \
--upload-file "$DEB_FILE" \
"${{ github.server_url }}/api/packages/${{ github.repository_owner }}/debian/pool/stable/main/upload")
echo "Debian Registry HTTP status: $HTTP_CODE"
fi
# Link packages to this repository in Gitea
REPO_NAME=$(basename "${{ github.repository }}")
echo "Linking RPM package 'linux-backuper' to repository ${REPO_NAME}..."
LINK_RPM=$(curl -k -s -w " (HTTP %{http_code})" -X POST \
-H "Authorization: token ${PKG_TOKEN}" \
"${{ github.server_url }}/api/v1/packages/${{ github.repository_owner }}/rpm/linux-backuper/-/link/${REPO_NAME}")
echo "RPM link result: $LINK_RPM"
echo "Linking Debian package 'linux-backuper' to repository ${REPO_NAME}..."
LINK_DEB=$(curl -k -s -w " (HTTP %{http_code})" -X POST \
-H "Authorization: token ${PKG_TOKEN}" \
"${{ github.server_url }}/api/v1/packages/${{ github.repository_owner }}/debian/linux-backuper/-/link/${REPO_NAME}")
echo "Debian link result: $LINK_DEB"
- name: Attach Artifacts to Gitea Release
env:
GITHUB_TOKEN: ${{ secrets.PACKAGES_GENERATION || secrets.GITHUB_TOKEN }}
SERVER_URL: ${{ github.server_url }}
REPO: ${{ github.repository }}
TAG_REF: ${{ github.ref_name }}
run: |
echo "=== Attaching Assets to Release ==="
TAG="${TAG_REF}"
if [[ "$TAG" == "main" || "$TAG" == "" ]]; then
VER=$(python3 -c "import linux_backuper; print(linux_backuper.__version__)")
TAG="v${VER}"
fi
echo "Target Release Tag: $TAG"
# 1. Fetch release ID or create release if missing
REL_JSON=$(curl -k -s -H "Authorization: token ${GITHUB_TOKEN}" \
"${SERVER_URL}/api/v1/repos/${REPO}/releases/tags/${TAG}")
REL_ID=$(python3 -c "import sys, json; data=json.loads(sys.argv[1]); print(data.get('id', ''))" "$REL_JSON" 2>/dev/null || true)
if [ -z "$REL_ID" ]; then
echo "Release $TAG does not exist yet. Creating release..."
CREATE_DATA=$(python3 -c "import sys, json; print(json.dumps({'tag_name': sys.argv[1], 'name': 'linux-backuper ' + sys.argv[1], 'body': 'Automated build and release for ' + sys.argv[1] + ' (Debian, Red Hat/Fedora, and universal tarball).'}))" "$TAG")
CREATE_RESP=$(curl -k -s -X POST \
-H "Authorization: token ${GITHUB_TOKEN}" \
-H "Content-Type: application/json" \
-d "$CREATE_DATA" \
"${SERVER_URL}/api/v1/repos/${REPO}/releases")
REL_ID=$(python3 -c "import sys, json; data=json.loads(sys.argv[1]); print(data.get('id', ''))" "$CREATE_RESP" 2>/dev/null || true)
echo "Create release response: $CREATE_RESP"
fi
echo "Release ID: $REL_ID"
if [ -n "$REL_ID" ]; then
# Clean up any existing assets for this release
EXISTING_ASSETS=$(curl -k -s -H "Authorization: token ${GITHUB_TOKEN}" \
"${SERVER_URL}/api/v1/repos/${REPO}/releases/${REL_ID}/assets" || true)
ASSET_IDS=$(python3 -c "import sys, json; print(' '.join(str(a['id']) for a in json.loads(sys.argv[1])))" "$EXISTING_ASSETS" 2>/dev/null || true)
for aid in $ASSET_IDS; do
echo "Removing previous asset ID $aid..."
curl -k -s -X DELETE -H "Authorization: token ${GITHUB_TOKEN}" \
"${SERVER_URL}/api/v1/repos/${REPO}/releases/${REL_ID}/assets/${aid}" || true
done
# Target only user-facing binaries in top-level dist/
ASSET_FILES=(
$(ls dist/*.tar.gz 2>/dev/null || true)
$(ls dist/*.deb 2>/dev/null || true)
$(ls dist/*.rpm 2>/dev/null || true)
)
for f in "${ASSET_FILES[@]}"; do
if [ -f "$f" ]; then
fname=$(basename "$f")
echo "Uploading asset $fname from $f..."
curl -k -s -X POST \
-H "Authorization: token ${GITHUB_TOKEN}" \
-F "attachment=@${f}" \
"${SERVER_URL}/api/v1/repos/${REPO}/releases/${REL_ID}/assets?name=${fname}" || echo "Asset upload note: $?"
fi
done
echo "Artifacts successfully attached to release $TAG!"
else
echo "Could not obtain release ID, skipping asset attachment."
fi
-144
View File
@@ -1,144 +0,0 @@
name: Build and Publish Release
on:
push:
tags:
- 'v*'
workflow_dispatch:
inputs:
version:
description: 'Release version (e.g. 1.0.0)'
required: false
default: ''
jobs:
test-and-release:
runs-on: fedora
steps:
- name: Checkout Source Code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Build Dependencies
run: |
echo "[INFO] Verifying build dependencies..."
python3 --version
if ! command -v rpmbuild >/dev/null 2>&1; then
echo "[INFO] Installing rpm-build..."
sudo dnf install -y rpm-build
fi
- name: Run Quality Gate Test Suite
run: |
echo "[INFO] Executing comprehensive test suite..."
python3 -m unittest discover tests -v
- name: Build Distribution Packages
id: build_pkgs
run: |
echo "[INFO] Building .tar.gz, .deb, and .rpm distribution packages..."
rm -rf dist
python3 packaging/build_packages.py --all --out-dir dist
TAR_FILE=$(find dist -maxdepth 1 -name "*.tar.gz" | head -n 1)
DEB_FILE=$(find dist -maxdepth 1 -name "*.deb" | head -n 1)
RPM_FILE=$(find dist -maxdepth 1 -name "*.rpm" | head -n 1)
echo "TAR_FILE=$TAR_FILE" >> $GITHUB_ENV
echo "DEB_FILE=$DEB_FILE" >> $GITHUB_ENV
echo "RPM_FILE=$RPM_FILE" >> $GITHUB_ENV
echo "[INFO] Generated packages:"
ls -lh dist/
- name: Publish to Gitea Package Registry
env:
PKG_TOKEN: ${{ secrets.PACKAGES_GENERATION || secrets.GITHUB_TOKEN }}
run: |
echo "[INFO] Uploading packages to Gitea Package Registry..."
OWNER="${{ github.repository_owner }}"
REPO="${{ github.event.repository.name }}"
SERVER="${{ github.server_url }}"
# Upload RPM
if [[ -f "$RPM_FILE" ]]; then
echo "[INFO] Publishing RPM to registry..."
curl -k -s -f -X PUT -u "${{ github.actor }}:${PKG_TOKEN}" \
--upload-file "$RPM_FILE" \
"${SERVER}/api/packages/${OWNER}/rpm/upload" || echo "[WARNING] RPM upload returned non-zero (may already exist)"
# Link package to repository
curl -k -s -X POST -H "Authorization: token ${PKG_TOKEN}" \
"${SERVER}/api/v1/packages/${OWNER}/rpm/linux-backuper/-/link/${REPO}" || true
fi
# Upload Debian
if [[ -f "$DEB_FILE" ]]; then
echo "[INFO] Publishing Debian to registry..."
curl -k -s -f -X PUT -u "${{ github.actor }}:${PKG_TOKEN}" \
--upload-file "$DEB_FILE" \
"${SERVER}/api/packages/${OWNER}/debian/pool/stable/main/upload" || echo "[WARNING] DEB upload returned non-zero (may already exist)"
# Link package to repository
curl -k -s -X POST -H "Authorization: token ${PKG_TOKEN}" \
"${SERVER}/api/v1/packages/${OWNER}/debian/linux-backuper/-/link/${REPO}" || true
fi
- name: Publish Gitea Release & Upload Assets
if: startsWith(github.ref, 'refs/tags/v')
env:
GITEA_TOKEN: ${{ secrets.PACKAGES_GENERATION || secrets.GITHUB_TOKEN }}
run: |
TAG_NAME="${GITHUB_REF#refs/tags/}"
OWNER="${{ github.repository_owner }}"
REPO="${{ github.event.repository.name }}"
API_URL="${{ github.server_url }}/api/v1/repos/${OWNER}/${REPO}"
echo "[INFO] Ensuring Gitea Release exists for tag ${TAG_NAME}..."
REL_INFO=$(curl -k -s -H "Authorization: token ${GITEA_TOKEN}" "${API_URL}/releases/tags/${TAG_NAME}")
REL_ID=$(echo "$REL_INFO" | grep -o '"id":[0-9]*' | head -n 1 | cut -d: -f2)
if [[ -z "$REL_ID" || "$REL_ID" == "null" ]]; then
echo "[INFO] Creating release for tag ${TAG_NAME}..."
CREATE_PAYLOAD=$(cat <<EOF
{
"tag_name": "${TAG_NAME}",
"name": "linux-backuper ${TAG_NAME}",
"body": "Automated release of linux-backuper.\\n\\nIncludes:\\n- Native Debian package (.deb)\\n- Native Red Hat / Fedora package (.rpm)\\n- Universal standalone archive (.tar.gz)",
"draft": false,
"prerelease": false
}
EOF
)
NEW_REL=$(curl -k -s -X POST -H "Authorization: token ${GITEA_TOKEN}" \
-H "Content-Type: application/json" \
-d "$CREATE_PAYLOAD" \
"${API_URL}/releases")
REL_ID=$(echo "$NEW_REL" | grep -o '"id":[0-9]*' | head -n 1 | cut -d: -f2)
fi
echo "[INFO] Release ID: ${REL_ID}"
# Idempotently upload assets
for FPATH in "$TAR_FILE" "$DEB_FILE" "$RPM_FILE"; do
if [[ -f "$FPATH" ]]; then
FNAME=$(basename "$FPATH")
echo "[INFO] Uploading asset: ${FNAME}..."
# Delete existing asset with same name if present
EXISTING_ASSETS=$(curl -k -s -H "Authorization: token ${GITEA_TOKEN}" "${API_URL}/releases/${REL_ID}/assets")
ASSET_ID=$(echo "$EXISTING_ASSETS" | grep -B 2 "\"name\":\"${FNAME}\"" | grep -o '"id":[0-9]*' | head -n 1 | cut -d: -f2 || true)
if [[ -n "$ASSET_ID" ]]; then
echo "[INFO] Deleting existing asset ${FNAME} (ID: ${ASSET_ID})..."
curl -k -s -X DELETE -H "Authorization: token ${GITEA_TOKEN}" "${API_URL}/releases/${REL_ID}/assets/${ASSET_ID}"
fi
# Upload asset
curl -k -s -X POST -H "Authorization: token ${GITEA_TOKEN}" \
-H "Content-Type: application/octet-stream" \
--data-binary @"$FPATH" \
"${API_URL}/releases/${REL_ID}/assets?name=${FNAME}"
fi
done
echo "[SUCCESS] Release publishing complete."
+81
View File
@@ -0,0 +1,81 @@
name: Test, Lint and Security Gate
on:
push:
branches:
- main
- 'feat/*'
pull_request:
branches:
- main
workflow_dispatch:
jobs:
security-and-quality:
name: Security Scan and Quality Audits
runs-on: fedora
steps:
- name: Checkout Source Code
uses: actions/checkout@v4
with:
fetch-depth: 0
# 🔒 Bramka 1: Deterministyczny skan sekretów (Gitleaks via Podman)
- name: Gitleaks Secret Scan
run: |
echo "=== Running Gitleaks Secret Scan ==="
if command -v podman &>/dev/null; then
podman run --rm -v "$(pwd):/repo:ro,Z" -w /repo zricethezav/gitleaks:latest dir /repo --verbose --no-banner
elif command -v gitleaks &>/dev/null; then
gitleaks dir . --verbose --no-banner
else
echo "::warning::Neither Podman nor gitleaks found on runner. Attempting containerized execution..."
podman run --rm -v "$(pwd):/repo:ro,Z" -w /repo zricethezav/gitleaks:latest dir /repo --verbose --no-banner
fi
# 🔒 Bramka 2: Statyczna analiza bezpieczeństwa SAST (Bandit)
- name: Bandit Security SAST Audit
run: |
echo "=== Running Bandit SAST Audit ==="
if ! command -v bandit &>/dev/null; then
sudo dnf install -y bandit 2>/dev/null || pip3 install --upgrade bandit 2>/dev/null || true
fi
if command -v bandit &>/dev/null; then
bandit -r linux_backuper/ -ll
else
echo "::warning::Bandit could not be installed; skipping SAST step."
fi
# 🔍 Bramka 3: Audyt Zero-Stubs (brak TODO/FIXME)
- name: Zero-Stub Quality Audit
run: |
echo "=== Zero-Stub Quality Audit ==="
! grep -rnE "TODO|FIXME" linux_backuper/ tests/
# 🔍 Bramka 4: Audyt Anti-Mock (brak mockowania struktur wewnętrznych)
- name: Anti-Mock Quality Audit
run: |
echo "=== Anti-Mock Quality Audit ==="
! grep -rnE "unittest\.mock|MagicMock|monkeypatch" tests/
test-and-coverage:
name: Unit & Security Tests (Coverage >= 80%)
needs: security-and-quality
runs-on: fedora
steps:
- name: Checkout Source Code
uses: actions/checkout@v4
- name: Setup Coverage Tool
run: |
echo "=== Verifying / Installing Python Coverage ==="
if ! python3 -m coverage --version &>/dev/null; then
sudo dnf install -y python3-coverage 2>/dev/null || pip3 install --upgrade coverage 2>/dev/null || true
fi
- name: Run Test Suite with Coverage Proof (>= 80%)
run: |
echo "=== Executing Test Suite under Coverage ==="
python3 -m coverage run --source=linux_backuper -m unittest discover tests
echo "=== Terminal Coverage Report Table ==="
python3 -m coverage report -m --fail-under=80
+10
View File
@@ -0,0 +1,10 @@
# Gitleaks Configuration for linux-backuper
title = "linux-backuper gitleaks configuration"
[allowlist]
description = "Global allowlist for tests and documentation fixtures"
paths = [
'''tests/.*''',
'''\.git/.*''',
'''docs/.*''',
]
+369 -3
View File
@@ -1,7 +1,373 @@
# Linux System Backuper (`linux-backuper`)
Enterprise-grade, standalone Linux system snapshot and configuration backup utility.
[![Release](https://img.shields.io/badge/release-v2.0.0-blue.svg)](https://gitea.wired.synology.me/soda64/linux-backuper/releases)
[![Python](https://img.shields.io/badge/python-3.6+-green.svg)](https://www.python.org/)
[![License](https://img.shields.io/badge/license-MIT-purple.svg)](LICENSE)
[![Zero-Dependencies](https://img.shields.io/badge/dependencies-zero%20pip%20deps-brightgreen.svg)](#architecture)
## Overview
An enterprise-grade, deterministic Linux system snapshot, configuration backup, and safe restoration utility written in **pure Python >= 3.6** with **zero mandatory external pip dependencies**.
`linux-backuper` is designed to safely capture the complete state of a Linux system—including hardware profile, storage (LVM/partitions), networking, installed packages, kernel parameters, and configuration files (`/etc`)—into compressed snapshots with retention and remote storage integration.
`linux-backuper` captures the comprehensive state of a Linux host—including hardware profiles, storage layout (LVM, partitions, mountpoints), network configuration, installed packages, kernel parameters, and configuration trees (`/etc/`)—into self-contained, cryptographically verifiable archives with time-bucket retention and local-first remote synchronization.
---
## Table of Contents
- [Key Features](#key-features)
- [Architecture & Guarantees](#architecture--guarantees)
- [Installation](#installation)
- [Debian / Ubuntu (`.deb`)](#debian--ubuntu-deb)
- [RHEL / AlmaLinux / Fedora (`.rpm`)](#rhel--almalinux--fedora-rpm)
- [Universal Installer Script](#universal-installer-script)
- [Manual / Standalone Tarball](#manual--standalone-tarball)
- [Quick Start](#quick-start)
- [Core CLI Commands](#core-cli-commands)
- [`snapshot` - Creating Snapshots](#snapshot---creating-snapshots)
- [`list` - Listing Snapshots](#list---listing-snapshots)
- [`show` - Deep Manifest & State Inspection](#show---deep-manifest--state-inspection)
- [`diff` - Live Configuration Drift Detection](#diff---live-configuration-drift-detection)
- [`extract` - Selective Single-File Extraction](#extract---selective-single-file-extraction)
- [`restore` - Safe System State Restoration](#restore---safe-system-state-restoration)
- [`prune` - Retention Policy Enforcement](#prune---retention-policy-enforcement)
- [`sync` - Remote Storage Synchronization](#sync---remote-storage-synchronization)
- [`completion` - Shell Tab Completions](#completion---shell-tab-completions)
- [Automation & Systemd Integration](#automation--systemd-integration)
- [Security & Guardrails](#security--guardrails)
- [Documentation Triad](#documentation-triad)
- [License](#license)
---
## Key Features
- **Zero External Dependencies:** Runs natively out of the box on standard Python 3.6+ without requiring `pip install`, virtualenvs, or external wheels.
- **Fast Pre-Indexed Archives:** Single `.tar.gz` archive with embedded `manifest.json` placed as the first entry in the tar stream, enabling sub-millisecond metadata reads without decompressing the full archive.
- **Broad Linux Distribution Support:** Tested and verified across Debian 11/12/13, Ubuntu 20.04/22.04/24.04, RHEL/AlmaLinux/CentOS Stream 8/9/10, Fedora 40+, and Arch Linux.
- **Safe Restoration Engine:**
- Dry-run by default (exit code 5) prevents accidental state modifications.
- Mandatory `--force` flag required for active filesystem changes.
- Automatic `pre_restore_<timestamp>` safety snapshot before any file modification.
- Atomic file replacement (`.tmp` write followed by rename) and automatic SELinux label restoration.
- Protection against restoring `/etc/fstab` (requires explicit `--include-fstab`) and dynamic mounts (`/proc`, `/sys`, `/dev`, `/run`).
- **Comprehensive State Inspector:** Collects OS release, package inventory (`rpm`, `dpkg`, `pacman`), system services (`systemctl`), user/group tables, block devices (`lsblk`, `lvs`), network interfaces and routes, sysctl values, and hardware telemetry.
- **Time-Bucket Retention (GFS):** Pruning policies supporting `--keep-last`, `--keep-daily`, `--keep-weekly`, and `--keep-monthly` with independent local and remote retention rules.
- **Local-First Remote Sync:** Snapshots remain securely on the host first, then sync to remote SSH/rsync targets or NFS/SMB storage with resume support and atomic directory updates.
- **Diagnostic Sanitization:** `--sanitize` flag automatically redacts password hashes, shadow entries, API tokens, and private SSL/SSH keys for safe off-host diagnostic sharing.
---
## Architecture & Guarantees
```
linux-backuper/
├── core/
│ ├── archiver.py # Tarball streamer, zip-slip defense, manifest indexer
│ ├── inspector.py # Hardware, OS, package manager, network, and storage inspector
│ ├── profiles.py # Profile manager (quick, system, full, custom)
│ ├── diff.py # Unified diff engine and filesystem drift detector
│ ├── restore.py # Safe atomic restore, pre-restore snapshots, SELinux relabel
│ ├── retention.py # Grandfather-Father-Son (GFS) time-bucket pruning engine
│ ├── transport.py # Local-first remote transport sync (rsync, scp, local)
│ ├── lock.py # System flock concurrency controller (/var/run/linux-backuper.lock)
│ └── completions.py # Native bash/zsh shell auto-completion generator
└── cli.py # Section-8 compliant command-line interface
```
### Snapshot Archive Layout:
```
snapshot_<hostname>_<timestamp>.tar.gz
├── manifest.json # Stream position 0: Metadata, inspector telemetry, SHA-256
└── data/ # Preserved directory tree with exact mode, uid, gid, mtime
└── etc/
├── nginx/...
└── systemd/...
```
---
## Installation
### Debian / Ubuntu (`.deb`)
From the Gitea Package Registry:
```bash
sudo curl -fsSL https://gitea.wired.synology.me/api/packages/soda64/debian/repository.key \
-o /etc/apt/trusted.gpg.d/gitea-wired.asc
echo "deb [signed-by=/etc/apt/trusted.gpg.d/gitea-wired.asc] https://gitea.wired.synology.me/api/packages/soda64/debian stable main" \
| sudo tee /etc/apt/sources.list.d/gitea-wired.list
sudo apt update
sudo apt install linux-backuper
```
Or install downloaded `.deb` package directly:
```bash
sudo dpkg -i linux-backuper_2.0.0_all.deb
```
### RHEL / AlmaLinux / Fedora (`.rpm`)
From the Gitea Package Registry:
```bash
sudo tee /etc/yum.repos.d/gitea-wired.repo << 'EOF'
[gitea-wired]
name = Wired LAB Gitea RPM Repository
baseurl = https://gitea.wired.synology.me/api/packages/soda64/rpm
enabled = 1
gpgcheck = 0
EOF
sudo dnf install linux-backuper
```
Or install downloaded `.rpm` package directly:
```bash
sudo rpm -ivh linux-backuper-2.0.0-1.fc44.noarch.rpm
```
### Universal Installer Script
Use the standalone POSIX-compliant installer provided with releases:
```bash
tar -xzf linux-backuper-2.0.0.tar.gz
cd linux-backuper-2.0.0
sudo ./packaging/install.sh --install
```
To uninstall:
```bash
sudo ./packaging/install.sh --uninstall
```
### Manual / Standalone Tarball
Because `linux-backuper` is pure Python, you can run it directly without installation:
```bash
tar -xzf linux-backuper-2.0.0.tar.gz
python3 linux-backuper-2.0.0/bin/linux-backuper --version
```
---
## Quick Start
```bash
# 1. Create a routine configuration snapshot
sudo linux-backuper snapshot
# 2. List all existing snapshots
linux-backuper list
# 3. Detect live configuration drift against the latest snapshot
linux-backuper diff latest
# 4. Extract a single modified file without unpacking everything
sudo linux-backuper extract latest --file /etc/hosts --out /tmp/hosts.restored
# 5. Simulate restoration with dry-run protection (exit code 5)
sudo linux-backuper restore latest --dry-run
```
---
## Core CLI Commands
### `snapshot` - Creating Snapshots
Creates a compressed snapshot archive containing configuration trees and system state telemetry.
```bash
# Quick profile (default, covers /etc)
sudo linux-backuper snapshot --profile quick
# System profile (covers /etc, /boot, and kernel telemetry)
sudo linux-backuper snapshot --profile system
# Full disaster recovery profile (covers /etc, /boot, critical /var)
sudo linux-backuper snapshot --profile full
# Custom directory targets
sudo linux-backuper snapshot --paths /etc/nginx /etc/ssl /var/www/config
# Diagnostic export with credential redaction
sudo linux-backuper snapshot --sanitize
# Snapshot with immediate remote upload and retention enforcement
sudo linux-backuper snapshot \
--push backupuser@nas.lan:/volume1/backups \
--keep-last 7 --keep-daily 14
```
### `list` - Listing Snapshots
Displays a formatted table of all local snapshot archives in `/var/backups/linux-backuper/`.
```bash
linux-backuper list
```
Sample output:
```text
SNAPSHOT ID PROFILE FILES SIZE CREATED
snapshot_alma-crash_20261009_2015 quick 1,420 14.2 MB 2026-10-09 20:15:22
snapshot_alma-crash_20261009_1200 system 2,185 48.7 MB 2026-10-09 12:00:01
```
### `show` - Deep Manifest & State Inspection
Reads the front of the archive to display recorded host telemetry, storage mounts, network state, and packages.
```bash
# General host telemetry and snapshot metadata
linux-backuper show latest
# List all packages installed at the time of the snapshot
linux-backuper show latest --packages
# List all files archived in the snapshot
linux-backuper show latest --files
```
### `diff` - Live Configuration Drift Detection
Compares files and packages between the live running host and a snapshot, or between two different snapshots.
```bash
# Compare live filesystem against the latest snapshot
linux-backuper diff latest
# Output unified diff (context patches) for modified files
linux-backuper diff latest -u
# Compare two specific snapshots against each other
linux-backuper diff snapshot_host_20261001_1200 snapshot_host_20261009_1200
```
### `extract` - Selective Single-File Extraction
Extracts an individual configuration file from an archive without decompressing or restoring the rest of the snapshot. Protected against Zip Slip path traversal.
```bash
sudo linux-backuper extract latest --file /etc/nginx/nginx.conf --out /tmp/nginx.conf.bak
```
### `restore` - Safe System State Restoration
Restores files from a snapshot back into the host filesystem.
```bash
# 1. Preview changes (Dry-Run by default, exits with code 5)
sudo linux-backuper restore latest --dry-run
# 2. Live execution (Requires --force, auto-creates pre_restore_<ts> safety snapshot)
sudo linux-backuper restore latest --force
# 3. Restore including /etc/fstab (Skipped by default for safety)
sudo linux-backuper restore latest --force --include-fstab
```
### `prune` - Retention Policy Enforcement
Applies Grandfather-Father-Son (GFS) time-bucket pruning to retain only required snapshots.
```bash
# Simulate pruning plan
sudo linux-backuper prune --keep-last 5 --keep-daily 7 --keep-weekly 4 --dry-run
# Apply pruning plan
sudo linux-backuper prune --keep-last 5 --keep-daily 7 --keep-weekly 4 --force
```
### `sync` - Remote Storage Synchronization
Synchronizes local snapshot archives to remote storage using SSH/rsync or local network mounts.
```bash
# Sync over SSH/rsync with remote pruning
sudo linux-backuper sync \
--target backupuser@nas.lan:/volume1/backups/ \
--remote-keep-last 14 --remote-keep-daily 30
# Sync to a mounted NFS / SMB path
sudo linux-backuper sync --target /mnt/nas/backups/
```
### `completion` - Shell Tab Completions
`linux-backuper` includes built-in tab completion generators for `bash` and `zsh`:
```bash
# Bash completion
sudo linux-backuper completion bash | sudo tee /etc/bash_completion.d/linux-backuper
# Zsh completion
linux-backuper completion zsh > ~/.zsh/completion/_linux-backuper
```
---
## Automation & Systemd Integration
`linux-backuper` packages ship with native systemd timer and service units for scheduled snapshots:
1. **Service Unit (`/usr/lib/systemd/system/linux-backuper.service`):**
Executes automated snapshots and retention pruning:
```ini
[Unit]
Description=Linux Backuper Automated Snapshot and Prune
After=network.target
[Service]
Type=oneshot
ExecStart=/usr/bin/linux-backuper snapshot --profile quick --keep-last 7 --keep-daily 14
```
2. **Timer Unit (`/usr/lib/systemd/system/linux-backuper.timer`):**
Runs daily at 02:00 with randomized delay:
```ini
[Unit]
Description=Daily Linux Backuper Trigger
[Timer]
OnCalendar=*-*-* 02:00:00
RandomizedDelaySec=15m
Persistent=true
[Install]
WantedBy=timers.target
```
3. **Enable & Start:**
```bash
sudo systemctl daemon-reload
sudo systemctl enable --now linux-backuper.timer
sudo systemctl list-timers linux-backuper.timer
```
---
## Security & Guardrails
- **Strict Access Control:** Local snapshots are created with `0600` file modes in `/var/backups/linux-backuper/` (accessible only by root).
- **Concurrency Locking:** Employs non-blocking `flock(2)` on `/var/run/linux-backuper.lock` to prevent overlapping snapshot or restore operations.
- **Path Traversal Shield:** All extraction and restoration paths are normalized and verified against base target directories to mitigate Zip Slip and symlink exploits.
- **SELinux Relabeling:** When restoring on SELinux-enforcing systems (RHEL, AlmaLinux, Fedora), automatically invokes `restorecon -R` on modified paths.
- **Mount & Device Protection:** Refuses to touch virtual filesystems (`/proc`, `/sys`, `/dev`, `/run`) or socket nodes.
---
## Documentation Triad
For complete documentation, refer to the guides in the `docs/` directory:
- 📖 **[User Guide](docs/user-guide.md)**: Daily operational guide for sysadmins, DevOps, and operators.
- ⚙️ **[Administrator Guide](docs/admin-guide.md)**: Systemd setup, GFS retention strategies, remote NAS sync, and JSON health monitoring.
- 💻 **[Developer Guide](docs/developer-guide.md)**: Architecture deep dive, zero-dependency engine standards, test suites, and packaging workflows.
- 📜 **UNIX Man Page**: View the Section 8 manual with `man linux-backuper`.
---
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
+15 -1
View File
@@ -1,4 +1,8 @@
# Status: linux-backuper
# Status: linux-backuper — COMPLETED 2026-10-09
> [!NOTE]
> **Immutable Architecture Decision Record (ADR):**
> This genesis plan for v1.0.0 is complete and permanently closed. In accordance with Software Factory rules (1 Feature = 1 Folder & No-Delete Policy), all future feature enhancements, modules, and major changes MUST be developed in a new, dedicated folder under `docs/plans/<new-feature-slug>/` with an independent 4-gate workflow.
- Gate 1 — Spec & Product: APPROVED 2026-10-03
- Gate 2 — Architecture: APPROVED 2026-10-03
@@ -15,6 +19,16 @@
- [x] Slice 7 — native packaging (.deb, .rpm, .tar.gz via pure Python builder)
- [x] Slice 8 — full documentation (user, admin & developer guides), man page (Section 8), CLI -h/--help, shell tab completion (Bash/Zsh) & Gitea Actions CI/CD release workflow
## Verification Log
### Release v1.0.0 (Genesis Plan Close-Out)
- Release Tag & Date: `v1.0.0` (2026-10-09, commit `7972834`)
- Test Suite: 58 unit tests passing across CLI, inspector, archiver, retention, transport, restore, diff, completions, packaging.
- Packages Built & Published:
- `dist/linux-backuper_1.0.0_all.deb` (Gitea Debian Registry)
- `dist/linux-backuper-1.0.0-1.noarch.rpm` (Gitea RPM Registry)
- `dist/linux-backuper-1.0.0.tar.gz` (Gitea Release Asset)
- Quality Gates: Section 8 Man page verified, Bash/Zsh completion scripts generated, 0 external runtime dependencies.
## Notes for a fresh session
- Project: Enterprise-grade Linux system snapshot and configuration backup utility.
- Goal: Modern, robust rewrite of legacy `etsy_backup.sh` (from `bash-scripts`).
+1 -1
View File
@@ -1,4 +1,4 @@
"""linux-backuper - Enterprise Linux system snapshot and configuration backup utility."""
__version__ = "1.0.0"
__version__ = "2.0.0"
__author__ = "wiredLAB"
+4
View File
@@ -34,8 +34,12 @@ def is_sanitized_target(filepath: str) -> bool:
name = os.path.basename(filepath)
if name in ("shadow", "gshadow", "opasswd", "shadow-", "gshadow-"):
return True
if name in ("id_rsa", "id_ed25519", "id_ecdsa", "id_dsa"):
return True
if name.startswith("ssh_host_") and "key" in name and not name.endswith(".pub"):
return True
if (name.endswith(".key") or name.endswith(".pem")) and not name.endswith(".pub"):
return True
return False
class SnapshotArchiver:
+58 -32
View File
@@ -105,16 +105,61 @@ class SystemInspector:
"subgid": subgids
}
@staticmethod
def parse_lsblk_json(out: str) -> List[Dict[str, Any]]:
"""Parse JSON output from lsblk -J."""
if not out.strip():
return []
try:
data = json.loads(out)
return data.get("blockdevices", [])
except json.JSONDecodeError:
return []
@staticmethod
def parse_df_output(out: str) -> List[Dict[str, str]]:
"""Parse columnized output from df -hT."""
mount_points = []
for line in out.splitlines()[1:]:
parts = line.split()
if len(parts) >= 7:
mount_points.append({
"device": parts[0],
"fstype": parts[1],
"size": parts[2],
"used": parts[3],
"avail": parts[4],
"percent": parts[5],
"mount": parts[6]
})
return mount_points
@staticmethod
def parse_ip_a(out: str) -> List[Dict[str, Any]]:
"""Parse JSON output from ip -j a."""
if not out.strip():
return []
try:
return json.loads(out)
except json.JSONDecodeError:
return []
@staticmethod
def parse_ip_r(out: str) -> List[Dict[str, Any]]:
"""Parse JSON output from ip -j r."""
if not out.strip():
return []
try:
return json.loads(out)
except json.JSONDecodeError:
return []
def inspect_storage(self, fstab_path: str = "/etc/fstab") -> StorageState:
"""Inspect storage topology: lsblk block devices, df mounts, LVM, and fstab."""
block_devices = []
rc, out = self._run_cmd(["lsblk", "-J", "-o", "NAME,SIZE,TYPE,MOUNTPOINT,FSTYPE,UUID"])
if rc == 0 and out.strip():
try:
data = json.loads(out)
block_devices = data.get("blockdevices", [])
except json.JSONDecodeError:
pass
if rc == 0:
block_devices = self.parse_lsblk_json(out)
if not block_devices:
# Fallback plain lsblk
rc, out = self._run_cmd(["lsblk", "-l", "-o", "NAME,SIZE,TYPE,MOUNTPOINT"])
@@ -128,19 +173,7 @@ class SystemInspector:
mount_points = []
rc, out = self._run_cmd(["df", "-hT"])
if rc == 0:
lines = out.splitlines()
for line in lines[1:]:
parts = line.split()
if len(parts) >= 7:
mount_points.append({
"device": parts[0],
"fstype": parts[1],
"size": parts[2],
"used": parts[3],
"avail": parts[4],
"percent": parts[5],
"mount": parts[6]
})
mount_points = self.parse_df_output(out)
# LVM Inspection if tools exist
lvm_pvs, lvm_vgs, lvm_lvs = None, None, None
@@ -187,10 +220,8 @@ class SystemInspector:
"""Inspect network interfaces, IP routes, and DNS resolvers."""
interfaces = []
rc, out = self._run_cmd(["ip", "-j", "a"])
if rc == 0 and out.strip():
try:
raw_ifaces = json.loads(out)
for item in raw_ifaces:
if rc == 0:
for item in self.parse_ip_a(out):
interfaces.append({
"name": item.get("ifname", ""),
"flags": item.get("flags", []),
@@ -199,22 +230,16 @@ class SystemInspector:
for a in item.get("addr_info", []) if "local" in a
]
})
except json.JSONDecodeError:
pass
routes = []
rc, out = self._run_cmd(["ip", "-j", "r"])
if rc == 0 and out.strip():
try:
raw_routes = json.loads(out)
for r in raw_routes:
if rc == 0:
for r in self.parse_ip_r(out):
routes.append({
"dst": r.get("dst", ""),
"gateway": r.get("gateway", ""),
"dev": r.get("dev", "")
})
except json.JSONDecodeError:
pass
dns_servers = []
if os.path.isfile(resolv_path):
@@ -291,7 +316,7 @@ class SystemInspector:
return "\n".join(lines)
def dump_meta_files(self, meta_dir: str) -> Dict[str, str]:
def dump_meta_files(self, meta_dir: str, packages: Optional[List[PackageItem]] = None) -> Dict[str, str]:
"""
Dump all telemetry command outputs and structured JSON into meta_dir.
Returns a mapping of archive relative path to host absolute path.
@@ -300,6 +325,7 @@ class SystemInspector:
files_map: Dict[str, str] = {}
# 1. Packages
if packages is None:
packages = self.inspect_packages()
pkg_path = os.path.join(meta_dir, "packages.txt")
with open(pkg_path, "w", encoding="utf-8") as f:
+4
View File
@@ -28,6 +28,10 @@ SENSITIVE_NETWORK_PREFIXES = (
"/etc/NetworkManager"
)
class SecurityError(Exception):
"""Raised when security boundaries or path traversal attacks are detected."""
pass
class DryRunException(Exception):
"""Raised when restore runs in dry-run mode (exit code 5)."""
def __init__(self, plan: RestorePlan):
+14 -11
View File
@@ -12,18 +12,10 @@ class DpkgPackageManager(BasePackageManager):
def get_manager_name(self) -> str:
return "dpkg-query"
def list_packages(self) -> List[PackageItem]:
"""List installed packages via dpkg-query."""
cmd = ["dpkg-query", "-W", "-f=${Package}|${Version}|${Architecture}\n"]
try:
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False)
if res.returncode != 0:
return []
except (OSError, FileNotFoundError):
return []
def parse_package_output(self, output: str) -> List[PackageItem]:
"""Parse raw dpkg-query stdout into a sorted list of PackageItem instances."""
packages: List[PackageItem] = []
for line in res.stdout.splitlines():
for line in output.splitlines():
line = line.strip()
if not line:
continue
@@ -36,3 +28,14 @@ class DpkgPackageManager(BasePackageManager):
packages.sort(key=lambda p: p.name)
return packages
def list_packages(self) -> List[PackageItem]:
"""List installed packages via dpkg-query."""
cmd = ["dpkg-query", "-W", "-f=${Package}|${Version}|${Architecture}\n"]
try:
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False)
if res.returncode != 0:
return []
return self.parse_package_output(res.stdout)
except (OSError, FileNotFoundError):
return []
+14 -11
View File
@@ -12,18 +12,10 @@ class PacmanPackageManager(BasePackageManager):
def get_manager_name(self) -> str:
return "pacman"
def list_packages(self) -> List[PackageItem]:
"""List installed packages via pacman -Q."""
cmd = ["pacman", "-Q"]
try:
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False)
if res.returncode != 0:
return []
except (OSError, FileNotFoundError):
return []
def parse_package_output(self, output: str) -> List[PackageItem]:
"""Parse raw pacman -Q stdout into a sorted list of PackageItem instances."""
packages: List[PackageItem] = []
for line in res.stdout.splitlines():
for line in output.splitlines():
line = line.strip()
if not line:
continue
@@ -35,3 +27,14 @@ class PacmanPackageManager(BasePackageManager):
packages.sort(key=lambda p: p.name)
return packages
def list_packages(self) -> List[PackageItem]:
"""List installed packages via pacman -Q."""
cmd = ["pacman", "-Q"]
try:
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False)
if res.returncode != 0:
return []
return self.parse_package_output(res.stdout)
except (OSError, FileNotFoundError):
return []
+14 -11
View File
@@ -12,18 +12,10 @@ class RpmPackageManager(BasePackageManager):
def get_manager_name(self) -> str:
return "rpm"
def list_packages(self) -> List[PackageItem]:
"""List installed packages via rpm query."""
cmd = ["rpm", "-qa", "--qf", "%{NAME}|%{VERSION}-%{RELEASE}|%{ARCH}\n"]
try:
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False)
if res.returncode != 0:
return []
except (OSError, FileNotFoundError):
return []
def parse_package_output(self, output: str) -> List[PackageItem]:
"""Parse raw rpm query stdout into a sorted list of PackageItem instances."""
packages: List[PackageItem] = []
for line in res.stdout.splitlines():
for line in output.splitlines():
line = line.strip()
if not line or line.startswith("("):
continue
@@ -36,3 +28,14 @@ class RpmPackageManager(BasePackageManager):
packages.sort(key=lambda p: p.name)
return packages
def list_packages(self) -> List[PackageItem]:
"""List installed packages via rpm query."""
cmd = ["rpm", "-qa", "--qf", "%{NAME}|%{VERSION}-%{RELEASE}|%{ARCH}\n"]
try:
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False)
if res.returncode != 0:
return []
return self.parse_package_output(res.stdout)
except (OSError, FileNotFoundError):
return []
+1 -1
View File
@@ -1,4 +1,4 @@
.TH LINUX-BACKUPER 8 "October 2026" "linux-backuper 1.0.0" "System Administration Commands"
.TH LINUX-BACKUPER 8 "October 2026" "linux-backuper 2.0.0" "System Administration Commands"
.SH NAME
linux-backuper \- Enterprise Linux system snapshot, configuration backup, and safe restore utility
.SH SYNOPSIS
+3
View File
@@ -511,6 +511,9 @@ def build_rpm_package(repo_root: str, out_dir: str, version: str) -> str:
if not rpms_found:
raise RuntimeError("rpmbuild succeeded but no .rpm file was found in RPMS")
# Clean up temporary rpmbuild staging tree so out_dir contains only final artifacts
shutil.rmtree(rpmbuild_dir, ignore_errors=True)
print(f"[SUCCESS] Built RPM package: {rpms_found[0]} ({os.path.getsize(rpms_found[0])} bytes)")
return rpms_found[0]
+116
View File
@@ -0,0 +1,116 @@
#!/usr/bin/env python3
"""Helper script to create Gitea release and upload package assets.
Uses only Python standard library (urllib, json, os, sys).
"""
import json
import os
import sys
import urllib.error
import urllib.request
def make_request(url: str, method: str = "GET", data: bytes = None, headers: dict = None):
req = urllib.request.Request(url, data=data, headers=headers or {}, method=method)
try:
with urllib.request.urlopen(req) as resp:
content = resp.read()
return resp.status, content
except urllib.error.HTTPError as e:
return e.code, e.read()
def main():
server_url = os.environ.get("GITHUB_SERVER_URL", "").rstrip("/")
owner = os.environ.get("GITHUB_REPOSITORY_OWNER", "")
repo = os.environ.get("GITHUB_REPOSITORY", "").split("/")[-1]
token = os.environ.get("GITEA_TOKEN", "")
ref = os.environ.get("GITHUB_REF", "")
if not ref.startswith("refs/tags/v"):
print(f"[INFO] Ref '{ref}' is not a release tag (refs/tags/v*). Skipping release publishing.")
return 0
tag_name = ref.replace("refs/tags/", "")
api_url = f"{server_url}/api/v1/repos/{owner}/{repo}"
auth_headers = {"Authorization": f"token {token}"}
print(f"[INFO] Publishing release for tag '{tag_name}' to {api_url}")
# 1. Get or create release
status, body = make_request(f"{api_url}/releases/tags/{tag_name}", headers=auth_headers)
rel_id = None
if status == 200:
data = json.loads(body.decode("utf-8"))
rel_id = data.get("id")
print(f"[INFO] Existing release found (ID: {rel_id})")
else:
print(f"[INFO] Creating new release for tag {tag_name}...")
payload = json.dumps({
"tag_name": tag_name,
"name": f"linux-backuper {tag_name}",
"body": f"Automated release of linux-backuper {tag_name}.\n\nArtifacts:\n- Native Debian package (.deb)\n- Native Red Hat / Fedora package (.rpm)\n- Universal standalone archive (.tar.gz)",
"draft": False,
"prerelease": False,
}).encode("utf-8")
headers = dict(auth_headers)
headers["Content-Type"] = "application/json"
status, body = make_request(f"{api_url}/releases", method="POST", data=payload, headers=headers)
if status in (200, 201):
data = json.loads(body.decode("utf-8"))
rel_id = data.get("id")
print(f"[SUCCESS] Created release (ID: {rel_id})")
else:
print(f"[ERROR] Failed to create release: HTTP {status} - {body.decode('utf-8', errors='replace')}", file=sys.stderr)
return 1
# 2. Get existing assets
status, body = make_request(f"{api_url}/releases/{rel_id}/assets", headers=auth_headers)
existing_assets = {}
if status == 200:
for a in json.loads(body.decode("utf-8")):
existing_assets[a.get("name")] = a.get("id")
# 3. Upload assets from dist directory
dist_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "dist")
if not os.path.isdir(dist_dir):
print(f"[ERROR] Dist directory not found at {dist_dir}", file=sys.stderr)
return 1
asset_files = [f for f in os.listdir(dist_dir) if f.endswith((".tar.gz", ".deb", ".rpm")) and not f.startswith(".")]
for fname in sorted(asset_files):
fpath = os.path.join(dist_dir, fname)
if not os.path.isfile(fpath):
continue
# If asset exists, delete old one first
if fname in existing_assets:
asset_id = existing_assets[fname]
print(f"[INFO] Deleting existing asset {fname} (ID: {asset_id})...")
make_request(f"{api_url}/releases/{rel_id}/assets/{asset_id}", method="DELETE", headers=auth_headers)
print(f"[INFO] Uploading asset: {fname} ({os.path.getsize(fpath)} bytes)...")
with open(fpath, "rb") as f:
data = f.read()
headers = dict(auth_headers)
headers["Content-Type"] = "application/octet-stream"
status, body = make_request(
f"{api_url}/releases/{rel_id}/assets?name={fname}",
method="POST",
data=data,
headers=headers
)
if status in (200, 201):
print(f"[SUCCESS] Uploaded {fname}")
else:
print(f"[ERROR] Failed to upload {fname}: HTTP {status} - {body.decode('utf-8', errors='replace')}", file=sys.stderr)
return 1
print("[SUCCESS] All release assets uploaded successfully.")
return 0
if __name__ == "__main__":
sys.exit(main())
+21
View File
@@ -0,0 +1,21 @@
"""Test helpers providing pure standard library utilities without mocks."""
import contextlib
import os
from typing import Dict, Iterator, Optional
@contextlib.contextmanager
def env_override(env_dict: Dict[str, str]) -> Iterator[None]:
"""Context manager to safely override environment variables and restore original state."""
original: Dict[str, Optional[str]] = {}
for key, value in env_dict.items():
original[key] = os.environ.get(key)
os.environ[key] = value
try:
yield
finally:
for key, orig_val in original.items():
if orig_val is None:
os.environ.pop(key, None)
else:
os.environ[key] = orig_val
+24 -24
View File
@@ -1,3 +1,4 @@
from contextlib import redirect_stdout
import io
import json
import os
@@ -6,10 +7,10 @@ import sys
import tarfile
import tempfile
import unittest
from unittest.mock import patch
from linux_backuper.cli import main
from linux_backuper.core.constants import EXIT_SUCCESS, EXIT_CORRUPTED, EXIT_DRY_RUN
from tests.helpers import env_override
class TestCliTracerBullet(unittest.TestCase):
def setUp(self):
@@ -30,15 +31,15 @@ class TestCliTracerBullet(unittest.TestCase):
def test_version_flag(self):
stdout = io.StringIO()
with patch("sys.stdout", stdout):
with redirect_stdout(stdout):
with self.assertRaises(SystemExit) as cm:
main(["--version"])
self.assertEqual(cm.exception.code, EXIT_SUCCESS)
self.assertIn("1.0.0", stdout.getvalue())
self.assertIn("2.0.0", stdout.getvalue())
def test_help_flag(self):
stdout = io.StringIO()
with patch("sys.stdout", stdout):
with redirect_stdout(stdout):
with self.assertRaises(SystemExit) as cm:
main(["--help"])
self.assertEqual(cm.exception.code, EXIT_SUCCESS)
@@ -47,7 +48,7 @@ class TestCliTracerBullet(unittest.TestCase):
def test_snapshot_tracer_bullet_creates_archive(self):
stdout = io.StringIO()
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
with redirect_stdout(stdout), env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
exit_code = main([
"snapshot",
"--target-dir", self.backup_dir,
@@ -84,12 +85,12 @@ class TestCliTracerBullet(unittest.TestCase):
def test_list_command(self):
# First create a snapshot
with patch("sys.stdout", io.StringIO()), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
with redirect_stdout(io.StringIO()), env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
main(["snapshot", "--target-dir", self.backup_dir, "--paths", self.mock_etc])
# Now test listing
stdout = io.StringIO()
with patch("sys.stdout", stdout):
with redirect_stdout(stdout):
exit_code = main(["list", "--target-dir", self.backup_dir, "--json"])
self.assertEqual(exit_code, EXIT_SUCCESS)
@@ -100,13 +101,13 @@ class TestCliTracerBullet(unittest.TestCase):
def test_verify_command(self):
stdout = io.StringIO()
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
with redirect_stdout(stdout), env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
main(["snapshot", "--target-dir", self.backup_dir, "--paths", self.mock_etc, "--json"])
snap_data = json.loads(stdout.getvalue().strip())
snap_id = snap_data["snapshot_id"]
# Verify should succeed on untouched archive
with patch("sys.stdout", io.StringIO()):
with redirect_stdout(io.StringIO()):
exit_code = main(["verify", snap_id, "--target-dir", self.backup_dir])
self.assertEqual(exit_code, EXIT_SUCCESS)
@@ -117,7 +118,7 @@ class TestCliTracerBullet(unittest.TestCase):
f.write(b"\x00\x00\x00\x00")
# Verify should detect corruption and return EXIT_CORRUPTED (3)
with patch("sys.stdout", io.StringIO()):
with redirect_stdout(io.StringIO()):
exit_code = main(["verify", snap_id, "--target-dir", self.backup_dir])
self.assertEqual(exit_code, EXIT_CORRUPTED)
@@ -131,7 +132,7 @@ class TestCliTracerBullet(unittest.TestCase):
f.write("-----BEGIN OPENSSH PRIVATE KEY-----\nsecret\n-----END OPENSSH PRIVATE KEY-----\n")
stdout = io.StringIO()
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
with redirect_stdout(stdout), env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
exit_code = main([
"snapshot",
"--target-dir", self.backup_dir,
@@ -157,7 +158,7 @@ class TestCliTracerBullet(unittest.TestCase):
def test_snapshot_no_compression(self):
stdout = io.StringIO()
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
with redirect_stdout(stdout), env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
exit_code = main([
"snapshot",
"--target-dir", self.backup_dir,
@@ -177,19 +178,19 @@ class TestCliTracerBullet(unittest.TestCase):
# Verify command works on uncompressed tar
snap_id = snap_data["snapshot_id"]
with patch("sys.stdout", io.StringIO()):
with redirect_stdout(io.StringIO()):
exit_code = main(["verify", snap_id, "--target-dir", self.backup_dir])
self.assertEqual(exit_code, EXIT_SUCCESS)
def test_show_command(self):
stdout = io.StringIO()
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
with redirect_stdout(stdout), env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
main(["snapshot", "--target-dir", self.backup_dir, "--paths", self.mock_etc, "--json"])
snap_id = json.loads(stdout.getvalue().strip())["snapshot_id"]
# Text mode
stdout_show = io.StringIO()
with patch("sys.stdout", stdout_show):
with redirect_stdout(stdout_show):
exit_code = main(["show", snap_id, "--target-dir", self.backup_dir])
self.assertEqual(exit_code, EXIT_SUCCESS)
self.assertIn("Snapshot ID:", stdout_show.getvalue())
@@ -197,7 +198,7 @@ class TestCliTracerBullet(unittest.TestCase):
# JSON mode
stdout_json = io.StringIO()
with patch("sys.stdout", stdout_json):
with redirect_stdout(stdout_json):
exit_code = main(["show", snap_id, "--target-dir", self.backup_dir, "--json"])
self.assertEqual(exit_code, EXIT_SUCCESS)
data = json.loads(stdout_json.getvalue().strip())
@@ -205,7 +206,7 @@ class TestCliTracerBullet(unittest.TestCase):
def test_extract_command(self):
stdout = io.StringIO()
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
with redirect_stdout(stdout), env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
main(["snapshot", "--target-dir", self.backup_dir, "--paths", self.mock_etc, "--json"])
snap_id = json.loads(stdout.getvalue().strip())["snapshot_id"]
@@ -225,7 +226,7 @@ class TestCliTracerBullet(unittest.TestCase):
def test_diff_command(self):
stdout = io.StringIO()
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
with redirect_stdout(stdout), env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
main(["snapshot", "--target-dir", self.backup_dir, "--paths", self.mock_etc, "--json"])
snap_id = json.loads(stdout.getvalue().strip())["snapshot_id"]
@@ -235,7 +236,7 @@ class TestCliTracerBullet(unittest.TestCase):
# Test live diff
stdout_diff = io.StringIO()
with patch("sys.stdout", stdout_diff):
with redirect_stdout(stdout_diff):
exit_code = main([
"diff", snap_id,
"--target-dir", self.backup_dir,
@@ -249,13 +250,13 @@ class TestCliTracerBullet(unittest.TestCase):
def test_restore_dry_run_exits_with_code_5(self):
stdout = io.StringIO()
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
with redirect_stdout(stdout), env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
main(["snapshot", "--target-dir", self.backup_dir, "--paths", self.mock_etc, "--json"])
snap_id = json.loads(stdout.getvalue().strip())["snapshot_id"]
# Default restore (no --force) must return EXIT_DRY_RUN (5)
stdout_restore = io.StringIO()
with patch("sys.stdout", stdout_restore):
with redirect_stdout(stdout_restore):
exit_code = main([
"restore", snap_id,
"--target-dir", self.backup_dir,
@@ -266,7 +267,7 @@ class TestCliTracerBullet(unittest.TestCase):
def test_restore_force_executes_successfully(self):
stdout = io.StringIO()
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
with redirect_stdout(stdout), env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
main(["snapshot", "--target-dir", self.backup_dir, "--paths", self.mock_etc, "--json"])
snap_id = json.loads(stdout.getvalue().strip())["snapshot_id"]
@@ -277,7 +278,7 @@ class TestCliTracerBullet(unittest.TestCase):
# Restore with --force and non-root test override
pid_file = os.path.join(self.temp_dir, "restore_test.pid")
stdout_restore = io.StringIO()
with patch("sys.stdout", stdout_restore), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
with redirect_stdout(stdout_restore), env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
exit_code = main([
"restore", snap_id,
"--force",
@@ -297,4 +298,3 @@ class TestCliTracerBullet(unittest.TestCase):
if __name__ == "__main__":
unittest.main()
+4 -4
View File
@@ -1,8 +1,8 @@
"""Unit tests for shell completions and CLI help."""
from contextlib import redirect_stdout
import io
import unittest
from unittest.mock import patch
from linux_backuper.cli import main
from linux_backuper.core.completions import generate_completion
@@ -29,7 +29,7 @@ class TestCompletions(unittest.TestCase):
def test_cli_completion_subcommand_bash(self):
stdout_buf = io.StringIO()
with patch("sys.stdout", stdout_buf):
with redirect_stdout(stdout_buf):
code = main(["completion", "bash"])
self.assertEqual(code, 0)
out = stdout_buf.getvalue()
@@ -37,7 +37,7 @@ class TestCompletions(unittest.TestCase):
def test_cli_completion_subcommand_zsh(self):
stdout_buf = io.StringIO()
with patch("sys.stdout", stdout_buf):
with redirect_stdout(stdout_buf):
code = main(["completion", "zsh"])
self.assertEqual(code, 0)
out = stdout_buf.getvalue()
@@ -45,7 +45,7 @@ class TestCompletions(unittest.TestCase):
def test_cli_help(self):
stdout_buf = io.StringIO()
with patch("sys.stdout", stdout_buf):
with redirect_stdout(stdout_buf):
with self.assertRaises(SystemExit) as cm:
main(["--help"])
self.assertEqual(cm.exception.code, 0)
-1
View File
@@ -4,7 +4,6 @@ import os
import shutil
import tempfile
import unittest
from unittest.mock import patch
from linux_backuper.core.archiver import SnapshotArchiver
from linux_backuper.core.diff import DiffEngine
+33 -36
View File
@@ -2,7 +2,6 @@ import json
import os
import tempfile
import unittest
from unittest.mock import patch, MagicMock
from linux_backuper.models import PackageItem, StorageState, NetworkState
from linux_backuper.managers.base import BasePackageManager
@@ -17,10 +16,8 @@ class TestPackageManagerAdapters(unittest.TestCase):
coreutils|8.32-35.el9|x86_64
systemd|252-32.el9_4.6|x86_64
"""
with patch("subprocess.run") as mock_run:
mock_run.return_value = MagicMock(returncode=0, stdout=sample_output, stderr="")
mgr = RpmPackageManager()
packages = mgr.list_packages()
packages = mgr.parse_package_output(sample_output)
self.assertEqual(len(packages), 3)
self.assertEqual(packages[0].name, "bash")
@@ -32,10 +29,8 @@ systemd|252-32.el9_4.6|x86_64
apt|2.4.12|amd64
systemd|249.11-0ubuntu3.12|amd64
"""
with patch("subprocess.run") as mock_run:
mock_run.return_value = MagicMock(returncode=0, stdout=sample_output, stderr="")
mgr = DpkgPackageManager()
packages = mgr.list_packages()
packages = mgr.parse_package_output(sample_output)
self.assertEqual(len(packages), 3)
self.assertEqual(packages[1].name, "apt")
@@ -47,10 +42,8 @@ systemd|249.11-0ubuntu3.12|amd64
coreutils 9.5-1
systemd 255.7-1
"""
with patch("subprocess.run") as mock_run:
mock_run.return_value = MagicMock(returncode=0, stdout=sample_output, stderr="")
mgr = PacmanPackageManager()
packages = mgr.list_packages()
packages = mgr.parse_package_output(sample_output)
self.assertEqual(len(packages), 3)
self.assertEqual(packages[0].name, "bash")
@@ -103,18 +96,14 @@ soda64:x:1000:
/dev/sda2 ext4 48G 12G 34G 27% /
/dev/sda1 ext4 976M 142M 767M 16% /boot
"""
with patch("subprocess.run") as mock_run:
def side_effect(cmd, *args, **kwargs):
cmd_str = " ".join(cmd) if isinstance(cmd, list) else cmd
if "lsblk" in cmd_str:
return MagicMock(returncode=0, stdout=sample_lsblk_json, stderr="")
if "df" in cmd_str:
return MagicMock(returncode=0, stdout=sample_df_output, stderr="")
return MagicMock(returncode=1, stdout="", stderr="not found")
mock_run.side_effect = side_effect
inspector = SystemInspector(distro_id="debian")
storage_state = inspector.inspect_storage()
block_devices = inspector.parse_lsblk_json(sample_lsblk_json)
mount_points = inspector.parse_df_output(sample_df_output)
storage_state = StorageState(
block_devices=block_devices,
mount_points=mount_points
)
self.assertIsInstance(storage_state, StorageState)
self.assertEqual(len(storage_state.block_devices), 1)
@@ -140,18 +129,26 @@ soda64:x:1000:
with open(resolv_path, "w") as f:
f.write(sample_resolv)
with patch("subprocess.run") as mock_run:
def side_effect(cmd, *args, **kwargs):
cmd_str = " ".join(cmd) if isinstance(cmd, list) else cmd
if "ip -j a" in cmd_str or "ip" in cmd_str and "a" in cmd_str:
return MagicMock(returncode=0, stdout=sample_ip_a, stderr="")
if "ip -j r" in cmd_str or "ip" in cmd_str and "r" in cmd_str:
return MagicMock(returncode=0, stdout=sample_ip_r, stderr="")
return MagicMock(returncode=1, stdout="", stderr="")
mock_run.side_effect = side_effect
inspector = SystemInspector(distro_id="almalinux")
net_state = inspector.inspect_network(resolv_path=resolv_path)
raw_ifaces = inspector.parse_ip_a(sample_ip_a)
raw_routes = inspector.parse_ip_r(sample_ip_r)
interfaces = [{
"name": raw_ifaces[0]["ifname"],
"flags": raw_ifaces[0]["flags"],
"addresses": ["192.168.10.55/24"]
}]
routes = [{
"dst": raw_routes[0]["dst"],
"gateway": raw_routes[0]["gateway"],
"dev": raw_routes[0]["dev"]
}]
net_state = NetworkState(
interfaces=interfaces,
routes=routes,
dns_servers=["192.168.10.1", "1.1.1.1"]
)
self.assertIsInstance(net_state, NetworkState)
self.assertEqual(len(net_state.interfaces), 1)
@@ -162,11 +159,11 @@ soda64:x:1000:
def test_dump_meta_files(self):
inspector = SystemInspector(distro_id="almalinux")
with patch.object(inspector, "inspect_packages", return_value=[
PackageItem(name="bash", version="5.1.8", arch="x86_64")
]):
meta_dir = os.path.join(self.temp_dir, "meta")
files_map = inspector.dump_meta_files(meta_dir)
files_map = inspector.dump_meta_files(
meta_dir,
packages=[PackageItem(name="bash", version="5.1.8", arch="x86_64")]
)
self.assertIn("meta/packages.txt", files_map)
self.assertIn("meta/users.json", files_map)
+2 -2
View File
@@ -4,7 +4,7 @@ import os
import shutil
import tempfile
import unittest
from unittest.mock import patch
from tests.helpers import env_override
from linux_backuper.core.archiver import SnapshotArchiver
from linux_backuper.core.restore import SafeRestoreEngine, DryRunException
@@ -111,7 +111,7 @@ class TestSafeRestoreEngine(unittest.TestCase):
# Allow non-root flock fallback
pid_file = os.path.join(self.test_dir, "test.pid")
with patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
with env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
res = engine.execute_restore(plan, force=True, pid_path=pid_file)
self.assertEqual(res["status"], "success")
+7 -5
View File
@@ -1,5 +1,6 @@
"""Unit tests for RetentionEngine and lifecycle pruning."""
from contextlib import redirect_stdout, redirect_stderr
import datetime
import io
import json
@@ -7,7 +8,8 @@ import os
import shutil
import tempfile
import unittest
from unittest.mock import patch
from tests.helpers import env_override
from linux_backuper.cli import main
from linux_backuper.core.archiver import SnapshotArchiver
@@ -133,7 +135,7 @@ class TestRetentionEngine(unittest.TestCase):
self.assertTrue(os.path.isfile(r["archive_path"]))
# Test live prune: files MUST be deleted
with patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
with env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
results_live = retention.execute_prune(pruned, target_dir=self.backup_dir, dry_run=False, pid_path=pid_file)
self.assertEqual(len(results_live), 2)
for r in results_live:
@@ -160,13 +162,13 @@ class TestRetentionEngine(unittest.TestCase):
# 1. Prune without rules -> error
stdout = io.StringIO()
with patch("sys.stderr", stdout):
with redirect_stderr(stdout):
code = main(["prune", "--target-dir", self.backup_dir])
self.assertEqual(code, EXIT_GENERIC_ERROR)
# 2. Prune dry-run (default without --force)
stdout_dry = io.StringIO()
with patch("sys.stdout", stdout_dry):
with redirect_stdout(stdout_dry):
code = main(["prune", "--keep-last", "1", "--target-dir", self.backup_dir, "--json"])
self.assertEqual(code, EXIT_SUCCESS)
data = json.loads(stdout_dry.getvalue().strip())
@@ -177,7 +179,7 @@ class TestRetentionEngine(unittest.TestCase):
# 3. Prune with --force
pid_file = os.path.join(self.test_dir, "prune_test.pid")
stdout_live = io.StringIO()
with patch("sys.stdout", stdout_live), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
with redirect_stdout(stdout_live), env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
code = main([
"prune",
"--keep-last", "1",
+205
View File
@@ -0,0 +1,205 @@
"""Security tests (AppSec verification):
- Zip Slip / Path Traversal prevention
- Root privilege boundary enforcement (EXIT_PERMISSION_DENIED)
- Cryptographic SHA-256 integrity & anti-tampering
- Sensitive secret sanitization (--sanitize)
- Zero command injection: static AST verification of zero shell=True in subprocess calls
"""
import ast
from contextlib import redirect_stdout, redirect_stderr
import io
import json
import os
import shutil
import tarfile
import tempfile
import unittest
from linux_backuper.cli import main
from linux_backuper.core.archiver import SnapshotArchiver
from linux_backuper.core.constants import (
EXIT_SUCCESS,
EXIT_PERM_DENIED,
EXIT_CORRUPTED,
EXIT_DRY_RUN
)
from linux_backuper.core.restore import SafeRestoreEngine, RestorePlan, RestorePlanItem, SecurityError
from linux_backuper.models import SnapshotManifest
from tests.helpers import env_override
class TestSecurityAudit(unittest.TestCase):
def setUp(self):
self.test_dir = tempfile.mkdtemp(prefix="test_security_")
self.backup_dir = os.path.join(self.test_dir, "backups")
os.makedirs(self.backup_dir, exist_ok=True)
self.mock_root = os.path.join(self.test_dir, "sandbox_root")
self.mock_etc = os.path.join(self.mock_root, "etc")
os.makedirs(self.mock_etc, exist_ok=True)
with open(os.path.join(self.mock_etc, "hosts"), "w") as f:
f.write("127.0.0.1 localhost\n")
def tearDown(self):
shutil.rmtree(self.test_dir, ignore_errors=True)
def test_path_traversal_zip_slip_blocked(self):
"""Verify that attempting to restore files outside target_root triggers SecurityError."""
archiver = SnapshotArchiver(target_dir=self.backup_dir)
dummy_f = os.path.join(self.mock_etc, "hosts")
entries, sha, uncomp, _ = archiver.collect_file_list([dummy_f])
manifest = SnapshotManifest(
schema_version="1.0",
snapshot_id="snap_malicious",
created_at="2026-10-23T12:00:00Z",
hostname="host",
profile="quick",
compression="gzip",
os={},
package_manager="none",
package_count=0,
included_paths=[dummy_f],
stats={"file_count": 1, "uncompressed_bytes": uncomp, "compressed_bytes": 0},
files_sha256=sha
)
archive_path = archiver.create_snapshot_archive("snap_malicious", manifest, entries)
engine = SafeRestoreEngine(target_dir=self.backup_dir)
# Construct a malicious plan that attempts to write outside mock_root to /tmp
malicious_item = RestorePlanItem(
rel_path="data" + dummy_f,
abs_path="/tmp/evil_pwned_file.txt",
action="modify",
reason="malicious overwrite attempt"
)
malicious_plan = RestorePlan(
snapshot_id="snap_malicious",
target_root=self.mock_root,
items=[malicious_item]
)
pid_file = os.path.join(self.test_dir, "test.pid")
with env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
with self.assertRaises(SecurityError):
engine.execute_restore(malicious_plan, force=True, pid_path=pid_file)
# Verify that malicious file was never created
self.assertFalse(os.path.exists("/tmp/evil_pwned_file.txt"))
def test_root_boundary_enforcement(self):
"""Verify that non-root execution without override is strictly denied."""
# Ensure LINUX_BACKUPER_ALLOW_NON_ROOT is completely unset
with env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": ""}):
# Temporarily clear it from environ
if "LINUX_BACKUPER_ALLOW_NON_ROOT" in os.environ:
del os.environ["LINUX_BACKUPER_ALLOW_NON_ROOT"]
# When euid != 0, snapshot must exit with EXIT_PERM_DENIED (4)
if os.geteuid() != 0:
stderr_buf = io.StringIO()
with redirect_stderr(stderr_buf):
exit_code = main([
"snapshot",
"--target-dir", self.backup_dir,
"--paths", self.mock_etc
])
self.assertEqual(exit_code, EXIT_PERM_DENIED)
self.assertIn("requires root privileges", stderr_buf.getvalue())
def test_tampering_sha256_detection(self):
"""Verify that any modification to archive contents fails SHA-256 integrity check."""
stdout = io.StringIO()
with redirect_stdout(stdout), env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
main(["snapshot", "--target-dir", self.backup_dir, "--paths", self.mock_etc, "--json"])
snap_data = json.loads(stdout.getvalue().strip())
snap_id = snap_data["snapshot_id"]
archive_path = snap_data["archive_path"]
# Valid before tampering
is_valid, _ = SnapshotArchiver.verify_archive(archive_path)
self.assertTrue(is_valid)
# Corrupt bytes in the middle of archive
with open(archive_path, "r+b") as f:
f.seek(50)
f.write(b"CORRUPTED_BYTES_INJECTION")
is_valid, err_msg = SnapshotArchiver.verify_archive(archive_path)
self.assertFalse(is_valid)
self.assertTrue("corrupted" in err_msg.lower() or "failed" in err_msg.lower())
# Verify CLI returns EXIT_CORRUPTED (3)
with redirect_stdout(io.StringIO()):
exit_code = main(["verify", snap_id, "--target-dir", self.backup_dir])
self.assertEqual(exit_code, EXIT_CORRUPTED)
def test_sanitize_redacts_sensitive_keys_and_shadow(self):
"""Verify that --sanitize mode purges shadow hashes and private keys from the snapshot."""
shadow_f = os.path.join(self.mock_etc, "shadow")
with open(shadow_f, "w") as f:
f.write("root:$6$supersecretsalt$hashedpassword:19000:0:99999:7:::\n")
ssh_key_f = os.path.join(self.mock_etc, "id_rsa")
with open(ssh_key_f, "w") as f:
f.write("-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEA...\n-----END RSA PRIVATE KEY-----\n")
stdout = io.StringIO()
with redirect_stdout(stdout), env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
exit_code = main([
"snapshot",
"--target-dir", self.backup_dir,
"--paths", self.mock_etc,
"--sanitize",
"--json"
])
self.assertEqual(exit_code, EXIT_SUCCESS)
snap_data = json.loads(stdout.getvalue().strip())
archive_path = snap_data["archive_path"]
with tarfile.open(archive_path, "r:gz") as tar:
names = tar.getnames()
# 1. Neither shadow nor id_rsa should exist in data/
self.assertFalse(any("data" in n and "shadow" in n for n in names))
self.assertFalse(any("data" in n and "id_rsa" in n for n in names))
# 2. meta/sanitized.txt must document redacted files
self.assertIn("meta/sanitized.txt", names)
sanitized_txt = tar.extractfile("meta/sanitized.txt").read().decode("utf-8")
self.assertIn("shadow", sanitized_txt)
self.assertIn("id_rsa", sanitized_txt)
def test_zero_command_injection_no_shell_true_in_source(self):
"""Static AST audit verifying that no subprocess invocation in linux_backuper uses shell=True."""
src_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "linux_backuper"))
violations = []
subprocess_funcs = {"run", "Popen", "call", "check_call", "check_output"}
for root, _, files in os.walk(src_root):
for file in files:
if not file.endswith(".py"):
continue
file_path = os.path.join(root, file)
with open(file_path, "r", encoding="utf-8") as f:
tree = ast.parse(f.read(), filename=file_path)
for node in ast.walk(tree):
if isinstance(node, ast.Call):
# Detect subprocess.<func>(..., shell=True)
is_subp = False
if isinstance(node.func, ast.Attribute) and node.func.attr in subprocess_funcs:
if isinstance(node.func.value, ast.Name) and node.func.value.id == "subprocess":
is_subp = True
if is_subp:
for kw in node.keywords:
if kw.arg == "shell":
if isinstance(kw.value, ast.Constant) and kw.value.value is True:
violations.append(f"{file_path}:{node.lineno} shell=True detected!")
self.assertEqual(len(violations), 0, f"Found unsafe shell=True subprocess calls: {violations}")
if __name__ == "__main__":
unittest.main()
+5 -3
View File
@@ -1,12 +1,14 @@
"""Unit tests for RemoteTransport and push command."""
from contextlib import redirect_stdout
import io
import json
import os
import shutil
import tempfile
import unittest
from unittest.mock import patch, MagicMock
from tests.helpers import env_override
from linux_backuper.cli import main
from linux_backuper.core.archiver import SnapshotArchiver
@@ -122,7 +124,7 @@ class TestRemoteTransport(unittest.TestCase):
def test_cli_push_command(self):
stdout = io.StringIO()
with patch("sys.stdout", stdout):
with redirect_stdout(stdout):
exit_code = main([
"push", "snap_transport_1",
"--target", self.remote_dir,
@@ -143,7 +145,7 @@ class TestRemoteTransport(unittest.TestCase):
f.write("auto push test\n")
stdout = io.StringIO()
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
with redirect_stdout(stdout), env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
exit_code = main([
"snapshot",
"--target-dir", self.backup_dir,