CTWeb Maps

Linux installation and operations

This procedure prepares CTWeb Maps for manual installation review. It does not install production, change DNS, create another Caddy instance, or edit/reload an existing proxy. Run lifecycle commands on the intended Linux Docker host, as root, from a dedicated checkout/installation directory. Required tools: Python 3.11+, Docker Engine with Compose v2 supporting JSON configuration, and age or GnuPG for encrypted backup. Keep the existing phase 1 demo running while validating the separate application.

Installation identity and configuration

Copy .env.example to .env, set mode 0600, and review every value. Never source the environment file or use shell eval. The scripts ask Docker Compose to parse it using config --format json; values are passed as process arguments/data. Environment values and credentials are not printed by the scripts.

Choose a unique COMPOSE_PROJECT_NAME for this installation, e.g. ctwebmaps-production, and a separate loopback MAPS_PORT, e.g. 54357. Do not reuse the identity or volumes of another checkout. init pins the project, local Docker engine identity, directory, environment file and selected Compose files in .ops/project.json; later commands reject changes to that identity. TCP/remote Docker endpoints are refused because secret bind mounts must resolve on this Linux host. Application image overrides are stored separately under .ops, without rewriting the central .env. Back up this directory's nonsecret release/configuration history separately from encrypted operational backups.

Important values:

MAPS_STATE_PATH (default /state) and MAPS_DATA_PATH (default /data) configure private absolute container mount targets for named maps-state and maps-data volumes. Their actual Docker names are ${COMPOSE_PROJECT_NAME}_maps-state and ${COMPOSE_PROJECT_NAME}_maps-data. These settings do not permit arbitrary host bind paths. The scripts reject overlapping/system/application targets, require environment roots to match volume mounts, and verify default-local volume driver plus project/directory ownership before touching them. Initialization prepares only those owned volume roots as UID/GID 1654, so nondefault targets also work. Backup/restore helpers mount the same volumes at their own canonical /state and /data, independently of the application's configured targets. Volumes from a previous manual Compose installation are not automatically adopted. Recover through a reviewed backup/import into a newly initialized project instead. Reusing an existing project's name from a second directory is refused.

cp .env.example .env
chmod 600 .env
# Edit .env using your normal protected configuration process.
# Build/load BOTH reviewed images before init; the maintenance image never starts as a service.
docker compose --env-file .env --profile maintenance build app ops-helper
sudo sh scripts/ops/maps init
sudo sh scripts/ops/maps preflight
sudo sh scripts/ops/maps start
sudo sh scripts/ops/maps health

init creates a 64-byte cryptographically random signing key and a random bootstrap password exceeding the server's 14-character policy, only if missing. It never replaces existing secret files or prints their values. Secret files are owned by UID/GID 1654:1654, mode 0400; their dedicated directory is root-owned, group 1654, mode 0710. A configured SMTP-password file is initialized empty and must be populated through the installation's secure secret procedure if SMTP authentication is used. Preflight rejects incorrect ownership/modes rather than silently making existing secrets accessible. The app runs as UID/GID 1654 with read-only application files and separate writable volumes.

First initialization creates the project's named volumes. Starting uses the existing reviewed image (up --no-build), then waits up to three minutes for readiness. Large initial imports may exceed that wait: inspect local operational status, allow validation to finish, then rerun health; never bypass authentication or expose the archive statically to make readiness succeed. No Caddy command is executed.

All lifecycle commands take the same optional prefix arguments. If selecting the Docker Caddy network overlay, use --caddy-network on init and every later command. An alternate installation location may use --directory /srv/ctwebmaps; environment-file selection is --env-file .env.production. One process lock per installation prevents concurrent lifecycle operations.

Existing Caddy integration

The app publishes only 127.0.0.1:MAPS_PORT, never ports 80 or 443. Review one of the supplied deploy/Caddyfile.*.example snippets and add it to the existing Caddy installation through its normal reviewed configuration process. The lifecycle scripts never edit, validate, reload, restart or uninstall Caddy.

For host Caddy, proxy to 127.0.0.1:54357 (or the chosen port). Check which exact peer address the application receives after Docker's port forwarding. Docker commonly presents a bridge gateway rather than 127.0.0.1; set MAPS_TRUSTED_PROXY_0 to that exact observed proxy/gateway IP after verifying the network boundary. Do not trust an entire private subnet or arbitrary forwarded headers. Keep the app's listener loopback-only.

For an existing Docker Caddy container, set MAPS_CADDY_NETWORK to the already-existing external network and initialize/run with --caddy-network. The app joins it with alias ${COMPOSE_PROJECT_NAME}-app; the existing Caddy container must already join the same network. Proxy to that unique alias on port 8080. Set MAPS_TRUSTED_PROXY_0 to the existing Caddy container's exact stable IP on this network. Plan address persistence with the network owner; a changed Caddy IP needs a reviewed configuration update. A shared network is a trust boundary: unrelated tenants must not be allowed to impersonate that address.

