From 871fe05dde3403957023bbbd3530a5595241e71a Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Wed, 18 Nov 2026 12:00:18 +1300 Subject: [PATCH 01/12] One repository for every way to run DocSpring Enterprise: reference/deployment.yml says what each deployment runs, scripts/check_deployments and CI check every folder against it, and the Convox install moves into convox/ with run_as_deploy commands, the hourly, daily and weekly tasks and a release step in update.sh --- .github/workflows/ci.yml | 86 +++++++++++ .github/workflows/publish-chart.yml | 33 +++++ .gitignore | 12 +- .vscode/settings.json | 3 - AGENTS.md | 57 ++++++++ LICENSE | 19 +++ README.md | 63 ++++---- {.convox => convox/.convox}/.keep | 0 .dockerignore => convox/.dockerignore | 0 convox/.gitignore | 5 + .rubocop.yml => convox/.rubocop.yml | 0 .../convox.example.yml | 68 +++++++-- install.rb => convox/install.rb | 0 convox/update.sh | 20 +++ reference/deployment.yml | 138 ++++++++++++++++++ scripts/check_deployments | 116 +++++++++++++++ update.sh | 18 --- 17 files changed, 573 insertions(+), 65 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/publish-chart.yml delete mode 100644 .vscode/settings.json create mode 100644 AGENTS.md create mode 100644 LICENSE rename {.convox => convox/.convox}/.keep (100%) rename .dockerignore => convox/.dockerignore (100%) create mode 100644 convox/.gitignore rename .rubocop.yml => convox/.rubocop.yml (100%) rename convox.example.yml => convox/convox.example.yml (51%) rename install.rb => convox/install.rb (100%) create mode 100755 convox/update.sh create mode 100644 reference/deployment.yml create mode 100755 scripts/check_deployments delete mode 100755 update.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..84518fc --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,86 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +jobs: + contract: + name: Every folder matches reference/deployment.yml + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: azure/setup-helm@2f5e7bc67f1f9972ab16657bb795f36d8f04de0e # v5.1.0 + - run: scripts/check_deployments + + docker-compose: + runs-on: ubuntu-latest + defaults: + run: + working-directory: docker-compose + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Compose file + run: ./setup.sh > /dev/null && docker compose config --quiet && rm .env + - name: Shell scripts + run: shellcheck *.sh + + kubernetes: + runs-on: ubuntu-latest + defaults: + run: + working-directory: kubernetes + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: azure/setup-helm@2f5e7bc67f1f9972ab16657bb795f36d8f04de0e # v5.1.0 + - name: Install kubeconform + run: | + curl -fsSL -o /tmp/kubeconform.tar.gz \ + https://github.com/yannh/kubeconform/releases/download/v0.8.0/kubeconform-linux-amd64.tar.gz + tar -xzf /tmp/kubeconform.tar.gz -C /usr/local/bin kubeconform + - name: Lint and validate the chart + run: ./scripts/validate + + aws-ecs: + runs-on: ubuntu-latest + defaults: + run: + working-directory: aws-ecs + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: hashicorp/setup-terraform@dfe3c3f87815947d99a8997f908cb6525fc44e9e # v4.0.1 + - uses: terraform-linters/setup-tflint@6ffdbaa3be476b3431f7275c26966ef32ff60337 # v6.3.2 + - run: terraform fmt -check -recursive + - working-directory: aws-ecs/example + run: terraform init -backend=false -input=false && terraform validate + - run: tflint --init && tflint --recursive + - run: shellcheck scripts/* + + convox: + runs-on: ubuntu-latest + defaults: + run: + working-directory: convox + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: ruby/setup-ruby@4e97ecde5048e1e0816923020652678063ffbf65 # v1.339.0 + with: + ruby-version: '3.4' + - run: ruby -c install.rb + - run: shellcheck *.sh + + aptible: + runs-on: ubuntu-latest + defaults: + run: + working-directory: aptible + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: The crontab parses + run: | + docker run --rm -v "$PWD/crontab:/crontab:ro" --entrypoint sh alpine:3.22 -c \ + 'apk add --no-cache supercronic > /dev/null && supercronic -test /crontab' diff --git a/.github/workflows/publish-chart.yml b/.github/workflows/publish-chart.yml new file mode 100644 index 0000000..f4640ba --- /dev/null +++ b/.github/workflows/publish-chart.yml @@ -0,0 +1,33 @@ +name: Publish the Helm chart + +# Pushes the chart to oci://ghcr.io/docspring/charts/docspring-enterprise when its version in Chart.yaml changes on +# main. A version that's already published is left alone, so bump `version` in Chart.yaml for every chart change. + +on: + push: + branches: [main] + paths: ['kubernetes/docspring-enterprise/**'] + +permissions: + contents: read + packages: write + +jobs: + publish: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: azure/setup-helm@2f5e7bc67f1f9972ab16657bb795f36d8f04de0e # v5.1.0 + - name: Push the chart unless its version is already published + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + version="$(sed -n 's/^version: *//p' kubernetes/docspring-enterprise/Chart.yaml | tr -d '"')" + echo "$GH_TOKEN" | helm registry login ghcr.io --username "${{ github.actor }}" --password-stdin + if helm show chart oci://ghcr.io/docspring/charts/docspring-enterprise --version "$version" > /dev/null 2>&1; then + echo "Chart $version is already published" + exit 0 + fi + helm package kubernetes/docspring-enterprise --destination /tmp/chart + helm push "/tmp/chart/docspring-enterprise-$version.tgz" oci://ghcr.io/docspring/charts diff --git a/.gitignore b/.gitignore index 38d9650..4ce82fd 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,7 @@ -.bundle -convox.yml -.installer_config* -.convox/app -.rack_name +.env +*.tfstate +*.tfstate.* +.terraform/ +*.tfvars +!*.tfvars.example +.DS_Store diff --git a/.vscode/settings.json b/.vscode/settings.json deleted file mode 100644 index ad92582..0000000 --- a/.vscode/settings.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "editor.formatOnSave": true -} diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..3c3e17f --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,57 @@ +# Agents: DocSpring Enterprise deployment + +This repository holds the ready-made setups for running the DocSpring Enterprise Docker image on each platform. You +may be here to change these setups (a DocSpring engineer's agent) or to install or run DocSpring for a customer (the +customer's agent). Both read this file first, then the `AGENTS.md` in the folder they work in. + +## The contract + +[`reference/deployment.yml`](reference/deployment.yml) is what every deployment runs: the image, three services (`web`, +`worker`, `worker_gj`), the release command run before each release goes live, three scheduled tasks +(`rake timers:hourly`, `timers:daily`, `timers:weekly`), the container's capabilities, health checks, the required +settings and the S3 bucket's CORS rule. Every folder implements all of it. `scripts/check_deployments` fails CI when a +folder drifts. When the contract changes, change every folder in the same pull request. + +Things that are easy to get wrong: + +- Every command starts with `run_as_deploy`. It runs the command under `tini` as the unprivileged `deploy` user, + after blocking the cloud metadata address. Without `tini`, the processes Chromium and LibreOffice leave behind stop + the worker. +- Containers start as root (`run_as_deploy` needs it to switch users). Never set `runAsNonRoot`, a `USER` or a + different `user:`. Drop every capability except `SETUID`, `SETGID` and `KILL`, plus `NET_ADMIN` where the + platform allows it (`reference/deployment.yml` says where it doesn't, and what to do instead). +- Run Puma, Sidekiq and GoodJob directly (`run_as_deploy sidekiq`), never under `foreman`: foreman kills its + processes 5 seconds after a stop signal, so jobs and requests stop part way through. +- The scheduled tasks are three buckets that each image release fills. Never add a scheduled job for a single rake + task: put it in a bucket in the DocSpring app instead. +- `worker_gj` needs a direct database connection, not a pgbouncer transaction pool. +- `DOCSPRING_SUBMISSION_DATA_ENCRYPTION_KEY` and `SECRET_KEY_BASE` are generated once per install and never change. A + lost encryption key means the data it encrypted can't be read. +- The image tags are the first 10 characters of a commit (`c648191044`). Pin one; `latest` moves with each release. + +## Checks + +```bash +scripts/check_deployments # every folder against reference/deployment.yml +``` + +Each folder's `AGENTS.md` lists its own checks (`docker compose config`, `helm lint`, `terraform validate`, ...). CI +runs all of them (`.github/workflows/ci.yml`). + +## Installing or running DocSpring for someone + +- Use the skills in `.agents/skills/`: `docspring-enterprise-install`, `docspring-enterprise-upgrade` and + `docspring-enterprise-operate`. +- Never print or log the license key, the registry credentials, `SECRET_KEY_BASE`, the encryption key, database + passwords or the admin password. Read them into variables; show only whether they're set. +- Ask before anything that deletes data or costs money: creating cloud resources, `terraform destroy`, + `docker compose down -v`, `helm uninstall`, dropping a database. +- Read the release notes (https://docspring.com/enterprise-releases) before an upgrade, and back up the database + first. Migrations only go forward: going back means restoring that backup. +- The docs at https://docspring.com/docs/enterprise/ are the source of truth for settings and behaviour. + +## Conventions + +- Plain English in READMEs and comments. Say what a thing does and why, not that it's powerful or easy. +- No customer names, hostnames or secrets anywhere. Example domain: `docspring.example.com`. +- Shell scripts: `set -euo pipefail`, shellcheck clean. Terraform: `terraform fmt`. YAML: two spaces. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0ffbd65 --- /dev/null +++ b/LICENSE @@ -0,0 +1,19 @@ +MIT License + +Copyright (c) 2018-2026 DocSpring, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the +Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +This license covers the files in this repository only. The DocSpring Enterprise Docker image is proprietary software +licensed separately by DocSpring, Inc. diff --git a/README.md b/README.md index bafd208..c294d8d 100644 --- a/README.md +++ b/README.md @@ -1,42 +1,49 @@ -# Convox Configuration for DocSpring Enterprise +# DocSpring Enterprise deployment -Please see the [Deploying DocSpring Enterprise to AWS via Convox Guide](https://guides.docspring.com/Deploying-DocSpring-Enterprise-to-AWS-via-Convox-6fb67d34d89e49f4ad15ddfc962e6b52) for more information. +Configuration and scripts for running [DocSpring Enterprise](https://docspring.com/docs/enterprise/) on your own +infrastructure. DocSpring Enterprise is one Docker image, for both amd64 and arm64, that runs anywhere you can run +containers with PostgreSQL, Redis and file storage. Each folder here is a ready-made setup for one platform: -### Requirements +| Folder | Platform | Good for | +| ------------------------------------ | --------------------------------------------- | ---------------------------------------------------------------- | +| [`docker-compose/`](docker-compose/) | Docker Compose on one Linux server | Trials, and production installs that one server can handle | +| [`kubernetes/`](kubernetes/) | A Helm chart for any Kubernetes cluster | Teams that already run Kubernetes (EKS, GKE, AKS, on-premises) | +| [`aws-ecs/`](aws-ecs/) | Terraform for AWS ECS on Fargate | AWS accounts without Kubernetes: no servers to manage | +| [`convox/`](convox/) | An install script for AWS with Convox | A complete AWS setup (EKS, RDS, ElastiCache, S3) from one script | +| [`aptible/`](aptible/) | Aptible | Teams on Aptible's compliance-focused platform | -- MacOS -- Convox v3 CLI - - https://docs.convox.com/installation/cli -- AWS CLI - - https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html -- Terraform - - https://learn.hashicorp.com/tutorials/terraform/install-cli +Another platform (Nomad, Render, Fly.io, OpenShift, plain `docker run` with systemd) works too: run the services, +release command and scheduled tasks that [`reference/deployment.yml`](reference/deployment.yml) describes. -This installation script requires the Convox and AWS CLI tools. +## Docs -The Convox CLI must be version 3 or greater. Older versions of the Convox CLI had a version string like this: `20210208170413`. -You can check your Convox CLI version by running: `convox version` -Install the Convox CLI by running `brew install convox`, or by following the instructions at: https://docs.convox.com/getting-started/introduction +The full guides are in our docs: https://docspring.com/docs/enterprise/ -Follow these instructions to install the AWS CLI: https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html +- [Choosing a deployment](https://docspring.com/docs/enterprise/) +- [Requirements](https://docspring.com/docs/enterprise/requirements/) +- [The Docker image](https://docspring.com/docs/enterprise/docker-image/): registries, tags, amd64 and arm64 +- [Services](https://docspring.com/docs/enterprise/services/) and + [scheduled tasks](https://docspring.com/docs/enterprise/scheduled-tasks/) +- [Upgrades](https://docspring.com/docs/enterprise/upgrades/) +- [Environment variables](https://docspring.com/docs/enterprise/configuration/environment-variables/) +- [Releases and their notes](https://docspring.com/enterprise-releases) -_Please let us know if you need to run this script on Linux. Linux support should not be too difficult to implement, but unfortunately we probably won't be able to support Windows._ +## Before you start -# Clone this repo +You'll need your DocSpring license key and the credentials for DocSpring's Docker registry. We send both by email +when you sign up for DocSpring Enterprise. Contact [enterprise@docspring.com](mailto:enterprise@docspring.com) if you +don't have them. -``` -git clone https://github.com/DocSpring/docspring_enterprise.git -``` +## AI agents -### Install Convox and set up DocSpring Enterprise +Each folder has an `AGENTS.md` for coding agents, and [`.agents/skills/`](.agents/skills/) has skills for installing, +upgrading and running DocSpring Enterprise. Start with [`AGENTS.md`](AGENTS.md). -Run the install script: +## Support -``` -cd docspring_enterprise -./install.rb -``` +Email [support@docspring.com](mailto:support@docspring.com). Issues and pull requests for these configs are welcome. -### Deploying Updates +## License -Run `./update.sh` to update to the latest DocSpring Enterprise image. This will perform a 'rolling deployment' with zero downtime, and it will also update your database. +The files in this repository are MIT licensed (see [LICENSE](LICENSE)). The DocSpring Enterprise image they run is +proprietary software that needs a DocSpring license. diff --git a/.convox/.keep b/convox/.convox/.keep similarity index 100% rename from .convox/.keep rename to convox/.convox/.keep diff --git a/.dockerignore b/convox/.dockerignore similarity index 100% rename from .dockerignore rename to convox/.dockerignore diff --git a/convox/.gitignore b/convox/.gitignore new file mode 100644 index 0000000..38d9650 --- /dev/null +++ b/convox/.gitignore @@ -0,0 +1,5 @@ +.bundle +convox.yml +.installer_config* +.convox/app +.rack_name diff --git a/.rubocop.yml b/convox/.rubocop.yml similarity index 100% rename from .rubocop.yml rename to convox/.rubocop.yml diff --git a/convox.example.yml b/convox/convox.example.yml similarity index 51% rename from convox.example.yml rename to convox/convox.example.yml index 75f289f..893c276 100644 --- a/convox.example.yml +++ b/convox/convox.example.yml @@ -6,7 +6,12 @@ services: path: ${HEALTH_CHECK_PATH} grace: 50 interval: 5 - command: run_command deploy DATABASE_URL foreman start -m web=1 + command: run_as_deploy puma -C config/puma.rb + # Requests can run for up to 210 seconds (the Admin API's synchronous imports and exports), and Puma finishes them + # when it stops + timeout: 240 + termination: + grace: 240 deployment: minimum: 50 maximum: 200 @@ -21,16 +26,15 @@ services: - "*" - WEB_CONCURRENCY=2 - RAILS_MAX_THREADS=5 - - REQUEST_TIMEOUT=30 - FORCE_SSL=true - PORT=4001 port: 4001 ingressAnnotations: - nginx.ingress.kubernetes.io/proxy-buffer-size=32k - # No privileged containers. run_command starts as root with only the capabilities it needs: NET_ADMIN to add the - # iptables rule that blocks the cloud metadata address, and SETUID and SETGID to switch to the deploy user. The app - # then runs as deploy with no capabilities. Needs Convox 3.24.10 or later. worker and command use the same - # securityContext. + # No privileged containers. run_as_deploy starts as root with only the capabilities it needs: NET_ADMIN to add the + # iptables rule that blocks the cloud metadata address, SETUID and SETGID to switch to the deploy user, and KILL so + # a stop signal reaches the app. The app then runs as deploy with no capabilities. Needs Convox + # 3.24.10 or later. worker, worker-gj and command use the same securityContext. securityContext: allowPrivilegeEscalation: false capabilities: @@ -40,17 +44,20 @@ services: - NET_ADMIN - SETUID - SETGID + - KILL seccompProfile: RuntimeDefault worker: image: 691950705664.dkr.ecr.us-east-1.amazonaws.com/docspring/enterprise - command: run_command deploy DATABASE_URL foreman start -m worker=1 + command: run_as_deploy sidekiq + termination: + grace: 60 deployment: minimum: 50 maximum: 200 scale: - memory: 2000 - cpu: 700 + memory: 3072 + cpu: 1000 count: 3-6 targets: cpu: 90 @@ -66,6 +73,35 @@ services: - NET_ADMIN - SETUID - SETGID + - KILL + seccompProfile: RuntimeDefault + + # GoodJob: account exports and imports + worker-gj: + image: 691950705664.dkr.ecr.us-east-1.amazonaws.com/docspring/enterprise + command: run_as_deploy good_job + termination: + grace: 60 + deployment: + minimum: 0 + maximum: 100 + scale: + memory: 1024 + cpu: 250 + count: 1 + environment: + - "*" + - FORCE_SSL=true + securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: + - ALL + add: + - NET_ADMIN + - SETUID + - SETGID + - KILL seccompProfile: RuntimeDefault command: @@ -86,10 +122,20 @@ services: - NET_ADMIN - SETUID - SETGID + - KILL seccompProfile: RuntimeDefault +# The image decides what each of these runs, so a release can add or remove scheduled tasks without a change here timers: - update-submissions: + hourly: + schedule: 15 * * * ? + command: run_as_deploy rake timers:hourly + service: command + daily: schedule: 0 3 * * ? - command: run_command deploy DATABASE_URL rake submissions:expire_overdue_submissions + command: run_as_deploy rake timers:daily + service: command + weekly: + schedule: 0 4 * * 0 + command: run_as_deploy rake timers:weekly service: command diff --git a/install.rb b/convox/install.rb similarity index 100% rename from install.rb rename to convox/install.rb diff --git a/convox/update.sh b/convox/update.sh new file mode 100755 index 0000000..31a488c --- /dev/null +++ b/convox/update.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Deploys convox.yml to your rack: builds a release, migrates the database with it, then promotes it (a rolling +# deploy, with no downtime). Run it after changing the image tag in convox.yml, or any other setting there. +set -euo pipefail +cd "$(dirname "$0")" + +if ! [ -f .rack_name ]; then + echo "ERROR: .rack_name not found. Run ./install.rb first, or write your rack's name to .rack_name." >&2 + exit 1 +fi +RACK_NAME="$(cat .rack_name)" + +echo "[${RACK_NAME}] => Building a release from convox.yml" +RELEASE_ID="$(convox build --id --rack "${RACK_NAME}")" + +echo "[${RACK_NAME}] => Migrating the database with ${RELEASE_ID}" +convox run --rack "${RACK_NAME}" --release "${RELEASE_ID}" command run_as_deploy rake db:prepare + +echo "[${RACK_NAME}] => Promoting ${RELEASE_ID}" +convox releases promote "${RELEASE_ID}" --rack "${RACK_NAME}" --wait diff --git a/reference/deployment.yml b/reference/deployment.yml new file mode 100644 index 0000000..0252a8c --- /dev/null +++ b/reference/deployment.yml @@ -0,0 +1,138 @@ +# What every DocSpring Enterprise deployment runs. Each folder in this repository (docker-compose, kubernetes, +# aws-ecs, convox, aptible) implements this, and scripts/check_deployments fails CI when one of them drifts from it. +# +# People: the docs explain all of this at https://docspring.com/docs/enterprise/ +# Agents: read AGENTS.md at the root of this repository first. + +image: + # One multi-arch image (linux/amd64 and linux/arm64). Pulling a tag picks the right architecture. + repositories: + docker_hub: docspringcom/docspring-enterprise + ecr: 691950705664.dkr.ecr.us-east-1.amazonaws.com/docspring/enterprise + # is the first 10 characters of the commit the image was built from, such as c648191044. Every release is + # listed at https://docspring.com/enterprise-releases. `latest` moves with each release: pin a version in production. + tags: ['', '-amd64', '-arm64', latest] + platforms: [linux/amd64, linux/arm64] + # Both registries are private: DocSpring sends each customer their registry credentials with their license key. + +# Every service and command starts with run_as_deploy, which runs it under tini as the unprivileged `deploy` user, +# after blocking the cloud metadata address (169.254.169.254) when the container has NET_ADMIN. +services: + web: + command: run_as_deploy puma -C config/puma.rb + port: 4001 # the PORT env var + health_checks: + # Answers once Rails has booted. Use it for liveness, readiness and load balancer target health. + liveness: /health/site + readiness: /health/site + # Also checks the database, Redis and the Rails cache: use it for uptime monitoring. + monitoring: /health + # Enterprise requests can run for 210 seconds (the Admin API's synchronous imports and exports), so give the load + # balancer or proxy at least 240 seconds, and allow request bodies up to 110 MB (template uploads). + request_timeout_seconds: 240 + max_request_body: 110MB + # On a stop, Puma finishes the requests it's running (up to 215 seconds). Give it that long where the platform + # allows; where it allows less, a long request is cut off. + stop_grace_seconds: 240 + recommended: + replicas: 2 + memory: 1536Mi + cpu: 1000m + worker: + # Sidekiq: generates PDFs, runs the document tools (Chromium, LibreOffice, the PDF and image tools) inline, + # sends email and webhooks. + command: run_as_deploy sidekiq + # On a stop, Sidekiq finishes its jobs for 25 seconds, then puts the rest back on the queue. + stop_grace_seconds: 60 + recommended: + replicas: 2 + memory: 3072Mi + cpu: 1000m + worker_gj: + # GoodJob: account exports and imports (the Admin API). Its DATABASE_URL must be a direct database connection, not + # a pgbouncer transaction pool. Goes away when these jobs move to Sidekiq. + command: run_as_deploy good_job + stop_grace_seconds: 60 + recommended: + replicas: 1 + memory: 1024Mi + cpu: 500m + +# Runs once before each release's services start (and on the first install, when it loads the database schema and +# creates the admin user from DOCSPRING_ADMIN_EMAIL and DOCSPRING_ADMIN_PASSWORD). Safe to run again. Like worker_gj, +# it needs a direct database connection. +release_command: run_as_deploy rake db:prepare + +# The image decides what each of these runs, so a new release can add or remove tasks without a change here. Times are +# UTC; any time works, as long as each runs on its schedule. A run that's still going when the next starts makes the +# next one exit. +scheduled_tasks: + hourly: + command: run_as_deploy rake timers:hourly + cron: '15 * * * *' + daily: + command: run_as_deploy rake timers:daily + cron: '0 3 * * *' + weekly: + command: run_as_deploy rake timers:weekly + cron: '0 4 * * 0' + +container: + # Starts as root so run_as_deploy can add the firewall rule and switch to `deploy`; the app itself never runs as + # root. Don't set runAsNonRoot or a USER. + capabilities: + drop: [ALL] + # SETUID and SETGID switch to `deploy`. KILL lets a stop signal reach the app, so it finishes its requests and jobs + # before it exits. + add: [SETUID, SETGID, KILL] + # Lets run_as_deploy block the cloud metadata address (169.254.169.254), so nothing in the app can read the + # server's cloud credentials. Add it where the platform allows. Where it doesn't (AWS Fargate, Aptible, a + # Kubernetes namespace below the `privileged` Pod Security level), run_as_deploy logs a warning and carries on: + # block that address at the network level instead (a NetworkPolicy), or run where it isn't reachable (Fargate). + recommended_add: [NET_ADMIN] + allow_privilege_escalation: false + seccomp_profile: RuntimeDefault + read_only_root_filesystem: false + +dependencies: + postgres: '14 or later (17 recommended)' + redis: '6.2 or later' + file_storage: 'An S3 bucket (any region), a Google Cloud Storage bucket, or a volume for one-server installs' + email: 'An SMTP server or Postmark, SendGrid, Mailgun or Amazon SES' + +network: + inbound: 'HTTPS to the web service, through your load balancer or reverse proxy (it terminates TLS and sets X-Forwarded-Proto)' + outbound: + - host: api.docspring.com + port: 443 + why: 'The license check, about once an hour (counts only: no documents, data or personal information)' + - host: 'your file storage, database, Redis and email service' + +# The settings an install can't run without. Every other setting is optional: +# https://docspring.com/docs/enterprise/configuration/environment-variables/ +environment: + required: + DATABASE_URL: 'postgres://user:password@host:5432/docspring' + REDIS_URL: 'redis://host:6379/0 (rediss:// for TLS)' + SECRET_KEY_BASE: 'openssl rand -hex 64' + DOCSPRING_SUBMISSION_DATA_ENCRYPTION_KEY: 'openssl rand -hex 32. Never change or lose it: it encrypts stored data' + DOCSPRING_LICENSE: 'Your license key' + DOCSPRING_DOMAIN_NAME: 'The host name people use, such as docspring.example.com' + first_install: + DOCSPRING_ADMIN_EMAIL: 'The first admin user, created by the release command on an empty database' + DOCSPRING_ADMIN_PASSWORD: 'Their password. Change it after you sign in' + file_storage: + s3: + DOCSPRING_AWS_UPLOADS_S3_BUCKET: 'The bucket' + DOCSPRING_AWS_UPLOADS_S3_REGION: 'Its region' + # Without these, the AWS SDK's default credentials are used: EKS Pod Identity, IRSA, an ECS task role, or + # AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY. Not an EC2 instance profile: run_as_deploy blocks the metadata + # address it's read from. + DOCSPRING_AWS_ACCESS_KEY_ID: 'Optional' + DOCSPRING_AWS_ACCESS_KEY_SECRET: 'Optional' + # The bucket needs a CORS rule for the app's origin: browsers upload template files straight to it. + s3_cors: + allowed_methods: [GET, PUT, POST] + allowed_headers: [Authorization, cache-control, x-requested-with, content-type] + allowed_origins: ['https://'] + max_age_seconds: 3000 diff --git a/scripts/check_deployments b/scripts/check_deployments new file mode 100755 index 0000000..b929161 --- /dev/null +++ b/scripts/check_deployments @@ -0,0 +1,116 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# Checks that every deployment folder runs what reference/deployment.yml says: each service's command, the release +# command, the three scheduled tasks and their schedules, and the container capabilities. Plain Ruby (no gems), so it +# runs anywhere. Renders the Helm chart with `helm template` when helm is installed (CI installs it). +# +# scripts/check_deployments + +require 'yaml' +require 'json' +require 'open3' + +ROOT = File.expand_path('..', __dir__) +CONTRACT = YAML.load_file(File.join(ROOT, 'reference/deployment.yml')) + +SERVICES = CONTRACT.fetch('services').transform_values { |s| s.fetch('command') } +RELEASE = CONTRACT.fetch('release_command') +TASKS = CONTRACT.fetch('scheduled_tasks').transform_values { |t| t.fetch('command') } +CAPS_ADD = CONTRACT.dig('container', 'capabilities', 'add').sort +CAPS_RECOMMENDED = CONTRACT.dig('container', 'capabilities', 'recommended_add').sort + +@failures = [] + +def check(folder, what, actual, expected) + return if actual == expected + + @failures << "#{folder}: #{what} is #{actual.inspect}, but reference/deployment.yml says #{expected.inspect}" +end + +# Every required capability, and no others than the recommended ones (a platform may not allow those) +def check_caps(folder, what, actual) + actual = Array(actual).sort + return if (CAPS_ADD - actual).empty? && (actual - CAPS_ADD - CAPS_RECOMMENDED).empty? + + @failures << "#{folder}: #{what} are #{actual.inspect}, but reference/deployment.yml says #{CAPS_ADD.inspect}, " \ + "plus #{CAPS_RECOMMENDED.inspect} where the platform allows" +end + +def words(command) = Array(command).join(' ').split.join(' ') + +def read(path) = File.read(File.join(ROOT, path)) + +# docker-compose +compose = YAML.load(read('docker-compose/compose.yaml'), aliases: true) +SERVICES.each do |name, command| + check('docker-compose', "#{name}'s command", words(compose.dig('services', name, 'command')), command) + check_caps('docker-compose', "#{name}'s cap_add", compose.dig('services', name, 'cap_add')) +end +check('docker-compose', "release's command", words(compose.dig('services', 'release', 'command')).include?(RELEASE), true) +schedule = read('docker-compose/install-schedule.sh') +TASKS.each do |name, command| + check('docker-compose', "install-schedule.sh running #{command}", + schedule.include?("rake timers:%s") && schedule.include?("' #{name}"), true) +end + +# convox +convox = YAML.load_file(File.join(ROOT, 'convox/convox.example.yml')) +SERVICES.each do |name, command| + service = convox.dig('services', name.tr('_', '-')) + check('convox', "#{name}'s command", words(service&.fetch('command')), command) + check_caps('convox', "#{name}'s capabilities", service&.dig('securityContext', 'capabilities', 'add')) +end +check('convox', 'the timers', convox.fetch('timers').transform_values { |t| t.fetch('command') }, TASKS) +check('convox', 'update.sh running the release command', read('convox/update.sh').include?("command #{RELEASE}"), true) + +# aptible +procfile = read('aptible/Procfile').lines.to_h { |line| line.chomp.split(': ', 2) } +SERVICES.each { |name, command| check('aptible', "Procfile's #{name}", procfile[name], command) } +check('aptible', '.aptible.yml before_release', YAML.load(read('aptible/.aptible.yml'))['before_release'], [RELEASE]) +crontab = read('aptible/crontab').lines.reject { |l| l.start_with?('#') || l.strip.empty? }.map { |l| l.split(' ', 6).last.strip } +check('aptible', 'the crontab', crontab.sort, TASKS.values.sort) + +# kubernetes: render the chart and read its objects +if system('helm version > /dev/null 2>&1') + chart = File.join(ROOT, 'kubernetes/docspring-enterprise') + values = File.join(ROOT, 'kubernetes/docspring-enterprise/ci/check-values.yaml') + args = ['helm', 'template', 'docspring', chart] + args += ['-f', values] if File.exist?(values) + out, err, status = Open3.capture3(*args) + if status.success? + docs = YAML.load_stream(out).compact + containers = lambda do |doc| + spec = doc.dig('spec', 'jobTemplate', 'spec', 'template', 'spec') || doc.dig('spec', 'template', 'spec') || {} + spec.fetch('containers', []) + end + commands = docs.flat_map { |doc| containers.call(doc).map { |c| words(Array(c['command']) + Array(c['args'])) } } + (SERVICES.values + [RELEASE] + TASKS.values).each do |command| + check('kubernetes', "a container running #{command}", commands.include?(command), true) + end + docs.each do |doc| + containers.call(doc).each do |c| + check_caps('kubernetes', "#{doc['kind']}/#{doc.dig('metadata', 'name')}'s capabilities", + c.dig('securityContext', 'capabilities', 'add')) + end + end + else + @failures << "kubernetes: helm template failed: #{err}" + end +else + warn 'helm not installed: skipping the Kubernetes chart' +end + +# aws-ecs: the commands are in the module's task definitions +ecs = Dir[File.join(ROOT, 'aws-ecs/modules/**/*.tf')].map { |f| File.read(f) }.join("\n") +(SERVICES.values + [RELEASE] + TASKS.values).each do |command| + quoted = command.split.map { |w| %("#{w}") }.join(', ') + check('aws-ecs', "a task running #{command}", ecs.include?(quoted) || ecs.include?(command), true) +end + +if @failures.empty? + puts 'Every deployment matches reference/deployment.yml' +else + puts @failures + exit 1 +end diff --git a/update.sh b/update.sh deleted file mode 100755 index a81276b..0000000 --- a/update.sh +++ /dev/null @@ -1,18 +0,0 @@ -#!/bin/bash -set -eo pipefail -CURRENT_DIR=$(dirname "$0") - -if ! [ -f "${CURRENT_DIR}/.rack_name" ]; then - echo "ERROR: .rack_name file not found" - exit 1 -fi -RACK_NAME=$(cat "${CURRENT_DIR}/.rack_name") - -echo "[${RACK_NAME}] => Creating new build..." -RELEASE_ID=$(convox build --id --rack "${RACK_NAME}") - -echo "[${RACK_NAME}] => Running bin/pre_release in: $RELEASE_ID" -convox run --release "$RELEASE_ID" command bin/pre_release --rack "${RACK_NAME}" - -echo "[${RACK_NAME}] => Promoting Release: $RELEASE_ID" -convox releases promote "$RELEASE_ID" --rack "${RACK_NAME}" From 164a5bfd5f1b2e56361826c33ab6ec3204282c8a Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Wed, 18 Nov 2026 12:00:19 +1300 Subject: [PATCH 02/12] Docker Compose: DocSpring on one server with PostgreSQL, Valkey and Caddy, setup, update, backup and cron scripts --- docker-compose/.env.example | 47 ++++++++++ docker-compose/AGENTS.md | 25 ++++++ docker-compose/Caddyfile | 13 +++ docker-compose/README.md | 104 +++++++++++++++++++++++ docker-compose/backup.sh | 28 ++++++ docker-compose/compose.yaml | 132 +++++++++++++++++++++++++++++ docker-compose/install-schedule.sh | 42 +++++++++ docker-compose/setup.sh | 40 +++++++++ docker-compose/update.sh | 34 ++++++++ 9 files changed, 465 insertions(+) create mode 100644 docker-compose/.env.example create mode 100644 docker-compose/AGENTS.md create mode 100644 docker-compose/Caddyfile create mode 100644 docker-compose/README.md create mode 100644 docker-compose/backup.sh create mode 100644 docker-compose/compose.yaml create mode 100644 docker-compose/install-schedule.sh create mode 100644 docker-compose/setup.sh create mode 100644 docker-compose/update.sh diff --git a/docker-compose/.env.example b/docker-compose/.env.example new file mode 100644 index 0000000..51e6000 --- /dev/null +++ b/docker-compose/.env.example @@ -0,0 +1,47 @@ +# DocSpring Enterprise settings for Docker Compose. ./setup.sh copies this file to .env and fills in the secrets. +# Every setting: https://docspring.com/docs/enterprise/configuration/environment-variables/ + +# The DocSpring release to run (not DOCSPRING_ prefixed: the app warns about DOCSPRING_ names it doesn't know). +# Every release: https://docspring.com/enterprise-releases +IMAGE_TAG=c648191044 + +# Caddy serves HTTPS with a Let's Encrypt certificate. Leave this empty if your own proxy or load balancer handles +# HTTPS: then publish web's port 4001 to it (see README.md). +COMPOSE_PROFILES=caddy + +# The host name people use. Point its DNS at this server before you start Caddy. +DOCSPRING_DOMAIN_NAME=docspring.example.com +DOCSPRING_FORCE_SSL=true + +# Your license key, from DocSpring +DOCSPRING_LICENSE= + +# The first admin user, created on the first start. Change the password after you sign in. +DOCSPRING_ADMIN_NAME=Admin +DOCSPRING_ADMIN_EMAIL=admin@example.com +DOCSPRING_ADMIN_PASSWORD=__GENERATED__ + +# Secrets: ./setup.sh generates these. Back them up with your database backups. If you lose +# DOCSPRING_SUBMISSION_DATA_ENCRYPTION_KEY, the data it encrypted can't be read. +POSTGRES_PASSWORD=__GENERATED__ +SECRET_KEY_BASE=__GENERATED__ +DOCSPRING_SUBMISSION_DATA_ENCRYPTION_KEY=__GENERATED__ + +# File storage. Without a bucket, files are kept in the `uploads` Docker volume on this server. For production we +# recommend S3: create a private bucket with the CORS rule in README.md, then set these. +# DOCSPRING_AWS_UPLOADS_S3_BUCKET= +# DOCSPRING_AWS_UPLOADS_S3_REGION= +# DOCSPRING_AWS_ACCESS_KEY_ID= +# DOCSPRING_AWS_ACCESS_KEY_SECRET= + +# Email: DocSpring sends sign-in, notification and signature request emails. Configure SMTP (or Postmark, SendGrid, +# Mailgun or Amazon SES: see the email notifications docs). Until then, DOCSPRING_DISABLE_EMAILS=true turns email off. +DOCSPRING_DISABLE_EMAILS=true +# DOCSPRING_SMTP_SERVER= +# DOCSPRING_SMTP_PORT=587 +# DOCSPRING_SMTP_USERNAME= +# DOCSPRING_SMTP_PASSWORD= +# DOCSPRING_FROM_EMAIL=DocSpring + +# Time zone for dates on PDFs when an account has none (a Rails time zone name) +DOCSPRING_TIMEZONE=UTC diff --git a/docker-compose/AGENTS.md b/docker-compose/AGENTS.md new file mode 100644 index 0000000..52ab36a --- /dev/null +++ b/docker-compose/AGENTS.md @@ -0,0 +1,25 @@ +# docker-compose + +DocSpring Enterprise on one server. Read the root `AGENTS.md` first, and `README.md` here for the install steps. + +## Changing these files + +- `compose.yaml` implements `../reference/deployment.yml`: the service names, commands, release command, + capabilities and health checks must match it. `scripts/check_deployments` (CI) checks. +- The image tag variable is `IMAGE_TAG`, not `DOCSPRING_*`: `env_file` passes every `.env` variable into the + containers, and the app warns about `DOCSPRING_` names it doesn't know. +- `release` is the only service that may add `CHOWN`: it gives the new `uploads` volume to the `deploy` user. +- The scheduled tasks come from the host's cron (`install-schedule.sh`), not a container with the Docker socket. +- Check your change: `docker compose config --quiet` (with a `.env` made by `./setup.sh`), `shellcheck *.sh`. +- Test it for real with `docker compose up -d --wait`, then + `docker compose run --rm tasks run_as_deploy rake checks:health_check checks:generate_test_submission` + (needs a valid license), then `./backup.sh`, then `docker compose down -v`. + +## Running an install for someone + +- Never print `.env`: it holds the license, the secrets and the admin password. Read single settings with + `grep '^NAME=' .env | cut -d= -f2-` into a variable when you must. +- Never run `./setup.sh` over an existing `.env` (it refuses) or delete the `postgres` volume without a backup: + `docker compose down -v` deletes the database. +- Upgrades: `./update.sh `, after reading that release's notes. Rollback means restoring the backup it made, + because migrations only go forward. diff --git a/docker-compose/Caddyfile b/docker-compose/Caddyfile new file mode 100644 index 0000000..de91abe --- /dev/null +++ b/docker-compose/Caddyfile @@ -0,0 +1,13 @@ +{$DOCSPRING_DOMAIN_NAME} { + # Template uploads and API requests can be large + request_body { + max_size 110MB + } + # Requests can run for up to 210 seconds (the Admin API's synchronous imports and exports) + reverse_proxy web:4001 { + transport http { + read_timeout 240s + write_timeout 240s + } + } +} diff --git a/docker-compose/README.md b/docker-compose/README.md new file mode 100644 index 0000000..1f3d8d8 --- /dev/null +++ b/docker-compose/README.md @@ -0,0 +1,104 @@ +# DocSpring Enterprise with Docker Compose + +Runs DocSpring Enterprise on one Linux server: the app's web server and workers, PostgreSQL, Valkey (Redis) and +Caddy, which gets a free HTTPS certificate from Let's Encrypt. Good for a trial, or for a production install that one +server can handle. For high availability, use the [Kubernetes chart](../kubernetes) or [AWS ECS](../aws-ecs). + +The full guide is in our docs: https://docspring.com/docs/enterprise/deploy/docker-compose/ + +## What you need + +- A Linux server with Docker Engine 24 or later and the Compose plugin, amd64 or arm64, with at least 4 CPUs, 8 GB of + memory and 50 GB of disk. (Docker Desktop on a Mac works for a trial.) +- A DNS name pointing at the server, with ports 80 and 443 open, unless your own proxy handles HTTPS. +- Your DocSpring license key and Docker Hub credentials, which DocSpring sends you. +- Outbound HTTPS to `api.docspring.com` for the license check. + +## Install + +```bash +git clone https://github.com/DocSpring/docspring-enterprise.git +cd docspring-enterprise/docker-compose +./setup.sh # writes .env with new secrets +$EDITOR .env # license, domain, admin email, email and file storage settings +docker login -u # with the token DocSpring sent you +docker compose up -d --wait # migrates the database, creates the admin user, starts everything +sudo ./install-schedule.sh # the hourly, daily and weekly tasks, from the host's cron +``` + +Then go to `https://` and sign in with `DOCSPRING_ADMIN_EMAIL` and `DOCSPRING_ADMIN_PASSWORD` from +`.env`. Change the password once you're in. + +## What runs + +| Service | What it does | +| ----------- | -------------------------------------------------------------------------------------------------- | +| `release` | Runs before the others on each `docker compose up`: creates or migrates the database, then exits | +| `web` | The app and the API, on port 4001 | +| `worker` | Sidekiq: generates PDFs, runs Chromium, LibreOffice and the PDF tools, sends email and webhooks | +| `worker_gj` | GoodJob: account exports and imports | +| `postgres` | PostgreSQL 17, in the `postgres` volume | +| `redis` | Valkey 8, in the `redis` volume | +| `caddy` | HTTPS for `DOCSPRING_DOMAIN_NAME` (the `caddy` profile) | +| `tasks` | Not a running service: `docker compose run --rm tasks run_as_deploy rake ...` runs one-off commands | + +The app's containers start as root only to block the cloud metadata address and switch to the `deploy` user. They +drop every Linux capability except the four that needs. + +## Your own proxy or load balancer + +Set `COMPOSE_PROFILES=` (empty) in `.env` to leave Caddy out, and publish web's port in a `compose.override.yaml`: + +```yaml +services: + web: + ports: ['127.0.0.1:4001:4001'] +``` + +Your proxy must send `X-Forwarded-Proto: https`, allow request bodies of at least 110 MB, and wait at least 240 +seconds for a response. + +## File storage + +Without a bucket, template files and generated PDFs are kept in the `uploads` volume. For production we recommend an +S3 bucket: it's backed up and versioned by AWS, and the server keeps no files. Create a private bucket, give it this +CORS rule (browsers upload template files straight to it), then set `DOCSPRING_AWS_UPLOADS_S3_BUCKET`, +`DOCSPRING_AWS_UPLOADS_S3_REGION` and an access key in `.env`: + +```json +[ + { + "AllowedMethods": ["GET", "PUT", "POST"], + "AllowedHeaders": ["Authorization", "cache-control", "x-requested-with", "content-type"], + "AllowedOrigins": ["https://docspring.example.com"], + "MaxAgeSeconds": 3000 + } +] +``` + +## Upgrade + +Read the release's notes at https://docspring.com/enterprise-releases, then: + +```bash +./update.sh +``` + +It backs up the database, pulls the new image, migrates the database and restarts the services. The site is down for +the minute or so the restart takes. + +## Back up + +`./backup.sh` writes a database dump (and the uploads volume, without a bucket) to `./backups` and keeps the last 14. +Run it from cron and copy `./backups` off the server. Keep a copy of `.env` somewhere safe too: without +`DOCSPRING_SUBMISSION_DATA_ENCRYPTION_KEY`, the encrypted data in a backup can't be read. + +## Commands + +```bash +docker compose ps # what's running +docker compose logs -f web worker # logs +docker compose run --rm tasks run_as_deploy rails console # a Rails console +docker compose run --rm tasks run_as_deploy rake checks:health_check checks:generate_test_submission +docker compose run --rm tasks run_as_deploy rake timers:daily # run the daily tasks now +``` diff --git a/docker-compose/backup.sh b/docker-compose/backup.sh new file mode 100644 index 0000000..53d09e6 --- /dev/null +++ b/docker-compose/backup.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +# Backs up the database to ./backups/docspring-