Fix production backup bootstrap guidance
CI / tests-and-images (pull_request) Has been cancelled

This commit is contained in:
agent committed 2026-10-11 22:50:39 +03:00
1 parent 9084fd4f16
commit d6d029d98c
6 files changed
+324 -106

No files matched your search

+77 -62
View File
@@ -1,76 +1,91 @@
# Production deployment
This compose project runs Caddy, the Search API, and a private OpenSearch node.
Caddy serves `akyldash.kg` over HTTPS and proxies to the API. Only Caddy publishes
ports `80` and `443`; the API has no host port, and OpenSearch is reachable only
from the backend's private network.
Compose runs Caddy, the Search API, and a private OpenSearch node. Only Caddy
publishes ports `80` and `443`; backend and OpenSearch have no host ports. The
OpenSearch security plugin is disabled to match the current API client, so keep
it on the private network.
The current compose intentionally disables the OpenSearch security plugin to
match the existing API client. Keep OpenSearch on its private network.
The application provides cookie-based accounts for its search API and review
workspace; it does not replace host-level network controls or TLS.
## Host access and configuration
## First deployment
1. Copy this directory to the host with the repository source.
2. Copy `.env.example` to `.env`, set an absolute `DATA_ROOT`, and create the
secret file referenced by `REVIEW_SECRET_FILE` outside the repository:
```bash
sudo install -d -o root -g root -m 0700 /etc/akyldash
sudo sh -c 'umask 077; openssl rand -hex 32 > /etc/akyldash/review_secret'
```
Do not commit `.env` or the secret file.
3. Put the normalized dataset under `$DATA_ROOT/minjust-normalized/`.
4. Confirm DNS points through Cloudflare to this origin. Have the owner review
the existing firewall rules and allow TCP `80` and `443` before Caddy starts.
Caddy requests and renews the origin certificate automatically; use
Cloudflare Full (strict) only after HTTPS succeeds.
5. Complete and verify the backup/restore setup before starting production.
The repository does not yet contain a tested backup script; do not continue
until the owner has approved and tested one.
6. Check the rendered configuration:
```bash
docker compose --env-file .env -f compose.yaml config
```
7. Start the services:
```bash
docker compose --env-file .env -f compose.yaml up -d --build
docker compose --env-file .env -f compose.yaml ps
curl -fsS https://akyldash.kg/review >/dev/null
```
8. Load the versioned index and switch its alias only after the import and
validation succeed, after creating another verified pre-change backup.
## Initial administrator and accounts
After starting the backend for the first time, create the initial `admin`
account with an interactive password prompt:
The production environment file is `/etc/akyldash/production.env`; the review
secret is `/etc/akyldash/review_secret`. Both must stay outside the checkout,
root-owned, and mode `0600`. `DATA_ROOT` must be an absolute path. The `codex`
account is intentionally outside the `sudo` and `docker` groups because access
to the Docker socket grants root-equivalent control. Run host operations with
the narrowly required `sudo` command; do not use `docker` as `codex` directly.
```bash
docker compose --env-file .env -f compose.yaml exec backend python -m search.api --create-admin
sudo install -d -o root -g root -m 0700 /etc/akyldash
sudo install -o root -g root -m 0600 deploy/production/.env.example /etc/akyldash/production.env
sudo sh -c 'umask 077; openssl rand -hex 32 > /etc/akyldash/review_secret'
sudoedit /etc/akyldash/production.env
```
The account database is stored at `DATA_ROOT/search-users.sqlite3`. Back it up
alongside the review database. Sign in at `/review`; `admin` can create accounts
with temporary passwords. Each new account must replace its temporary password
at first sign-in. Only the `admin` login can create, reset, or delete accounts.
Set `DATA_ROOT` to the approved data directory and ensure the normalized corpus
is at `$DATA_ROOT/minjust-normalized/`. The first host setup is documented in
[`docs/operations/DEPLOYMENT.md`](../../docs/operations/DEPLOYMENT.md); the
root bootstrap installs packages and creates directories, but does not deploy
the application or alter SSH, firewall, user groups, or sudoers.
If the `admin` password is lost, reset it in an interactive terminal with:
## First deployment and upgrades
Run commands from the root-owned checkout at `/opt/akyldash/current`. Render
and review Compose before changing services:
```bash
docker compose --env-file .env -f compose.yaml exec backend python -m search.api --reset-admin-password
cd /opt/akyldash/current
sudo docker compose --env-file /etc/akyldash/production.env -f deploy/production/compose.yaml config --quiet
```
The next sign-in requires another password change. Serve the backend behind
HTTPS, rate-limit login requests at the reverse proxy, and keep
`COOKIE_SECURE=true` in production.
On a clean first deployment, `infra/backup/archive.py create` reports that no
backup is required when all persistent mounts are empty and no Compose
containers exist. Continue without a backup in that case. If any persistent
data exists, create and verify a backup before changing schema, images, or
starting a new application version. This also applies when containers are
absent. The archive tool refuses ambiguous storage state, running containers,
and incomplete Compose service containers. See
[`docs/operations/BACKUP.md`](../../docs/operations/BACKUP.md) for the exact
commands. Do not remove an older usable backup to make room; retain the
pre-change archive until the new deployment and a newer verified backup are
confirmed.
This is a deployment baseline, not a public internet exposure recipe. TLS,
backups, monitoring, and a production OpenSearch security configuration must
be provided by the host reverse proxy/operations setup.
For an initial clean installation, start the stack only after config review:
```bash
sudo docker compose --env-file /etc/akyldash/production.env -f deploy/production/compose.yaml up -d --build
sudo docker compose --env-file /etc/akyldash/production.env -f deploy/production/compose.yaml ps
curl -fsS https://akyldash.kg/review >/dev/null
```
Before this step, confirm DNS and have the owner review firewall rules for TCP
`80` and `443`. Caddy manages the origin certificate; confirm HTTPS before
setting Cloudflare to Full (strict). On the initial start, create the `admin`
account interactively:
```bash
sudo docker compose --env-file /etc/akyldash/production.env -f deploy/production/compose.yaml exec backend python -m search.api --create-admin
```
The account database is `$DATA_ROOT/search-users.sqlite3` and is included in
the `data` backup. Admin password reset is also interactive:
```bash
sudo docker compose --env-file /etc/akyldash/production.env -f deploy/production/compose.yaml exec backend python -m search.api --reset-admin-password
```
## Backup, restore, and rollback
Backups are cold and require downtime. Stop services, create the archive, then
verify both its checksum and contents before proceeding. Do not run an upgrade
or schema change until verification succeeds. Keep archives root-only under
`/var/backups/akyldash` and copy them to separately managed encrypted storage.
Restore is a staged operation on a marked replacement host; it does not
overwrite production. For application-only rollback, use the guarded helper
with a verified pre-release backup and explicit data-compatibility review.
Follow the procedures in [`BACKUP.md`](../../docs/operations/BACKUP.md),
[`ROLLBACK.md`](../../docs/operations/ROLLBACK.md), and
[`RECOVERY.md`](../../docs/operations/RECOVERY.md).
Automated production deployment is not enabled. Deployments remain owner-run;
record the release and verify service health before considering it complete.
+15 -3
View File
@@ -14,13 +14,22 @@ and `/var/backups/akyldash` remains a planned root-only location.
`search-reviews.sqlite3`, the OpenSearch index/snapshot, deployment digest,
Caddy's certificate data, and required secret file in the protected backup
set. Store secrets and Caddy private keys with equivalent access controls.
- Verify archive readability, checksums, and SQLite integrity before
replacing the previous known-good backup.
- Verify archive readability, checksums, and SQLite integrity before relying
on it. Never overwrite or delete the only usable backup.
- Keep one current pre-release backup. If deployment fails, retain the backup
required to restore the previous state.
- Test restore into an isolated target before relying on the backup. Do not
restore over production as a test.
## Clean first deployment
No backup is needed only when Compose has no containers and all four
persistent mounts are confirmed empty. Named volumes not created yet count as
empty on a clean first deployment. Review the rendered config and let the
archive tool make this determination; missing mount definitions, inaccessible
volumes, or missing volumes alongside existing data are an error and must stop
deployment. Do not create placeholder containers to make backup pass.
## Cold backup procedure
The script requires every Compose container to be stopped. Schedule downtime,
@@ -37,7 +46,10 @@ sudo python3 infra/backup/archive.py verify /var/backups/akyldash/akyldash-YYYYM
```
Replace the timestamp placeholder with one real UTC timestamp before running.
The create command refuses running services and archives the application data,
On a clean first deployment, `create` exits with a clear message that backup
can be skipped. With any existing persistent data it archives the available
storage even when no Compose containers exist; partial service containers or
running services are rejected as unsafe. The create command archives the application data,
OpenSearch volume, Caddy data/config volumes, production environment file, and
review secret. It records the checked-out Git revision, deployment-file hashes,
and image references/IDs for each stopped Compose service, writes a SHA-256
+8 -1
View File
@@ -48,7 +48,10 @@ from planned configuration.
deployment are not configured on the host.
- The repository has a cold-backup archive/verification tool and a one-shot
restore apply tool that requires a marked replacement host. Backup/restore
tests use synthetic data; neither tool has run against production.
tests use synthetic data; neither tool has run against production. The
archive preflight now permits a clean first deployment to skip backup,
requires backup for existing persistent data even without containers, and
rejects missing/ambiguous mounts or incomplete/running service containers.
- Recovery bootstrap has an explicit `--recovery-target` mode that refuses the
inventoried production hostname/IP; its host-identity guard has shell tests.
The mode has not been run on a VPS.
@@ -71,6 +74,10 @@ from planned configuration.
- 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.
- Production instructions now use `/etc/akyldash/production.env` and root-run
Docker commands, consistent with the `codex` account's restricted access.
Initial deployment and upgrade backup ordering are documented; no production
host was changed for this PR.
- 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.
+9 -4
View File
@@ -19,7 +19,9 @@ proxy/firewall configuration, and a backup and restore have been tested.
`--recovery-target` only on a replacement host; it refuses the known
production host identity.
2. Install the approved repository checkout at `/opt/akyldash/current`,
root-owned and not group/world-writable. Configure
root-owned and not group/world-writable. Copy
`deploy/production/.env.example` to `/etc/akyldash/production.env`, set
`DATA_ROOT`, and configure
`/etc/akyldash/production.env` plus `/etc/akyldash/review_secret` outside
Git. The secret file must be root-readable only.
3. After reviewing the root-owned checkout, run
@@ -31,9 +33,12 @@ proxy/firewall configuration, and a backup and restore have been tested.
existing SSH access. The Compose Caddy service obtains and renews its HTTPS
certificate automatically; Cloudflare Full (strict) still needs owner-side
verification.
5. Create and verify the first backup before starting services. Load and
validate the OpenSearch index, create the initial admin interactively, and
verify `/review` over HTTPS. Record the backend image ID for drift checks:
5. For a clean first deployment, skip backup only when Compose confirms there
are no containers and all persistent mounts are empty. If any data exists,
create and verify a backup before starting a new version. An uncertain or
partial state stops deployment. Then start services, load and validate the
OpenSearch index, create the initial admin interactively, and verify
`/review` over HTTPS. Record the backend image ID for drift checks:
```bash
sudo sh -c 'docker compose --env-file /etc/akyldash/production.env -f /opt/akyldash/current/deploy/production/compose.yaml ps --quiet backend | xargs -r docker inspect --format "{{.Image}}" > /opt/akyldash/deployed-image.txt'
+53 -34
View File
@@ -127,6 +127,51 @@ def check_sqlite(root: Path) -> None:
connection.close()
def compose_storage(config: dict) -> dict[str, Path | None]:
mounts = {
mount["target"]: mount
for service in config["services"].values()
for mount in service.get("volumes", [])
}
volumes = subprocess.run(
["docker", "volume", "ls", "--quiet"], check=True, capture_output=True, text=True
).stdout.split()
sources: dict[str, Path | None] = {}
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"]
if volume_name not in volumes:
sources[component] = None
continue
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}")
if not source.is_dir() or source.is_symlink():
raise ValueError(f"cannot determine persistent data state for {component}: {source}")
sources[component] = source
return sources
def has_persistent_data(sources: dict[str, Path | None]) -> bool:
return any(any(path.iterdir()) for path in sources.values() if path is not None)
def compose_sources(
compose_file: Path, env_file: Path
) -> tuple[dict[str, Path], str, dict[str, dict[str, str]], dict[str, str]]:
@@ -139,8 +184,12 @@ def compose_sources(
[*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")
storage = compose_storage(config)
persistent_data = has_persistent_data(storage)
if not containers and not persistent_data:
raise ValueError("no backup is required for a clean first deployment; skip backup and start the initial stack")
if any(path is None for path in storage.values()):
raise ValueError("persistent Compose volumes are missing while data exists; refusing an incomplete backup")
images: dict[str, dict[str, str]] = {}
for container in containers:
result = subprocess.run(
@@ -159,42 +208,12 @@ def compose_sources(
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"]):
if containers and 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,
**storage,
"production-env": env_file,
"review-secret": secret_file,
}
+162 -2
View File
@@ -84,18 +84,176 @@ class BackupArchiveTests(unittest.TestCase):
verify_archive(archive_path)
def test_cold_backup_refuses_a_running_compose_container(self):
config = {"services": {}, "volumes": {}, "secrets": {}}
config, volume_paths, env_file, _secret = self.compose_fixture()
def run(command, **_kwargs):
if "config" in command:
return SimpleNamespace(stdout=json.dumps(config))
if "ps" in command:
return SimpleNamespace(stdout="container-id\n")
if command[1] == "volume":
if "ls" in command:
return SimpleNamespace(stdout="\n".join(volume_paths) + "\n")
return SimpleNamespace(stdout=f"{volume_paths[command[-1]]}\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"))
compose_sources(Path.cwd() / "deploy/production/compose.yaml", env_file)
def compose_fixture(self):
paths = {}
mounts = {
"backend": [{"type": "bind", "source": str(self.root / "data"), "target": "/app/data"}],
"opensearch": [{"type": "volume", "source": "os-data", "target": "/usr/share/opensearch/data"}],
"caddy": [
{"type": "volume", "source": "caddy-data", "target": "/data"},
{"type": "volume", "source": "caddy-config", "target": "/config"},
],
}
volumes = {}
for volume in ("os-data", "caddy-data", "caddy-config"):
name = f"akyldash_{volume}"
path = self.root / name
path.mkdir()
paths[name] = path
volumes[volume] = {"name": name}
env_file = self.root / "production.env"
env_file.write_text("DATA_ROOT=/var/lib/akyldash/data\n", encoding="utf-8")
secret = self.root / "review-secret.txt"
secret.write_text("secret", encoding="utf-8")
config = {
"services": {name: {"volumes": value} for name, value in mounts.items()},
"volumes": volumes,
"secrets": {"review_secret": {"file": str(secret)}},
}
return config, paths, env_file, secret
def test_clean_first_deployment_does_not_require_backup(self):
config, volume_paths, env_file, _secret = self.compose_fixture()
(self.root / "data/search-users.sqlite3").unlink()
def run(command, **_kwargs):
if "config" in command:
return SimpleNamespace(stdout=json.dumps(config))
if "ps" in command:
return SimpleNamespace(stdout="")
if command[1] == "volume":
if "ls" in command:
return SimpleNamespace(stdout="\n".join(volume_paths) + "\n")
return SimpleNamespace(stdout=f"{volume_paths[command[-1]]}\n")
if "status" in command:
return SimpleNamespace(stdout="")
raise AssertionError(command)
with patch("archive.subprocess.run", side_effect=run):
with self.assertRaisesRegex(ValueError, "clean first deployment"):
compose_sources(Path.cwd() / "deploy/production/compose.yaml", env_file)
def test_first_deployment_with_uncreated_named_volumes_is_clean(self):
config, _volume_paths, env_file, _secret = self.compose_fixture()
(self.root / "data/search-users.sqlite3").unlink()
def run(command, **_kwargs):
if "config" in command:
return SimpleNamespace(stdout=json.dumps(config))
if "ps" in command:
return SimpleNamespace(stdout="")
if command[1] == "volume" and "ls" in command:
return SimpleNamespace(stdout="")
raise AssertionError(command)
with patch("archive.subprocess.run", side_effect=run):
with self.assertRaisesRegex(ValueError, "clean first deployment"):
compose_sources(Path.cwd() / "deploy/production/compose.yaml", env_file)
def test_existing_data_without_containers_is_backup_eligible(self):
config, volume_paths, env_file, _secret = self.compose_fixture()
(volume_paths["akyldash_os-data"] / "node-data").mkdir()
def run(command, **_kwargs):
if "config" in command:
return SimpleNamespace(stdout=json.dumps(config))
if "ps" in command:
return SimpleNamespace(stdout="")
if command[1] == "volume":
if "ls" in command:
return SimpleNamespace(stdout="\n".join(volume_paths) + "\n")
return SimpleNamespace(stdout=f"{volume_paths[command[-1]]}\n")
if "status" in command:
return SimpleNamespace(stdout="")
if "rev-parse" in command:
return SimpleNamespace(stdout="abc123\n")
raise AssertionError(command)
with patch("archive.subprocess.run", side_effect=run):
sources, _revision, images, _deployment_files = compose_sources(
Path.cwd() / "deploy/production/compose.yaml", env_file
)
self.assertEqual(set(sources), COMPONENTS)
self.assertEqual(images, {})
self.assertEqual(sources["opensearch"], volume_paths["akyldash_os-data"])
def test_missing_persistent_mount_state_is_rejected(self):
config, volume_paths, env_file, _secret = self.compose_fixture()
volume_paths["akyldash_os-data"].rmdir()
def run(command, **_kwargs):
if "config" in command:
return SimpleNamespace(stdout=json.dumps(config))
if "ps" in command:
return SimpleNamespace(stdout="")
if command[1] == "volume":
if "ls" in command:
return SimpleNamespace(stdout="\n".join(volume_paths) + "\n")
return SimpleNamespace(stdout=f"{volume_paths[command[-1]]}\n")
raise AssertionError(command)
with patch("archive.subprocess.run", side_effect=run):
with self.assertRaisesRegex(ValueError, "cannot determine persistent data state"):
compose_sources(Path.cwd() / "deploy/production/compose.yaml", env_file)
def test_partial_compose_containers_are_rejected_with_existing_data(self):
config, volume_paths, env_file, _secret = self.compose_fixture()
(volume_paths["akyldash_os-data"] / "node-data").mkdir()
def run(command, **_kwargs):
if "config" in command:
return SimpleNamespace(stdout=json.dumps(config))
if "ps" in command:
return SimpleNamespace(stdout="backend-id\n")
if command[1] == "volume":
if "ls" in command:
return SimpleNamespace(stdout="\n".join(volume_paths) + "\n")
return SimpleNamespace(stdout=f"{volume_paths[command[-1]]}\n")
if command[1] == "inspect":
return SimpleNamespace(stdout="false\tbackend\tbackend:local\tsha256:backend\n")
raise AssertionError(command)
with patch("archive.subprocess.run", side_effect=run):
with self.assertRaisesRegex(ValueError, "not all configured Compose services"):
compose_sources(Path.cwd() / "deploy/production/compose.yaml", env_file)
def test_existing_data_with_missing_named_volume_is_rejected_as_incomplete(self):
config, volume_paths, env_file, _secret = self.compose_fixture()
(self.root / "data/search-users.sqlite3").unlink()
(self.root / "data/existing.json").write_text("data", encoding="utf-8")
available = set(volume_paths) - {"akyldash_os-data"}
def run(command, **_kwargs):
if "config" in command:
return SimpleNamespace(stdout=json.dumps(config))
if "ps" in command:
return SimpleNamespace(stdout="")
if command[1] == "volume" and "ls" in command:
return SimpleNamespace(stdout="\n".join(available) + "\n")
if command[1] == "volume":
return SimpleNamespace(stdout=f"{volume_paths[command[-1]]}\n")
raise AssertionError(command)
with patch("archive.subprocess.run", side_effect=run):
with self.assertRaisesRegex(ValueError, "persistent Compose volumes are missing"):
compose_sources(Path.cwd() / "deploy/production/compose.yaml", env_file)
def test_compose_backup_records_sources_and_image_ids(self):
data = self.root / "production-data"
@@ -137,6 +295,8 @@ class BackupArchiveTests(unittest.TestCase):
name = command[-1].removesuffix("-id")
return SimpleNamespace(stdout=f"false\t{name}\t{name}:local\tsha256:{name}\n")
if command[1] == "volume":
if "ls" in command:
return SimpleNamespace(stdout="\n".join(volume_paths) + "\n")
return SimpleNamespace(stdout=f"{volume_paths[command[-1]]}\n")
return SimpleNamespace(stdout="")