Installation checks to perform manually before public traffic:

  1. Confirm maps.ctweb.dk (or the actual reviewed domain) resolves to the intended existing proxy and obtains a valid HTTPS certificate.
  2. Verify forwarded scheme/host behavior and secure admin cookies with the exact trusted-proxy IP; spoofed headers from an untrusted source must not affect those values.
  3. Ensure protected PMTiles Range responses pass through without compression. Expect 206, exact Content-Range, Accept-Ranges: bytes, correct Content-Length and stable strong ETag across requests to one immutable version.
  4. Confirm unauthorized GET/HEAD/Range requests are denied, CORS permits only the authorized token origin, and the proxy does not strip Authorization, Origin, Range or conditional headers. Do not configure a public static-data alias.
  5. Retain the application's private cache policy, and never cache protected responses in a shared CDN/proxy cache. Review cache keys and responses at the actual proxy.
  6. Disable persistent viewer access logs at Caddy and any upstream edge. The examples use log_skip; review any broader/global logging configuration too. App operational logs are bounded and minimized; do not enable request/access logging containing URLs, tokens, visitor identifiers or IPs.
  7. Check local SDK/style/glyph/sprite resources in a browser and confirm no tracking, third-party map requests, or persistent visitor cookies.

These are installation acceptance checks, not a claim of production approval from the local fixture.

Start, stop, restart and health

sudo sh scripts/ops/maps stop
sudo sh scripts/ops/maps start
sudo sh scripts/ops/maps restart
sudo sh scripts/ops/maps health

These operate only on the pinned app service and its project. Health uses Docker readiness health status when defined, otherwise runs the application's actual /health/ready probe inside its own container. A running process alone is not considered ready. There are no global restart, prune, container enumeration-and-delete, or unrelated-project operations.

Preflight verifies a Linux engine, secure secrets, explicit bootstrap archive, nonroot app user, loopback-only published ports, existing external networks and owned named volumes. It does not prove DNS, TLS, firewall reachability, filesystem power-loss behavior, sufficient backup capacity, organizational policy or notification delivery; validate those on the target installation.

Encrypted consistent backups

Backups include the complete state volume (SQLite plus data-protection keys), data volume (catalogue and retained immutable archives), configured secret files, the central environment file, and a small source-project/image/time manifest. Store public encryption recipients separately from the private restore key. Keep private restore keys offline or in the organization's recovery secret store; do not colocate the only private key with the ciphertext backup.

# Recipient is public, not a password. Use your existing approved age recipient.
sudo sh scripts/ops/maps --recipient age1YOUR_PUBLIC_RECIPIENT backup /secure/backups/maps-2026-11-30.age

# Omit the path to use MAPS_BACKUP_ROOT from the central .env/Compose extension.
sudo sh scripts/ops/maps --recipient age1YOUR_PUBLIC_RECIPIENT backup

# Or use an existing imported GPG public recipient with an explicitly verified fingerprint.
sudo sh scripts/ops/maps --encrypt-with gpg --recipient VERIFIED_FINGERPRINT backup /secure/backups/maps-2026-11-30.gpg

MAPS_BACKUP_ROOT defaults to ./backups and is resolved through the x-ctwebmaps-ops.backup-root Compose extension, without sourcing/evaluating .env. Relative configured roots must remain within the installation; explicit operator-selected absolute roots are supported. Linked paths and relative traversal are rejected. An omitted backup path or update --backup generates PROJECT-UTC_TIMESTAMP-RANDOM.age (or .gpg) inside that root. An explicit command-line destination overrides it. Files are never overwritten; restore always requires its source path.

The app is stopped gracefully for the duration of archiving, so SQLite and archive activation cannot change mid-backup. This introduces maintenance downtime proportional to retained data size and encryption throughput; schedule it accordingly. No plaintext tar file is ever written. A locked-down, network-disabled helper reads volumes/secrets and streams tar bytes directly into age/GPG. Only ciphertext is written to a mode-0600 .part file, flushed and atomically published without replacing an existing name. Publication uses a same-directory hard link, so the backup filesystem must support that operation; unsupported filesystems fail safely. A destination created concurrently is also preserved. A failed encryption/archive discards the partial ciphertext and restarts the previously running app in a finally block. An app that was already stopped remains stopped.

Helpers use the separately built reviewed ops-helper maintenance image selected through MAPS_OPS_IMAGE (default ctwebmaps-ops:1.0.0-development). build/ops/Dockerfile pins the patched Python base/OS packages and removes pip/ensurepip; operations use only the standard library. The CLI requires a locally available Linux image with ctwebmaps.ops.reviewed=true and ctwebmaps.ops.helper-api=1, rejects custom entrypoints, resolves the local immutable image ID once per operation, and runs with --pull never. Labels are a local review gate, not a cryptographic signature; installation owners must build/load and verify the approved artifact. The maintenance profile is for building this image, not running a persistent service.

