This commit is contained in:
1 parent
fb556228c7
commit
97803ca5de
9 files changed
+557
-14
No files matched your search
@@ -17,6 +17,8 @@ jobs:
|
||||
run: PYTHONPATH=backend python3 -m unittest discover -s backend -p 'test_*.py' -v
|
||||
- name: Run Telegram bot tests
|
||||
run: python3 -m unittest discover -s tools/telegram-bot -p 'test_*.py' -v
|
||||
- name: Run infrastructure backup tests
|
||||
run: python3 -m unittest discover -s infra/backup -p 'test_*.py' -v
|
||||
- name: Validate production Compose and Caddyfile
|
||||
run: |
|
||||
secret_file=$(mktemp)
|
||||
|
||||
@@ -14,10 +14,14 @@ Python, SQLite и OpenSearch. Production пока не развернут.
|
||||
`codex` общий sudo или доступ к Docker socket. Root-действия требует владелец.
|
||||
Для Gitea используй `gitea-api`, не читай файлы с учётными данными.
|
||||
- Локальные проверки: `PYTHONPATH=backend python3 -m unittest discover -s backend -p 'test_*.py' -v` и
|
||||
`python3 -m unittest discover -s tools/telegram-bot -p 'test_*.py' -v`.
|
||||
`python3 -m unittest discover -s tools/telegram-bot -p 'test_*.py' -v`,
|
||||
`python3 -m unittest discover -s infra/backup -p 'test_*.py' -v`.
|
||||
Production images собираются командами из `.gitea/workflows/ci.yaml`.
|
||||
- Перед изменениями production необходим проверенный backup. Формального
|
||||
механизма миграций нет; проверяй совместимость SQLite/OpenSearch. Не меняй
|
||||
SSH, firewall или production вручную без владельца и последующего PR.
|
||||
- Холодный backup требует согласованного окна простоя; восстановление допускается
|
||||
только в новый staging-каталог, пока владелец отдельно не проверил процедуру
|
||||
для нового хоста.
|
||||
- После каждого изменения инфраструктуры обновляй
|
||||
`docs/operations/CURRENT_STATE.md` по фактическим проверкам.
|
||||
@@ -2,10 +2,9 @@
|
||||
|
||||
## Current status
|
||||
|
||||
No production data or backup mechanism existed during the 2026-10-11 audit.
|
||||
`/var/backups/akyldash` is a planned root-only location, not an active backup.
|
||||
Do not report backup protection as enabled until an archive and restore have
|
||||
both been checked.
|
||||
No production data or backup existed during the 2026-10-11 audit. The repository
|
||||
now contains `infra/backup/archive.py`; it is not installed or run on the VPS,
|
||||
and `/var/backups/akyldash` remains a planned root-only location.
|
||||
|
||||
## Required release policy
|
||||
|
||||
@@ -22,7 +21,45 @@ both been checked.
|
||||
- Test restore into an isolated target before relying on the backup. Do not
|
||||
restore over production as a test.
|
||||
|
||||
The data is not yet managed by a tested backup script. Until that exists, the
|
||||
owner must pause deployment and approve a maintenance window for a reviewed
|
||||
backup/restore procedure. Copying live SQLite files with `cp` or an unchecked
|
||||
tar archive is not an approved backup.
|
||||
## Cold backup procedure
|
||||
|
||||
The script requires every Compose container to be stopped. Schedule downtime,
|
||||
then run from the approved checkout on the VPS:
|
||||
|
||||
```bash
|
||||
cd /opt/akyldash/current
|
||||
sudo docker compose --env-file /etc/akyldash/production.env -f deploy/production/compose.yaml stop
|
||||
sudo python3 infra/backup/archive.py create \
|
||||
--compose-file deploy/production/compose.yaml \
|
||||
--env-file /etc/akyldash/production.env \
|
||||
--output /var/backups/akyldash/akyldash-YYYYMMDDTHHMMSSZ.tar.gz
|
||||
sudo python3 infra/backup/archive.py verify /var/backups/akyldash/akyldash-YYYYMMDDTHHMMSSZ.tar.gz
|
||||
```
|
||||
|
||||
Replace the timestamp placeholder with one real UTC timestamp before running.
|
||||
The create command refuses running services and archives the application data,
|
||||
OpenSearch volume, Caddy data/config volumes, production environment file, and
|
||||
review secret. It records the checked-out Git revision and image IDs for each
|
||||
stopped Compose service, writes a SHA-256 sidecar, and refuses to overwrite an
|
||||
existing archive. It also runs SQLite `quick_check`. Start the stack again only
|
||||
after verification succeeds:
|
||||
|
||||
```bash
|
||||
cd /opt/akyldash/current
|
||||
sudo docker compose --env-file /etc/akyldash/production.env -f deploy/production/compose.yaml up -d
|
||||
```
|
||||
|
||||
Keep the local archive root-only, then copy it to separately managed encrypted
|
||||
storage. A local archive alone does not protect against loss of the VPS disk.
|
||||
Restore extracts only to a new `akyldash-restore-*` directory under `/tmp` or
|
||||
`/var/tmp` and validates the checksum and SQLite databases; it never writes
|
||||
production paths. Example test on an isolated host:
|
||||
|
||||
```bash
|
||||
sudo python3 infra/backup/archive.py restore /var/backups/akyldash/backup.tar.gz \
|
||||
--target-dir /var/tmp/akyldash-restore-test
|
||||
```
|
||||
|
||||
This validates and stages the archive; it does not install data into Compose
|
||||
volumes. Complete and verify the host-specific restore on a separate recovery
|
||||
host before relying on it. Do not run an unreviewed restore over existing data.
|
||||
@@ -44,6 +44,13 @@ from planned configuration.
|
||||
application data use persistent volumes/bind mounts. TLS, registry digest
|
||||
deployment for backend/OpenSearch, backup, rollback helper, and systemd
|
||||
deployment are not configured on the host.
|
||||
- The repository has a cold-backup archive/verification tool with staging-only
|
||||
restore and unit tests. It has not run against production; do not treat this
|
||||
as an active backup or verified recovery.
|
||||
- An isolated local Compose smoke test built the backend/OpenSearch images,
|
||||
reached healthy status for OpenSearch, backend, and Caddy, and returned HTTP
|
||||
200 for `/review` through Caddy. Its containers, networks, and volumes were
|
||||
removed afterward. This does not verify VPS startup, DNS, or public TLS.
|
||||
- The app has no migration framework or SMTP setup. Current app versions:
|
||||
backend `0.11.3`, frontend `0.1.2`, Telegram bot `0.2.2` (the bot is not
|
||||
deployed on this VPS).
|
||||
@@ -53,6 +60,9 @@ from planned configuration.
|
||||
- SSH completed with the user config explicitly selected; plain SSH was blocked
|
||||
by permissions on a system config include. The private key was not read.
|
||||
- UFW rules require root and remain unverified.
|
||||
- The backup archive/restore tool was tested with synthetic local data; a backup
|
||||
and restore of real production data remain unverified because production is
|
||||
not deployed.
|
||||
- The Cloudflare edge response was checked, but origin DNS configuration,
|
||||
Cloudflare Full (strict), certificate validity, Actions runner availability,
|
||||
registry publishing, and production deployment have not been tested.
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
## Current status
|
||||
|
||||
Production deployment is not enabled or tested. The VPS has no Docker, Git,
|
||||
Production deployment is not enabled or tested on the VPS. An isolated local
|
||||
Compose smoke test passed; the VPS has no Docker, Git,
|
||||
application data, proxy, registry pull configuration, backup process, or
|
||||
restricted deploy-helper. Do not deploy until the owner has completed the root
|
||||
bootstrap, provided a protected secret file and a reviewed proxy/firewall
|
||||
|
||||
@@ -24,9 +24,11 @@ run recovery commands against the existing production by accident.
|
||||
(strict) end to end before cutover.
|
||||
5. Provide production configuration and secret files through the owner's
|
||||
protected channel; never commit or paste secret values into chat.
|
||||
6. Restore the latest verified backup to the new host. Validate SQLite
|
||||
databases, corpus checksums, and the OpenSearch snapshot/index before serving
|
||||
traffic.
|
||||
6. Verify the archive and extract it to a new `/var/tmp/akyldash-restore-*`
|
||||
staging directory with `infra/backup/archive.py`. The tool checks the archive
|
||||
checksum and SQLite integrity but does not install staged files into Compose
|
||||
volumes; have the owner review and perform that host-specific step. Validate
|
||||
the corpus and OpenSearch index before serving traffic.
|
||||
7. Start the approved image digest, verify container health and
|
||||
`https://akyldash.kg/review`, then record actual versions and checks in
|
||||
[CURRENT_STATE.md](CURRENT_STATE.md).
|
||||
|
||||
@@ -0,0 +1,333 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Create and verify cold, local Akyldash backups; restore only into staging."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
from pathlib import Path, PurePosixPath
|
||||
|
||||
COMPONENTS = {
|
||||
"data",
|
||||
"opensearch",
|
||||
"caddy-data",
|
||||
"caddy-config",
|
||||
"production-env",
|
||||
"review-secret",
|
||||
}
|
||||
NAME_RE = re.compile(r"^[a-z][a-z0-9-]*$")
|
||||
|
||||
|
||||
def digest(path: Path) -> str:
|
||||
value = hashlib.sha256()
|
||||
with path.open("rb") as stream:
|
||||
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
value.update(chunk)
|
||||
return value.hexdigest()
|
||||
|
||||
|
||||
def checked_members(archive: tarfile.TarFile) -> list[tarfile.TarInfo]:
|
||||
members = archive.getmembers()
|
||||
names: set[str] = set()
|
||||
for member in members:
|
||||
name = PurePosixPath(member.name)
|
||||
if name.is_absolute() or ".." in name.parts or not name.parts:
|
||||
raise ValueError(f"unsafe archive path: {member.name}")
|
||||
if member.name not in {name.as_posix(), f"{name.as_posix()}/"}:
|
||||
raise ValueError(f"non-canonical archive path: {member.name}")
|
||||
if member.name in names:
|
||||
raise ValueError(f"duplicate archive path: {member.name}")
|
||||
names.add(member.name)
|
||||
if not (member.isdir() or member.isfile() or member.issym()):
|
||||
raise ValueError(f"unsupported archive entry: {member.name}")
|
||||
if member.issym():
|
||||
tarfile.data_filter(member, Path("/tmp/akyldash-restore-check"))
|
||||
if "manifest.json" not in names:
|
||||
raise ValueError("backup manifest is missing")
|
||||
if {PurePosixPath(name).parts[0] for name in names if name != "manifest.json"} != COMPONENTS:
|
||||
raise ValueError("backup is missing one or more required components")
|
||||
manifest_member = next(item for item in members if item.name == "manifest.json")
|
||||
if not manifest_member.isfile() or manifest_member.size > 1024 * 1024:
|
||||
raise ValueError("backup manifest is not a regular file")
|
||||
return members
|
||||
|
||||
|
||||
def read_manifest(archive: tarfile.TarFile) -> dict:
|
||||
checked_members(archive)
|
||||
stream = archive.extractfile("manifest.json")
|
||||
if stream is None:
|
||||
raise ValueError("backup manifest is unreadable")
|
||||
manifest = json.load(stream)
|
||||
components = manifest.get("components") if isinstance(manifest, dict) else None
|
||||
if (
|
||||
not isinstance(manifest, dict)
|
||||
or manifest.get("format") != 1
|
||||
or not isinstance(components, list)
|
||||
or not all(isinstance(item, str) for item in components)
|
||||
or set(components) != COMPONENTS
|
||||
):
|
||||
raise ValueError("backup manifest has an unsupported format or component set")
|
||||
if not isinstance(manifest.get("images"), dict):
|
||||
raise ValueError("backup manifest has no image records")
|
||||
for member in archive.getmembers():
|
||||
if member.name == "manifest.json":
|
||||
continue
|
||||
if PurePosixPath(member.name).parts[0] not in COMPONENTS:
|
||||
raise ValueError(f"unexpected top-level archive path: {member.name}")
|
||||
return manifest
|
||||
|
||||
|
||||
def verify_archive(path: Path) -> dict:
|
||||
checksum_path = Path(f"{path}.sha256")
|
||||
expected = checksum_path.read_text(encoding="ascii").split()[0]
|
||||
if not re.fullmatch(r"[0-9a-f]{64}", expected) or digest(path) != expected:
|
||||
raise ValueError("archive SHA-256 does not match its sidecar")
|
||||
with tarfile.open(path, "r:gz") as archive:
|
||||
return read_manifest(archive)
|
||||
|
||||
|
||||
def parse_sources(values: list[str]) -> dict[str, Path]:
|
||||
sources: dict[str, Path] = {}
|
||||
for value in values:
|
||||
name, separator, raw_path = value.partition("=")
|
||||
if not separator or not NAME_RE.fullmatch(name) or name in sources:
|
||||
raise ValueError(f"invalid or duplicate source: {value}")
|
||||
source = Path(raw_path)
|
||||
if not source.is_absolute() or not source.exists() or source.is_symlink():
|
||||
raise ValueError(f"source must be an existing absolute path: {raw_path}")
|
||||
sources[name] = source.resolve(strict=True)
|
||||
if set(sources) != COMPONENTS:
|
||||
missing = ", ".join(sorted(COMPONENTS - sources.keys()))
|
||||
extra = ", ".join(sorted(sources.keys() - COMPONENTS))
|
||||
raise ValueError(f"source set mismatch (missing: {missing or 'none'}; extra: {extra or 'none'})")
|
||||
return sources
|
||||
|
||||
|
||||
def check_sqlite(root: Path) -> None:
|
||||
for path in root.rglob("*.sqlite3"):
|
||||
connection = sqlite3.connect(f"{path.resolve().as_uri()}?mode=ro", uri=True)
|
||||
try:
|
||||
result = connection.execute("PRAGMA quick_check").fetchone()
|
||||
if result != ("ok",):
|
||||
raise ValueError(f"SQLite integrity check failed: {path}")
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
def compose_sources(compose_file: Path, env_file: Path) -> tuple[dict[str, Path], str, dict[str, dict[str, str]]]:
|
||||
command = ["docker", "compose", "--env-file", str(env_file), "-f", str(compose_file)]
|
||||
rendered = subprocess.run(
|
||||
[*command, "config", "--format", "json"], check=True, capture_output=True, text=True
|
||||
)
|
||||
config = json.loads(rendered.stdout)
|
||||
container_result = subprocess.run(
|
||||
[*command, "ps", "--all", "--quiet"], check=True, capture_output=True, text=True
|
||||
)
|
||||
containers = container_result.stdout.split()
|
||||
if not containers:
|
||||
raise ValueError("Compose has no containers; refusing to create an incomplete backup")
|
||||
images: dict[str, dict[str, str]] = {}
|
||||
for container in containers:
|
||||
result = subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"inspect",
|
||||
"--format",
|
||||
'{{.State.Running}}\t{{index .Config.Labels "com.docker.compose.service"}}\t{{.Config.Image}}\t{{.Image}}',
|
||||
container,
|
||||
],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
fields = result.stdout.strip().split("\t")
|
||||
if len(fields) != 4 or fields[0].lower() != "false":
|
||||
raise ValueError("stop all Compose services before taking a cold backup")
|
||||
images[fields[1]] = {"configured": fields[2], "image_id": fields[3]}
|
||||
if set(images) != set(config["services"]):
|
||||
raise ValueError("not all configured Compose services have stopped containers")
|
||||
|
||||
mounts = {
|
||||
mount["target"]: mount
|
||||
for service in config["services"].values()
|
||||
for mount in service.get("volumes", [])
|
||||
}
|
||||
volume_sources: dict[str, Path] = {}
|
||||
for target, component in (
|
||||
("/app/data", "data"),
|
||||
("/usr/share/opensearch/data", "opensearch"),
|
||||
("/data", "caddy-data"),
|
||||
("/config", "caddy-config"),
|
||||
):
|
||||
mount = mounts.get(target)
|
||||
if not mount:
|
||||
raise ValueError(f"persistent Compose mount is missing: {target}")
|
||||
if mount["type"] == "bind":
|
||||
source = Path(mount["source"])
|
||||
elif mount["type"] == "volume":
|
||||
volume_name = config["volumes"][mount["source"]]["name"]
|
||||
result = subprocess.run(
|
||||
["docker", "volume", "inspect", "--format", "{{.Mountpoint}}", volume_name],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
source = Path(result.stdout.strip())
|
||||
else:
|
||||
raise ValueError(f"unsupported persistent mount type at {target}")
|
||||
volume_sources[component] = source
|
||||
|
||||
secret_file = Path(config["secrets"]["review_secret"]["file"])
|
||||
sources = {
|
||||
**volume_sources,
|
||||
"production-env": env_file,
|
||||
"review-secret": secret_file,
|
||||
}
|
||||
repository = compose_file.resolve().parents[2]
|
||||
changed = subprocess.run(
|
||||
["git", "-C", str(repository), "status", "--porcelain", "--", "deploy/production/compose.yaml", "deploy/production/Caddyfile", "deploy/production/Dockerfile.backend", "deploy/production/Dockerfile.opensearch"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
).stdout.strip()
|
||||
if changed:
|
||||
raise ValueError("production deployment files have local Git changes; refusing an untracked backup revision")
|
||||
revision = subprocess.run(
|
||||
["git", "-C", str(repository), "rev-parse", "HEAD"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
).stdout.strip()
|
||||
return parse_sources([f"{name}={path}" for name, path in sources.items()]), revision, images
|
||||
|
||||
|
||||
def create_backup(output: Path, sources: dict[str, Path], revision: str, images: dict | None = None) -> None:
|
||||
output = output.absolute()
|
||||
parent = output.parent
|
||||
if not parent.is_dir() or parent.stat().st_mode & 0o077:
|
||||
raise ValueError("backup directory must exist and have mode 0700 or stricter")
|
||||
if output.exists() or Path(f"{output}.sha256").exists():
|
||||
raise ValueError("refusing to overwrite an existing backup")
|
||||
for name, source in sources.items():
|
||||
if source.is_symlink() or not (source.is_dir() or source.is_file()):
|
||||
raise ValueError(f"source must be a regular file or directory: {name}")
|
||||
if source.is_dir() and (output == source or source in output.parents):
|
||||
raise ValueError(f"backup output cannot be inside source {name}")
|
||||
for name in ("production-env", "review-secret"):
|
||||
if not sources[name].is_file():
|
||||
raise ValueError(f"sensitive component must be a regular file: {name}")
|
||||
if sources["data"].is_dir():
|
||||
check_sqlite(sources["data"])
|
||||
|
||||
manifest = {
|
||||
"format": 1,
|
||||
"created_at": dt.datetime.now(dt.timezone.utc).isoformat(),
|
||||
"git_revision": revision,
|
||||
"images": images or {},
|
||||
"components": sorted(sources),
|
||||
}
|
||||
with tempfile.NamedTemporaryFile(dir=parent, prefix=".akyldash-backup-", delete=False) as temp:
|
||||
temporary = Path(temp.name)
|
||||
os.chmod(temporary, 0o600)
|
||||
checksum_temp = Path(f"{temporary}.sha256")
|
||||
try:
|
||||
with tarfile.open(temporary, "w:gz") as archive:
|
||||
encoded = json.dumps(manifest, sort_keys=True).encode("utf-8")
|
||||
info = tarfile.TarInfo("manifest.json")
|
||||
info.size = len(encoded)
|
||||
info.mode = 0o600
|
||||
archive.addfile(info, io.BytesIO(encoded))
|
||||
for name, source in sorted(sources.items()):
|
||||
def protect_secrets(member: tarfile.TarInfo) -> tarfile.TarInfo:
|
||||
if name in {"production-env", "review-secret"}:
|
||||
member.mode = 0o600
|
||||
if member.name.endswith((".sqlite3", ".sqlite3-wal", ".sqlite3-shm")):
|
||||
member.mode = 0o600
|
||||
return member
|
||||
|
||||
archive.add(source, arcname=name, recursive=True, filter=protect_secrets)
|
||||
with tarfile.open(temporary, "r:gz") as archive:
|
||||
read_manifest(archive)
|
||||
checksum_fd = os.open(checksum_temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||
with os.fdopen(checksum_fd, "w", encoding="ascii") as stream:
|
||||
stream.write(f"{digest(temporary)} {output.name}\n")
|
||||
os.link(temporary, output)
|
||||
try:
|
||||
os.link(checksum_temp, Path(f"{output}.sha256"))
|
||||
except Exception:
|
||||
output.unlink(missing_ok=True)
|
||||
raise
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
checksum_temp.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def restore_to_staging(backup: Path, target: Path) -> None:
|
||||
if not target.name.startswith("akyldash-restore-"):
|
||||
raise ValueError("restore target must be a new akyldash-restore-* staging directory")
|
||||
parent = target.parent.resolve()
|
||||
if not any(parent == root or root in parent.parents for root in (Path("/tmp"), Path("/var/tmp"))):
|
||||
raise ValueError("restore staging directory must be under /tmp or /var/tmp")
|
||||
if target.exists():
|
||||
raise ValueError("restore target already exists; refusing to overwrite it")
|
||||
target = parent / target.name
|
||||
verify_archive(backup)
|
||||
target.mkdir(mode=0o700)
|
||||
try:
|
||||
with tarfile.open(backup, "r:gz") as archive:
|
||||
members = checked_members(archive)
|
||||
required_bytes = sum(member.size for member in members if member.isfile())
|
||||
if shutil.disk_usage(parent).free < required_bytes + 512 * 1024 * 1024:
|
||||
raise ValueError("insufficient free space for a validated restore staging copy")
|
||||
for member in members:
|
||||
archive.extract(member, target, filter="data")
|
||||
check_sqlite(target / "data")
|
||||
except Exception:
|
||||
shutil.rmtree(target)
|
||||
raise
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
subparsers = parser.add_subparsers(dest="command", required=True)
|
||||
create = subparsers.add_parser("create", help="create a cold backup archive")
|
||||
create.add_argument("--output", required=True, type=Path)
|
||||
create.add_argument("--compose-file", required=True, type=Path)
|
||||
create.add_argument("--env-file", required=True, type=Path)
|
||||
verify = subparsers.add_parser("verify", help="verify archive checksum and contents")
|
||||
verify.add_argument("archive", type=Path)
|
||||
restore = subparsers.add_parser("restore", help="extract into a new staging directory")
|
||||
restore.add_argument("archive", type=Path)
|
||||
restore.add_argument("--target-dir", required=True, type=Path)
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
if args.command in {"create", "restore"} and os.geteuid() != 0:
|
||||
raise ValueError("create and restore must run as root to protect production secrets and data")
|
||||
if args.command == "create":
|
||||
sources, revision, images = compose_sources(args.compose_file, args.env_file)
|
||||
create_backup(args.output, sources, revision, images)
|
||||
elif args.command == "verify":
|
||||
manifest = verify_archive(args.archive)
|
||||
print(f"PASS backup {args.archive}: {manifest['git_revision']} ({len(manifest['components'])} components)")
|
||||
else:
|
||||
restore_to_staging(args.archive, args.target_dir)
|
||||
print(f"PASS restored and validated staging data at {args.target_dir}")
|
||||
except (OSError, ValueError, tarfile.TarError, json.JSONDecodeError, sqlite3.Error, IndexError, subprocess.SubprocessError) as error:
|
||||
print(f"ERROR: {error}", file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,153 @@
|
||||
import hashlib
|
||||
import json
|
||||
import sqlite3
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from archive import COMPONENTS, compose_sources, create_backup, restore_to_staging, verify_archive
|
||||
|
||||
|
||||
class BackupArchiveTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temporary = tempfile.TemporaryDirectory()
|
||||
self.root = Path(self.temporary.name)
|
||||
self.private = self.root / "private"
|
||||
self.private.mkdir(mode=0o700)
|
||||
self.sources = {}
|
||||
for name in COMPONENTS:
|
||||
source = self.root / name
|
||||
source.mkdir()
|
||||
self.sources[name] = source
|
||||
for name in ("production-env", "review-secret"):
|
||||
path = self.root / f"{name}.txt"
|
||||
path.write_text("private", encoding="utf-8")
|
||||
path.chmod(0o644)
|
||||
self.sources[name] = path
|
||||
connection = sqlite3.connect(self.sources["data"] / "search-users.sqlite3")
|
||||
connection.execute("CREATE TABLE users (id INTEGER PRIMARY KEY)")
|
||||
connection.commit()
|
||||
connection.close()
|
||||
self.backup = self.private / "backup.tar.gz"
|
||||
|
||||
def tearDown(self):
|
||||
self.temporary.cleanup()
|
||||
|
||||
def test_create_verify_and_restore_only_to_new_staging(self):
|
||||
create_backup(self.backup, self.sources, "abc123")
|
||||
manifest = verify_archive(self.backup)
|
||||
self.assertEqual(manifest["git_revision"], "abc123")
|
||||
self.assertEqual(manifest["images"], {})
|
||||
|
||||
target = self.root / "akyldash-restore-test"
|
||||
restore_to_staging(self.backup, target)
|
||||
self.assertTrue((target / "data/search-users.sqlite3").is_file())
|
||||
self.assertEqual((target / "data/search-users.sqlite3").stat().st_mode & 0o777, 0o600)
|
||||
self.assertEqual((target / "production-env").stat().st_mode & 0o777, 0o600)
|
||||
self.assertEqual((target / "review-secret").stat().st_mode & 0o777, 0o600)
|
||||
self.assertEqual(verify_archive(self.backup)["components"], sorted(COMPONENTS))
|
||||
|
||||
def test_rejects_checksum_mismatch_without_creating_staging(self):
|
||||
create_backup(self.backup, self.sources, "abc123")
|
||||
self.backup.write_bytes(self.backup.read_bytes() + b"tamper")
|
||||
target = self.root / "akyldash-restore-tampered"
|
||||
with self.assertRaisesRegex(ValueError, "SHA-256"):
|
||||
restore_to_staging(self.backup, target)
|
||||
self.assertFalse(target.exists())
|
||||
|
||||
def test_rejects_non_staging_and_existing_targets(self):
|
||||
create_backup(self.backup, self.sources, "abc123")
|
||||
with self.assertRaisesRegex(ValueError, "staging"):
|
||||
restore_to_staging(self.backup, self.root / "production")
|
||||
target = self.root / "akyldash-restore-existing"
|
||||
target.mkdir()
|
||||
with self.assertRaisesRegex(ValueError, "already exists"):
|
||||
restore_to_staging(self.backup, target)
|
||||
|
||||
def test_create_checks_sqlite_integrity_before_writing_archive(self):
|
||||
(self.sources["data"] / "search-reviews.sqlite3").write_bytes(b"not a database")
|
||||
with self.assertRaises(sqlite3.DatabaseError):
|
||||
create_backup(self.backup, self.sources, "abc123")
|
||||
self.assertFalse(self.backup.exists())
|
||||
|
||||
def test_rejects_unsafe_archive_paths(self):
|
||||
archive_path = self.private / "unsafe.tar.gz"
|
||||
with tarfile.open(archive_path, "w:gz") as archive:
|
||||
archive.addfile(tarfile.TarInfo("manifest.json"))
|
||||
archive.addfile(tarfile.TarInfo("../outside"))
|
||||
checksum = hashlib.sha256(archive_path.read_bytes()).hexdigest()
|
||||
Path(f"{archive_path}.sha256").write_text(f"{checksum} unsafe.tar.gz\n")
|
||||
with self.assertRaisesRegex(ValueError, "unsafe archive path"):
|
||||
verify_archive(archive_path)
|
||||
|
||||
def test_cold_backup_refuses_a_running_compose_container(self):
|
||||
config = {"services": {}, "volumes": {}, "secrets": {}}
|
||||
|
||||
def run(command, **_kwargs):
|
||||
if "config" in command:
|
||||
return SimpleNamespace(stdout=json.dumps(config))
|
||||
if "ps" in command:
|
||||
return SimpleNamespace(stdout="container-id\n")
|
||||
return SimpleNamespace(stdout="true\n")
|
||||
|
||||
with patch("archive.subprocess.run", side_effect=run):
|
||||
with self.assertRaisesRegex(ValueError, "stop all Compose services"):
|
||||
compose_sources(Path("deploy/production/compose.yaml"), Path("/etc/akyldash/production.env"))
|
||||
|
||||
def test_compose_backup_records_sources_and_image_ids(self):
|
||||
data = self.root / "production-data"
|
||||
data.mkdir()
|
||||
secret = self.root / "secret"
|
||||
secret.write_text("private", encoding="utf-8")
|
||||
env_file = self.root / "production.env"
|
||||
env_file.write_text("DATA_ROOT=/var/lib/akyldash/data\n", encoding="utf-8")
|
||||
volumes = {}
|
||||
volume_paths = {}
|
||||
mounts = {
|
||||
"caddy": [
|
||||
{"type": "volume", "source": "caddy-data", "target": "/data"},
|
||||
{"type": "volume", "source": "caddy-config", "target": "/config"},
|
||||
],
|
||||
"backend": [{"type": "bind", "source": str(data), "target": "/app/data"}],
|
||||
"opensearch": [
|
||||
{"type": "volume", "source": "opensearch-data", "target": "/usr/share/opensearch/data"}
|
||||
],
|
||||
}
|
||||
for name in ("caddy-data", "caddy-config", "opensearch-data"):
|
||||
path = self.root / f"volume-{name}"
|
||||
path.mkdir()
|
||||
volumes[name] = {"name": f"akyldash_{name}"}
|
||||
volume_paths[f"akyldash_{name}"] = path
|
||||
config = {
|
||||
"services": {name: {"volumes": values} for name, values in mounts.items()},
|
||||
"volumes": volumes,
|
||||
"secrets": {"review_secret": {"file": str(secret)}},
|
||||
}
|
||||
service_names = ["caddy", "backend", "opensearch"]
|
||||
|
||||
def run(command, **_kwargs):
|
||||
if "config" in command:
|
||||
return SimpleNamespace(stdout=json.dumps(config))
|
||||
if "ps" in command:
|
||||
return SimpleNamespace(stdout="\n".join(f"{name}-id" for name in service_names))
|
||||
if command[1] == "inspect":
|
||||
name = command[-1].removesuffix("-id")
|
||||
return SimpleNamespace(stdout=f"false\t{name}\t{name}:local\tsha256:{name}\n")
|
||||
if command[1] == "volume":
|
||||
return SimpleNamespace(stdout=f"{volume_paths[command[-1]]}\n")
|
||||
return SimpleNamespace(stdout="")
|
||||
|
||||
with patch("archive.subprocess.run", side_effect=run):
|
||||
sources, revision, images = compose_sources(
|
||||
Path.cwd() / "deploy/production/compose.yaml", env_file
|
||||
)
|
||||
self.assertEqual(revision, "")
|
||||
self.assertEqual(set(sources), COMPONENTS)
|
||||
self.assertEqual(images["backend"]["image_id"], "sha256:backend")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -71,7 +71,8 @@ target:
|
||||
- infra/bootstrap/verify.sh akyldash_vps
|
||||
- docker compose -f deploy/production/compose.yaml ps
|
||||
- curl -fsS https://akyldash.kg/review
|
||||
backup_path: /var/backups/akyldash (target; mechanism not configured)
|
||||
- python3 infra/backup/archive.py verify /var/backups/akyldash/<archive>.tar.gz
|
||||
backup_path: /var/backups/akyldash (target; archive script in infra/backup/archive.py is not installed or run)
|
||||
versions:
|
||||
application:
|
||||
backend: 0.11.3
|
||||
|
||||
Reference in new issue
Block a user