From fb556228c7d7e61c70a614938ab4514ae4dcbca3 Mon Sep 17 00:00:00 2001 From: Codex Agent Date: Sun, 11 Oct 2026 18:57:08 +0300 Subject: [PATCH] Configure Caddy HTTPS proxy for production --- .gitea/workflows/ci.yaml | 6 +++++ CHANGELOG.md | 2 +- deploy/production/.env.example | 1 - deploy/production/Caddyfile | 4 +++ deploy/production/README.md | 27 ++++++++++++-------- deploy/production/compose.yaml | 42 +++++++++++++++++++++++++++++-- docs/operations/BACKUP.md | 4 +-- docs/operations/CURRENT_STATE.md | 15 ++++++----- docs/operations/DECISIONS.md | 3 ++- docs/operations/DEPLOYMENT.md | 15 ++++++----- docs/operations/INFRASTRUCTURE.md | 31 ++++++++++++----------- docs/operations/RECOVERY.md | 6 +++-- infra/bootstrap/verify.sh | 14 +++++++++-- infra/inventory/production.yml | 16 +++++++++--- 14 files changed, 134 insertions(+), 52 deletions(-) create mode 100644 deploy/production/Caddyfile diff --git a/.gitea/workflows/ci.yaml b/.gitea/workflows/ci.yaml index 8926c02..8b14560 100644 --- a/.gitea/workflows/ci.yaml +++ b/.gitea/workflows/ci.yaml @@ -17,6 +17,12 @@ 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: Validate production Compose and Caddyfile + run: | + secret_file=$(mktemp) + trap 'rm -f "$secret_file"' EXIT + REVIEW_SECRET_FILE="$secret_file" docker compose --env-file deploy/production/.env.example -f deploy/production/compose.yaml config --quiet + docker run --rm --entrypoint caddy -v "$PWD/deploy/production/Caddyfile:/etc/caddy/Caddyfile:ro" caddy:2.11.6-alpine@sha256:881bbc60f9986d5ab8e7cfd6cf7e4ef3c9c0439fef2429d035d065577882f028 validate --config /etc/caddy/Caddyfile --adapter caddyfile - name: Build production images run: | docker build -f deploy/production/Dockerfile.backend -t akyldash-backend:ci . diff --git a/CHANGELOG.md b/CHANGELOG.md index ee7ec4f..d40a38c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Не выпущено -- Backend `0.11.3`: ключ подписи поисковых снимков читается из Docker secret-файла, а не из аргументов процесса. Добавлена базовая инфраструктура VPS, drift-проверка и CI для тестов и сборки образов; production-деплой остаётся выключен до проверки runner, backup/restore и ограниченного deploy-helper. +- Backend `0.11.3`: ключ подписи поисковых снимков читается из Docker secret-файла, а не из аргументов процесса. Добавлена базовая инфраструктура VPS, Caddy HTTPS proxy с разделёнными Compose-сетями и CI-проверка конфигурации; публикация образов и production-деплой остаются выключены до проверки runner, registry, backup/restore и ограниченного deploy-helper. - Frontend `0.1.2`: на планшетной ширине экран поиска переходит в одну колонку, чтобы фильтры, результаты и документ помещались в окно. - Backend `0.11.2`: смена пароля требует текущий пароль и запрещает оставить прежний, включая временный пароль при первом входе. - Backend `0.11.1` и frontend `0.1.1`: в управлении пользователями показываются даты первого и последнего входа, а также последнего сброса пароля. diff --git a/deploy/production/.env.example b/deploy/production/.env.example index 2840663..e4d4a4d 100644 --- a/deploy/production/.env.example +++ b/deploy/production/.env.example @@ -1,7 +1,6 @@ # Absolute path on the production host containing minjust-normalized/. DATA_ROOT=/var/lib/akyldash/data REVIEW_SECRET_FILE=/etc/akyldash/review_secret -BACKEND_PORT=8080 SEARCH_INDEX=akyldash-fragments-current OPENSEARCH_MEM_LIMIT=4g OPENSEARCH_JAVA_OPTS=-Xms2g -Xmx2g diff --git a/deploy/production/Caddyfile b/deploy/production/Caddyfile new file mode 100644 index 0000000..5c12485 --- /dev/null +++ b/deploy/production/Caddyfile @@ -0,0 +1,4 @@ +akyldash.kg { + encode zstd gzip + reverse_proxy backend:8080 +} diff --git a/deploy/production/README.md b/deploy/production/README.md index aef98ec..7e4918a 100644 --- a/deploy/production/README.md +++ b/deploy/production/README.md @@ -1,11 +1,12 @@ # Production deployment -This compose project runs the Search API and its private OpenSearch node. It -binds the API only to `127.0.0.1`; publish it through an authenticated reverse -proxy or VPN. OpenSearch is not published outside the compose network. +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. The current compose intentionally disables the OpenSearch security plugin to -match the existing API client. Keep both services on a private host/network. +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. @@ -22,23 +23,29 @@ workspace; it does not replace host-level network controls or TLS. Do not commit `.env` or the secret file. 3. Put the normalized dataset under `$DATA_ROOT/minjust-normalized/`. -4. Check the rendered configuration: +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 ``` -5. Start the services: +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 http://127.0.0.1:${BACKEND_PORT:-8080}/review >/dev/null + curl -fsS https://akyldash.kg/review >/dev/null ``` -6. Load the versioned index and switch its alias only after the import and - validation succeed. Back up `DATA_ROOT` and the `opensearch-data` volume - before the first import. +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 diff --git a/deploy/production/compose.yaml b/deploy/production/compose.yaml index c510ebe..232d1a9 100644 --- a/deploy/production/compose.yaml +++ b/deploy/production/compose.yaml @@ -1,6 +1,32 @@ name: akyldash services: + caddy: + image: caddy:2.11.6-alpine@sha256:881bbc60f9986d5ab8e7cfd6cf7e4ef3c9c0439fef2429d035d065577882f028 + restart: unless-stopped + logging: + driver: local + options: + max-size: 10m + max-file: "3" + ports: + - "80:80" + - "443:443" + volumes: + - ./Caddyfile:/etc/caddy/Caddyfile:ro + - caddy-data:/data + - caddy-config:/config + networks: + - proxy + depends_on: + backend: + condition: service_healthy + healthcheck: + test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:2019/config/"] + interval: 30s + timeout: 5s + retries: 3 + opensearch: build: context: ../.. @@ -28,6 +54,8 @@ services: hard: 65536 volumes: - opensearch-data:/usr/share/opensearch/data + networks: + - search healthcheck: test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:9200/_cluster/health || exit 1"] interval: 30s @@ -68,17 +96,27 @@ services: - /run/secrets/review_secret secrets: - review_secret - ports: - - "127.0.0.1:${BACKEND_PORT:-8080}:8080" + expose: + - "8080" depends_on: opensearch: condition: service_healthy volumes: - ${DATA_ROOT:?set DATA_ROOT in .env}:/app/data + networks: + - proxy + - search volumes: + caddy-data: + caddy-config: opensearch-data: +networks: + proxy: + search: + internal: true + secrets: review_secret: file: ${REVIEW_SECRET_FILE:?set REVIEW_SECRET_FILE in .env} diff --git a/docs/operations/BACKUP.md b/docs/operations/BACKUP.md index d0759b0..cd2ff08 100644 --- a/docs/operations/BACKUP.md +++ b/docs/operations/BACKUP.md @@ -13,8 +13,8 @@ both been checked. or index migration. - Include the normalized corpus, `search-users.sqlite3`, `search-reviews.sqlite3`, the OpenSearch index/snapshot, deployment digest, - and required secret file in the protected backup set. Store secrets separately - with equivalent access controls. + 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. - Keep one current pre-release backup. If deployment fails, retain the backup diff --git a/docs/operations/CURRENT_STATE.md b/docs/operations/CURRENT_STATE.md index 98381d1..107a307 100644 --- a/docs/operations/CURRENT_STATE.md +++ b/docs/operations/CURRENT_STATE.md @@ -35,12 +35,15 @@ from planned configuration. publishing permissions could not be checked. This change adds `.gitea/workflows/ci.yaml`; PR #42's run remains `Waiting to run` at the last status check, so a compatible runner is not confirmed. -- Production Compose describes Python Search API `0.11.3`, SQLite account and - review data, and OpenSearch `3.7.0` with `analysis-icu`. Nothing is running. -- Compose binds the API to `127.0.0.1:8080`, leaves OpenSearch private, uses a - named OpenSearch volume, and a host data bind mount. TLS/reverse proxy, - registry digest deployment, backup, rollback helper, and systemd deployment - are not configured. +- Nothing is running on the VPS. Repository Compose now describes Caddy + `2.11.6` pinned by digest, Python Search API `0.11.3`, SQLite account/review + data, and OpenSearch `3.7.0` with `analysis-icu`. +- The target publishes only Caddy on TCP `80`/`443`. Backend and Caddy share a + proxy network; OpenSearch and backend share a separate internal network, and + the backend has no host port. Caddy certificate storage, OpenSearch, and + 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 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). diff --git a/docs/operations/DECISIONS.md b/docs/operations/DECISIONS.md index 3785da3..e665643 100644 --- a/docs/operations/DECISIONS.md +++ b/docs/operations/DECISIONS.md @@ -4,6 +4,7 @@ |---|---|---|---| | 2026-10-11 | Use Docker Compose on the dedicated Ubuntu VPS | Matches the existing production Compose baseline and workload; Kubernetes adds no demonstrated need | Planned; Docker is not installed | | 2026-10-11 | Keep `codex` out of sudo and the Docker group | Docker socket access is effectively root; use an owner-run bootstrap and a narrowly reviewed deploy-helper | No helper installed yet | -| 2026-10-11 | Keep Search API on loopback and OpenSearch on the private Compose network | Minimizes host exposure; HTTPS terminates at a reviewed reverse proxy | Compose target only; no proxy or firewall audit privileges | +| 2026-10-11 | Put Caddy and Search API on a proxy network and OpenSearch on a separate internal network | Keeps OpenSearch unreachable from the proxy and host; the API has no published host port | Repository Compose target only; not deployed | +| 2026-10-11 | Use Caddy in Compose for HTTPS at `akyldash.kg` | Automatic certificate issuance/renewal keeps proxy config small; Nginx with separately managed certificates was considered | Caddy image pinned by digest; requires public ports 80/443 and owner confirmation of Cloudflare Full (strict) | | 2026-10-11 | Mount the review signing key as a Compose secret file | Avoids putting its value in command-line arguments; an environment variable or CLI value is easier to inspect in process metadata | Implemented in repository Compose; not deployed | | 2026-10-11 | Do not enable production deployment from Gitea Actions yet | Runner, package publishing scope, deploy-helper, backup/restore, and production health are not verified | Revisit after controlled end-to-end test | diff --git a/docs/operations/DEPLOYMENT.md b/docs/operations/DEPLOYMENT.md index 171d0bc..a3ae71e 100644 --- a/docs/operations/DEPLOYMENT.md +++ b/docs/operations/DEPLOYMENT.md @@ -15,12 +15,15 @@ configuration, and a backup and restore have been tested. of this branch on the VPS. The script installs Docker Engine/Compose and Git, sets Docker log rotation, and creates root-owned paths. It refuses other OS versions and does not change SSH, UFW, sudoers, or user groups. -2. Install the repository checkout at `/opt/akyldash/current` and configure - `/etc/akyldash/production.env` plus `/etc/akyldash/review_secret` outside - Git. The secret file must be root-readable only. -3. Review DNS and certificate issuance, choose and configure the reverse proxy, - then ask the owner to open only the required ports after confirming current - firewall rules. +2. Install the approved repository checkout at `/opt/akyldash/current` and + configure `/etc/akyldash/production.env` plus + `/etc/akyldash/review_secret` outside Git. The secret file must be + root-readable only. +3. Confirm DNS points through Cloudflare to this origin, then have the owner + review firewall rules and open only TCP `80` and `443` in addition to the + existing SSH access. The Compose Caddy service obtains and renews its HTTPS + certificate automatically; Cloudflare Full (strict) still needs owner-side + verification. 4. 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. diff --git a/docs/operations/INFRASTRUCTURE.md b/docs/operations/INFRASTRUCTURE.md index 5a19667..74bfaea 100644 --- a/docs/operations/INFRASTRUCTURE.md +++ b/docs/operations/INFRASTRUCTURE.md @@ -3,17 +3,17 @@ ## Intended layout Production is planned for the dedicated Ubuntu VPS at `206.223.249.118`. -`deploy/production/compose.yaml` defines a Python Search API and private -OpenSearch 3.7 node. The API binds to loopback port `8080`; OpenSearch is only -exposed to the Compose network. The host reverse proxy should terminate HTTPS -for `akyldash.kg` and proxy to the API. Cloudflare should use Full (strict) only -after the origin certificate and DNS path are verified. +`deploy/production/compose.yaml` defines Caddy, a Python Search API, and private +OpenSearch 3.7. Caddy terminates HTTPS for `akyldash.kg` and proxies to the API. +The API is reachable only on private Compose networks; OpenSearch is reachable +only by the backend. Cloudflare should use Full (strict) only after the origin +certificate and DNS path are verified. The API stores its account and review SQLite files beside the normalized corpus -under the persistent data directory. OpenSearch uses a named volume. The API's -review signing key is mounted from a host file; it is not passed in process -arguments or committed to Git. Docker logs are bounded to 10 MiB per file and -three files per service. +under the persistent data directory. OpenSearch and Caddy use named volumes. +The API's review signing key is mounted from a host file; it is not passed in +process arguments or committed to Git. Docker logs are bounded to 10 MiB per +file and three files per service. ## Actual state @@ -23,10 +23,11 @@ and backups are not installed/configured. The `codex` account has no non-interactive sudo. See [CURRENT_STATE.md](CURRENT_STATE.md) and the [production inventory](../../infra/inventory/production.yml). -The Compose file is a repository baseline, not proof of deployment. It still -builds images locally; immutable registry images and automated deploy are not -configured. No migration framework exists. The application uses SQLite and -OpenSearch; SMTP registration/recovery is not implemented. +The Compose file is a repository target, not proof of deployment. The Caddy +image is pinned by digest, while backend and OpenSearch still build locally; +immutable registry images and automated deploy are not configured. No migration +framework exists. The application uses SQLite and OpenSearch; SMTP +registration/recovery is not implemented. ## Repository paths and target host paths @@ -44,8 +45,8 @@ application, or grant `codex` Docker/root access. ## Network and operations -Target public TCP listeners are SSH `22` and HTTPS proxy `80`/`443`. Backend -`8080` must remain loopback-only and OpenSearch `9200` private to Compose. The +Target public TCP listeners are SSH `22` and Caddy `80`/`443`. Backend `8080` +and OpenSearch `9200` must remain private to Compose. The firewall state could not be independently verified because the SSH account has no sudo; do not change it without owner approval. The domain resolves to Cloudflare edge addresses, but HTTP and HTTPS return `521`, so the origin is diff --git a/docs/operations/RECOVERY.md b/docs/operations/RECOVERY.md index c30f7f1..3c8e8c1 100644 --- a/docs/operations/RECOVERY.md +++ b/docs/operations/RECOVERY.md @@ -18,8 +18,10 @@ run recovery commands against the existing production by accident. 3. Check out the approved Git revision and run `sudo bash infra/bootstrap/bootstrap-ubuntu-24.04.sh`. It installs Docker Engine, Compose, Git, Docker log limits, and target directories. -4. Install the reviewed reverse proxy and its HTTPS configuration after DNS - points to the recovery host. Verify Cloudflare Full (strict) end to end. +4. Configure DNS to point through Cloudflare to the recovery host and allow the + owner to review/open TCP `80` and `443`. The production Compose Caddy service + obtains its origin certificate automatically. Verify Cloudflare Full + (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 diff --git a/infra/bootstrap/verify.sh b/infra/bootstrap/verify.sh index c5c476f..dd167c2 100755 --- a/infra/bootstrap/verify.sh +++ b/infra/bootstrap/verify.sh @@ -76,8 +76,8 @@ done checkout=/opt/akyldash/current compose_file=$checkout/deploy/production/compose.yaml -if git -C "$checkout" diff --quiet HEAD -- deploy/production/compose.yaml deploy/production/Dockerfile.backend deploy/production/Dockerfile.opensearch; then - echo 'PASS production Compose and Dockerfiles match the checked-out Git revision' +if git -C "$checkout" diff --quiet HEAD -- deploy/production/compose.yaml deploy/production/Caddyfile deploy/production/Dockerfile.backend deploy/production/Dockerfile.opensearch; then + echo 'PASS production Compose, Caddyfile, and Dockerfiles match the checked-out Git revision' else echo 'FAIL production Compose or Dockerfile has local drift' failed=1 @@ -149,4 +149,14 @@ else echo 'FAIL deployed image digest record missing' failed=1 fi + +expected_proxy=$(docker compose --env-file /etc/akyldash/production.env -f "$compose_file" config --format json 2>/dev/null | python3 -c 'import json,sys; print(json.load(sys.stdin)["services"]["caddy"]["image"])' 2>/dev/null || true) +proxy_container=$(docker ps -aq --filter label=com.docker.compose.project=akyldash --filter label=com.docker.compose.service=caddy | head -n1) +actual_proxy=$(docker inspect --format '{{.Config.Image}}' "$proxy_container" 2>/dev/null || true) +if [[ $expected_proxy == *@sha256:* && $actual_proxy == "$expected_proxy" ]]; then + printf 'PASS running Caddy image matches %s\n' "$expected_proxy" +else + echo 'FAIL running Caddy image does not match the pinned Compose digest' + failed=1 +fi exit "$failed" diff --git a/infra/inventory/production.yml b/infra/inventory/production.yml index 8f98a1d..39e1a06 100644 --- a/infra/inventory/production.yml +++ b/infra/inventory/production.yml @@ -40,10 +40,15 @@ target: data_directory: /var/lib/akyldash/data backup_directory: /var/backups/akyldash services: + caddy: + container: compose project service caddy + image: caddy:2.11.6-alpine pinned by digest in deploy/production/compose.yaml + host_ports: [80, 443] + persistent_data: named Compose volumes caddy-data and caddy-config backend: container: compose project service backend image: built from deploy/production/Dockerfile.backend; digest deployment not configured - host_bind: 127.0.0.1:8080 + port: 8080 on private proxy and search Compose networks only healthcheck: HTTP GET /review on container port 8080 persistent_data: /var/lib/akyldash/data (bind mount) opensearch: @@ -52,10 +57,12 @@ target: port: 9200 on private Compose network only persistent_data: named Compose volume opensearch-data reverse_proxy: - target: Caddy or another reviewed HTTPS proxy on TCP 80/443 - status: not installed or configured + target: Caddy in Compose; Caddyfile proxies akyldash.kg to backend:8080 + status: repository configuration exists; not installed or running on VPS external_ports_target: [22, 80, 443] - compose_network: default private Compose network + compose_networks: + proxy: caddy and backend + search: backend and OpenSearch; internal network secrets: - REVIEW_SECRET (host file mounted as /run/secrets/review_secret) - Gitea credentials from environment-backed gitea-api helper @@ -71,4 +78,5 @@ versions: frontend: 0.1.2 telegram_bot: 0.2.2 infrastructure: unknown; no production install or release exists + caddy_image: 2.11.6-alpine pinned by manifest digest in Compose docker_engine: not installed