Each helper has a read-only root filesystem, no network, a 256 MiB memory limit without swap, one CPU, at most 64 processes and minimal capabilities; the app never receives the Docker socket. Backup helpers receive only read-only mounts and permission to read the UID-1654 files. Build/load and scan both app/helper images before planned maintenance; no image is fetched automatically during a secret-bearing operation. The encrypted backup manifest records the helper image ID too.

Keep enough space for ciphertext plus the next data extract and retained archives. Test decryption/recovery regularly into an isolated installation, record backup age and recovery time, and copy encrypted backups off-host according to the agreed retention policy. The scripts do not silently delete backups.

Restore

Restore requires a stopped installation with empty owned state/data volumes. It never overwrites a running or nonempty installation. Prefer a separate recovery directory, unique Compose project and distinct loopback port, then validate the recovered instance before proxy cutover. For an intentional in-place rebuild, first retain a verified encrypted backup, stop the app, and explicitly purge only this project's disposable volumes using the scoped uninstall command below. Reinitialize afterward. Do not remove unrelated volumes or proxy resources.

sudo sh scripts/ops/maps stop
sudo sh scripts/ops/maps --identity /secure/offline/maps-recovery.agekey restore /secure/backups/maps-2026-11-30.age

# Restore into a newly initialized isolated project: source identity must be explicit.
sudo sh scripts/ops/maps --directory /srv/ctwebmaps-recovery \
	--identity /secure/offline/maps-recovery.agekey \
	--source-project ctwebmaps-production restore /secure/backups/maps-2026-11-30.age

# GPG uses the root invocation's approved keyring/agent; no passphrase in arguments.
sudo sh scripts/ops/maps --encrypt-with gpg restore /secure/backups/maps-2026-11-30.gpg

The decryptor streams into a separate temporary, project-labelled staging volume. The helper validates every archive member, refuses absolute/traversal paths, unknown roots, symlinks, hardlinks, device/special entries, duplicate members and excessive size/count, then checks the manifest identity and required secrets. Both decryption/authentication and archive validation must finish successfully before target volumes are written. A default 100 GiB extracted-byte cap is adjustable using --max-restore-bytes; the effective cap is also bounded by half the staging filesystem's free space minus a 1 GiB margin, preserving room for the second copy. Set it to the measured recovery size and available capacity. Staging plus target extraction needs roughly twice the unencrypted dataset size. No plaintext tar persists, though restored/staged files necessarily exist on the private Docker data volume until cleanup. Helpers normally delete staging immediately afterward; a hard-killed host may leave an owned PROJECT_ops-restore-* volume requiring privileged inspection and explicit cleanup by exact name.

After validation, the CLI checks that every archived secret has a configured target file. A backup containing smtp-password is refused before state/data mutation when the target has no such optional file. To restore it while leaving SMTP disabled, explicitly provision an empty smtp-password under the target's configured secrets directory with UID/GID 1654 and mode 0400, rerun init, then retry restore. SMTP configuration is not silently enabled and no secret is silently omitted.

A second helper then opens all required secret targets for writing and checks both target volumes are empty before copying anything. Missing/readonly secret mounts fail at preflight, preserving existing signing keys and empty target volumes. It restores ownership to UID/GID 1654, data files mode 0600, directories 0700, and secrets 0400. If installation fails during disk I/O, leave the app stopped; inspect/clear only the failed recovery project's partial volumes and retry. The process is validated before installation, but a multi-volume copy is not one filesystem transaction.

The archived .env is not automatically applied because it may point to the source installation's domain, port or secret paths. Retain/review target configuration separately. The source manifest records the old app image for operator review; deploy the matching reviewed image before starting. Restored secret files replace only the currently configured files inside the recovery installation's secrets directory. The private key used for backup encryption is never included in the backup.

After restore, run preflight/start/health, validate database administration/MFA, project credentials, signed-token behavior and immutable PMTiles Range reads, then run browser acceptance and the manual HTTPS/proxy checks. Do not cut over DNS/proxy merely because SQLite opens.

Application and data updates/rollback

Build/review/test the new image first, record its immutable reference, and retain the prior image. An application update automatically requires an encrypted pre-update checkpoint:

sudo sh scripts/ops/maps --recipient age1YOUR_PUBLIC_RECIPIENT update \
	--image registry.example/ctwebmaps@sha256:REVIEWED_64_HEX_DIGEST \
	--backup /secure/backups/maps-before-release.age
sudo sh scripts/ops/maps health
sudo sh scripts/ops/maps rollback

