Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(backup): resolve DB paths from env, fail hard, and take consistent SQLite snapshots (#926)

Yudhi Armyndharisd95074720948
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 0ae950c54..650c23990 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -195,10 +195,36 @@ jobs:
- name: Run dashboard unit tests
run: cd dashboard && npm run test:unit
+ # The repo ships several host-level shell smoke scripts (scripts/smoke-test-*.sh, plus
+ # scripts/backup.sh / scripts/restore.sh exercised by smoke-test-backup-restore.sh). None of them
+ # are exercised by the jest suites, so without this gate a regression in the bash hardening lands
+ # silently. The job is cheap (no npm install, no build) and parallel to the others.
+ scripts-smoke:
+ name: Shell scripts
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v7
+
+ - name: Install sqlite3
+ # smoke-test-backup-restore.sh skips its sqlite3 .backup roundtrip case (with a notice) when
+ # the host lacks the CLI; installing it here exercises that path on every run instead.
+ run: sudo apt-get update && sudo apt-get install -y --no-install-recommends sqlite3
+
+ - name: Install shellcheck
+ run: sudo apt-get install -y --no-install-recommends shellcheck
+
+ - name: shellcheck the backup/restore scripts
+ # Scope this PR: lint the three scripts #926 added or rewrote. Widening to the rest of
+ # scripts/*.sh is tracked separately so a pre-existing warning elsewhere can't fail this gate.
+ run: shellcheck scripts/backup.sh scripts/restore.sh scripts/smoke-test-backup-restore.sh
+
+ - name: Run backup/restore smoke test
+ run: ./scripts/smoke-test-backup-restore.sh
+
build:
name: Build
runs-on: ubuntu-latest
- needs: [lint, audit, test, dashboard]
+ needs: [lint, audit, test, dashboard, scripts-smoke]
steps:
- uses: actions/checkout@v7
diff --git a/Dockerfile b/Dockerfile
index e4f8fd9ea..86ad31d35 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -60,6 +60,8 @@ FROM docker.io/node:22-slim AS production
# --no-sandbox would otherwise get a chromium that can't launch. Verified on real arm64 hardware:
# with --no-install-recommends the package is dropped, and chromium launches fine under --no-sandbox.
ARG TARGETARCH
+# sqlite3 ships the CLI so an in-container scripts/backup.sh run takes online-consistent SQLite
+# snapshots (.backup) instead of plain-copying a live database (which can archive a torn file).
RUN apt-get update && apt-get install -y --no-install-recommends \
$([ "$TARGETARCH" = arm64 ] && echo "chromium chromium-sandbox") \
fonts-liberation \
@@ -84,6 +86,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
patch \
curl \
procps \
+ sqlite3 \
&& rm -rf /var/lib/apt/lists/*
# Set Puppeteer to skip automatic download during npm install (we download it explicitly below)
diff --git a/docs/11-operational-runbooks.md b/docs/11-operational-runbooks.md
index b5e830fcd..63ae24716 100644
--- a/docs/11-operational-runbooks.md
+++ b/docs/11-operational-runbooks.md
@@ -493,16 +493,24 @@ User-managed files outside that list (for example the project-level `.env`) must
```bash
# scripts/backup.sh captures:
-# - main.sqlite — auth (API keys) + audit log (ALWAYS SQLite)
-# - openwa.sqlite — user data (or a pg_dump when DATABASE_TYPE=postgres)
+# - main.sqlite — auth (API keys) + audit log (ALWAYS SQLite; MAIN_DATABASE_NAME, default ./data/main.sqlite)
+# - openwa.sqlite — user data (DATABASE_NAME, default ./data/openwa.sqlite;
+# or a pg_dump when DATABASE_TYPE=postgres)
# - sessions/ — whatsapp-web.js state (SESSION_DATA_PATH)
# - baileys/ — Baileys credentials (BAILEYS_AUTH_DIR)
# - media/ — local media (skipped automatically when STORAGE_TYPE=s3)
# - plugin-packages/ — installed plugin code from PLUGINS_DIR
# - plugin-state/ — registry + ctx.storage state under OPENWA_DATA_DIR
# - .env.generated / .api-key — generated configuration and bootstrap secret
-
-# Run from the repo root (operates on the data dir, default ./data):
+#
+# The database paths resolve exactly like the app: the explicit MAIN_DATABASE_NAME /
+# DATABASE_NAME env path wins, otherwise the fixed ./data defaults — they are NOT derived from
+# OPENWA_DATA_DIR. A missing source database fails the run (no silent empty backup), the finished
+# archive is checked to contain every configured database, and with the sqlite3 CLI present the
+# databases are snapshotted online via .backup (otherwise plain-copied with a CONSISTENCY-WARNING
+# marker inside the archive).
+
+# Run from the repo root (database defaults are ./data/...; state dirs follow OPENWA_DATA_DIR):
./scripts/backup.sh
# Customize via environment:
@@ -516,7 +524,8 @@ OPENWA_DATA_DIR=/srv/openwa/data \
> compose. Run the script where that volume is mounted — e.g. point `OPENWA_DATA_DIR`
> at the volume's mountpoint, or run it inside a container with `/app/data` mounted. When operating
> directly on the host mount, also set any path that does not use its default below `OPENWA_DATA_DIR`
-> (notably compose's colocated `PLUGINS_DIR`) to the corresponding host-visible path.
+> (notably compose's colocated `PLUGINS_DIR`, and `MAIN_DATABASE_NAME` / `DATABASE_NAME` when the app
+> overrides them) to the corresponding host-visible path.
**Verification:**
@@ -554,7 +563,9 @@ the current data dir first so a bad restore can be undone:
docker compose down
# 2. Restore from an archive produced by scripts/backup.sh
-# (operates on the data dir, default ./data; override with OPENWA_DATA_DIR)
+# (databases land on MAIN_DATABASE_NAME / DATABASE_NAME, default ./data/... — the same paths
+# the app reads; non-DB state follows OPENWA_DATA_DIR. Pass --strict to refuse an archive
+# whose CONSISTENCY-WARNING marker reports plain-copied, possibly-torn database snapshots)
./scripts/restore.sh ./backups/openwa-backup-<timestamp>.tar.gz
# 3. (Postgres only) the archive contains database.sql — import it manually:
diff --git a/scripts/backup.sh b/scripts/backup.sh
index 7fc9f20fd..2855d9385 100755
--- a/scripts/backup.sh
+++ b/scripts/backup.sh
@@ -18,13 +18,23 @@
# Usage:
# ./scripts/backup.sh
# Environment:
-# OPENWA_DATA_DIR data directory (default: ./data)
+# MAIN_DATABASE_NAME auth/audit SQLite file (default: ./data/main.sqlite)
+# DATABASE_NAME data-store SQLite file (default: ./data/openwa.sqlite; sqlite only)
+# Both resolve EXACTLY like the app (src/config/configuration.ts): the
+# explicit env path wins, otherwise the fixed ./data default. They are NOT
+# derived from OPENWA_DATA_DIR — the app never does that either.
+# OPENWA_DATA_DIR data directory for the non-DB state below (default: ./data)
# BACKUP_DIR where archives are written (default: ./backups)
# DATABASE_TYPE sqlite (default) | postgres
# SESSION_DATA_PATH, BAILEYS_AUTH_DIR, STORAGE_LOCAL_PATH, PLUGINS_DIR
# override the corresponding state directories
# For postgres: DATABASE_URL, or DATABASE_HOST/PORT/USERNAME/PASSWORD/NAME
#
+# Failure policy: a missing source database is FATAL (no silent empty backup), and the finished
+# archive must contain every configured database or it is deleted and the run fails. When the
+# sqlite3 CLI is unavailable the databases are plain-copied (possibly torn if the app is live) and
+# the archive carries a CONSISTENCY-WARNING marker that restore.sh surfaces.
+#
set -euo pipefail
# The archive now contains bootstrap credentials and generated database secrets. Never inherit a
# permissive operator umask for newly-created backup artifacts.
@@ -35,8 +45,11 @@ BACKUP_DIR="${BACKUP_DIR:-./backups}"
DATABASE_TYPE="${DATABASE_TYPE:-sqlite}"
TIMESTAMP="$(date +%Y%m%d-%H%M%S)"
-MAIN_DB="$DATA_DIR/main.sqlite"
-DATA_DB="$DATA_DIR/openwa.sqlite"
+# Database paths resolve exactly like the app (src/config/configuration.ts): the explicit env path
+# wins, otherwise the fixed ./data default. OPENWA_DATA_DIR below only bases the non-DB state
+# directories — deriving DB paths from it would back up files the app never reads.
+MAIN_DB="${MAIN_DATABASE_NAME:-./data/main.sqlite}"
+DATA_DB="${DATABASE_NAME:-./data/openwa.sqlite}"
SESSIONS_DIR="${SESSION_DATA_PATH:-$DATA_DIR/sessions}"
BAILEYS_DIR="${BAILEYS_AUTH_DIR:-$DATA_DIR/baileys}"
MEDIA_DIR="${STORAGE_LOCAL_PATH:-$DATA_DIR/media}"
@@ -50,24 +63,48 @@ log() { echo "[backup] $*"; }
STAGE="$(mktemp -d)"
trap 'rm -rf "$STAGE"' EXIT
-# Online SQLite backup (consistent without stopping the app) when sqlite3 is present,
-# else a plain copy with a warning.
+CONSISTENCY_WARNING="$STAGE/CONSISTENCY-WARNING"
+
+# Marker file shipped INSIDE the archive so restore.sh can surface that the database snapshot was
+# plain-copied from a possibly-live app (rollback-journal mode) and may be torn.
+record_consistency_warning() {
+ if [ ! -f "$CONSISTENCY_WARNING" ]; then
+ cat >"$CONSISTENCY_WARNING" <<'EOF'
+This archive was produced WITHOUT sqlite3 .backup (the sqlite3 CLI was not found on the backup
+host). The database file(s) listed below were plain-copied while the app may have been writing
+(SQLite rollback-journal mode), so the snapshot may be TORN (partially committed). Re-take the
+backup with sqlite3 installed — or with the app stopped — before relying on it for recovery.
+EOF
+ fi
+ echo "plain-copied: $1" >>"$CONSISTENCY_WARNING"
+}
+
+# Online SQLite backup (consistent without stopping the app) when sqlite3 is present. A missing
+# source database is FATAL: an archive without the configured databases is not a backup, and a
+# silent skip is how an empty archive gets reported as "Backup complete".
backup_sqlite() {
src="$1"
dest="$2"
if [ ! -f "$src" ]; then
- log "WARN: $src not found — skipping"
- return 0
+ log "ERROR: database file not found: $src"
+ log " the app reads this exact path — check MAIN_DATABASE_NAME / DATABASE_NAME / cwd, or start the app first"
+ exit 1
fi
if command -v sqlite3 >/dev/null 2>&1; then
sqlite3 "$src" ".backup '$dest'"
else
- log "WARN: sqlite3 not found — plain-copying $src (stop the app first for a consistent copy)"
+ log "WARN: sqlite3 not found — plain-copying live database $src (the snapshot may be torn)"
cp "$src" "$dest"
+ record_consistency_warning "$src"
fi
}
-log "Backing up auth/audit DB (main.sqlite) — the API-key + audit store"
+# Members the finished archive MUST contain (relative tar paths). A run that cannot stage any of
+# them has already failed hard above; the post-archive min-content check below is the last gate
+# against shipping an archive that would "restore" into a fresh-empty install.
+REQUIRED_MEMBERS=("./main.sqlite")
+
+log "Backing up auth/audit DB ($MAIN_DB) — the API-key + audit store"
backup_sqlite "$MAIN_DB" "$STAGE/main.sqlite"
if [ "$DATABASE_TYPE" = "postgres" ]; then
@@ -85,9 +122,11 @@ if [ "$DATABASE_TYPE" = "postgres" ]; then
-U "${DATABASE_USERNAME:-openwa}" \
"${DATABASE_NAME:-openwa}" >"$STAGE/database.sql"
fi
+ REQUIRED_MEMBERS+=("./database.sql")
else
- log "Backing up data store (openwa.sqlite)"
+ log "Backing up data store ($DATA_DB)"
backup_sqlite "$DATA_DB" "$STAGE/openwa.sqlite"
+ REQUIRED_MEMBERS+=("./openwa.sqlite")
fi
if [ -d "$SESSIONS_DIR" ]; then
@@ -133,7 +172,24 @@ mkdir -p "$BACKUP_DIR"
ARCHIVE="$BACKUP_DIR/openwa-backup-$TIMESTAMP.tar.gz"
tar -czf "$ARCHIVE" -C "$STAGE" .
+ARCHIVE_LIST="$(tar -tzf "$ARCHIVE")"
+
+# Min-content check on the finished archive: every configured database must be present. If not,
+# delete the defective archive and fail — leaving it on disk invites a restore into a fresh-empty
+# install (new API keys, new master key) reported as success.
+MISSING_MEMBERS=""
+for member in "${REQUIRED_MEMBERS[@]}"; do
+ if ! printf '%s\n' "$ARCHIVE_LIST" | grep -qxF "$member"; then
+ MISSING_MEMBERS="$MISSING_MEMBERS $member"
+ fi
+done
+if [ -n "$MISSING_MEMBERS" ]; then
+ log "ERROR: archive failed the min-content check — missing required member(s):$MISSING_MEMBERS"
+ rm -f "$ARCHIVE"
+ exit 1
+fi
+
log "Backup complete: $ARCHIVE"
log "SECURITY: this archive can contain database passwords, plugin secrets, and an admin API key; restrict and encrypt it"
log "Contents:"
-tar -tzf "$ARCHIVE" | sed 's/^/[backup] /'
+printf '%s\n' "$ARCHIVE_LIST" | sed 's/^/[backup] /'
diff --git a/scripts/restore.sh b/scripts/restore.sh
index 96fcf7314..1ce67645f 100755
--- a/scripts/restore.sh
+++ b/scripts/restore.sh
@@ -7,9 +7,19 @@
# PostgreSQL dumps are staged for the explicit psql import printed at the end of the restore.
#
# Usage:
-# ./scripts/restore.sh <backup-archive.tar.gz>
+# ./scripts/restore.sh <backup-archive.tar.gz> [--strict]
+# Options:
+# --strict refuse to restore an archive whose CONSISTENCY-WARNING marker reports
+# plain-copied (possibly torn) database snapshots; without it the restore
+# continues after a loud warning
# Environment:
-# OPENWA_DATA_DIR data directory to restore into (default: ./data)
+# MAIN_DATABASE_NAME restore target for the auth/audit DB (default: ./data/main.sqlite)
+# DATABASE_NAME restore target for the SQLite data store (default: ./data/openwa.sqlite)
+# Both resolve EXACTLY like the app (src/config/configuration.ts): the
+# explicit env path wins, otherwise the fixed ./data default. They are NOT
+# derived from OPENWA_DATA_DIR — restoring there would write databases the
+# app never reads (fresh-empty boot + new master key).
+# OPENWA_DATA_DIR data directory to restore non-DB state into (default: ./data)
# SESSION_DATA_PATH, BAILEYS_AUTH_DIR, STORAGE_LOCAL_PATH, PLUGINS_DIR
# override the corresponding state directories
#
@@ -20,8 +30,38 @@ set -euo pipefail
# Restored databases, credentials, and snapshots must not inherit a permissive operator umask.
umask 077
-ARCHIVE="${1:-}"
+STRICT=0
+ARCHIVE=""
+for arg in "$@"; do
+ case "$arg" in
+ --strict)
+ STRICT=1
+ ;;
+ -h | --help)
+ echo "Usage: $0 <backup-archive.tar.gz> [--strict]"
+ exit 0
+ ;;
+ -*)
+ echo "Unknown option: $arg" >&2
+ echo "Usage: $0 <backup-archive.tar.gz> [--strict]" >&2
+ exit 1
+ ;;
+ *)
+ if [ -n "$ARCHIVE" ]; then
+ echo "Unexpected extra argument: $arg" >&2
+ echo "Usage: $0 <backup-archive.tar.gz> [--strict]" >&2
+ exit 1
+ fi
+ ARCHIVE="$arg"
+ ;;
+ esac
+done
+
DATA_DIR="${OPENWA_DATA_DIR:-./data}"
+# Database targets resolve exactly like the app (src/config/configuration.ts): explicit env path,
+# else the fixed ./data defaults. They may legitimately live outside OPENWA_DATA_DIR.
+MAIN_DB="${MAIN_DATABASE_NAME:-./data/main.sqlite}"
+DATA_DB="${DATABASE_NAME:-./data/openwa.sqlite}"
SESSIONS_DIR="${SESSION_DATA_PATH:-$DATA_DIR/sessions}"
BAILEYS_DIR="${BAILEYS_AUTH_DIR:-$DATA_DIR/baileys}"
MEDIA_DIR="${STORAGE_LOCAL_PATH:-$DATA_DIR/media}"
@@ -117,8 +157,26 @@ replace_tree() {
cp -pR "$source_dir" "$target_dir"
}
+# The data-dir safety snapshot below cannot cover a database target that lives OUTSIDE it (custom
+# MAIN_DATABASE_NAME / DATABASE_NAME). Preserve such a file separately before overwriting it, so a
+# restore pointed at the wrong archive remains recoverable.
+snapshot_external_db() {
+ target="$1"
+ resolved_target="$(resolve_path "$target")"
+ case "$resolved_target" in
+ "$RESOLVED_DATA_DIR"/*) ;;
+ *)
+ if [ -e "$target" ]; then
+ external_snapshot="${target}.pre-restore-$RESTORE_TIMESTAMP"
+ log "Snapshotting current $target -> $external_snapshot"
+ cp -p "$target" "$external_snapshot"
+ fi
+ ;;
+ esac
+}
+
if [ -z "$ARCHIVE" ] || [ ! -f "$ARCHIVE" ]; then
- echo "Usage: $0 <backup-archive.tar.gz>" >&2
+ echo "Usage: $0 <backup-archive.tar.gz> [--strict]" >&2
exit 1
fi
@@ -138,6 +196,19 @@ while IFS= read -r entry; do
done < <(tar -tzf "$ARCHIVE")
tar -xzf "$ARCHIVE" -C "$STAGE"
+# A backup taken without sqlite3 .backup carries this marker: the database snapshots were
+# plain-copied from a possibly-live app and may be torn. Warn loudly and continue — unless
+# --strict makes it fatal. Refuse BEFORE touching any existing state.
+if [ -f "$STAGE/CONSISTENCY-WARNING" ]; then
+ log "WARN: archive carries CONSISTENCY-WARNING — database snapshot(s) may be torn:"
+ sed 's/^/[restore] /' "$STAGE/CONSISTENCY-WARNING"
+ if [ "$STRICT" -eq 1 ]; then
+ log "ERROR: --strict given — refusing to restore a possibly-torn database snapshot"
+ exit 1
+ fi
+ log "WARN: continuing anyway; verify data integrity after the restore (re-run with --strict to make this fatal)"
+fi
+
# Safety snapshot of whatever is there now.
if [ -d "$DATA_DIR" ] && [ -n "$(ls -A "$DATA_DIR" 2>/dev/null || true)" ]; then
SAFETY="${DATA_DIR%/}.pre-restore-$RESTORE_TIMESTAMP"
@@ -148,15 +219,19 @@ fi
mkdir -p "$DATA_DIR"
if [ -f "$STAGE/main.sqlite" ]; then
- log "Restoring auth/audit DB (main.sqlite)"
- cp "$STAGE/main.sqlite" "$DATA_DIR/main.sqlite"
+ log "Restoring auth/audit DB -> $MAIN_DB"
+ snapshot_external_db "$MAIN_DB"
+ mkdir -p "$(dirname "$MAIN_DB")"
+ cp "$STAGE/main.sqlite" "$MAIN_DB"
else
log "WARN: main.sqlite not in archive — API keys / audit log will NOT be restored"
fi
if [ -f "$STAGE/openwa.sqlite" ]; then
- log "Restoring data store (openwa.sqlite)"
- cp "$STAGE/openwa.sqlite" "$DATA_DIR/openwa.sqlite"
+ log "Restoring data store -> $DATA_DB"
+ snapshot_external_db "$DATA_DB"
+ mkdir -p "$(dirname "$DATA_DB")"
+ cp "$STAGE/openwa.sqlite" "$DATA_DB"
fi
if [ -d "$STAGE/sessions" ]; then
diff --git a/scripts/smoke-test-backup-restore.sh b/scripts/smoke-test-backup-restore.sh
new file mode 100755
index 000000000..b49932f9c
--- /dev/null
+++ b/scripts/smoke-test-backup-restore.sh
@@ -0,0 +1,245 @@
+#!/usr/bin/env bash
+# Smoke test: scripts/backup.sh + scripts/restore.sh.
+#
+# Covers:
+# (a) custom MAIN_DATABASE_NAME / DATABASE_NAME are honored by BOTH scripts
+# (b) a missing source database fails hard (non-zero, clear message, no archive)
+# (c) backup -> restore roundtrip via sqlite3 .backup (skipped with a notice when the host
+# has no sqlite3 — everything else still runs)
+# (d) the cp fallback writes a CONSISTENCY-WARNING marker into the archive, restore warns
+# but continues, and restore --strict refuses
+# (e) the archive min-content check rejects (and deletes) an archive missing a required DB
+#
+# Usage: ./scripts/smoke-test-backup-restore.sh
+# Requires: bash, tar, node (restore.sh path resolution). sqlite3 is optional (see (c)).
+set -euo pipefail
+
+REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+BACKUP="$REPO_ROOT/scripts/backup.sh"
+RESTORE="$REPO_ROOT/scripts/restore.sh"
+WORK="$(mktemp -d)"
+trap 'rm -rf "$WORK"' EXIT
+
+HAS_SQLITE3=0
+if command -v sqlite3 >/dev/null 2>&1; then
+ HAS_SQLITE3=1
+fi
+
+pass() { echo "PASS: $*"; }
+fail() { echo "FAIL: $*" >&2; exit 1; }
+
+# A fixture database: a real SQLite file with a sentinel row when sqlite3 is available (backup.sh
+# uses .backup then, which refuses non-database files), else a plain marker file for the cp path.
+make_fixture() {
+ if [ "$HAS_SQLITE3" -eq 1 ]; then
+ sqlite3 "$1" "CREATE TABLE sentinel(payload TEXT); INSERT INTO sentinel VALUES('$2');"
+ else
+ printf 'sentinel:%s\n' "$2" >"$1"
+ fi
+}
+
+# Content fingerprint that works for both fixture kinds above. sqlite3 .backup does NOT guarantee
+# a byte-identical copy, so never cmp(1) databases that went through it.
+db_fingerprint() {
+ if [ "$HAS_SQLITE3" -eq 1 ]; then
+ sqlite3 "$1" "SELECT payload FROM sentinel;"
+ else
+ cat "$1"
+ fi
+}
+
+# A PATH farm with every tool backup.sh needs. Used to hide sqlite3 (forcing the cp fallback) or
+# to shadow tar (simulating an incomplete archive) without touching the real scripts.
+populate_shim() {
+ shim_dir="$1"
+ tools="env bash sh cp tar gzip mktemp date rm sed mkdir ls cat chmod grep printf uname dirname"
+ if [ "${2:-}" = "with-sqlite3" ]; then
+ tools="$tools sqlite3"
+ fi
+ for tool in $tools; do
+ src="$(command -v "$tool" 2>/dev/null || true)"
+ if [ -n "$src" ]; then
+ ln -sf "$src" "$shim_dir/$tool"
+ fi
+ done
+}
+
+echo "==> (a) custom MAIN_DATABASE_NAME / DATABASE_NAME are honored"
+A="$WORK/a"
+mkdir -p "$A/custom" "$A/state" "$A/restore"
+make_fixture "$A/custom/auth.sqlite" "alpha-main"
+make_fixture "$A/custom/store.sqlite" "alpha-data"
+(
+ cd "$A"
+ MAIN_DATABASE_NAME="$A/custom/auth.sqlite" \
+ DATABASE_NAME="$A/custom/store.sqlite" \
+ OPENWA_DATA_DIR="$A/state" \
+ BACKUP_DIR="$A/out" \
+ "$BACKUP" >/dev/null
+)
+ARCHIVE_A="$(ls "$A"/out/openwa-backup-*.tar.gz)"
+if ! tar -tzf "$ARCHIVE_A" | grep -qx './main.sqlite'; then
+ fail "(a) archive missing ./main.sqlite"
+fi
+if ! tar -tzf "$ARCHIVE_A" | grep -qx './openwa.sqlite'; then
+ fail "(a) archive missing ./openwa.sqlite"
+fi
+(
+ cd "$A/restore"
+ MAIN_DATABASE_NAME="$A/restore/custom-main.sqlite" \
+ DATABASE_NAME="$A/restore/custom-data.sqlite" \
+ OPENWA_DATA_DIR="$A/restore/state" \
+ "$RESTORE" "$ARCHIVE_A" >/dev/null
+)
+if [ "$(db_fingerprint "$A/restore/custom-main.sqlite")" != "alpha-main" ]; then
+ fail "(a) main DB not restored to the MAIN_DATABASE_NAME path"
+fi
+if [ "$(db_fingerprint "$A/restore/custom-data.sqlite")" != "alpha-data" ]; then
+ fail "(a) data DB not restored to the DATABASE_NAME path"
+fi
+pass "(a) env-resolved DB paths honored by backup.sh and restore.sh"
+
+echo ""
+echo "==> (b) missing source database fails hard"
+B="$WORK/b"
+mkdir -p "$B"
+set +e
+OUT_B="$(cd "$B" && OPENWA_DATA_DIR="$B/state" BACKUP_DIR="$B/out" "$BACKUP" 2>&1)"
+RC_B=$?
+set -e
+if [ "$RC_B" -eq 0 ]; then
+ fail "(b) backup.sh exited 0 with no database present (silent empty backup)"
+fi
+if ! printf '%s' "$OUT_B" | grep -q 'main.sqlite'; then
+ fail "(b) error message does not name the missing main database"
+fi
+if [ -n "$(ls "$B/out" 2>/dev/null || true)" ]; then
+ fail "(b) an archive was written despite the missing database"
+fi
+# Only the data store missing (default paths) must also fail, naming openwa.sqlite.
+B2="$WORK/b2"
+mkdir -p "$B2/data"
+make_fixture "$B2/data/main.sqlite" "b2-main"
+set +e
+OUT_B2="$(cd "$B2" && BACKUP_DIR="$B2/out" "$BACKUP" 2>&1)"
+RC_B2=$?
+set -e
+if [ "$RC_B2" -eq 0 ]; then
+ fail "(b) backup.sh exited 0 with the data store missing"
+fi
+if ! printf '%s' "$OUT_B2" | grep -q 'openwa.sqlite'; then
+ fail "(b) error message does not name the missing data store"
+fi
+pass "(b) missing DB -> non-zero exit, clear message, no archive"
+
+echo ""
+if [ "$HAS_SQLITE3" -eq 1 ]; then
+ echo "==> (c) backup -> restore roundtrip via sqlite3 .backup (default paths)"
+ C="$WORK/c"
+ mkdir -p "$C/src/data" "$C/dst"
+ sqlite3 "$C/src/data/main.sqlite" "CREATE TABLE sentinel(payload TEXT); INSERT INTO sentinel VALUES('c-main');"
+ sqlite3 "$C/src/data/openwa.sqlite" "CREATE TABLE sentinel(payload TEXT); INSERT INTO sentinel VALUES('c-data');"
+ (
+ cd "$C/src"
+ BACKUP_DIR="$C/out" "$BACKUP" >/dev/null
+ )
+ ARCHIVE_C="$(ls "$C"/out/openwa-backup-*.tar.gz)"
+ if tar -tzf "$ARCHIVE_C" | grep -q 'CONSISTENCY-WARNING'; then
+ fail "(c) unexpected CONSISTENCY-WARNING marker with sqlite3 present"
+ fi
+ (
+ cd "$C/dst"
+ "$RESTORE" "$ARCHIVE_C" >/dev/null
+ )
+ if [ "$(sqlite3 "$C/dst/data/main.sqlite" 'SELECT payload FROM sentinel;')" != "c-main" ]; then
+ fail "(c) main DB contents did not survive the roundtrip"
+ fi
+ if [ "$(sqlite3 "$C/dst/data/openwa.sqlite" 'SELECT payload FROM sentinel;')" != "c-data" ]; then
+ fail "(c) data store contents did not survive the roundtrip"
+ fi
+ pass "(c) .backup roundtrip preserves database contents"
+else
+ echo "SKIP: (c) sqlite3 not found on this host — skipping the .backup roundtrip"
+fi
+
+echo ""
+echo "==> (d) cp fallback marker + restore warning + --strict refusal"
+D="$WORK/d"
+mkdir -p "$D/src/data" "$D/shim" "$D/dst"
+# Plain files are fine here: the shim PATH hides sqlite3, so backup.sh takes the cp branch
+# regardless of what the host provides.
+printf 'd-main\n' >"$D/src/data/main.sqlite"
+printf 'd-data\n' >"$D/src/data/openwa.sqlite"
+populate_shim "$D/shim"
+(
+ cd "$D/src"
+ PATH="$D/shim" BACKUP_DIR="$D/out" "$BACKUP" >"$D/backup.log" 2>&1
+)
+ARCHIVE_D="$(ls "$D"/out/openwa-backup-*.tar.gz)"
+if ! tar -tzf "$ARCHIVE_D" | grep -q 'CONSISTENCY-WARNING'; then
+ fail "(d) fallback archive does not carry the CONSISTENCY-WARNING marker"
+fi
+if ! grep -q 'sqlite3' "$D/backup.log"; then
+ fail "(d) backup.sh did not print the loud fallback warning"
+fi
+OUT_D="$(cd "$D/dst" && "$RESTORE" "$ARCHIVE_D" 2>&1)"
+if ! printf '%s' "$OUT_D" | grep -q 'CONSISTENCY-WARNING'; then
+ fail "(d) restore.sh did not surface the consistency warning"
+fi
+if [ "$(cat "$D/dst/data/main.sqlite")" != "d-main" ]; then
+ fail "(d) fallback archive did not restore the main DB"
+fi
+set +e
+OUT_DS="$(cd "$D/dst" && "$RESTORE" "$ARCHIVE_D" --strict 2>&1)"
+RC_DS=$?
+set -e
+if [ "$RC_DS" -eq 0 ]; then
+ fail "(d) restore --strict exited 0 on a marked archive"
+fi
+if ! printf '%s' "$OUT_DS" | grep -q -- '--strict'; then
+ fail "(d) --strict refusal message is not explicit"
+fi
+pass "(d) fallback marker written, restore warns and continues, --strict refuses"
+
+echo ""
+echo "==> (e) archive min-content check rejects an incomplete archive"
+E="$WORK/e"
+mkdir -p "$E/src/data" "$E/shim"
+make_fixture "$E/src/data/main.sqlite" "e-main"
+make_fixture "$E/src/data/openwa.sqlite" "e-data"
+if [ "$HAS_SQLITE3" -eq 1 ]; then
+ populate_shim "$E/shim" with-sqlite3
+else
+ populate_shim "$E/shim"
+fi
+# Shadow tar: create the archive WITHOUT ./openwa.sqlite to simulate a truncated backup.
+# (remove the populate_shim symlink first — writing through it would target the real tar)
+rm -f "$E/shim/tar"
+REAL_TAR="$(command -v tar)"
+cat >"$E/shim/tar" <<EOF
+#!/usr/bin/env bash
+if [ "\$1" = "-czf" ]; then
+ out="\$2"
+ shift 2
+ exec "$REAL_TAR" -czf "\$out" --exclude='./openwa.sqlite' "\$@"
+fi
+exec "$REAL_TAR" "\$@"
+EOF
+chmod +x "$E/shim/tar"
+set +e
+OUT_E="$(cd "$E/src" && PATH="$E/shim" BACKUP_DIR="$E/out" "$BACKUP" 2>&1)"
+RC_E=$?
+set -e
+if [ "$RC_E" -eq 0 ]; then
+ fail "(e) min-content check passed an archive missing openwa.sqlite"
+fi
+if ! printf '%s' "$OUT_E" | grep -q 'openwa.sqlite'; then
+ fail "(e) error message does not name the missing archive member"
+fi
+if [ -n "$(ls "$E/out" 2>/dev/null || true)" ]; then
+ fail "(e) the defective archive was left on disk"
+fi
+pass "(e) min-content check fails hard and removes the defective archive"
+
+echo ""
+echo "All smoke tests passed!"