update records the current immutable image ID under .ops/previous-image.json, writes a Compose image override, recreates only this project's app and waits for readiness. It never builds code or modifies Caddy. If the new image fails readiness, it reports failure and preserves the encrypted checkpoint and prior image reference; use rollback explicitly after assessing database compatibility. Rollback reselects the recorded previous application image and waits for readiness. It does not reverse database/schema changes; if a release changed persisted formats incompatibly, restore the encrypted checkpoint into an isolated matching-version instance instead. Do not prune the previous image before the rollback window ends.

Map data rollback is a separate admin operation through the data catalogue. It validates a retained immutable archive and atomically changes the active catalogue pointer; it does not change application images, project configuration or signing keys. See data-updates.md for manual update/import/rollback tooling and retention/session limits. Emergency signing-key rotation and credential revocation require a separate reviewed security procedure because active tokens/sessions may be invalidated.

Uninstall

# Remove only this project's containers/default network; keep data and secrets.
sudo sh scripts/ops/maps uninstall

# Explicitly delete only this installation's two labelled volumes after verified backup.
sudo sh scripts/ops/maps uninstall --purge --confirm-project ctwebmaps-production

Purge requires the exact pinned project name and verifies volume ownership before deleting. Images, secret files, .env, .ops, encrypted backups, the existing Caddy container/configuration/network and other Compose projects are preserved. Remove secret files or backups only through the organization's separate retention/destruction procedure. There is deliberately no docker system prune, global volume cleanup or automatic proxy teardown.

Local test fixture and remaining acceptance

Safety tests run with Python standard-library unittest:

python3 -m unittest discover -s tests/ops -v
docker build -f tests/ops/Dockerfile -t ctwebmaps-ops-fixture:local .
docker run --rm --privileged --name ctwebmaps-ops-fixture-validation ctwebmaps-ops-fixture:local

The privileged fixture launches its own isolated nested Docker daemon, without the host Docker socket or host cgroup namespace. It uses synthetic Python/SQLite app images and generated disposable encryption keys, never production secrets or map files. Docker Desktop's nested cgroups lack some domain controllers, so a documented test-only adapter omits helper CPU/RAM/PID flags inside this fixture; production operations retain those flags and real-host limits are verified separately. Its own project-scoped resources disappear with the disposable fixture container. Do not run that test image as the production app. The fixture checks actual Linux file ownership, literal .env handling, lifecycle commands, encrypted backups, database/secrets restoration, unsafe/nonempty/running restore refusal, immutable update/application rollback and preservation of a second concurrent installation during uninstall. Unit tests inspect project/image identifiers, port bindings and hostile tar members.

This fixture does not establish production installation approval, Caddy/DNS/TLS behavior, organizational backup-key custody, full-size backup performance, filesystem crash durability or actual SMTP/webhook delivery. Record the target-host evidence and organizational decisions before production traffic.

On 2026-11-30 all ten Python operations safety/path tests passed on Linux, including symlink refusal, literal/no-eval values, configured backup placement and atomic no-overwrite publication. The isolated Linux Docker fixture exercised both age and GPG, restored actual SQLite rows and exact signing-key bytes, rejected same-project reuse from a second directory, running/nonempty targets, hostile tar paths, tampered ciphertext and wrong source identity, recovered the app after an encryption failure, updated/rolled back immutable images, used the configured default destination for backup/update checkpoints, and purged one project while a second remained healthy. A separate disposable-container check verified the helper's 256 MiB cgroup memory bound and 64-process limit. That fixture used tiny synthetic data; no production recovery objective is claimed.

Full-size acceptance was also run separately against the real ASP.NET 10.0.15 application image with patched CLI 1.31.2-ctweb.1: complete Denmark import, encrypted state/data/secrets backup, restore at different container paths, actual Identity SQLite/catalogue and signing-key checks, two simultaneously ready instances, and target uninstall preserving the source all passed. Infrastructure review records the exact tested image and reproduction command. This adds full application/data recovery evidence; it does not establish a production recovery-time objective or validate the target host's HTTPS/proxy environment.

The final full-size run used the patched reviewed helper recipe. Separate actual-Docker regressions verify that missing optional SMTP targets leave state/data and signing keys unchanged, explicit provisioning restores the SMTP secret while mail stays disabled, and unreviewed/missing/entrypoint-overridden helper images are rejected before volume mutation. The helper gate honors MAPS_OPS_IMAGE by explicitly resolving the maintenance profile; starting still selects only the app service.

Caddy-eksemplernes handle_errors begrænser request/IP-logning ved almindelige upstreamforbindelsesfejl med debug slået fra. Den afprøvede effekt og grænserne ved streaming/TLS/global logning er beskrevet i logningspolitikken. Anvend ikke log_skip alene som bevis for fravær af alle IP-fejlposter. Fejlteksten er fast og indeholder ingen credentials; beskyttede Range-svar komprimeres fortsat ikke.